diff --git a/code/train/Python/0050467_test_scrubber.py b/code/train/Python/0050467_test_scrubber.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc16dc661629f4d23213dee76cd171e64bb45cf --- /dev/null +++ b/code/train/Python/0050467_test_scrubber.py @@ -0,0 +1,145 @@ +# Copyright 2013 Red Hat, Inc. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import uuid + +import eventlet +import glance_store +from mock import patch +from mox3 import mox +from oslo_config import cfg +# NOTE(jokke): simplified transition to py3, behaves like py2 xrange +from six.moves import range + +from glance.common import exception +from glance import scrubber +from glance.tests import utils as test_utils + +CONF = cfg.CONF + + +class TestScrubber(test_utils.BaseTestCase): + + def setUp(self): + super(TestScrubber, self).setUp() + glance_store.register_opts(CONF) + self.config(group='glance_store', default_store='file', + filesystem_store_datadir=self.test_dir) + glance_store.create_stores() + self.mox = mox.Mox() + + def tearDown(self): + self.mox.UnsetStubs() + # These globals impact state outside of this test class, kill them. + scrubber._file_queue = None + scrubber._db_queue = None + super(TestScrubber, self).tearDown() + + def _scrubber_cleanup_with_store_delete_exception(self, ex): + uri = 'file://some/path/%s' % uuid.uuid4() + id = 'helloworldid' + scrub = scrubber.Scrubber(glance_store) + scrub.registry = self.mox.CreateMockAnything() + scrub.registry.get_image(id).AndReturn({'status': 'pending_delete'}) + scrub.registry.update_image(id, {'status': 'deleted'}) + self.mox.StubOutWithMock(glance_store, "delete_from_backend") + glance_store.delete_from_backend( + uri, + mox.IgnoreArg()).AndRaise(ex) + self.mox.ReplayAll() + scrub._scrub_image(eventlet.greenpool.GreenPool(1), + id, [(id, '-', uri)]) + self.mox.VerifyAll() + + def test_store_delete_unsupported_backend_exception(self): + ex = glance_store.UnsupportedBackend() + self._scrubber_cleanup_with_store_delete_exception(ex) + + def test_store_delete_notfound_exception(self): + ex = exception.NotFound() + self._scrubber_cleanup_with_store_delete_exception(ex) + + +class TestScrubDBQueue(test_utils.BaseTestCase): + + def setUp(self): + super(TestScrubDBQueue, self).setUp() + + def tearDown(self): + super(TestScrubDBQueue, self).tearDown() + + def _create_image_list(self, count): + images = [] + for x in range(count): + images.append({'id': x}) + + return images + + def test_get_all_images(self): + scrub_queue = scrubber.ScrubDBQueue() + images = self._create_image_list(15) + image_pager = ImagePager(images) + + def make_get_images_detailed(pager): + def mock_get_images_detailed(filters, marker=None): + return pager() + return mock_get_images_detailed + + with patch.object(scrub_queue.registry, 'get_images_detailed') as ( + _mock_get_images_detailed): + _mock_get_images_detailed.side_effect = ( + make_get_images_detailed(image_pager)) + actual = list(scrub_queue._get_all_images()) + + self.assertEqual(images, actual) + + def test_get_all_images_paged(self): + scrub_queue = scrubber.ScrubDBQueue() + images = self._create_image_list(15) + image_pager = ImagePager(images, page_size=4) + + def make_get_images_detailed(pager): + def mock_get_images_detailed(filters, marker=None): + return pager() + return mock_get_images_detailed + + with patch.object(scrub_queue.registry, 'get_images_detailed') as ( + _mock_get_images_detailed): + _mock_get_images_detailed.side_effect = ( + make_get_images_detailed(image_pager)) + actual = list(scrub_queue._get_all_images()) + + self.assertEqual(images, actual) + + +class ImagePager(object): + def __init__(self, images, page_size=0): + image_count = len(images) + if page_size == 0 or page_size > image_count: + page_size = image_count + self.image_batches = [] + start = 0 + l = len(images) + while start < l: + self.image_batches.append(images[start: start + page_size]) + start += page_size + if (l - start) < page_size: + page_size = l - start + + def __call__(self): + if len(self.image_batches) == 0: + return [] + else: + return self.image_batches.pop(0) diff --git a/code/train/Python/0051088_test_utils.py b/code/train/Python/0051088_test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e432e03f989a94fb4a6a889de36d0433f2a4de3c --- /dev/null +++ b/code/train/Python/0051088_test_utils.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +# +# This file is part of pysenslog. +# Copyright 2015 Leonardo Rossi . +# +# pysenslog is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# pysenslog is distributed in the hope that it will be useful, but WITHOUT ANY +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR +# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with pysenslog. If not, see . + +"""Test utils.""" + +from __future__ import absolute_import, unicode_literals + +from numpy import around, matrix, multiply, random +from pylocating.utils import _points_in_surface_sphere, \ + generate_points_in_surface_sphere, distance, \ + generate_points_random_in_surface_sphere, \ + generate_sequential_points + + +class TestUtils(object): + + """Test utils.""" + + @staticmethod + def _check_points(radius, points, center=None): + """Check points.""" + square_radius = radius * radius + center = center if center is not None else matrix([0, 0, 0]) + for point in points: + point = point - center + val = around(multiply(point, point).sum(), decimals=3) + assert val == square_radius + + def test_point_in_surface_sphere(self): + """Test point in surface sphere generation.""" + points = _points_in_surface_sphere(num_of_points=256) + self._check_points(1, points) + + def test_point_in_surface_sphere_1(self): + """Test point in surface sphere generation.""" + radius = 4 + points = generate_points_in_surface_sphere( + center=matrix([0, 0, 0]), radius=radius, num_of_points=16) + self._check_points(radius, points) + + def test_point_in_surface_sphere_2(self): + """Test point in surface sphere generation.""" + center = matrix([5, 6, 7]) + radius = 1 + points = generate_points_in_surface_sphere( + center=center, radius=radius, num_of_points=16) + self._check_points(radius, points, center=center) + + def test_distance(self): + """Test distance.""" + for i in range(20): + point = matrix(random.random(3)) + assert 0 == distance(point, point) + + pa = matrix([5, 3, 4]) + pb = matrix([10, 3, 4]) + assert 5 == distance(pa, pb) + + pa = matrix([5, 3, 4]) + pb = matrix([5, 7, 4]) + assert 4 == distance(pa, pb) + + pa = matrix([5, 3, 4]) + pb = matrix([5, 3, 11]) + assert 7 == distance(pa, pb) + + def test_generate_points_random_in_surface_sphere_1(self): + """Test generate points random in surface sphere.""" + center = matrix([0, 0, 0]) + radius = 1 + gen = generate_points_random_in_surface_sphere(center, radius) + points = [] + for i in range(50): + points.append(next(gen)) + self._check_points(radius, points, center) + + def test_generate_points_random_in_surface_sphere_2(self): + """Test generate points random in surface sphere.""" + center = matrix([0, 0, 0]) + radius = 55 + gen = generate_points_random_in_surface_sphere(center, radius) + points = [] + for i in range(50): + points.append(next(gen)) + self._check_points(radius, points, center) + + def test_generate_points_random_in_surface_sphere_3(self): + """Test generate points random in surface sphere.""" + center = matrix([45, -23, 67]) + radius = 1 + gen = generate_points_random_in_surface_sphere(center, radius) + points = [] + for i in range(50): + points.append(next(gen)) + self._check_points(radius, points, center) + + def test_generate_points_random_in_surface_sphere_4(self): + """Test generate points random in surface sphere.""" + center = matrix([45, -23, 67]) + radius = 43 + gen = generate_points_random_in_surface_sphere(center, radius) + points = [] + for i in range(50): + points.append(next(gen)) + self._check_points(radius, points, center) + + def test_generate_sequential_points(self): + """Test generate sequential points.""" + gen = generate_sequential_points(matrix([0, 0, 0]), random) + + point = next(gen) + for i in range(30): + next_point = next(gen) + assert distance(point, next_point) < 0.87 + point = next_point diff --git a/code/train/Python/0051246_utils.py b/code/train/Python/0051246_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4f8123734b28ad6ab1fac7597d7ba3963ace98a6 --- /dev/null +++ b/code/train/Python/0051246_utils.py @@ -0,0 +1,153 @@ +from django.conf import settings +from django.utils.translation import ugettext as _ + +from datetime import datetime, timedelta + +from .signals import willEvaluateAvailabilityForRange as rangeSignal + + +def strfdate(date): + return date.strftime(settings.TIMESLOTS_DATE_FORMAT) + +def strftime(time): + return time.strftime(settings.TIMESLOTS_TIME_FORMAT) + +def strpdate(date): + return datetime.strptime(date, settings.TIMESLOTS_DATE_FORMAT).date() + +def strptime(time): + return datetime.strptime(time, settings.TIMESLOTS_TIME_FORMAT).time() + + +WEEKDAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] + + +def __get_timeslots(date, definition): + # Return timeslots for date given definition + if date < definition.valid: + raise ValueError('out of bounds') + if definition.until and date > definition.until: + raise ValueError('out of bounds') + + from copy import copy + return copy(definition.timeslots[WEEKDAYS[date.weekday()]]) + +def __timeslots_generator(lbound, ubound, constraint): + + definitions = constraint.definitions.filter(enabled=True) + + # Select all definitions in the date rage + future_set = definitions.filter(valid__range=(lbound, ubound)) + current = definitions.filter(valid__lt=lbound).order_by('-valid')[:1] + + # Union of the current definition and all future definitions in the date + # range. The union operator | may set me up for all sorts of associativity + # problems. writing (current | future_set) throws AssertionError: Cannot + # combine queries once a slice has been taken + + # There's no risk of getting duplicate rows, so I should be able to drop the + # call to distinct('id'). only PostgreSQL supports DISTINCT ON + + # definitions = (future_set | current).distinct('id').order_by('valid') + definitions = (future_set | current).order_by('valid') + + # Raise warnings if definitions is over- or underspecified + + def timeslots(date): + final = None + for definition in definitions: + if definition.valid <= date: + final = definition + else: + break + return __get_timeslots(date, final) if final else None + + return timeslots + +def availability(lbound, ubound, constraint): + # I can load the entire queryset in one fould sweep here... + generator = __timeslots_generator(lbound, ubound, constraint) + + # Take note of holidays + holidays = constraint.holidays.filter(date__range=(lbound, ubound)) + + # Allow signal listeners to register callback function + callbacks = rangeSignal.send(__name__, lbound=lbound, ubound=ubound, constraint=constraint) + + for n in range((ubound-lbound).days): + date = lbound + timedelta(n) + # If date is a holiday, bail here + + if holidays.filter(date=date).count() > 0: + data = { + 'available' : False, + 'status' : 'holiday', + 'code' : 3, + # Replace with holiday message + 'msg' : _("holiday"), + 'timeslots' : [], + } + + else: + timeslots = generator(date) + if timeslots: + # Allow signal handlers to update timeslots + for (receiver, callback) in callbacks: + try: + callback(date, timeslots) + except Exception as e: + import logging + l = logging.getLogger(__name__) + l.warning("willEvaluateAvailabilityForRange callback threw an exception.", extra=e) + # If final is empty then the date is fully booked... + final = [strftime(k) for (k, v) in timeslots.items() if v > 0] + data = { + 'available' : True if final else False, + 'status' : 'available' if final else 'fully booked', + 'code' : 0 if final else 2, + 'msg' : _("available") if final else _("fully booked"), + 'timeslots' : final, + } + + else: + data = { + 'available' : False, + 'status' : 'unavailable', + 'code' : 1, + 'msg' : _("unavailable"), + 'timeslots' : [], + } + + yield date, data + + +def is_available(constraint, date, time): + # Not available if date is a holiday + if constraint.holidays.filter(date=date).count() > 0: + return False + + # Create a timeslots generator for date only + generator = __timeslots_generator(date, date, constraint) + timeslots = generator(date) + if not timeslots: + return False + + # I can reduce the size of timeslots to time (but my callback may throw a warning) + if time not in timeslots: + return False + timeslots = {time: timeslots[time]} + + # Allow signal listeners to register callback function + callbacks = rangeSignal.send(__name__, lbound=date, ubound=date, constraint=constraint) + for (receiver, callback) in callbacks: + try: + callback(date, timeslots, supress_warnings=True) + except Exception as e: + import logging + l = logging.getLogger(__name__) + l.warning("willEvaluateAvailabilityForRange callback threw an exception.", extra=e) + + if timeslots[time] < 1: + return False + + return True \ No newline at end of file diff --git a/code/train/Python/0051270_calendars.py b/code/train/Python/0051270_calendars.py new file mode 100644 index 0000000000000000000000000000000000000000..7bdd1e0032319806b6c7e8699633bb3daf220ab1 --- /dev/null +++ b/code/train/Python/0051270_calendars.py @@ -0,0 +1,147 @@ +from __future__ import unicode_literals + +from django import http +from django.db import models +from django.contrib.databrowse.datastructures import EasyModel +from django.contrib.databrowse.sites import DatabrowsePlugin +from django.shortcuts import render_to_response +from django.utils.html import format_html, format_html_join +from django.utils.text import capfirst +from django.utils.encoding import force_unicode +from django.views.generic import dates +from django.utils import datetime_safe + + +class DateViewMixin(object): + allow_empty = False + allow_future = True + root_url = None + model = None + field = None + + def get_context_data(self, **kwargs): + context = super(DateViewMixin, self).get_context_data(**kwargs) + context.update({ + 'root_url': self.root_url, + 'model': self.model, + 'field': self.field + }) + return context + + +class DayView(DateViewMixin, dates.DayArchiveView): + template_name = 'databrowse/calendar_day.html' + + +class MonthView(DateViewMixin, dates.MonthArchiveView): + template_name = 'databrowse/calendar_month.html' + + +class YearView(DateViewMixin, dates.YearArchiveView): + template_name = 'databrowse/calendar_year.html' + + +class IndexView(DateViewMixin, dates.ArchiveIndexView): + template_name = 'databrowse/calendar_main.html' + + +class CalendarPlugin(DatabrowsePlugin): + def __init__(self, field_names=None): + self.field_names = field_names + + def field_dict(self, model): + """ + Helper function that returns a dictionary of all DateFields or + DateTimeFields in the given model. If self.field_names is set, it takes + take that into account when building the dictionary. + """ + if self.field_names is None: + return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.DateField)]) + else: + return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.DateField) and f.name in self.field_names]) + + def model_index_html(self, request, model, site): + fields = self.field_dict(model) + if not fields: + return '' + return format_html('

View calendar by: {0}

', + format_html_join(', ', '{1}', + ((f.name, force_unicode(capfirst(f.verbose_name))) for f in fields.values()))) + + def urls(self, plugin_name, easy_instance_field): + if isinstance(easy_instance_field.field, models.DateField): + d = easy_instance_field.raw_value + return ['%s%s/%s/%s/%s/%s/' % ( + easy_instance_field.model.url(), + plugin_name, easy_instance_field.field.name, + str(d.year), + datetime_safe.new_date(d).strftime('%b').lower(), + d.day)] + + def model_view(self, request, model_databrowse, url): + self.model, self.site = model_databrowse.model, model_databrowse.site + self.fields = self.field_dict(self.model) + + # If the model has no DateFields, there's no point in going further. + if not self.fields: + raise http.Http404('The requested model has no calendars.') + + if url is None: + return self.homepage_view(request) + url_bits = url.split('/') + if url_bits[0] in self.fields: + return self.calendar_view(request, self.fields[url_bits[0]], *url_bits[1:]) + + raise http.Http404('The requested page does not exist.') + + def homepage_view(self, request): + easy_model = EasyModel(self.site, self.model) + field_list = self.fields.values() + field_list.sort(key=lambda k:k.verbose_name) + return render_to_response('databrowse/calendar_homepage.html', { + 'root_url': self.site.root_url, + 'model': easy_model, + 'field_list': field_list + }) + + def calendar_view(self, request, field, year=None, month=None, day=None): + easy_model = EasyModel(self.site, self.model) + root_url = self.site.root_url + + if day is not None: + return DayView.as_view( + year=year, month=month, day=day, + date_field=field.name, + queryset=easy_model.get_query_set(), + root_url=root_url, + model=easy_model, + field=field + )(request) + elif month is not None: + return MonthView.as_view( + year=year, month=month, + date_field=field.name, + queryset=easy_model.get_query_set(), + root_url=root_url, + model=easy_model, + field=field + )(request) + elif year is not None: + return YearView.as_view( + year=year, + date_field=field.name, + queryset=easy_model.get_query_set(), + root_url=root_url, + model=easy_model, + field=field + )(request) + else: + return IndexView.as_view( + date_field=field.name, + queryset=easy_model.get_query_set(), + root_url=root_url, + model=easy_model, + field=field + )(request) + + assert False, ('%s, %s, %s, %s' % (field, year, month, day)) diff --git a/code/train/Python/0051563_graphs.py b/code/train/Python/0051563_graphs.py new file mode 100644 index 0000000000000000000000000000000000000000..9d65ee7b420fb81863897c9e1cbdbc0ac76b1e15 --- /dev/null +++ b/code/train/Python/0051563_graphs.py @@ -0,0 +1,167 @@ +# ----------------------------------------------------------------------------- +# Name: graphs.py (part of PyGMI) +# +# Author: Patrick Cole +# E-Mail: pcole@geoscience.org.za +# +# Copyright: (c) 2019 Council for Geoscience +# Licence: GPL-3.0 +# +# This file is part of PyGMI +# +# PyGMI is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PyGMI is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# ----------------------------------------------------------------------------- +"""Plot Vector Data using Matplotlib.""" + +import numpy as np +from PyQt5 import QtWidgets, QtCore +from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg +from matplotlib.figure import Figure +from matplotlib.backends.backend_qt5 import NavigationToolbar2QT +import segyio + + +class GraphWindow(QtWidgets.QDialog): + """Graph Window - Main QT Dialog class for graphs.""" + + def __init__(self, parent=None): + super().__init__(parent) + self.parent = parent + + self.setAttribute(QtCore.Qt.WA_DeleteOnClose) + self.setWindowTitle('Graph Window') + + vbl = QtWidgets.QVBoxLayout(self) + self.mmc = MyMplCanvas(self) + mpl_toolbar = NavigationToolbar2QT(self.mmc, self.parent) + + vbl.addWidget(self.mmc) + vbl.addWidget(mpl_toolbar) + + self.setFocus() + + def change_band(self): + """ + Combo box to choose band. + + Returns + ------- + None. + + """ + + +class MyMplCanvas(FigureCanvasQTAgg): + """ + MPL Canvas class. + + This routine will also allow the picking and movement of nodes of data. + """ + + def __init__(self, parent=None): + fig = Figure() + self.axes = fig.add_subplot(111) + self.line = None + self.ind = None + self.background = None + + super().__init__(fig) + + def update_segy(self, data): + """ + Update the plot from point data. + + Parameters + ---------- + data : segyio object + SEG-Y data + + Returns + ------- + None. + + """ + self.figure.clear() + + ax1 = self.figure.add_subplot(111, label='SEG-Y') + + ax1.set_title('SEG-Y') + self.axes = ax1 + + samplecnt = data.header[0][segyio.TraceField.TRACE_SAMPLE_COUNT] + sampleint = data.header[0][segyio.TraceField.TRACE_SAMPLE_INTERVAL]/1000. + rectime = samplecnt*sampleint + + y = np.linspace(0, rectime, samplecnt) + start = 0 + finish = samplecnt + offset = 0 + gdist = 1 # in meters + tracemult = 2. + + ax1.invert_yaxis() + + tmax = -1 + for trace in data.trace: + tmp = np.max(np.abs([trace.max(), trace.min()])) + if tmax < tmp: + tmax = tmp + tracemult = 1/tmax + + for trace in data.trace: + x = tracemult*trace+offset + ax1.plot(x[start:finish], y[start:finish], 'k-') + + ax1.fill_betweenx(y, offset, x, where=(x > offset), color='k') + + ax1.set_xlabel('Trace Number') + ax1.set_ylabel('Time (ms)') + + offset += gdist + + self.figure.tight_layout() + self.figure.canvas.draw() + + +class PlotSEGY(GraphWindow): + """Plot SEG-Y Class.""" + + def __init__(self, parent=None): + super().__init__(parent) + self.indata = {} + self.parent = parent + + def change_band(self): + """ + Combo to choose band. + + Returns + ------- + None. + + """ + data = self.indata['ESEIS'] + self.mmc.update_segy(data) + + def run(self): + """ + Run. + + Returns + ------- + None. + + """ + self.show() + self.change_band() diff --git a/code/train/Python/0051716_test_socketserver.py b/code/train/Python/0051716_test_socketserver.py new file mode 100644 index 0000000000000000000000000000000000000000..1245ba5fbf27da9a6216442d58ff7d17aaf6f4b0 --- /dev/null +++ b/code/train/Python/0051716_test_socketserver.py @@ -0,0 +1,180 @@ +# Test suite for SocketServer.py + +from test import test_support +from test.test_support import verbose, verify, TESTFN, TestSkipped +test_support.requires('network') + +from SocketServer import * +import socket +import select +import time +import threading +import os + +NREQ = 3 +DELAY = 0.5 + +class MyMixinHandler: + def handle(self): + time.sleep(DELAY) + line = self.rfile.readline() + time.sleep(DELAY) + self.wfile.write(line) + +class MyStreamHandler(MyMixinHandler, StreamRequestHandler): + pass + +class MyDatagramHandler(MyMixinHandler, DatagramRequestHandler): + pass + +class MyMixinServer: + def serve_a_few(self): + for i in range(NREQ): + self.handle_request() + def handle_error(self, request, client_address): + self.close_request(request) + self.server_close() + raise + +teststring = "hello world\n" + +def receive(sock, n, timeout=20): + r, w, x = select.select([sock], [], [], timeout) + if sock in r: + return sock.recv(n) + else: + raise RuntimeError, "timed out on %r" % (sock,) + +def testdgram(proto, addr): + s = socket.socket(proto, socket.SOCK_DGRAM) + s.sendto(teststring, addr) + buf = data = receive(s, 100) + while data and '\n' not in buf: + data = receive(s, 100) + buf += data + verify(buf == teststring) + s.close() + +def teststream(proto, addr): + s = socket.socket(proto, socket.SOCK_STREAM) + s.connect(addr) + s.sendall(teststring) + buf = data = receive(s, 100) + while data and '\n' not in buf: + data = receive(s, 100) + buf += data + verify(buf == teststring) + s.close() + +class ServerThread(threading.Thread): + def __init__(self, addr, svrcls, hdlrcls): + threading.Thread.__init__(self) + self.__addr = addr + self.__svrcls = svrcls + self.__hdlrcls = hdlrcls + def run(self): + class svrcls(MyMixinServer, self.__svrcls): + pass + if verbose: print "thread: creating server" + svr = svrcls(self.__addr, self.__hdlrcls) + if verbose: print "thread: serving three times" + svr.serve_a_few() + if verbose: print "thread: done" + +seed = 0 +def pickport(): + global seed + seed += 1 + return 10000 + (os.getpid() % 1000)*10 + seed + +host = "localhost" +testfiles = [] +def pickaddr(proto): + if proto == socket.AF_INET: + return (host, pickport()) + else: + fn = TESTFN + str(pickport()) + if os.name == 'os2': + # AF_UNIX socket names on OS/2 require a specific prefix + # which can't include a drive letter and must also use + # backslashes as directory separators + if fn[1] == ':': + fn = fn[2:] + if fn[0] in (os.sep, os.altsep): + fn = fn[1:] + fn = os.path.join('\socket', fn) + if os.sep == '/': + fn = fn.replace(os.sep, os.altsep) + else: + fn = fn.replace(os.altsep, os.sep) + testfiles.append(fn) + return fn + +def cleanup(): + for fn in testfiles: + try: + os.remove(fn) + except os.error: + pass + testfiles[:] = [] + +def testloop(proto, servers, hdlrcls, testfunc): + for svrcls in servers: + addr = pickaddr(proto) + if verbose: + print "ADDR =", addr + print "CLASS =", svrcls + t = ServerThread(addr, svrcls, hdlrcls) + if verbose: print "server created" + t.start() + if verbose: print "server running" + for i in range(NREQ): + time.sleep(DELAY) + if verbose: print "test client", i + testfunc(proto, addr) + if verbose: print "waiting for server" + t.join() + if verbose: print "done" + +tcpservers = [TCPServer, ThreadingTCPServer] +if hasattr(os, 'fork') and os.name not in ('os2',): + tcpservers.append(ForkingTCPServer) +udpservers = [UDPServer, ThreadingUDPServer] +if hasattr(os, 'fork') and os.name not in ('os2',): + udpservers.append(ForkingUDPServer) + +if not hasattr(socket, 'AF_UNIX'): + streamservers = [] + dgramservers = [] +else: + class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): pass + streamservers = [UnixStreamServer, ThreadingUnixStreamServer] + if hasattr(os, 'fork') and os.name not in ('os2',): + streamservers.append(ForkingUnixStreamServer) + class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): pass + dgramservers = [UnixDatagramServer, ThreadingUnixDatagramServer] + if hasattr(os, 'fork') and os.name not in ('os2',): + dgramservers.append(ForkingUnixDatagramServer) + +def testall(): + testloop(socket.AF_INET, tcpservers, MyStreamHandler, teststream) + testloop(socket.AF_INET, udpservers, MyDatagramHandler, testdgram) + if hasattr(socket, 'AF_UNIX'): + testloop(socket.AF_UNIX, streamservers, MyStreamHandler, teststream) + # Alas, on Linux (at least) recvfrom() doesn't return a meaningful + # client address so this cannot work: + ##testloop(socket.AF_UNIX, dgramservers, MyDatagramHandler, testdgram) + +def test_main(): + import imp + if imp.lock_held(): + # If the import lock is held, the threads will hang. + raise TestSkipped("can't run when import lock is held") + + try: + testall() + finally: + cleanup() + +if __name__ == "__main__": + test_main() diff --git a/code/train/Python/0051801_train_cartpole_pg.py b/code/train/Python/0051801_train_cartpole_pg.py new file mode 100644 index 0000000000000000000000000000000000000000..cc1800a7677328b394069de770c6f4473345aca4 --- /dev/null +++ b/code/train/Python/0051801_train_cartpole_pg.py @@ -0,0 +1,258 @@ +import tensorflow as tf +import numpy as np +import random +import gym +import math +import matplotlib.pyplot as plt + +""" +Vanilla Policy Gradient (PG) + +- Sources of inspiration: + - https://github.com/kvfrans/openai-cartpole/blob/master/cartpole-policygradient.py + - http://kvfrans.com/simple-algoritms-for-solving-cartpole/ + - https://github.com/awjuliani/DeepRL-Agents/blob/master/Vanilla-Policy.ipynb + - https://gist.github.com/greydanus/7cef68683ec955720ddde6b3edf8820e + - https://gist.github.com/cgnicholls/0127c885dbff07fde8dc1d7bfe62ac1a + - https://gist.github.com/mohakbhardwaj/1cebbf58d4c0627c9335d9b7eb55b803 + - https://theneuralperspective.com/2016/11/26/1656/ + - https://theneuralperspective.com/2016/11/25/reinforcement-learning-rl-policy-gradients-i/ + - https://gist.github.com/cgnicholls/0127c885dbff07fde8dc1d7bfe62ac1a + - https://github.com/dennybritz/reinforcement-learning/tree/master/PolicyGradient + - https://github.com/dennybritz/reinforcement-learning/blob/master/PolicyGradient/CliffWalk%20REINFORCE%20with%20Baseline%20Solution.ipynb + +- Paper: http://www-anw.cs.umass.edu/~barto/courses/cs687/williams92simple.pdf +- Pseudocode (vanilla PG): +1. Initialize policy (e.g. NNs) parameter $\theta$ and baseline $b$ +2. For iteration=1,2,... do + 2.1 Collect a set of trajectories by executing the current policy obtaining + $\mathbf{s}_{0:H},\mathbf{a}_{0:H},r_{0:H}$ + 2.2 At each timestep in each trajectory, compute + 2.2.1 the return $R_t = \sum_{t'=t}^{T-1} \gamma^{t'-t}r_{t'}$ and + 2.2.2 the advantage estimate $\hat{A_t} = R_t - b(s_t)$. + 2.3 Re-fit the baseline (recomputing the value function) by minimizing + $|| b(s_t) - R_t||^2$, summed over all trajectories and timesteps. + + 2.3 Re-fit the baseline (recomputing the value function) by minimizing + $|| b(s_t) - R_t||^2$, summed over all trajectories and timesteps. + In other words, estimate optimal baseline: + + $b=\frac{\left\langle \left( \sum\nolimits_{h=0}^{H} \mathbf{\nabla}_{\theta_{k}}\log\pi_{\mathbf{\theta}} + \left( \mathbf{a}_{h}\left\vert \mathbf{s}_{h}\right. \right) \right) ^{2}\sum\nolimits_{l=0}^{H} + \gamma r_{l}\right\rangle }{\left\langle \left( + \sum\nolimits_{h=0}^{H}\mathbf{\nabla}_{\theta_{k}}\log\pi_{\mathbf{\theta} + }\left( \mathbf{a}_{h}\left\vert \mathbf{x}_{h}\right. \right) \right) + ^{2}\right\rangle }$ + + 2.4 Update the policy, using a policy gradient estimate $\hat{g}$, + which is a sum of terms + $\nabla_\theta log\pi(a_t | s_t,\theta)\hat(A_t)$ +3. **end for** +""" + +def softmax(x): + """ + Softmax function implementation + """ + e_x = np.exp(x - np.max(x)) + out = e_x / e_x.sum() + return out + +def policy_gradient(): + """ + Implementation of an optimizer that allows to incrementally update + the policy. + + Parameters + ---------- + None + + Returns + ------- + probabilities + tensor containing the probabilities + state + tensor containing the state of the environment + actions + one-hot encoded vector containing a "one" at the action + we want to increase probability of. + advantages + tensor with the advantage from the environment + optimizer + Adam optimizer + """ + with tf.variable_scope("policy"): + params = tf.get_variable("policy_parameters",[4,2]) + state = tf.placeholder("float",[None,4]) + actions = tf.placeholder("float",[None,2]) + advantages = tf.placeholder("float",[None,1]) + linear = tf.matmul(state,params) + probabilities = tf.nn.softmax(linear) + good_probabilities = tf.reduce_sum(tf.multiply(probabilities, actions),reduction_indices=[1]) + eligibility = tf.log(good_probabilities) * advantages + # maximize the log probability + loss = -tf.reduce_sum(eligibility) + optimizer = tf.train.AdamOptimizer(0.01).minimize(loss) + return probabilities, state, actions, advantages, optimizer + +def value_gradient(): + """ + Define the value network (the critic) which returns a value + for each state. Critic is implemented as a single hidden layer + neural network (with 10 hidden neurons). + + Returns + ------- + calculated + tensor containing the probabilities + state + tensor containing the state of the environment + newvals + tensor containing updated value function outputs (for optimization) + optimizer + Adam optimizer + loss + loss tensor. Debug purposes. + """ + with tf.variable_scope("value"): + state = tf.placeholder("float",[None,4]) + newvals = tf.placeholder("float",[None,1]) + w1 = tf.get_variable("w1",[4,10]) + b1 = tf.get_variable("b1",[10]) + h1 = tf.nn.relu(tf.matmul(state,w1) + b1) + w2 = tf.get_variable("w2",[10,1]) + b2 = tf.get_variable("b2",[1]) + calculated = tf.matmul(h1,w2) + b2 + diffs = calculated - newvals + loss = tf.nn.l2_loss(diffs) + optimizer = tf.train.AdamOptimizer(0.1).minimize(loss) + return calculated, state, newvals, optimizer, loss + +def run_episode(env, policy_grad, value_grad, sess, render = False): + """ + This function implements the main part of PG + + Params + ------- + env + Environment where to use PG + policy_grad + Policy gradient function that a) calculates the policy and b) optimizes it + value_grad + Value network (the critic) + sess + TF session object + + Returns + ------- + totalreward + the total reward of the episode (200 steps) + + """ + # initialize variables + pl_calculated, pl_state, pl_actions, pl_advantages, pl_optimizer = policy_grad + vl_calculated, vl_state, vl_newvals, vl_optimizer, vl_loss = value_grad + observation = env.reset() + totalreward = 0 + states = [] + actions = [] + advantages = [] + transitions = [] + update_vals = [] + + # 2.1 Collect a set of trajectories by executing the current policy obtaining + # $\mathbf{s}_{0:H},\mathbf{a}_{0:H},r_{0:H}$ + for _ in range(200): + if render: + env.render() + # calculate policy + obs_vector = np.expand_dims(observation, axis=0) + probs = sess.run(pl_calculated,feed_dict={pl_state: obs_vector}) + action = 0 if random.uniform(0,1) < probs[0][0] else 1 + # record the transition + states.append(observation) + actionblank = np.zeros(2) # hardcode to specific environment + actionblank[action] = 1 + actions.append(actionblank) + # take the action in the environment + old_observation = observation + observation, reward, done, info = env.step(action) + transitions.append((old_observation, action, reward)) + totalreward += reward + + if done: + break + # 2.2 At each timestep in each trajectory, compute + for index, trans in enumerate(transitions): + # invidivual transition + obs, action, reward = trans + + # calculate discounted monte-carlo return + future_reward = 0 + future_transitions = len(transitions) - index + decrease = 1 + for index2 in range(future_transitions): + # 2.2.1 the return $R_t = \sum_{t'=t}^{T-1} \gamma^{t'-t}r_{t'}$ + future_reward += transitions[(index2) + index][2] * decrease + # here "decrease" represents the gamma + decrease = decrease * 0.97 + obs_vector = np.expand_dims(obs, axis=0) + currentval = sess.run(vl_calculated,feed_dict={vl_state: obs_vector})[0][0] + # 2.2.2 the advantage estimate $\hat{A_t} = R_t - b(s_t)$. + # advantage: how much better was this action than normal + advantages.append(future_reward - currentval) + + # add future_reward to update the value function towards new return + update_vals.append(future_reward) + + # 2.3 Re-fit the baseline (recomputing the value function) by minimizing + # $|| b(s_t) - R_t||^2$, summed over all trajectories and timesteps. + # In other words, estimate optimal baseline: + # + # $b=\frac{\left\langle \left( \sum\nolimits_{h=0}^{H} \mathbf{\nabla}_{\theta_{k}}\log\pi_{\mathbf{\theta}} + # \left( \mathbf{a}_{h}\left\vert \mathbf{s}_{h}\right. \right) \right) ^{2}\sum\nolimits_{l=0}^{H} + # \gamma r_{l}\right\rangle }{\left\langle \left( + # \sum\nolimits_{h=0}^{H}\mathbf{\nabla}_{\theta_{k}}\log\pi_{\mathbf{\theta} + # }\left( \mathbf{a}_{h}\left\vert \mathbf{x}_{h}\right. \right) \right) + # ^{2}\right\rangle }$ + # update value function + update_vals_vector = np.expand_dims(update_vals, axis=1) + sess.run(vl_optimizer, feed_dict={vl_state: states, vl_newvals: update_vals_vector}) + # real_vl_loss = sess.run(vl_loss, feed_dict={vl_state: states, vl_newvals: update_vals_vector}) + + # 2.4 Update the policy, using a policy gradient estimate $\hat{g}$, + # which is a sum of terms $\nabla_\theta log\pi(a_t | s_t,\theta)\hat(A_t)$. + # In other words: + # + # $g_{k}=\left\langle \left( \sum\nolimits_{h=0}^{H}\mathbf{\nabla + # }_{\theta_{k}}\log\pi_{\mathbf{\theta}}\left( \mathbf{a}_{h}\left\vert + # \mathbf{s}_{h}\right. \right) \right) \left( \sum\nolimits_{l=0}^{H} + # \gamma r_{l}-b\right) \right\rangle$ + advantages_vector = np.expand_dims(advantages, axis=1) + sess.run(pl_optimizer, feed_dict={pl_state: states, pl_advantages: advantages_vector, pl_actions: actions}) + + return totalreward + + +env = gym.make('CartPole-v0') + # 1. Initialize policy (e.g. NNs) parameter $\theta$ and baseline $b$ +policy_grad = policy_gradient() +value_grad = value_gradient() +sess = tf.InteractiveSession() +sess.run(tf.initialize_all_variables()) + # 2. For iteration=1,2,... do +for i in range(1000): + reward = run_episode(env, policy_grad, value_grad, sess) + print("episode ",i, "reward: ",reward) + # if reward == 200: + # print("reward 200") + # print(i) + # break + # 3. **end for** + +# Validate the training in 1000 epidodes +t = 0 +for _ in range(1000): + reward = run_episode(env, policy_grad, value_grad, sess, render=True) + t += reward +print(t / 1000) diff --git a/code/train/Python/0052182_695._Max_Area_of_Island.py b/code/train/Python/0052182_695._Max_Area_of_Island.py new file mode 100644 index 0000000000000000000000000000000000000000..d7aa303a0391ca9324aa4c54064ff063d7290587 --- /dev/null +++ b/code/train/Python/0052182_695._Max_Area_of_Island.py @@ -0,0 +1,55 @@ +from collections import deque +class Solution(object): + def maxAreaOfIsland(self, grid): + """ + :type grid: List[List[int]] + :rtype: int + """ + R = len(grid) + if not R: + return 0 + C = len(grid[0]) + q = deque() + + def dfs(r, c): + q.append( (r, c) ) + grid[r][c] = 2 + size = 0 + while q: + r, c = q.popleft() + size += 1 + for nr, nc in ( (r-1, c), (r+1, c), (r, c-1), (r, c+1) ): + if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 1: + grid[nr][nc] = 2 + q.append( (nr, nc) ) + + return size + + + maxsize = 0 + for r in xrange(R): + for c in xrange(C): + if grid[r][c] == 1: + maxsize = max(maxsize, dfs(r, c)) + + return maxsize + +print Solution().maxAreaOfIsland( + [[1,1,0,0,0], + [1,1,0,0,0], + [0,0,0,1,1], + [0,0,0,1,1]]) + + +print Solution().maxAreaOfIsland( + [[0,0,1,0,0,0,0,1,0,0,0,0,0], + [0,0,0,0,0,0,0,1,1,1,0,0,0], + [0,1,1,0,1,0,0,0,0,0,0,0,0], + [0,1,0,0,1,1,0,0,1,0,1,0,0], + [0,1,0,0,1,1,0,0,1,1,1,0,0], + [0,0,0,0,0,0,0,0,0,0,1,0,0], + [0,0,0,0,0,0,0,1,1,1,0,0,0], + [0,0,0,0,0,0,0,1,1,0,0,0,0]]) + +print Solution().maxAreaOfIsland( + [[0,0,1,0,0,0,0,1,1,1,0,0,0]]) diff --git a/code/train/Python/0052527_530.py b/code/train/Python/0052527_530.py new file mode 100644 index 0000000000000000000000000000000000000000..6e0127fde51d28e7f734d6cf43ac998ea12cd60e --- /dev/null +++ b/code/train/Python/0052527_530.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python +# coding=utf-8 + +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution(object): + def getMinimumDifference(self, root): + """ + :type root: TreeNode + :rtype: int + """ + l=[] + self.getAllNums(root,l) + l.sort() + Min = 2140000 + for i in range(1,len(l)): + Min = min(Min,l[i]-l[i-1]) + + return Min + + def getAllNums(self, root, l): + if root == None: + return + l.append(root.val) + self.getAllNums(root.left,l) + self.getAllNums(root.right,l) + return + diff --git a/code/train/Python/0052648_plotAlphaSensitivity.py b/code/train/Python/0052648_plotAlphaSensitivity.py new file mode 100644 index 0000000000000000000000000000000000000000..cd0d07e5c8515711fcaff1c4e417a00a1aa88bc0 --- /dev/null +++ b/code/train/Python/0052648_plotAlphaSensitivity.py @@ -0,0 +1,78 @@ +import matplotlib as mpl +mpl.use('Agg') +import plotter +import glob +import scipy.stats as sps +from matplotlib import pylab as plt + + +def alphaSensitivity(db=None, outdir="./"): + """ Plot results with different values of alpha """ + + pr = plotter.Plotter(db=db) + cursor = pr.cursor[0] + refAlpha = 0 + refExpid = None + + # Get expid and alpha values from "experiment" table + expRaw = cursor.execute("SELECT id, args FROM experiment ") + exp = {} + for expid, args in expRaw: + alpha = [float(x.rpartition("=")[2]) for x in args.split(",") if x.startswith(" alpha=")] + exp[expid] = alpha[0] + if alpha[0]>refAlpha: + refExpid = expid + refAlpha= alpha[0] + + asHegemonyRef = dict(cursor.execute("SELECT asn, hege FROM hegemony WHERE ts=0 AND scope=0 AND expid=?",(refExpid,))) + # Remove AS with a score == 0.0 + toremove = [asn for asn, score in asHegemonyRef.iteritems() if score==0.0] + if not toremove is None: + for asn in toremove: + del asHegemonyRef[asn] + minVal = min(asHegemonyRef.values()) + + y = [] + x = [] + for expid, alpha in exp.iteritems(): + asHegemony = dict(cursor.execute("SELECT asn, hege FROM hegemony WHERE ts=0 AND scope=0 AND expid=?", (expid,))) + if not len(asHegemony): + continue + + # Remove AS with a score == 0.0 + toremove = [asn for asn, score in asHegemony.iteritems() if score==0.0] + if not toremove is None: + for asn in toremove: + del asHegemony[asn] + + # Set the same number of ASN for both distributions + missingAS = set(asHegemonyRef.keys()).difference(asHegemony.keys()) + if not missingAS is None: + for asn in missingAS: + asHegemony[asn] = minVal + + # Compute the KL-divergence + dist = [asHegemony[asn] for asn in asHegemonyRef.keys()] + kldiv = sps.entropy(dist, asHegemonyRef.values()) + y.append(kldiv) + x.append(alpha) + + + sx, sy = zip(*sorted(zip(x,y))) + plt.figure(figsize=(4,3)) + plt.plot(sx, sy, "+-") + plt.xlabel("$\\alpha$") + plt.ylabel("KL divergence") + plt.tight_layout() + plt.savefig("results/alphaSensitivity/alphaSensitivity.pdf") + + + +if __name__ == "__main__": + # parser = argparse.ArgumentParser() + # parser.add_argument("-i", "--input", help="Folder containing the .sql file produced by ashash", type=str, required=True) + # parser.add_argument("-t", "--title", help="Title for the figure", type=str, default=None) + # args = parser.parse_args() + + db = glob.glob("results/alphaSensitivity/*.sql") + alphaSensitivity(db=db) diff --git a/code/train/Python/0052999_postfix2bdt.py b/code/train/Python/0052999_postfix2bdt.py new file mode 100644 index 0000000000000000000000000000000000000000..beb013ac9393a0f74ca860afd06f90c8a3d1136a --- /dev/null +++ b/code/train/Python/0052999_postfix2bdt.py @@ -0,0 +1,89 @@ +# Title : postfix to binary tree +# Developed by : Yogesh Mahajan (y.mahajan456@gmail.com) (14D070022 @ IITB EE) +# OV Shashank (shashank[at]ee.iitb.ac.in) (14D070021 @ IITB EE) +# Avineil Jain (avineil96[at]ee.iitb.ac.in)(14D170002 @ IITB EE) +# Description : Convert postfix expression to binary expression tree +#-------------------------------------------------------------------------------------------------- +from stack import Stack + +class Op_Node: + childs_count = 0 + childs = [] #just names of child nodes + level = None + + def __init__(self): + self.name = None + + def __init__(self,name,*vars): + self.name = name + if(len(vars) > 0): + self.childs = vars[0] + self.childs_count = len(vars[0]) + + def __str__(self): + return str([self.name,self.childs,self.level]) + + def node_obj2list(self): + return [self.name,self.childs,self.level] +#--------------------------------------------------------------------------------------------------- +# Operand count of operators not having 2 operands +ns_operand_count = {} # ns for non standard -> not having 2 operands +ns_operand_count['!'] = 1 + +op_list = ['@','%','*','/','+','-','!','&','^','|'] + +ns_op = list(ns_operand_count.keys()) +#-------------------------------------------------------------------------------------------------- +def postfix2bdt(postfix,prefix = 'n'): + tmp_stack = Stack() + node_list = {} + node_names = [] + for token in postfix: + if(token not in op_list): + if(token not in node_names): + new_var = Op_Node(token) + new_var.level = 0 + node_names.append(token) + node_list[token] = new_var + + tmp_stack.push(token) + + else: + operands_list = [] + if(token in ns_op): + for i in range(ns_operand_count[token]): + new_operand_node_name = tmp_stack.pop() + if(new_operand_node_name != None): + operands_list.append(new_operand_node_name) + else: + print("\nNumber of operands mismatch for operator : ", token,"\n") + return None + else: + for i in range(2): + new_operand = tmp_stack.pop() + if(new_operand != None): + operands_list.append(new_operand) + else: + print("\nNumber of operands mismatch for operator : ", token,"\n") + return None + + level_count = 0 + for child in operands_list: + if(level_count < node_list[child].level): + level_count = node_list[child].level + + node_name = prefix+str(len(node_names)) + node_names.append(node_name) + + new_op_node = Op_Node(token,operands_list) + new_op_node.level = level_count+1 + + node_list[node_name] = new_op_node + tmp_stack.push(node_name) + + bt = {node:node_list[node].node_obj2list() for node in node_names} + + parent_node = tmp_stack.pop() + return [bt,parent_node] +#-------------------------------------------------------------------------------------------------- + diff --git a/code/train/Python/0053127_Longest_consecutive_sequence.py b/code/train/Python/0053127_Longest_consecutive_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3bbe6cc322bb2b51ba8d146e44659e3bcd7c88 --- /dev/null +++ b/code/train/Python/0053127_Longest_consecutive_sequence.py @@ -0,0 +1,50 @@ +""" + +Given an unsorted array of integers, find the length of the longest consecutive elements sequence. + +For example, +Given [100, 4, 200, 1, 3, 2], +The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. + +Your algorithm should run in O(n) complexity. + +""" + +class Solution: + + # @param num, a list of integer + # @return an integer + def longestConsecutive(self, num): + + # base case + if len(num) == 0: + return 0 + + # for O(1) element searching + s = set(num) + + # means single element itself is a sequence + max_count = 1 + + # for each number move left and right to check + # if there is a sequence + for n in num: + left = n - 1 + right = n + 1 + count = 1 + + while left in s: + s.remove(left) + left = left - 1 + count = count + 1 + + while right in s: + s.remove(right) + right = right + 1 + count = count + 1 + + max_count = max(max_count, count) + return max_count + +s = Solution() +print s.longestConsecutive([100, 4, 200, 1, 3, 2]) \ No newline at end of file diff --git a/code/train/Python/0053169_utils.py b/code/train/Python/0053169_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ddb95e49d76f4f70950ac46390d2eab3bd217e47 --- /dev/null +++ b/code/train/Python/0053169_utils.py @@ -0,0 +1,168 @@ +from __future__ import absolute_import +import socket +import struct + +from .consts import * +import six + + +def uint8(n): + return struct.pack("B", n) + + +def uint64(n): + return struct.pack("!Q", n) + + +class Error(Exception): + def __init__(self, code): + self.code = code + + def __str__(self): + return strerror(self.code) + + +def pack(cmd, *args): + msg = [] + for a in args: + if isinstance(a, six.integer_types): + msg.append(struct.pack("!I", a)) + elif isinstance(a, bytes): + msg.append(a) + else: + raise TypeError(str(type(a))+str(a)) + header = struct.pack("!II", cmd, sum(len(i) for i in msg)) + return header + b''.join(msg) + + +def unpack(fmt, buf): + if not fmt.startswith("!"): + fmt = "!" + fmt + return struct.unpack(fmt, buf[:struct.calcsize(fmt)]) + + +class FileInfo: + def __init__(self, inode, name, ftype, mode, uid, gid, + atime, mtime, ctime, nlink, length): + self.inode = inode + self.name = name + self.ftype = self._get_ftype(ftype) + if ftype == TYPE_DIRECTORY: + mode |= S_IFDIR + elif ftype == TYPE_SYMLINK: + mode |= S_IFLNK + elif ftype == TYPE_FILE: + mode |= S_IFREG + self.mode = mode + self.uid = uid + self.gid = gid + self.atime = atime + self.mtime = mtime + self.ctime = ctime + self.nlink = nlink + self.length = length + self.blocks = (length + 511) / 512 + + def __repr__(self): + return ("FileInfo(%s, inode=%d, type=%s, length=%d)" % + (self.name, self.inode, self.ftype, self.length)) + + def is_symlink(self): + return self.ftype == TYPE_SYMLINK + + def _get_ftype(self, ftype): + ftype_str_map = {1: TYPE_FILE, 2: TYPE_DIRECTORY, 3: TYPE_SYMLINK, + 4: TYPE_FIFO, 5: TYPE_BLOCKDEV, 6: TYPE_CHARDEV, + 7: TYPE_SOCKET, 8: TYPE_TRASH, 9: TYPE_SUSTAINED} + if ftype in ftype_str_map: + return ftype_str_map[ftype] + return '?' + + +def attrToFileInfo(inode, attrs, name='', version=(0, 0, 0)): + if len(attrs) != 35: + raise Exception('bad length') + if version < (1, 7, 32): + return FileInfo(inode, name, *struct.unpack("!BHIIIIIIQ", attrs)) + else: + return _unpack_to_file_info(inode, attrs, name) + + +def _unpack_to_file_info(inode, attrs, name): + tup = struct.unpack("!BHIIIIIIQ", attrs) + type_mode = tup[1] + ftype = (type_mode & 0xf000) >> 12 + mode = type_mode & 0x0fff + return FileInfo(inode, name, ftype, mode, *(tup[2:])) + + +def read_chunk(host, port, chunkid, version, size, offset=0): + if offset + size > CHUNKSIZE: + raise ValueError("size too large %s > %s" % + (size, CHUNKSIZE-offset)) + + conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + conn.settimeout(10) + conn.connect((host, port)) + + msg = pack(CLTOCS_READ, uint64(chunkid), version, offset, size) + n = conn.send(msg) + while n < len(msg): + if not n: + raise IOError("write failed") + msg = msg[n:] + n = conn.send(msg) + + def recv(n): + d = conn.recv(n) + while len(d) < n: + nd = conn.recv(n-len(d)) + if not nd: + raise IOError("not enough data") + d += nd + return d + + while size > 0: + cmd, l = unpack("II", recv(8)) + + if cmd == CSTOCL_READ_STATUS: + if l != 9: + raise Exception("readblock: READ_STATUS incorrect message size") + cid, code = unpack("QB", recv(l)) + if cid != chunkid: + raise Exception("readblock; READ_STATUS incorrect chunkid") + conn.close() + return + + elif cmd == CSTOCL_READ_DATA: + if l < 20 : + raise Exception("readblock; READ_DATA incorrect message size") + cid, bid, boff, bsize, crc = unpack("QHHII", recv(20)) + if cid != chunkid: + raise Exception("readblock; READ_STATUS incorrect chunkid") + if l != 20 + bsize: + raise Exception("readblock; READ_DATA incorrect message size ") + if bsize == 0 : # FIXME + raise Exception("readblock; empty block") + if bid != offset >> 16: + raise Exception("readblock; READ_DATA incorrect block number") + if boff != offset & 0xFFFF: + raise Exception("readblock; READ_DATA incorrect block offset") + breq = 65536 - boff + if size < breq: + breq = size + if bsize != breq: + raise Exception("readblock; READ_DATA incorrect block size") + + while breq > 0: + data = conn.recv(breq) + if not data: + raise IOError("unexpected ending: need %d" % breq) + yield data + breq -= len(data) + + offset += bsize + size -= bsize + else: + raise Exception("readblock; unknown message: %s" % cmd) + conn.close() diff --git a/code/train/Python/0053206_teststep.py b/code/train/Python/0053206_teststep.py new file mode 100644 index 0000000000000000000000000000000000000000..cb3d62def162d1c784ba9970c7aa69e6f1184259 --- /dev/null +++ b/code/train/Python/0053206_teststep.py @@ -0,0 +1,183 @@ +# +# Copyright (C) 2015 BMW Car IT GmbH +# +# 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. +# + +import datetime +import os +import signal +from threading import Thread +import time +from subprocess import Popen, PIPE + +import psutil + +from pyrate.exception import ParseException +from pyrate.model.common import needs_token +from pyrate.output.terminal import STATUS_RUN, STATUS_OK, STATUS_FAILED +from pyrate.util import duration, resolveVariables +from pyrate.validator.exitcode import ExitCodeValidator +from pyrate.validator.stream import StreamValidator +from pyrate.model.env import parse_env + + +class TestStep: + KEY = 'teststep' + KEY_NAME = 'name' + KEY_MESSAGE = 'message' + KEY_COMMAND = 'command' + KEY_EXIT = 'exit' + KEY_STDOUT = 'stdout' + KEY_STDERR = 'stderr' + KEY_FATAL = 'fatal' + KEY_TIMEOUT = 'timeout' + + def __init__(self, yaml_tree): + # default values + self.name = None + self.message = None + self.command = None + self.fatal = False + self.timeout = 0 + self.validators = [] + + self.failed = False + self.abort_timeout = False + self.executed = False + self.arguments = {} + + for key, value in yaml_tree.items(): + if key == self.KEY_NAME: + self.name = value + elif key == self.KEY_MESSAGE: + self.message = value + elif key == self.KEY_COMMAND: + self.command = value + elif key == self.KEY_EXIT: + self.validators.append(ExitCodeValidator(value)) + elif key == self.KEY_STDOUT: + self.validators.append(StreamValidator(value, 'stdout')) + elif key == self.KEY_STDERR: + self.validators.append(StreamValidator(value, 'stderr')) + elif key == self.KEY_FATAL: + if type(value) is not bool: + raise ParseException("%s '%s': error parsing %s (%s) : " + "must be a bool" % + (self.KEY, + self.name, + self.KEY_FATAL, + value)) + self.fatal = value + elif key == self.KEY_TIMEOUT: + if type(value) is not int: + raise ParseException("%s '%s': error parsing %s (%s) : " + "must be an integer" % + (self.KEY, self.name, + self.KEY_TIMEOUT, value)) + self.timeout = yaml_tree[self.KEY_TIMEOUT] + else: + raise ParseException("%s (%s): Unknown token '%s'" % ( + self.KEY, self.name, key)) + + # validate mandatory fields + needs_token(self.name, self.KEY, self.KEY_NAME, self.name) + needs_token(self.command, self.KEY, self.KEY_COMMAND, self.name) + + def parse_args(self, yaml_tree): + self.arguments = parse_env(yaml_tree) + + def process_timeout(self, process): + try: + start = datetime.datetime.now() + + while duration(start) < self.timeout: + # when abort is signaled there is no need to kill + # anything anymore + if self.abort_timeout: + return + + time.sleep(0.001) + + parent = psutil.Process(process.pid) + for child in parent.children(recursive=True): + os.kill(child.pid, signal.SIGKILL) + os.kill(parent.pid, signal.SIGKILL) + except: + pass + + def execute(self, variables): + command = resolveVariables(self.command, variables) + + process = Popen(command, stdout=PIPE, stderr=PIPE, shell=True) + + # if a timeout was specified start a thread which kills the process + # tree if it's still running after the timeout + kill_thread = None + if self.timeout > 0: + self.abort_timeout = False + kill_thread = Thread(target=self.process_timeout, args=(process,)) + kill_thread.start() + + stdout, stderr = process.communicate() + exitcode = process.wait() + + # if the timeout thread is still there we have to stop it + if kill_thread is not None: + self.abort_timeout = True + kill_thread.join() + + success = True + for validator in self.validators: + if not validator.validate(exitcode, + stdout.decode("utf-8"), + stderr.decode("utf-8"), + variables, + command): + success = False + + # don't print command on further validators + command = None + + return success + + def run(self, testcase, variables): + self.executed = True + start = datetime.datetime.now() + + # merge global and step variables + # step variables take precedence + used_variables = {} + for key, value in variables.items(): + used_variables[key] = value + for key, value in self.arguments.items(): + used_variables[key] = value + + + description = self.message + if description is None: + description = self.name + + description = resolveVariables(description, used_variables) + + print("%s %s: %s" % (STATUS_RUN, testcase.name, description)) + + status = STATUS_OK + if not self.execute(used_variables): + status = STATUS_FAILED + self.failed = True + + print("%s %s: %s (%d ms)" % + (status, testcase.name, description, duration(start))) + + return not (self.failed and self.fatal) diff --git a/code/train/Python/0053393_document.py b/code/train/Python/0053393_document.py new file mode 100644 index 0000000000000000000000000000000000000000..1bd96df20b700866e5f8c3304fbd41341b216904 --- /dev/null +++ b/code/train/Python/0053393_document.py @@ -0,0 +1,112 @@ +""" +""" +import pygame + +import container +import layout + +class _document_widget: + def __init__(self,w,align=None): + #w.rect.w,w.rect.h = w.resize() + #self.rect = w.rect + self.widget = w + if align != None: self.align = align + +class Document(container.Container): + """A document container contains many widgets strung together in a document format. (How informative!) + +
Document()
+ + """ + def __init__(self,**params): + params.setdefault('cls','document') + container.Container.__init__(self,**params) + self.layout = layout.Layout(pygame.Rect(0,0,self.rect.w,self.rect.h)) + + def add(self,e,align=None): + """Add a widget. + +
Document.add(e,align=None)
+ +
+
e
widget +
align
alignment (None,-1,0,1) +
+ """ + dw = _document_widget(e,align) + self.layout.add(dw) + e.container = self + e._c_dw = dw + self.widgets.append(e) + self.chsize() + + def remove(self,e): + self.layout._widgets.remove(e._c_dw) + self.widgets.remove(e) + self.chsize() + + + def block(self,align): + """Start a new block. + +
Document.block(align)
+ +
+
align
alignment of block (-1,0,1) +
+ """ + self.layout.add(align) + + def space(self,e): + """Add a spacer. + +
Document.space(e)
+ +
+
e
a (w,h) size for the spacer +
+ """ + self.layout.add(e) + + def br(self,height): + """Add a line break. + +
Document.br(height)
+ +
+
height
height of line break +
+ """ + self.layout.add((0,height)) + + def resize(self,width=None,height=None): + if self.style.width: width = self.style.width + if self.style.height: height = self.style.height + + for w in self.widgets: + w.rect.w,w.rect.h = w.resize() + + if (width != None and w.rect.w > width) or (height != None and w.rect.h > height): + w.rect.w,w.rect.h = w.resize(width,height) + + dw = w._c_dw + dw.rect = pygame.Rect(0,0,w.rect.w,w.rect.h) + + if width == None: width = 65535 + self.layout.rect = pygame.Rect(0,0,width,0) + self.layout.resize() + + _max_w = 0 + + for w in self.widgets: + #xt,xl,xb,xr = w.getspacing() + dw = w._c_dw + w.style.x,w.style.y,w.rect.w,w.rect.h = dw.rect.x,dw.rect.y,dw.rect.w,dw.rect.h + #w.resize() + w.rect.x,w.rect.y = w.style.x,w.style.y + _max_w = max(_max_w,w.rect.right) + + #self.rect.w = _max_w #self.layout.rect.w + #self.rect.h = self.layout.rect.h + #print 'document',_max_w,self.layout.rect.h + return _max_w,self.layout.rect.h diff --git a/code/train/Python/0053584_test_pyregrid.py b/code/train/Python/0053584_test_pyregrid.py new file mode 100644 index 0000000000000000000000000000000000000000..3723d9e472dc09e249247879174358e8ab7947fe --- /dev/null +++ b/code/train/Python/0053584_test_pyregrid.py @@ -0,0 +1,162 @@ + +def build_analytic_field(field, grid, domask): + ''' + PRECONDITIONS: An ESMP_Field has been created as 'field'. 'grid' has + been created and coordinates have been set on both the + center and corner stagger locations. 'mask' holds the + masked values of 'grid'.\n + POSTCONDITIONS: The 'field' has been initialized to an analytic field.\n + RETURN VALUES: \n ESMP_Field :: field \n + ''' + DEG2RAD = 3.141592653589793/180.0 + + # get the field pointer + fieldPtr = ESMP.ESMP_FieldGetPtr(field) + + # get the grid bounds and coordinate pointers + exLB, exUB = ESMP.ESMP_GridGetCoord(grid, ESMP.ESMP_STAGGERLOC_CENTER) + + # get the mask + if domask: + mask = ESMP.ESMP_GridGetItem(grid, item=ESMP.ESMP_GRIDITEM_MASK) + + # get the coordinate pointers and set the coordinates + [x,y] = [0, 1] + gridXCoord = ESMP.ESMP_GridGetCoordPtr(grid, x, ESMP.ESMP_STAGGERLOC_CENTER) + gridYCoord = ESMP.ESMP_GridGetCoordPtr(grid, y, ESMP.ESMP_STAGGERLOC_CENTER) + + p = 0 + for i1 in range(exLB[1], exUB[1]): + for i0 in range(exLB[0], exUB[0]): + theta = DEG2RAD*gridXCoord[p] + phi = DEG2RAD*(90.0 - gridYCoord[p]) + fieldPtr[p] = 2.0 + np.cos(theta)**2 * np.cos(2.0*phi) + p = p + 1 + + ''' + theta = np.array(DEG2RAD*gridXCoord[:]) + phi = np.array(DEG2RAD*(90. - gridYCoord[:])) + fieldPtr[:] = 2. + np.cos(theta[:])**2 * np.cos(2.*phi[:]) + ''' + return field + + +def compute_mass(valuefield, areafield, fracfield, dofrac): + ''' + PRECONDITIONS: Two ESMP_Fields have been created and initialized. 'valuefield' + contains data values of a field built on the cells of a grid, + 'areafield' contains the areas associated with the grid + cells, and 'fracfield' contains the fractions of each cell + which contributed to a regridding operation involving + 'valuefield. 'dofrac' is a boolean value that gives the + option to not use the 'fracfield'.\n + POSTCONDITIONS: The mass of the data field is computed and returned.\n + RETURN VALUES: integer :: mass \n + ''' + + mass = 0.0 + ESMP.ESMP_FieldRegridGetArea(areafield) + area = ESMP.ESMP_FieldGetPtr(areafield) + value = ESMP.ESMP_FieldGetPtr(valuefield) + frac = 0 + if dofrac: + frac = ESMP.ESMP_FieldGetPtr(fracfield) + + for i in range(valuefield.size): + if dofrac: + mass += area[i]*value[i]*frac[i] + else: + mass += area[i]*value[i] + + return (mass, area) + + +def compare_fields(interp_field, exact_field, dstfracfield, srcmass, dstmass): + ''' + PRECONDITIONS: 'interp_field' is a Field that holds the values resulting + from a regridding operation, 'exact_field' is a Field + containing the values of the exact solution that is + expected, and 'dstfracfield' is a Field containing the + fractions of the 'interp_field' which contributed to the + regridding product. 'srcmass' and 'dstmass' are the + mass values for the source and destination data fields. \n + POSTCONDITIONS: The interpolation accuracy of a regridding operation is + determined by comparing the 'interp_field' to the + 'exact_field'. The mass conservation is validated by + comparing the 'srcmass' to the 'dstmass'.\n + RETURN VALUES: None \n + ''' + + vm = ESMP.ESMP_VMGetGlobal() + localPet, _ = ESMP.ESMP_VMGet(vm) + + # get the data pointers for the fields + interp = ESMP.ESMP_FieldGetPtr(interp_field) + exact = ESMP.ESMP_FieldGetPtr(exact_field) + dstfrac = ESMP.ESMP_FieldGetPtr(dstfracfield) + + if (interp_field.size != exact_field.size): + raise TypeError('compare_fields: Fields must be the same size!') + + # initialize to True, and check for False point values + total_error = 0.0 + max_error = 0.0 + min_error = 1000000.0 + for i in range(interp_field.size): + if (exact[i] != 0.0): + err = abs(interp[i]/dstfrac[i] - exact[i])/abs(exact[i]) + else: + err = abs(interp[i]/dstfrac[i] - exact[i]) + total_error = total_error + err + + if (err > max_error): + max_error = err + if (err < min_error): + min_error = err + + # check the mass + csrv = False + csrv_error = abs(dstmass - srcmass)/srcmass + if (csrv_error < 10e-12): + csrv = True + itrp = False + if (max_error < 10E-2): + itrp = True + + if (itrp and csrv): + print "PASS" + else: + print "FAIL" + print " Total error = "+str(total_error) + print " Max error = "+str(max_error) + print " Min error = "+str(min_error) + print " Csrv error = "+str(csrv_error) + print " srcmass = "+str(srcmass) + print " dstmass = "+str(dstmass) + + return + +def test_regrid(): + """ + Check the OASIS grids by regridding and analytic function and comparing to the expected result. + + This does not pass, although close. Need to experiment with some different grid setups to see + what's going on. Leave this for now. + """ + src_grid, dest_grid, src_field, dest_field, src_frac, dest_frac, src_area, dest_area = setup_grid_and_fields() + + dest_exact = ESMP.ESMP_FieldCreateGrid(dest_grid, 'dest_exact') + + # Intialise analytic test field. + src_field = build_analytic_field(src_field, src_grid, False) + dest_exact = build_analytic_field(dest_exact, dest_grid, False) + + # Do the regridding + dest_field, src_frac, dest_frac = run_regridding(src_field, dest_field, src_frac, dest_frac) + + # Compute mass + src_mass, _ = compute_mass(src_field, src_area, src_frac, True) + dest_mass, _ = compute_mass(dest_field, dest_area, 0, False) + + compare_fields(dest_field, dest_exact, dest_frac, src_mass, dest_mass) + diff --git a/code/train/Python/0053695_timeseries.py b/code/train/Python/0053695_timeseries.py new file mode 100644 index 0000000000000000000000000000000000000000..25b7bc7dc45fca91b760fb006ccf43d90a400b50 --- /dev/null +++ b/code/train/Python/0053695_timeseries.py @@ -0,0 +1,140 @@ +import cv2 + +import numpy as np + +from PyQt4 import QtGui, QtCore +from qt_ui.ui_timeseries import Ui_Timeseries + +from PyQt4.Qt import * +from PyQt4.Qwt5 import * +from PyQt4.Qwt5.qplt import * + +import snippet + +class TimeseriesWindow(QtGui.QWidget): + def __init__(self, player, parent=None): + QtGui.QWidget.__init__(self, parent) + self.ui = Ui_Timeseries() + self.ui.setupUi(self) + self.img = None + + def show_img(self,npimg): + self.img = cv2.cvtColor(npimg,cv2.COLOR_BGR2BGRA) + h, w ,c = self.img.shape + + # Qt expects 32bit BGRA data for color images: + self.qimg = QtGui.QImage(self.img.data, w, h, QtGui.QImage.Format_RGB32) + self.qimg.ndarray = self.img + + scene = QtGui.QGraphicsScene() + scene.addPixmap(QtGui.QPixmap(self.qimg)) + self.ui.graphicsView.setScene(scene) + +class TimeSeries: + """A time series is a time-ordered vector of (time, value)-vectors. Time is + given in seconds (float) and value is any numeric format.""" + + def __init__(self, filename, label = "noname", approx = "none"): + """filename: path to text-file of tab-separated values + label (optional): string that describe this time series + approx (default=none): approximation type between values (actually just none)""" + + self.filename = filename + self.data = np.loadtxt(filename) + self.val_min = np.amin(self.data[:,1]) + self.val_max = np.amax(self.data[:,1]) + self.label = label + self.equal_tupel_length = self.calc_tupel_length() + self.approx = approx + self.act_pos = 0 + + #self.win_w = 300 + #self.win_h = 200 + #self.win = None + #self.img = np.zeros((self.win_h,self.win_w,3),'uint8') + + self.p = Plot( + Curve(self.data[:,0], self.data[:,1], Pen(Magenta, 2), self.label)) + #Curve([self.act_pos, self.act_pos], [self.val_min, self.val_max], Pen(Red), "pos")) + #self.p.setAxisScale(2,0,200) + self.m = QwtPlotMarker() + self.m.setLineStyle(2) + self.m.attach(self.p) + + def show(self, time): + self.act_pos = time + #if self.p.AxisInterval(2) + #self.p.set + self.m.setXValue(self.act_pos) + self.p.replot() + """ + if self.win is None: + self.win = TimeseriesWindow(self) + self.win.setWindowTitle(self.label) + self.win + self.win.show() + + val = self.get_elem(time) + p_val = int((val-self.val_min) / (self.val_max-self.val_min) * self.win_h) + + # shift left + self.img[:,0:self.win_w-1,:] = self.img[:,1:self.win_w,:] + self.img[:,self.win_w-1,:] = 0 + # draw value + self.img[p_val,self.win_w-1,:] = 255 + + #cv2.imshow('sd',self.img) + self.win.show_img(self.img) + + pass + #self. + """ + + def get_elem(self, request_time): + """returns the value of the time series at a specific time point""" + if self.approx == "none": + if self.equal_tupel_length > 0: + n = int( (request_time - self.data[0,0]) / self.equal_tupel_length) + return self.data[n][1] + else: + print "ERROR: not implemented yet" #TODO + return None + else: + print "ERROR: only approx = 'none' implemented" + + def calc_tupel_length(self): + """returns the duration of one tupel, if constant. Otherwise returns -1""" + dist = self.data[1,0]-self.data[0,0] + for i in range(len(self.data)-1): + if dist != (self.data[i+1,0]-self.data[i,0]): + return -1 + + return dist + + def get_snippets(self, offset = 0, function = None ): + """returns a list of snippets where function returns true if calculated + with time series values""" + snippets = [] + if self.approx == "none": + last_val = False + begin = 0 + end = 0 + for (i,val) in self.data: + if function is None: + act_val = bool(val > 0) + else: + act_val = function(val) + if last_val != act_val: + if act_val: + begin = i + else: + end = i + snippets.append(snippet.Snippet(min(max(0,begin+offset),self.data[len(self.data)-1,0]), end-begin, self.label)) + last_val = act_val + + return snippets + +# TODO delete (helper function for testing get_snippets) +def greater_zero(a): + return a>0 + diff --git a/code/train/Python/0054658_8.py b/code/train/Python/0054658_8.py new file mode 100644 index 0000000000000000000000000000000000000000..2b63cb54ae69fb42ace887e41470df301d7e79fb --- /dev/null +++ b/code/train/Python/0054658_8.py @@ -0,0 +1,27 @@ +""" + The four adjacent digits in the 1000-digit number that have the greatest + product are 9 × 9 × 8 × 9 = 5832. + + {{ 8_input.txt }} + + Find the thirteen adjacent digits in the 1000-digit number that have the + greatest product. What is the value of this product? +""" + +from os.path import dirname, abspath, join + +if __name__ == '__main__': + + digits = 13 + with open(join(dirname(abspath(__file__)), '8_input.txt')) as f: + number = ''.join(f.read().splitlines()) + + greatest_product = 0 + for i in range(len(number) - digits + 1): + product = 1 + for j in range(i, i + digits): + product *= int(number[j]) + if product > greatest_product: + greatest_product = product + + print(greatest_product) diff --git a/code/train/Python/0054760_vocaCreator.py b/code/train/Python/0054760_vocaCreator.py new file mode 100644 index 0000000000000000000000000000000000000000..a57074035562d52c3fa762ad3b016c463de35241 --- /dev/null +++ b/code/train/Python/0054760_vocaCreator.py @@ -0,0 +1,82 @@ +import requests, os +from bs4 import BeautifulSoup +from termcolor import colored +from voca.vocaDict import vocaDict +from voca.vocaUtil import vocaUtil + +class vocaCreator(vocaUtil): + def __init__(self): + self.refrance_url = 'https://www.vocabulary.com/dictionary/%s' + self.sentence_url = 'http://sentence.yourdictionary.com/%s' + self.write_dict_flag = False + self.short = '' + self.long = '' + self.sentences = [] + + def looking_for_list(self, SEARCH_LIST): + if SEARCH_LIST: + for word in SEARCH_LIST: + word = word.lower() + short_text, long_text, sentences = self.check_word_in_local_dect(word) + if not short_text: + self.short, self.long = self.get_description(word) + if not self.short: + continue + self.sentences = self.get_sentences(word) + self.update_dict(word, self.short, self.long, self.sentences) + else: + self.print_short_description(word, short_text) + self.print_long_description(long_text) + self.print_sentences(sentences) + if self.write_dict_flag: + self.write_dict() + + def get_description(self, word): + self.write_dict_flag = True + content = requests.get(url=self.refrance_url % word).content + soup = BeautifulSoup(content, 'lxml') + short = self.get_short_description(word, soup) + long = self.get_long_description(soup) + return short, long + + def get_sentences(self, word): + sentences = [] + content = requests.get(url=self.sentence_url % word).content + soup = BeautifulSoup(content, 'lxml') + data = soup.findAll('div', attrs={'class': 'li_content'}) + if data: + for index in range(3): + sentence = data[index].getText() + sentences.append(sentence) + vocaCreator.print_sentences(self, sentences) + return sentences + + def get_short_description(self, word, soup): + short = soup.findAll('p', attrs={'class': 'short'}) + if short: + short_text = short[0].getText() + vocaCreator.print_short_description(self, word, short_text) + return short_text + else: + print(colored(' * There is no description :( !!', 'red')) + + def get_long_description(self, soup): + long = soup.findAll('p', attrs={'class': 'long'}) + if long: + long_text = long[0].getText() + vocaCreator.print_long_description(self, long_text) + return long_text + + @staticmethod + def update_dict(word, short, long, sentences): + vocaDict[word] = {'short': short, + 'long': long, + 'sentences': sentences} + + @staticmethod + def write_dict(): + script_dir = os.path.dirname(__file__) + voca_path = os.path.join(script_dir, 'vocaDict.py') + tmp = open(voca_path, 'w') + tmp.write('vocaDict = %s' % str(vocaDict)) + tmp.close() diff --git a/code/train/Python/0055295_shuffling.py b/code/train/Python/0055295_shuffling.py new file mode 100644 index 0000000000000000000000000000000000000000..115648d177a545938f78ece9aa0bdd916da648dc --- /dev/null +++ b/code/train/Python/0055295_shuffling.py @@ -0,0 +1,71 @@ +from itertools import chain, groupby +from operator import attrgetter +import random as random_mod + + +def weighted_pick(x, key_weight=None): + """Returns one element from the sequence x. + A "heavy" element is more likely to be picked. + The `key_weight` argument can be used to define how to access the element's weight. + By default, we assume x to be a sequence of (element, weight) tuples. + """ + if key_weight is None: + key_weight = lambda t: t[1] + + total_weights = sum(key_weight(e) for e in x) + target = random_mod.randint(0, total_weights) + for e in x: + target -= e[1] + if target <= 0: + return e[0] + + +def weighted_shuffle(x, key_weight=None): + """Shuffles the sequence x in place. + Elements that are "heavier" will be more likely to be at the beginning. + The `key_weight` argument can be used to define how to access the element's weight. + By default, we assume x to be a sequence of (element, weight) tuples. + """ + if key_weight is None: + key_weight = lambda t: t[1] + + weights = [(i, key_weight(e)) for e in enumerate(x)] + + for i in reversed(xrange(1, len(x))): + j = weighted_pick(weights[:i+1]) + x[i], x[j] = x[j], x[i] + + +def shuffled(iterable, weight=None): + """ + Return a shuffled copy of the given iterable. + If a callable is passed for `weight`, then a weighted_shuffle will be used. + If not, a plain random.shuffle will be used. + """ + l = list(iterable) # copy + if weight is None: + random_mod.shuffle(l) + else: + weighted_shuffle(l, key_weight=weight) + return l + + +def sequential(elements, key=attrgetter('position')): + return sorted(elements, key=key) + + +def random(elements): + return shuffled(elements) + + +def weighted_random(elements, key=attrgetter('position')): + l = list(elements) + weighted_shuffle(l, key_weight=key) + return l + + +def cluster_random(elements, key=attrgetter('position')): + ordered = sorted(elements, key=key) + grouped = groupby(ordered, key=key) + clustered = chain.from_iterable(shuffled(elements) for _, elements in grouped) + return list(clustered) diff --git a/code/train/Python/0056031_pyrmEval.py b/code/train/Python/0056031_pyrmEval.py new file mode 100644 index 0000000000000000000000000000000000000000..9deaab24ac5000bb773951ddf8cc0cbff9458291 --- /dev/null +++ b/code/train/Python/0056031_pyrmEval.py @@ -0,0 +1,39 @@ +import random +import sys +#slices a list into n nearly-equal-length partitions +#returns list of lists +def random_partition(lst, n, shuffle=True): + if shuffle is True: + random.shuffle(lst) #optional + division = len(lst) / float(n) + return [ lst[int(round(division * i)): int(round(division * (i+1)))] for i in xrange(n) ] + +#Randomly resamples labeled datasets into comprehensive training set and test set +#reshuffles data and returns training/test sets as list of dictionaries +#the arguments should be lists that represent classes + +#output: tuple +def make_training_and_test_set(trainProportion, shuffle=True, **kwargs): + if trainProportion > 1.0 or trainProportion < 0.0: + raise ValueError('trainPartition can only be between 0 and 1.0') + training_data = [] + test_data = [] + for key, class_list in kwargs.iteritems(): + if shuffle is True: + random.shuffle(class_list) #optional + trainIndex = trainProportion * len(class_list) #calculates index for end of training set + trainIndex = int(round(trainIndex)) + training_data.append( {key : class_list[:trainIndex]} ) #partitions training set from start to random index + test_data.append( {key : class_list[trainIndex:]} ) #partition test set from random index to end + return (training_data, test_data) + +#perform n-fold cross validation +#returns list of lists of dictionaries +def create_cross_validate_set(n, shuffle=True, **kwargs): + dataset = [] + for key, value_list in kwargs.items(): + for values in value_list: + dataset.append({ key : values }) + #dataset, filler = make_training_and_test_set(1.0, True, **kwargs) + subpartitions = random_partition(dataset, n) + return subpartitions diff --git a/code/train/Python/0056597_test_study_get.py b/code/train/Python/0056597_test_study_get.py new file mode 100644 index 0000000000000000000000000000000000000000..33de86f9449346ab197011231a332b7bf528a021 --- /dev/null +++ b/code/train/Python/0056597_test_study_get.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python +import sys, os +from opentreetesting import test_http_json_method, config, get_response_from_http +from peyotl import convert_nexson_format + +DOMAIN = config('host', 'apihost') +SUBMIT_URI = DOMAIN + '/v4/study/list' +#sys.stderr.write('Calling "{}"...\study_obj'.format(SUBMIT_URI)) +r = test_http_json_method(SUBMIT_URI, + 'GET', + expected_status=200, + return_bool_data=True) +if not r[0]: + sys.exit(1) + +def do_tree_test_get(study_id, tree_id): + NEXUS_SUBMIT_URI = DOMAIN + '/v1/study/{}/tree/{}.nex'.format(study_id, tree_id) + t = get_response_from_http(NEXUS_SUBMIT_URI, 'GET') + nexus = t.content + if not nexus.startswith('#NEXUS'): + sys.exit('Did not get content starting with #NEXUS') + data = {'tip_label': 'ot:ottTaxonName'} + NEWICK_SUBMIT_URI = DOMAIN + '/v1/study/{}/tree/{}.tre'.format(study_id, tree_id) + r = test_http_json_method(NEWICK_SUBMIT_URI, + 'GET', + data=data, + expected_status=200, + return_bool_data=True, + is_json=False) + if r[0]: + assert r[1].startswith('(') + assert '[pre-ingroup-marker]' not in r[1] + else: + sys.exit(1) + data['bracket_ingroup'] = True + r = test_http_json_method(NEWICK_SUBMIT_URI, + 'GET', + data=data, + expected_status=200, + return_bool_data=True, + is_json=False) + if r[0]: + assert r[1].startswith('(') + assert '[pre-ingroup-marker]' in r[1] + else: + sys.exit(1) + + +def dict_eq(a, b): + if a == b: + return True + d = True + ka, kb = a.keys(), b.keys() + ka.sort() + kb.sort() + if ka != kb: + sa = set(ka) + sb = set(kb) + ao = sa - sb + ao = list(ao) + ao.sort() + bo = sb - sa + c = {u'^ot:candidateTreeForSynthesis', u'^ot:tag'} + bextra = bo - c + bo = list(bextra) + bo.sort() + if bextra or ao: + sys.stdout.write(' keys in a only "{a}"."\n'.format(a=ao)) + sys.stdout.write(' keys in b only "{a}"."\n'.format(a=bo)) + d = False + for k in ka: + if k in kb: + va = a[k] + vb = b[k] + if va != vb: + if isinstance(va, dict) and isinstance(vb, dict): + if not dict_eq(va, vb): + d = False + elif isinstance(va, list) and isinstance(vb, list): + for n, ela in enumerate(va): + elb = vb[n] + if not dict_eq(ela, elb): + d = False + if len(va) != len(vb): + d = False + sys.stdout.write(' lists for {} differ in length.\n'.format(k)) + else: + d = False + sys.stdout.write(' value for {k}: "{a}" != "{b}"\n'.format(k=k, a=va, b=vb)) + else: + d = False + return d + +# loop over studies to find one with a tree so we can test the tree_get... +for study_id in r[1]: + SUBMIT_URI = DOMAIN + '/v1/study/{}'.format(study_id) + # a bogus value for nexml2json should give us a 400 + data = {'output_nexml2json': 'x1.2.1'} + test_http_json_method(SUBMIT_URI, 'GET', data=data, expected_status=400) + # now get the study in the "legacy" format + data = {'output_nexml2json': '0.0.0'} + pb = test_http_json_method(SUBMIT_URI, 'GET', data=data, expected_status=200, return_bool_data=True) + if not pb[0]: + sys.exit(1) + # ... and in our transitional format... + data = {'output_nexml2json': '1.0.0'} + pl = test_http_json_method(SUBMIT_URI, 'GET', data=data, expected_status=200, return_bool_data=True) + if not pl[0]: + sys.exit(1) + badger = pb[1]['data'] + legacy = pl[1]['data'] + # ...they should differ... + assert (badger != legacy) + # ... but convertable to the same info... + lfromb = convert_nexson_format(badger, '1.0.0', current_format='0.0.0') + if lfromb != legacy: + with open('.tmp1', 'w') as fo_one: + json.dump(legacy, fo_one, indent=0, sort_keys=True) + with open('.tmp2', 'w') as fo_one: + json.dump(lfromb, fo_one, indent=0, sort_keys=True) + assert (dict_eq(lfromb, legacy)) + # ...finally we grab it in HBF... + data = {'output_nexml2json':'1.2.1'} + r = test_http_json_method(SUBMIT_URI, 'GET', data=data, expected_status=200, return_bool_data=True) + if r[0]: + # ... and do some tests of grabbing just a tree from the study... + nexm_el = r[1]['data']['nexml'] + if nexm_el["@nexml2json"] != "1.2.1": + msg = 'requested conversion to NexSON format not performed. nexml_el["@nexml2json"] = {}\n' + sys.exit(msg.format(nexm_el["@nexml2json"])) + tree_group_coll_el = nexm_el.get('treesById') + if tree_group_coll_el: + for trees_group_id, trees_group in tree_group_coll_el.items(): + if trees_group and trees_group.get('treeById'): + tree_id_list = list(trees_group['treeById'].keys()) + tree_id_list.sort() #to make the test repeatable... + tree_id = tree_id_list[0] + do_tree_test_get(study_id, tree_id) + sys.exit(0) + else: + sys.exit(1) diff --git a/code/train/Python/0057109_train_triplets.py b/code/train/Python/0057109_train_triplets.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab43a94d12a13be060fa08c0eb9b08997e1f57a --- /dev/null +++ b/code/train/Python/0057109_train_triplets.py @@ -0,0 +1,176 @@ +"""A script to train a triplet distance based model. + +This script is used to train models that expect to be fed triplets for +training. Currently it can be used to train EmbedNet, based on the FaceNet +paper, and TripletNet, based on Hoffer, Ailon: "Deep Metric Learning Using +Triplet Network". +""" + +import numpy as np +import time + +import chainer +from chainer import cuda +from chainer import optimizers + +from tripletembedding.predictors import TripletNet +from tripletembedding.aux import Logger, load_snapshot + +from aux import helpers +from aux.triplet_loader import TripletLoader +from aux.mcyt_loader import McytLoader +from aux.index_loader import IndexLoader, load_dict, anchors_in + +from models.vgg_small import VGGSmall, VGGSmallConv, VGGClf +from models.vgg_xs import VGGXSClf, VGGXSEmbed +# import models.vgg_small_legacy as legacy +import queue + +import pickle + + +args = helpers.get_args() + +xp = cuda.cupy if args.gpu >= 0 else np +dl = IndexLoader(xp) + +# - old method - +# train, test = helpers.split_anchors(anchors_in(args.data), args.test) + +# === inter-class split === +data = load_dict(args.data) + +# - loading existing train/test split for continued training - +# train_anchors, test_anchors = pickle.load(open('snapshots/16-06-20_vgg_small_triplets/vgg_small_triplets_train_test_split.pkl', 'rb')) +# - create train and test dictionaries from train/test split - +# train = { +# 'Genuine': {label: data['Genuine'][label] +# for label in train_anchors['Genuine'].keys()}, +# 'Forged': {label: data['Forged'][label] +# for label in train_anchors['Genuine'].keys()} +# } +# test = { +# 'Genuine': {label: data['Genuine'][label] +# for label in test_anchors['Genuine'].keys()}, +# 'Forged': {label: data['Forged'][label] +# for label in test_anchors['Genuine'].keys()} +# } + +# - create new inter-class split - +all_ancs = list(data['Genuine'].keys()) +np.random.shuffle(all_ancs) +t = int(len(all_ancs) * args.test) +train_anchors, test_anchors = all_ancs[:-t], all_ancs[-t:] +# - create train and test dictionaries from train/test split - +train = { + 'Genuine': {label: data['Genuine'][label] for label in train_anchors}, + 'Forged': {label: data['Forged'][label] for label in train_anchors} +} +test = { + 'Genuine': {label: data['Genuine'][label] for label in test_anchors}, + 'Forged': {label: data['Forged'][label] for label in test_anchors} +} + +# === intra-class split -- writer-dependent === +# data = load_dict(args.data) +# train = {group: {} for group in data.keys()} +# test = {group: {} for group in data.keys()} +# for group in data.keys(): +# for label in data[group].keys(): +# samples = data[group][label] +# np.random.shuffle(samples) + +# t = int(len(samples) * args.test) +# train[group][label] = samples[:-t] +# test[group][label] = samples[-t:] + +# - save train/test split - +pickle.dump([train, test], open(args.out+'_train_test_split.pkl', 'wb')) + +model = TripletNet(VGGSmall) + +if args.gpu >= 0: + cuda.get_device(args.gpu).use() + dl.use_device(args.gpu) + model = model.to_gpu() + +optimizer = optimizers.MomentumSGD(lr=0.001) +optimizer.setup(model) +optimizer.add_hook(chainer.optimizer.WeightDecay(args.weight_decay)) +optimizer.add_hook(chainer.optimizer.GradientClipping(10.0)) + +if args.initmodel and args.resume: + load_snapshot(args.initmodel, args.resume, model, optimizer) + print("Continuing from snapshot. LR: {}".format(optimizer.lr)) + +# load pre-trained CNN +# from chainer import serializers +# pretrained = VGGClf(100) +# serializers.load_hdf5(args.initmodel, pretrained) +# model.cnn.conv.copyparams(pretrained.conv) + +logger = Logger(args, optimizer, args.out) + +graph_generated = False +for _ in range(1, args.epoch + 1): + time_started = time.time() + + optimizer.new_epoch() + print('========\nepoch', optimizer.epoch) + + # margin = min(3.0, 1.0 + 0.005 * optimizer.epoch**2) + # print('margin:\t{}'.format(margin)) + margin = 1.0 + + # training + dl.create_source('train', + args.batchsize, train, skilled=args.skilled) + dl.create_source('test', + args.batchsize, test, skilled=args.skilled) + + while True: + model.zerograds() + model.clean() + + try: + x_data = dl.get_batch('train') + except queue.Empty: + break + + x = chainer.Variable(x_data) + optimizer.update(model, x) + # optimizer.update(model, x, margin) + logger.log_iteration("train", + float(model.loss.data), float(model.accuracy), + float(model.mean_diff), float(model.max_diff)) + + if not graph_generated: + helpers.write_graph(model.loss) + graph_generated = True + + logger.log_mean("train") + print("iteration time:\t{:.3f} sec" + .format((time.time() - time_started) / len(train))) + + if optimizer.epoch % args.lrinterval == 0 and optimizer.lr > 0.000001: + optimizer.lr *= 0.5 + logger.mark_lr() + print("learning rate decreased to {}".format(optimizer.lr)) + if optimizer.epoch % args.interval == 0: + logger.make_snapshot(model) + + # testing + while True: + try: + x = chainer.Variable(dl.get_batch('test'), volatile=True) + except queue.Empty: + break + loss = model(x) + logger.log_iteration("test", + float(model.loss.data), float(model.accuracy), + float(model.mean_diff), float(model.max_diff)) + logger.log_mean("test") + +# make final snapshot if not just taken one +if optimizer.epoch % args.interval != 0: + logger.make_snapshot(model) diff --git a/code/train/Python/0057194_summary.py b/code/train/Python/0057194_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..73d51579a49476647e976e384636b0dd6550b708 --- /dev/null +++ b/code/train/Python/0057194_summary.py @@ -0,0 +1,186 @@ +import logging +import os +import subprocess +import sys + +from assertEquals.cli.utils import BANNER, BORDER, HEADERS +from assertEquals.interactive.utils import RefreshError, Process + + +logger = logging.getLogger('assertEquals.interactive.summary') + + +class Summary: + """Represent the data from an inter-process summarize() call. + + This is designed to be a persistent object. Repeated calls to refresh will + update the dataset. On partial updates, existing data will be marked as + stale. There is also a show flag for each record; only items for which this + are true are included in the name index and __len__ calls. + + """ + + module = '' # the current module dotted module name + data = None # a dictionary, {name:(stats, fresh)}: + # stats: None or (pass5, fail, err, all) + # fresh: None or False or True + names = None # a sorted list of names for which show is True + run = True # the current state of the run flag + totals = () # a single 4-tuple per summarize() + __lines = None # for communication between _set_totals and _set_data + __raw = '' # for communication between _call and _set_data + + + def __init__(self, stopwords=()): + """Takes a sequence. + """ + self.stopwords = stopwords + self.data = {} + self.totals = () + self.names = [] + + + # Container emulation + # =================== + + def __getitem__(self, i): + """Takes an int index into self.names + """ + name = self.names[i] + return [name] + self.data[name] + + def __len__(self): + """Only count items for which show is True. + """ + return len(self.names) + + def __iter__(self): + return self.names.__iter__() + iterkeys = __iter__ + + + # Main callable + # ============= + + def refresh(self, module, find_only=True): + """Update our information. + """ + self.module = module + self.find_only = find_only + + self._call() + + self._set_stale() + self._set_totals() + self._set_data() + + + def update(self, name, pass5, fail, err, all): + """Given data on one testcase, update its info. + + This is called from DetailScreen. + + """ + if name not in self.data: + raise StandardError("Running detail for module not in " + + "summary: %s." % name) + self._set_stale() + self.data[name] = [(pass5, fail, err, all), True] + self.totals = [pass5, fail, err, all] + + + # Helpers + # ======= + + def _call(self): + """Invoke a child process and return its output. + + We hand on our environment and any sys.path manipulations to the child, + and we capture stderr as well as stdout so we can handle errors. + + """ + args = [ sys.executable + , '-u' # unbuffered, so we can interact with it + , sys.argv[0] + , '--stopwords=%s' % ','.join(self.stopwords) + , '--scripted' + , self.module + ] + if self.find_only: + args.insert(4, '--find-only') + + environ = os.environ.copy() + environ['PYTHONPATH'] = ':'.join(sys.path) + + proc = Process(args=args, env=environ) + + raw = proc.communicate() + if BANNER not in raw: + raise RefreshError(raw) + self.__raw = raw + + + def _set_stale(self): + """Mark currently fresh data as stale. + """ + for name, datum in self.data.iteritems(): + if datum[1] is True: + datum[1] = False + + + def _set_totals(self): + """Given self.__raw, set totals and __lines on self. + """ + lines = self.__raw.splitlines() + self.totals = tuple(lines[-1].split()[1:]) + del lines[-1] + self.__lines = lines + + + def _set_data(self): + """Extract and store data from __lines. + """ + + data = {} + reading_report = False # ignore any output that precedes our report + + for line in self.__lines: + + # Decide if we want this line, and if so, split it on spaces. + # =========================================================== + + line = line.strip('\n') + if line == BANNER: + reading_report = True + continue + if (not reading_report) or (not line) or line in (HEADERS, BORDER): + continue + tokens = line.split() + + + # Convert the row to our record format. + # ===================================== + # The raw report lists TestCases by full dotted name, but we want to + # only show short names, and indent under a module tree. So we add + # all parent modules to data, and set their value to (None, None) + + name = tokens[0] + stats = tuple(tokens[1:]) + + module_dotted, testcase = name.rsplit('.',1) + + parts = module_dotted.split('.') + for i in range(len(parts),self.module.count('.'),-1): + ancestor = '.'.join(parts[:i]) + data[ancestor] = [None, None] + + fresh = None + if '-' not in stats: + fresh = True + + data[name] = [stats, fresh] + + self.data.update(data) + self.names = sorted(self.data.keys()) + del self.__lines + diff --git a/code/train/Python/0057882_Databases.py b/code/train/Python/0057882_Databases.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2c73e034c876fa108b73791439f00efc4f544d --- /dev/null +++ b/code/train/Python/0057882_Databases.py @@ -0,0 +1,221 @@ +#import os +#os.environ['DYLD_LIBRARY_PATH'] = '/Library/PostgreSQL/9.5/lib' +import psycopg2 +import time +import itertools + +# Dictionary of database connections. Key is the database name (only within python relevant). Value is List of: [host, user, password, database, port] +databaseSetups = { + +} + + +class Database: + + def __init__(self, setup): + ''' + @param setup: string. Database Setup. Must match a key from the databaseSetups dictionary (see above) + Creates an connection to database + ''' + self.setup = setup + self.db = self._getConnection() + + def _getConnection(self): + ''' + Returns database connection. Function checks if database connection is still alive and if this is not the case it automatically reconnects to database + @return: MySQLdb connection object + ''' + try: + # check if database connection is still alive + db = self.db + cursor = db.cursor() + cursor.execute("SELECT VERSION()") + results = cursor.fetchone() + + # if result is not empty connection is alive + if results: + return db + # create new connection + else: + connectionDetails = databaseSetups[self.setup] + self.db = psycopg2.connect(host = connectionDetails[0], user = connectionDetails[1], password = connectionDetails[2], database = connectionDetails[3], port = connectionDetails[4]) + return self.db + + except: + # if an exception occurs during checking if database connection is still alive create a new connection; if it's not possible to connect to Datbase Server wait 120 sec and try to connect again + reConnect = True + while reConnect is True: + try: + connectionDetails = databaseSetups[self.setup] + self.db = psycopg2.connect(host = connectionDetails[0], user = connectionDetails[1], password = connectionDetails[2], database = connectionDetails[3], port = connectionDetails[4]) + reConnect = False + except: + time.sleep(120) + return self.db + + def closeConnection(self): + ''' + @summary: Closes connection to database + @author: JScelle + @version: 10.06.2013 + ''' + try: + self.db.close() + except: + # if closing of connection fails ignore it + pass + + def getValuesFromTable(self, sqlQueryStatement): + ''' + gets records from table + @param sqlQueryStatement: String, sql query statement e.g. "SELECT * FROM employee WHERE country = 'DE'" + @return: tuple of tuples + ''' + # get database connection from runTimeController + try: + db = self.db + except Exception as exc: + print("EXCEPTION: Module: Database, Function: getValuesFromTable, Error: Could not get database connection. ", str(exc.args)) + return ((),) + + #excecute sql statement + try: + # prepare a cursor object using cursor() method + cursor = db.cursor() + # Execute the SQL command + cursor.execute(sqlQueryStatement) + # Fetch all the rows in a list of lists. + results = cursor.fetchall() + db.commit() + return results + except Exception as exc: + # Rollback in case there is any error + db.rollback() + print("EXCEPTION: Module: Database, Function: getValuesFromTable, Error: Could not execute query. ", str(exc.args)) + return ((),) + + def runQuery(self, sqlStatement): + ''' + Executes any sql statement. For getting data from the database, please use the getValuesFromTable-method + @param sqlStatement: string. any sql statement e.g. Update, Delete + @return: Returns True if everything went good. + ''' + # get database connection from runTimeController + try: + db = self.db + except Exception as exc: + print("EXCEPTION: Module: Database, Function: runQuery, Error: Could not get database connection. ", str(exc.args)) + return False + + #excecute sql statement + try: + # prepare a cursor object using cursor() method + cursor = db.cursor() + # Execute the SQL command + cursor.execute(sqlStatement) + # Commit your changes in the Settings.database + db.commit() + return True + except Exception as exc: + # Rollback in case there is any error + db.rollback() + print("EXCEPTION: Module: Database, Function: runQuery, Error: Could not execute query. ", str(exc.args)) + return False + + def runMultipleQueries(self, sqlStatements): + """ + Executes multiple SQL-statements as one transaction + @param sqlStatements: List of strings. Each String is one SQL-statement + @return: Returns True if everything went good. + """ + # get database connection from runTimeController + try: + db = self.db + except Exception as exc: + print("EXCEPTION: Module: Database, Function: runMultipleQueries, Error: Could not get database connection. ", str(exc.args)) + return False + + # excecute sql statement + try: + # prepare a cursor object using cursor() method + cursor = db.cursor() + for sqlStatement in sqlStatements: + # Execute the SQL command + cursor.execute(sqlStatement) + # Commit your changes in the Settings.database + db.commit() + return True + except Exception as exc: + # Rollback in case there is any error + db.rollback() + print("EXCEPTION: Module: Database, Function: runMultipleQueries, Error: One of the queries could not be executed. ", str(exc.args)) + return False + + + def insertValuesIntoTable(self, tableName, fieldList, valueList): + """ + calls _executeInsertValuesIntoTable which inserts values into table + @param tableName: String, name of table + @param fieldList: List of string, list of field names e.g ,["firstName", "lastName"] + @param valueList: List of list, e.g [["Sebastian", "Stuetz"],["Ingo", "Tschach"]] + @return: Returns True if everything went good. + """ + try: + #define INSERT INTO part of sql query + insertIntoSqlPart = "INSERT INTO " + tableName + " (" + ",".join(fieldList) + ") VALUES" + #define ON DUPLICATE KEY part of sql query + onDuplicateKeyPart = " ON DUPLICATE KEY UPDATE " + for field in fieldList: + #replace old values with new values + onDuplicateKeyPart += str(field) + " = VALUES(" + str(field) + "), " + onDuplicateKeyPart = onDuplicateKeyPart[0:(len(onDuplicateKeyPart) - 2)] + + return self._executeInsertValuesIntoTable(fieldList, valueList, insertIntoSqlPart, onDuplicateKeyPart) + + except Exception as exc: + print("EXCEPTION: Module: Database, Function: insertValuesIntoTable, Error: Error when building the query frame. ", str(exc.args)) + return False + + + def _executeInsertValuesIntoTable(self, fieldList, valueList, insertIntoSqlPart, onDuplicateKeyPart): + ''' + inserts values into table + @param fieldList: List, list of field names e.g ,["firstName", "lastName"] + @param valueList: List of list, e.g [["Sebastian", "Stuetz"],["Ingo", "Tschach"]] + @return: Returns True if everything went good. + ''' + # get database connection from runTimeController + try: + db = self.db + except Exception as exc: + print("EXCEPTION: Module: Database, Function: _executeInsertValuesIntoTable, Error: Could not get database connection. ", str(exc.args)) + return False + + try: + # prepare a cursor object using cursor() method + cursor = db.cursor() + + #Insert data + #divide valueList into chunks to avoid that too big packets are send to sql server + maxPackets = 5000 + for i in range(0, len(valueList), maxPackets): + chunk = valueList[i:i + maxPackets] + #define data part of sql query (string consisting of "%s" for each field for each row) + dataSqlPart = ",".join(["(" + ",".join(["%s"] * len(fieldList)) + ")"] * len(chunk)) + #put sql parts together + sql = insertIntoSqlPart + dataSqlPart + onDuplicateKeyPart + #flatten data list + valueListChunk = tuple(itertools.chain(*chunk)) + #Insert values into DB + cursor.execute(sql, valueListChunk) + + # Commit your changes in the Settings.database + db.commit() + + return True + except Exception as exc: + # Rollback in case there is any error + db.rollback() + print("EXCEPTION: Module: Database, Function: _executeInsertValuesIntoTable, Error: Could not insert values. ", str(exc.args)) + return False + diff --git a/code/train/Python/0057969_loading.py b/code/train/Python/0057969_loading.py new file mode 100644 index 0000000000000000000000000000000000000000..c4931ca7a8d2181033b34563892390c787868e44 --- /dev/null +++ b/code/train/Python/0057969_loading.py @@ -0,0 +1,109 @@ +import sys +import traceback + +from django.conf import settings + + +class AppNotFoundError(Exception): + pass + + +class ClassNotFoundError(Exception): + pass + + +def get_class(module_label, classname): + return get_classes(module_label, [classname, ])[0] + + +def get_classes(module_label, classnames): + """ Imports a set of classes from a given module. + + Usage:: + + get_classes('forum.models', ['Forum', 'ForumReadTrack', ]) + + """ + app_label = module_label.split('.')[0] + + app_module_path = _get_app_module_path(module_label) + if not app_module_path: + raise AppNotFoundError('No app found matching \'{}\''.format(module_label)) + + # Determines the full module path by appending the module label + # to the base package path of the considered application. + module_path = app_module_path + if '.' in app_module_path: + base_package = app_module_path.rsplit('.' + app_label, 1)[0] + module_path = '{}.{}'.format(base_package, module_label) + + # Try to import this module from the related app that is specified + # in the Django settings. + local_imported_module = _import_module(module_path, classnames) + + # If the module we tried to import is not located inside the machina + # vanilla apps, try to import it from the corresponding machina app. + machina_imported_module = None + if not app_module_path.startswith('machina.apps'): + machina_imported_module = _import_module( + '{}.{}'.format('machina.apps', module_label), classnames, + ) + + if local_imported_module is None and machina_imported_module is None: + raise AppNotFoundError('Error importing \'{}\''.format(module_path)) + + # Any local module is prioritized over the corresponding machina module + imported_modules = [ + m for m in (local_imported_module, machina_imported_module) if m is not None + ] + return _pick_up_classes(imported_modules, classnames) + + +def _import_module(module_path, classnames): + """ Tries to import the given Python module path. """ + try: + imported_module = __import__(module_path, fromlist=classnames) + return imported_module + except ImportError: + # In case of an ImportError, the module being loaded generally does not exist. But an + # ImportError can occur if the module being loaded exists and another import located inside + # it failed. + # + # In order to provide a meaningfull traceback, the execution information can be inspected in + # order to determine which case to consider. If the execution information provides more than + # a certain amount of frames, this means that an ImportError occured while loading the + # initial Python module. + __, __, exc_traceback = sys.exc_info() + frames = traceback.extract_tb(exc_traceback) + if len(frames) > 1: + raise + + +def _pick_up_classes(modules, classnames): + """ Given a list of class names to retrieve, try to fetch them from the specified list of + modules and returns the list of the fetched classes. + """ + klasses = [] + for classname in classnames: + klass = None + for module in modules: + if hasattr(module, classname): + klass = getattr(module, classname) + break + if not klass: + raise ClassNotFoundError('Error fetching \'{}\' in {}'.format( + classname, str([module.__name__ for module in modules])) + ) + klasses.append(klass) + return klasses + + +def _get_app_module_path(module_label): + """ Given a module label, loop over the apps specified in the INSTALLED_APPS to find the + corresponding application module path. + """ + app_name = module_label.rsplit('.', 1)[0] + for app in settings.INSTALLED_APPS: + if app.endswith('.' + app_name) or app == app_name: + return app + return None diff --git a/code/train/Python/0058914_lists.py b/code/train/Python/0058914_lists.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe86b733e0b9eb26a3674588e0cc150b95a7d8c --- /dev/null +++ b/code/train/Python/0058914_lists.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python2.5 +# +# Copyright 2008 the Melange authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""List generation logic. +""" + +__authors__ = [ + '"Sverre Rabbelier" ', + ] + + +class Lists(object): + """List array suitable for enumerating over with just 'for in'. + """ + + DEF_PASSTHROUGH_FIELDS = [ + 'pagination', + 'pagination_form', + 'description', + 'export', + 'heading', + 'row', + 'limit', + 'newest', + 'prev', + 'next', + 'first', + 'last', + 'idx', + ] + + def __init__(self, contents): + """Constructs a new Lists object with the specified contents. + """ + + # All the contents of all the lists + self._contents = contents + self._content = {} + + # For iterating over all the lists + self._lists = range(len(contents)) + + def __getattr__(self, attr): + """Delegate field lookup to the current list if appropriate. + + If, and only if, a lookup is done on one of the fields defined in + DEF_PASSTHROUGH_FIELDS, and the current list defines this field, + the value from the current list is returned. + """ + + if attr not in self.DEF_PASSTHROUGH_FIELDS: + raise AttributeError() + + if attr not in self._content: + raise AttributeError() + + return self.get(attr) + + def get(self, item): + """Returns the item for the current list data. + """ + + return self._content[item] + + def nextList(self): + """Shifts out the current list content. + + The main content of the next list is returned for further processing. + """ + + # Advance the list data once + self._content = self._contents[0] + self._contents = self._contents[1:] + + return self + + def empty(self): + """Returns true iff there are no lists + """ + + return not self._lists + + def lists(self): + """Returns a list of numbers the size of the amount of lists. + + This method can be used to iterate over all lists with shift, + without using a while loop. + """ + + return self._lists diff --git a/code/train/Python/0059093_path.py b/code/train/Python/0059093_path.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2ac6c40ad4ab8d45e5cf06ba54f2d8fabeb3e8 --- /dev/null +++ b/code/train/Python/0059093_path.py @@ -0,0 +1,89 @@ +#!/usr/env python +from math import sqrt +import pygame +class Path: + def __init__(self,points=None,filename=None): + self.points=[] + if points is not None: + for px,py in points: + self.points.append((float(px),float(py))) + self.calcLength() + if filename is not None: + self.load(filename) + def calcLength(self): + lastpoint=None + dist=0.0 + ptotal=[0.0] + for point in self.points: + if lastpoint is not None: + dx=point[0]-lastpoint[0] + dy=point[1]-lastpoint[1] + dist+=sqrt(dx*dx + dy*dy) + ptotal.append(dist) + lastpoint=point + + self.length=dist + self.ptotal=ptotal + def getLength(self): + return self.length + + def setPoints(self,pointlist): + self.points=[] + for a,b in pointlist: + self.points.append((float(a),float(b))) + self.calcLength() + def load(self,filename): + self.points=[] + for line in open(filename,'r'): + a,b=line.strip().split(' ') + pf=(float(a),float(b)) + self.points.append(pf) + self.calcLength() + def render(self,size,palette=None,drawlines=True,drawpoints=True,pointsize=2): + surf=pygame.Surface(size,0,8) + if palette is not None: + surf.set_palette(palette) + bg=12 + linecolor=16 + pointcolor=68 + else: + surf.set_palette([(255,255,255),(0,0,0),(127,127,127)]) + bg=0 + linecolor=1 + pointcolor=2 + surf.fill(bg) + if drawlines: + lastpoint=None + for point in self.points: + px=point[0]*size[0] + py=point[1]*size[1] + if lastpoint is not None: + pygame.draw.line(surf,linecolor,lastpoint,(px,py)) + lastpoint=(px,py) + if drawpoints: + for point in self.points: + px=point[0]*size[0] + py=point[1]*size[1] + surf.fill(pointcolor,(px-pointsize,py-pointsize,pointsize*2,pointsize*2)) + return surf + def getPointByPercent(self,amt): + return self.getPointByDist((amt/100.0)*(self.getLength())) + def getPointByDist(self,dist): + fi=None + fidist=None + for i,pdist in enumerate(self.ptotal): + if pdist<=dist and self.ptotal[i+1]>=dist: + fi=i + fidist=pdist + break + if fi is None: return None + p1=self.points[fi] + p2=self.points[fi+1] + pdx=p1[0]-p2[0] + pdy=p1[1]-p2[1] + ldist=sqrt(pdx*pdx + pdy*pdy) + adist=dist-fidist + amt=(adist/float(ldist)) + x=p1[0]*(1-amt) + p2[0]*amt + y=p1[1]*(1-amt) + p2[1]*amt + return (x,y) diff --git a/code/train/Python/0059516_ranzhi_advanced_tests.py b/code/train/Python/0059516_ranzhi_advanced_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..03e2b6578cb93a15c54c7779242ec1f57f2ab51c --- /dev/null +++ b/code/train/Python/0059516_ranzhi_advanced_tests.py @@ -0,0 +1,95 @@ +import csv +import unittest + +from box_driver import BoxDriver +from ranzhi_common import RanzhiCommon + + +class RanzhiAdvancedTests(unittest.TestCase): + """ + 测试主页 + 1. 测试登录 + 2. 测试语言 + """ + + # 成员变量 + base_driver = None + base_url = None + common = None + + def setUp(self): + """ + 前置条件 + :return: + """ + profile = "C:/python35/chromedriver.exe" + + self.base_driver = BoxDriver(",", profile, "chrome") + self.base_driver.clear_cookies() + self.base_url = "http://localhost/" + self.common = RanzhiCommon(self.base_driver, self.base_url) + + def tearDown(self): + """ + 测试清理 + :return: + """ + self.base_driver.quit() + + def test_add_member_by_csv(self): + """ + 测试 添加多个用户 + 从CSV文件读取数据,并添加到系统各种 + :return: + """ + common = self.common + driver = self.base_driver + + csv_file = open("member_list_with_header.csv", "r", + encoding="utf8") + csv_data = csv.reader(csv_file) + + is_header = True + for row in csv_data: + if is_header: + is_header = False + continue + + lang = "zh_CN" + common.open_page("") + common.change_language(lang) + common.log_in("admin", "123456") + common.select_admin_app() + expected_url = self.base_url + "sys/admin/" + self.assertEqual(expected_url, driver.get_url(), + "后台管理按钮点击后页面跳转失败!") + + common.click_add_member_button() + + expected_url = self.base_url + "sys/user-create.html" + self.assertEqual(expected_url, driver.get_url(), + "添加成员按钮点击后页面跳转失败!") + + # dict 类型的数据 + member_data = { + "account": row[0], + "real_name": row[1], + "gender": row[2], + "dept": row[3], + "role": row[4], + "password": row[5], + "email": row[6] + } + common.add_member_data(member_data) + expected_url = self.base_url + "sys/user-admin.html" + self.assertEqual(expected_url, driver.get_url(), + "添加成员保存失败!") + + common.log_out(lang) + common.open_page("") + common.log_in(member_data["account"], member_data["password"]) + expected_url = self.base_url + "sys/index.html" + self.assertEqual(expected_url, driver.get_url(), + "新用户登录失败!") + common.log_out(lang) + csv_file.close() diff --git a/code/train/Python/0060131_plot_hyperparameter.py b/code/train/Python/0060131_plot_hyperparameter.py new file mode 100644 index 0000000000000000000000000000000000000000..b77da21844aa6e71a760b5e23527eee29fa4e518 --- /dev/null +++ b/code/train/Python/0060131_plot_hyperparameter.py @@ -0,0 +1,178 @@ +""" +Simple Parallel Model Selection +=============================== + +In this example, we'll demonstrate how to quickly write a hyperparameter +tuning script that evaluates a set of hyperparameters in parallel. + +This script will demonstrate how to use two important parts of the Ray API: +using ``ray.remote`` to define remote functions and ``ray.wait`` to wait for +their results to be ready. + +.. important:: For a production-grade implementation of distributed + hyperparameter tuning, use `Tune`_, a scalable hyperparameter + tuning library built using Ray's Actor API. + +.. _`Tune`: https://ray.readthedocs.io/en/latest/tune.html +""" +import os +import numpy as np +from filelock import FileLock + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.optim as optim +from torchvision import datasets, transforms + +import ray + +ray.init() + +# The number of sets of random hyperparameters to try. +num_evaluations = 10 + + +# A function for generating random hyperparameters. +def generate_hyperparameters(): + return { + "learning_rate": 10**np.random.uniform(-5, 1), + "batch_size": np.random.randint(1, 100), + "momentum": np.random.uniform(0, 1) + } + + +def get_data_loaders(batch_size): + mnist_transforms = transforms.Compose( + [transforms.ToTensor(), + transforms.Normalize((0.1307, ), (0.3081, ))]) + + # We add FileLock here because multiple workers will want to + # download data, and this may cause overwrites since + # DataLoader is not threadsafe. + with FileLock(os.path.expanduser("~/data.lock")): + train_loader = torch.utils.data.DataLoader( + datasets.MNIST( + "~/data", + train=True, + download=True, + transform=mnist_transforms), + batch_size=batch_size, + shuffle=True) + test_loader = torch.utils.data.DataLoader( + datasets.MNIST("~/data", train=False, transform=mnist_transforms), + batch_size=batch_size, + shuffle=True) + return train_loader, test_loader + + +class ConvNet(nn.Module): + """Simple two layer Convolutional Neural Network.""" + + def __init__(self): + super(ConvNet, self).__init__() + self.conv1 = nn.Conv2d(1, 3, kernel_size=3) + self.fc = nn.Linear(192, 10) + + def forward(self, x): + x = F.relu(F.max_pool2d(self.conv1(x), 3)) + x = x.view(-1, 192) + x = self.fc(x) + return F.log_softmax(x, dim=1) + + +def train(model, optimizer, train_loader, device=torch.device("cpu")): + """Optimize the model with one pass over the data. + + Cuts off at 1024 samples to simplify training. + """ + model.train() + for batch_idx, (data, target) in enumerate(train_loader): + if batch_idx * len(data) > 1024: + return + data, target = data.to(device), target.to(device) + optimizer.zero_grad() + output = model(data) + loss = F.nll_loss(output, target) + loss.backward() + optimizer.step() + + +def test(model, test_loader, device=torch.device("cpu")): + """Checks the validation accuracy of the model. + + Cuts off at 512 samples for simplicity. + """ + model.eval() + correct = 0 + total = 0 + with torch.no_grad(): + for batch_idx, (data, target) in enumerate(test_loader): + if batch_idx * len(data) > 512: + break + data, target = data.to(device), target.to(device) + outputs = model(data) + _, predicted = torch.max(outputs.data, 1) + total += target.size(0) + correct += (predicted == target).sum().item() + + return correct / total + + +@ray.remote +def evaluate_hyperparameters(config): + model = ConvNet() + train_loader, test_loader = get_data_loaders(config["batch_size"]) + optimizer = optim.SGD( + model.parameters(), + lr=config["learning_rate"], + momentum=config["momentum"]) + train(model, optimizer, train_loader) + return test(model, test_loader) + + +# Keep track of the best hyperparameters and the best accuracy. +best_hyperparameters = None +best_accuracy = 0 +# A list holding the object IDs for all of the experiments that we have +# launched but have not yet been processed. +remaining_ids = [] +# A dictionary mapping an experiment's object ID to its hyperparameters. +# hyerparameters used for that experiment. +hyperparameters_mapping = {} + +# Randomly generate sets of hyperparameters and launch a task to test each set. +for i in range(num_evaluations): + hyperparameters = generate_hyperparameters() + accuracy_id = evaluate_hyperparameters.remote(hyperparameters) + remaining_ids.append(accuracy_id) + hyperparameters_mapping[accuracy_id] = hyperparameters + +# Fetch and print the results of the tasks in the order that they complete. +while remaining_ids: + # Use ray.wait to get the object ID of the first task that completes. + done_ids, remaining_ids = ray.wait(remaining_ids) + # There is only one return result by default. + result_id = done_ids[0] + + hyperparameters = hyperparameters_mapping[result_id] + accuracy = ray.get(result_id) + print("""We achieve accuracy {:.3}% with + learning_rate: {:.2} + batch_size: {} + momentum: {:.2} + """.format(100 * accuracy, hyperparameters["learning_rate"], + hyperparameters["batch_size"], hyperparameters["momentum"])) + if accuracy > best_accuracy: + best_hyperparameters = hyperparameters + best_accuracy = accuracy + +# Record the best performing set of hyperparameters. +print("""Best accuracy over {} trials was {:.3} with + learning_rate: {:.2} + batch_size: {} + momentum: {:.2} + """.format(num_evaluations, 100 * best_accuracy, + best_hyperparameters["learning_rate"], + best_hyperparameters["batch_size"], + best_hyperparameters["momentum"])) diff --git a/code/train/Python/0060499_market_origin.py b/code/train/Python/0060499_market_origin.py new file mode 100644 index 0000000000000000000000000000000000000000..55a9bf7b18622ff60f7bce902ab2b4835720ef7a --- /dev/null +++ b/code/train/Python/0060499_market_origin.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- + +import logging +import time + +import requests + +from quant import config + + +class Market(object): + def __init__(self, base_currency, market_currency, pair_code, fee_rate): + self._name = None + self.base_currency = base_currency + self.market_currency = market_currency + self.pair_code = pair_code + self.fee_rate = fee_rate + + self.depth_updated = 0 + self.update_rate = 3 + + self.is_terminated = False + self.request_timeout = 5 # 5s + self.depth = {'asks': [{'price': 0, 'amount': 0}], 'bids': [ + {'price': 0, 'amount': 0}]} + + def request_get(self, url): + try: + resp = requests.get(url, timeout=self.request_timeout) + except requests.exceptions.RequestException as e: + logging.debug("get %s failed: " % url + str(e)) + else: + if resp.status_code == requests.codes.ok: + return resp.json() + + @property + def name(self): + return self._name + + @name.setter + def name(self, value): + self._name = value + + def terminate(self): + self.is_terminated = True + + def get_depth(self): + time_diff = time.time() - self.depth_updated + # logging.warn('Market: %s order book1:(%s>%s)', self.name, time_diff, self.depth_updated) + if time_diff > self.update_rate: + logging.debug('%s should update...', self.name) + if not self.ask_update_depth(): + return None + + time_diff = time.time() - self.depth_updated + # logging.warn('Market: %s order book2:(%s>%s)', self.name, time_diff, self.depth_updated) + + if time_diff > config.market_expiration_time: + # logging.warn('Market: %s order book is expired(%s>%s)', self.name, timediff, + # config.market_expiration_time) + return None + return self.depth + + def ask_update_depth(self): + try: + self.update_depth() + # self.convert_to_usd() + self.depth_updated = time.time() + return True + except Exception as e: + logging.error("Can't update market: %s - err:%s" % (self.name, str(e))) + # log_exception(logging.DEBUG) + return False + # traceback.print_exc() + + def get_ticker(self): + depth = self.get_depth() + if not depth: + return None + + res = {'ask': {'price': 0, 'amount': 0}, 'bid': {'price': 0, 'amount': 0}} + + if len(depth['asks']) > 0: + res['ask'] = depth['asks'][0] + if len(depth["bids"]) > 0: + res['bid'] = depth['bids'][0] + return res + + def update_depth(self): + """子类重写该方法,每个market的数据不一样""" + pass diff --git a/code/train/Python/0060919_base.py b/code/train/Python/0060919_base.py new file mode 100644 index 0000000000000000000000000000000000000000..302b45172fa8b2ad6e28a64e88174e6cc03c6005 --- /dev/null +++ b/code/train/Python/0060919_base.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python +# +# vim: tabstop=4 shiftwidth=4 + +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation; only version 2 of the License is applicable. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# +# Authors: +# Ricardo Rocha +# +# About this plugin: +# Helper object for all plugins. +# +# collectd: +# http://collectd.org +# collectd-python: +# http://collectd.org/documentation/manpages/collectd-python.5.shtml +# + +import collectd +import datetime +import traceback +import socket +import json +import struct +import re + +from ceph_argparse import parse_json_funcsigs, validate_command + + +class Base(object): + + def __init__(self): + self.verbose = False + self.debug = False + self.prefix = '' + self.cluster = 'ceph' + self.testpool = 'test' + self.interval = 60.0 + + def config_callback(self, conf): + """Takes a collectd conf object and fills in the local config.""" + for node in conf.children: + if node.key == "Verbose": + if node.values[0] in ['True', 'true']: + self.verbose = True + elif node.key == "Debug": + if node.values[0] in ['True', 'true']: + self.debug = True + elif node.key == "Prefix": + self.prefix = node.values[0] + elif node.key == 'Cluster': + self.cluster = node.values[0] + elif node.key == 'TestPool': + self.testpool = node.values[0] + elif node.key == 'Interval': + self.interval = float(node.values[0]) + else: + collectd.warning("%s: unknown config key: %s" % (self.prefix, node.key)) + + def dispatch(self, stats): + """ + Dispatches the given stats. + + stats should be something like: + + {'plugin': {'plugin_instance': {'type': {'type_instance': , ...}}}} + """ + if not stats: + collectd.error("%s: failed to retrieve stats" % self.prefix) + return + + self.logdebug("dispatching %d new stats :: %s" % (len(stats), stats)) + try: + for plugin in stats.keys(): + for plugin_instance in stats[plugin].keys(): + for type in stats[plugin][plugin_instance].keys(): + type_value = stats[plugin][plugin_instance][type] + if not isinstance(type_value, dict): + self.dispatch_value(plugin, plugin_instance, type, None, type_value) + else: + for type_instance in stats[plugin][plugin_instance][type].keys(): + self.dispatch_value(plugin, plugin_instance, + type, type_instance, + stats[plugin][plugin_instance][type][type_instance]) + except Exception as exc: + collectd.error("%s: failed to dispatch values :: %s :: %s" + % (self.prefix, exc, traceback.format_exc())) + + def dispatch_value(self, plugin, plugin_instance, type, type_instance, value): + """Looks for the given stat in stats, and dispatches it""" + self.logdebug("dispatching value %s.%s.%s.%s=%s" + % (plugin, plugin_instance, type, type_instance, value)) + + val = collectd.Values(type='gauge') + val.plugin=plugin + val.plugin_instance=plugin_instance + if type_instance is not None: + val.type_instance="%s-%s" % (type, type_instance) +# val.type_instance = "%s" % type_instance + else: + val.type_instance=type + val.values=[value] + val.interval = self.interval + val.dispatch() + self.logdebug("sent metric %s.%s.%s.%s.%s" + % (plugin, plugin_instance, type, type_instance, value)) + + # + # From /usr/bin/ceph: do socket IO against a ceph admin socket + # + # We copy / paste the code instead of just invoking /usr/bin/ceph to prevent a python interpreter start everytime + # + def admin_socket(self, asok_path, cmd, format=''): + """ + Send a daemon (--admin-daemon) command 'cmd'. asok_path is the + path to the admin socket; cmd is a list of strings; format may be + set to one of the formatted forms to get output in that form + (daemon commands don't support 'plain' output). + """ + + def do_sockio(path, cmd): + """ helper: do all the actual low-level stream I/O """ + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.connect(path) + try: + sock.sendall(cmd + '\0') + len_str = sock.recv(4) + if len(len_str) < 4: + raise RuntimeError("no data returned from admin socket") + l, = struct.unpack(">I", len_str) + ret = '' + + got = 0 + while got < l: + bit = sock.recv(l - got) + ret += bit + got += len(bit) + + except Exception as e: + raise RuntimeError('exception: ' + str(e)) + return ret + + try: + cmd_json = do_sockio(asok_path, + json.dumps({"prefix":"get_command_descriptions"})) + except Exception as e: + raise RuntimeError('exception getting command descriptions: ' + str(e)) + + if cmd == 'get_command_descriptions': + return cmd_json + + sigdict = parse_json_funcsigs(cmd_json, 'cli') + valid_dict = validate_command(sigdict, cmd) + if not valid_dict: + raise RuntimeError('invalid command') + + if format: + valid_dict['format'] = format + + try: + ret = do_sockio(asok_path, json.dumps(valid_dict)) + except Exception as e: + raise RuntimeError('exception: ' + str(e)) + + return ret + + def copy_stats(self, source_hash, selection): + """ + Copy stats from source_hash to target_hash based on applying the selection regex against the names + in the hash at the root level on the source hash. + + Additonally, the following transformations are applied: + + - For stat names ending in latency and referencing a hash the latency is calculated and substitutes + the hash in the target hash + """ + + target_hash = {} + + for key in source_hash.keys(): + + stat_name = key + stat_value = source_hash[key] + +# print 'Checking stat "%s"' % stat_name + + if not re.match(r'%s' % selection, stat_name): + # Ignore not selected stats + continue + + # Process latency + if isinstance(stat_value, dict): + lat_sum = float(stat_value['sum']) + lat_avgcount = float(stat_value['avgcount']) + if lat_avgcount == 0: + target_hash[stat_name] = 0 + else: + target_hash[stat_name] = lat_sum / lat_avgcount + continue + + # Process simple stats + target_hash[stat_name] = stat_value + + return target_hash + + def read_callback(self): + try: + start = datetime.datetime.now() + stats = self.get_stats() + self.logverbose("collectd new data from service :: took %d seconds" + % (datetime.datetime.now() - start).seconds) + except Exception as exc: + collectd.error("%s: failed to get stats :: %s :: %s" + % (self.prefix, exc, traceback.format_exc())) + self.dispatch(stats) + + def get_stats(self): + collectd.error('Not implemented, should be subclassed') + + def logverbose(self, msg): + if self.verbose: + collectd.info("%s: %s" % (self.prefix, msg)) + + def logdebug(self, msg): + if self.debug: + collectd.info("%s: %s" % (self.prefix, msg)) + diff --git a/code/train/Python/0061284_answer.py b/code/train/Python/0061284_answer.py new file mode 100644 index 0000000000000000000000000000000000000000..79e9c6f470ac5e647f8825af1671b4029e26d0b0 --- /dev/null +++ b/code/train/Python/0061284_answer.py @@ -0,0 +1,48 @@ +#!/usr/bin/python + +class Solution(object): + def lengthOfLongestSubstring(self, s): + """ + :type s: str + :rtype: int + """ + + length = 0 + i = 0 + j = 0 + substring = set() + while i < len(s) and j < len(s): + if not s[i] in substring: + substring.add(s[i]) + i += 1 + length = max(length, i - j) + else: + substring.remove(s[j]) + j += 1 + return length +#------------------------------------------------------------------------------- +# Optimized o(n) solution + +class Optimized(object): + def lengthOfLongestSubstring(self, s): + length = 0 + i = 0 + j = 0 + dict = {} + for j in range (0, len(s)): + if s[j] in dict: + i = max(dict[s[j]], i) + length = max(length, j - i + 1) + dict[s[j]] = j + 1 + + return length + +#------------------------------------------------------------------------------- +#Testing + +def main(): + x = Optimized() + y = x.lengthOfLongestSubstring("abcdedfffqwertyuioplkjtksladnf") + print y + +main() diff --git a/code/train/Python/0062850_hmi.py b/code/train/Python/0062850_hmi.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd047488b53aa21fba0cb57171b7d9686edda7e --- /dev/null +++ b/code/train/Python/0062850_hmi.py @@ -0,0 +1,281 @@ +# (c) 2015,2016 - Jaguar Land Rover. +# +# Mozilla Public License 2.0 +# +# Python-based hmi PoC for Software Loading Manager +# + +import gtk +import dbus +import dbus.service +from dbus.mainloop.glib import DBusGMainLoop +import time +import threading +import code, signal +import traceback +import swm +from termios import tcflush, TCIOFLUSH +import settings +import sys +import os +import getopt +import daemon + + +class DisplayProgress(threading.Thread): + + def __init__(self, *arg): + super(DisplayProgress, self).__init__(*arg) + self.in_progress = True + self.update_description = None + self.update_start_time = None + self.update_stop_time = None + self.operation_hmi_message = None + self.operation_start_time = None + self.operation_stop_time = None + + def set_manifest(self, description, start_time, stop_time): + self.update_description = description + self.update_start_time = start_time + self.update_stop_time = stop_time + + + def set_operation(self, hmi_message, start_time, stop_time): + self.operation_hmi_message = hmi_message + self.operation_start_time = start_time + self.operation_stop_time = stop_time + + + def exit_thread(self): + self.in_progress = False + self.join() + + def run(self): + while self.in_progress: + if not self.update_description: + time.sleep(0.5) + continue + + time.sleep(0.1) + + + ct = time.time() + if self.update_stop_time >= ct: + completion = (self.update_stop_time - ct) / (self.update_stop_time - self.update_start_time) + else: + completion = 0.0 + + print "\033[HUpdate: {}\033[K".format(self.update_description) + + print "{}{}\033[K".format("+"*int(60.0 - completion*60), "-"*int(completion*60)) + + + # If no operation is in progress, clear sreen + if not self.operation_start_time: + continue + + if self.update_stop_time >= ct: + completion = (self.operation_stop_time - ct) / (self.operation_stop_time - self.operation_start_time) + else: + completion = 0.0 + + print "\nOperation: {}\033[K".format(self.operation_hmi_message) + print "{}{}".format("+"*int(60.0 - completion*60), "-"*int(completion*60)) + print "\033[J" + +# +# Human Machine Interface Service +# +class HMIService(dbus.service.Object): + def __init__(self): + bus_name = dbus.service.BusName('org.genivi.Hmi', + bus=dbus.SessionBus()) + + dbus.service.Object.__init__(self, bus_name, '/org/genivi/Hmi') + self.progress_thread = DisplayProgress() + self.progress_thread.start() + + + @dbus.service.method('org.genivi.Hmi', + async_callbacks=('send_reply', 'send_error')) + def updateNotification(self, + update_id, + description, + send_reply, + send_error): + + try: + print "HMI: updateNotification()" + print " ID: {}".format(update_id) + print " description: {}".format(description) + print "---" + + # + # Send back an async reply to the invoking SoftwareLoadingManager + # so that we can continue with user interaction without + # risking a DBUS timeout + # + send_reply(True) + + print + print + print "DIALOG:" + print "DIALOG: UPDATE AVAILABLE" + print "DIALOG: update_id: {}".format(update_id) + print "DIALOG: Description: {}".format(description) + print "DIALOG:" + print "DIALOG: Process? (yes/no)" + + # If we use input or raw_input, the whole dbus loop hangs after + # this method returns, for some reason. + tcflush(sys.stdin, TCIOFLUSH) + resp = sys.stdin.read(1) + tcflush(sys.stdin, TCIOFLUSH) + + # resp = raw_input("DIALOG: Process? (yes/no): ") + print + + if len(resp) == 0 or (resp[0] != 'y' and resp[0] != 'Y'): + approved = False + else: + approved = True + + # + # Call SoftwareLoadingManager.package_confirmation() + # to inform it of user approval / decline. + # + swm.dbus_method('org.genivi.SoftwareLoadingManager','updateConfirmation', update_id, approved) + + except Exception as e: + print "Exception: {}".format(e) + traceback.print_exc() + + return None + + + @dbus.service.method('org.genivi.Hmi', + async_callbacks=('send_reply', 'send_error')) + def manifestStarted(self, + update_id, + total_time_estimate, + description, + send_reply, + send_error): + try: + print "Manifest started" + send_reply(True) + print "\033[H\033[J" + ct = time.time() + self.progress_thread.set_manifest(description, + ct, + ct + float(total_time_estimate) / 1000.0) + + except Exception as e: + print "Exception: {}".format(e) + traceback.print_exc() + + return None + + @dbus.service.method('org.genivi.Hmi', + async_callbacks=('send_reply', 'send_error')) + def operationStarted(self, + operation_id, + time_estimate, + description, + send_reply, + send_error): + + try: + print "Op started" + send_reply(True) + ct = time.time() + self.progress_thread.set_operation(description, ct, ct + float(time_estimate) / 1000.0) + except Exception as e: + print "Exception: {}".format(e) + traceback.print_exc() + return None + + @dbus.service.method('org.genivi.Hmi', + async_callbacks=('send_reply', 'send_error')) + def updateReport(self, + update_id, + results, + send_reply, + send_error): + try: + send_reply(True) + self.progress_thread.exit_thread() + print "Update report" + print " ID: {}".format(update_id) + print " results:" + for result in results: + print " operation_id: {}".format(result['id']) + print " code: {}".format(result['result_code']) + print " text: {}".format(result['result_text']) + print " ---" + print "---" + except Exception as e: + print "Exception: {}".format(e) + traceback.print_exc() + return None + +class HMIDaemon(daemon.Daemon): + """ + """ + + def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): + super(HMIDaemon, self).__init__(pidfile, stdin, stdout, stderr) + + def run(self): + gtk.gdk.threads_init() + DBusGMainLoop(set_as_default=True) + hmi = HMIService() + while True: + gtk.main_iteration() + + +def usage(): + print "Usage:", sys.argv[0], "foreground|start|stop|restart" + print + print " foreground Start in foreground" + print " start Start in background" + print " stop Stop daemon running in background" + print " restart Restart daemon running in background" + print + print "Example:", sys.argv[0],"foreground" + sys.exit(1) + + +if __name__ == "__main__": + print "HMI Simulator - Initializing" + pid_file = settings.PID_FILE_DIR + os.path.splitext(os.path.basename(__file__))[0] + '.pid' + + try: + opts, args = getopt.getopt(sys.argv[1:], "") + except getopt.GetoptError: + print "HMI Simulator - Could not parse arguments." + usage() + + + for a in args: + if a in ('foreground', 'fg'): + print "HMI Simulator - Running" + print "Please enter package installation approval when prompted" + hmi_daemon = HMIDaemon(pid_file, stdin='/dev/stdin', stdout='/dev/stdout', stderr='/dev/stderr') + hmi_daemon.run() + elif a in ('start', 'st'): + print "HMI Simulator - Starting" + hmi_daemon = HMIDaemon(pid_file, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null') + hmi_daemon.start() + elif a in ('stop', 'sp'): + print "HMI Simulator - Stopping" + hmi_daemon = HMIDaemon(pid_file, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null') + hmi_daemon.stop() + elif a in ('restart', 're'): + print "HMI Simulator - Restarting" + hmi_daemon = HMIDaemon(pid_file, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null') + hmi_daemon.restart() + else: + print "Unknown command: {}".format(a) + usage() + sys.exit(1) diff --git a/code/train/Python/0062944_rnnlm-batch.py b/code/train/Python/0062944_rnnlm-batch.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e8457cd1e84722ff32e95f31ec4a86d60400f1 --- /dev/null +++ b/code/train/Python/0062944_rnnlm-batch.py @@ -0,0 +1,148 @@ +from dynet import * +import time +import random + +LAYERS = 2 +INPUT_DIM = 256 #50 #256 +HIDDEN_DIM = 256 # 50 #1024 +VOCAB_SIZE = 0 +MB_SIZE = 50 # mini batch size + +import argparse +from collections import defaultdict +from itertools import count +import sys +import util + +class RNNLanguageModel: + def __init__(self, model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOCAB_SIZE, builder=SimpleRNNBuilder): + # Char-level LSTM (layers=2, input=256, hidden=128, model) + self.builder = builder(LAYERS, INPUT_DIM, HIDDEN_DIM, model) + # Lookup parameters for word embeddings + self.lookup = model.add_lookup_parameters((VOCAB_SIZE, INPUT_DIM)) + # Softmax weights/biases on top of LSTM outputs + self.R = model.add_parameters((VOCAB_SIZE, HIDDEN_DIM)) + self.bias = model.add_parameters((VOCAB_SIZE)) + + # Build the language model graph + def BuildLMGraph(self, sents): + renew_cg() + # initialize the RNN + init_state = self.builder.initial_state() + # parameters -> expressions + R = parameter(self.R) + bias = parameter(self.bias) + + S = vocab.w2i[""] + # get the cids and masks for each step + tot_chars = 0 + cids = [] + masks = [] + + for i in range(len(sents[0])): + cids.append([(vocab.w2i[sent[i]] if len(sent) > i else S) for sent in sents]) + mask = [(1 if len(sent)>i else 0) for sent in sents] + masks.append(mask) + tot_chars += sum(mask) + + # start the rnn with "" + init_ids = cids[0] + s = init_state.add_input(lookup_batch(self.lookup, init_ids)) + + losses = [] + + # feed char vectors into the RNN and predict the next char + for cid, mask in zip(cids[1:], masks[1:]): + score = affine_transform([bias, R, s.output()]) + loss = pickneglogsoftmax_batch(score, cid) + # mask the loss if at least one sentence is shorter + if mask[-1] != 1: + mask_expr = inputVector(mask) + mask_expr = reshape(mask_expr, (1,), len(sents)) + loss = loss * mask_expr + + losses.append(loss) + # update the state of the RNN + cemb = lookup_batch(self.lookup, cid) + s = s.add_input(cemb) + + return sum_batches(esum(losses)), tot_chars + + + def sample(self, first=1, nchars=0, stop=-1): + res = [first] + renew_cg() + state = self.builder.initial_state() + + R = parameter(self.R) + bias = parameter(self.bias) + cw = first + while True: + x_t = lookup(self.lookup, cw) + state = state.add_input(x_t) + y_t = state.output() + r_t = bias + (R * y_t) + ydist = softmax(r_t) + dist = ydist.vec_value() + rnd = random.random() + for i,p in enumerate(dist): + rnd -= p + if rnd <= 0: break + res.append(i) + cw = i + if cw == stop: break + if nchars and len(res) > nchars: break + return res + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('corpus', help='Path to the corpus file.') + args = parser.parse_args() + + train = util.CharsCorpusReader(args.corpus, begin="") + vocab = util.Vocab.from_corpus(train) + + VOCAB_SIZE = vocab.size() + + model = Model() + sgd = SimpleSGDTrainer(model) + + #lm = RNNLanguageModel(model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOCAB_SIZE, builder=SimpleRNNBuilder) + lm = RNNLanguageModel(model, LAYERS, INPUT_DIM, HIDDEN_DIM, VOCAB_SIZE, builder=LSTMBuilder) + + train = list(train) + # Sort training sentences in descending order and count minibatches + train.sort(key=lambda x: -len(x)) + train_order = [x*MB_SIZE for x in range(int((len(train)-1)/MB_SIZE + 1))] + + # Perform training + i = 0 + chars = loss = 0.0 + for ITER in range(100): + random.shuffle(train_order) + #_start = time.time() + for sid in train_order: + i += 1 + #if i % int(50) == 0: + sgd.status() + if chars > 0: print(loss / chars,) + for _ in range(1): + samp = lm.sample(first=vocab.w2i[""],stop=vocab.w2i["\n"]) + print("".join([vocab.i2w[c] for c in samp]).strip()) + loss = 0.0 + chars = 0.0 + + # train on the minibatch + errs, mb_chars = lm.BuildLMGraph(train[sid: sid + MB_SIZE]) + loss += errs.scalar_value() + chars += mb_chars + errs.backward() + sgd.update() + + + #print "TM:",(time.time() - _start)/chars + print("ITER",ITER,loss) + #print(loss / chars,) + #print "TM:",(time.time() - _start)/len(train) + sgd.status() + sgd.update_epoch(1.0) diff --git a/code/train/Python/0063615_init__.py b/code/train/Python/0063615_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5100889ff24598896d1da4283f268f0c8681589 --- /dev/null +++ b/code/train/Python/0063615_init__.py @@ -0,0 +1,165 @@ +import json +import asyncio +from pitcrew import task +from uuid import uuid4 + + +class DeployPitcrew(task.BaseTask): + """This example builds and deploys pitcrew.io. It uses s3, cloudfront and acm to deploy + this website using ssl. """ + + async def run(self): + # make sure the build requirements are installed + await self.sh("pip install -r requirements-build.txt") + # create the bucket + await self.sh("aws s3api create-bucket --bucket pitcrew-site") + # setup aws & build + upload site + await asyncio.gather(self.setup_aws(), self.build_and_sync()) + + async def setup_aws(self): + # first find the zone + zones = json.loads(await self.sh("aws route53 list-hosted-zones"))[ + "HostedZones" + ] + zone_id = None + for zone in zones: + if zone["Name"] == "pitcrew.io.": + zone_id = zone["Id"] + break + + assert zone_id, "no zone_id found for pitcrew.io" + + # setup the certificate + cert_arn = await self.setup_acm(zone_id) + # setup the CDN + cf_id = await self.setup_cloudfront(zone_id, cert_arn) + dist = json.loads( + await self.sh(f"aws cloudfront get-distribution --id {self.esc(cf_id)}") + )["Distribution"] + domain_name = dist["DomainName"] + + # add the DNS records + await self.ensure.aws.route53.has_records( + zone_id, + [ + { + "Name": "pitcrew.io.", + "Type": "A", + "AliasTarget": { + "HostedZoneId": "Z2FDTNDATAQYW2", + "DNSName": f"{domain_name}.", + "EvaluateTargetHealth": False, + }, + }, + { + "Name": "pitcrew.io.", + "Type": "AAAA", + "AliasTarget": { + "HostedZoneId": "Z2FDTNDATAQYW2", + "DNSName": f"{domain_name}.", + "EvaluateTargetHealth": False, + }, + }, + { + "Name": "www.pitcrew.io.", + "Type": "CNAME", + "TTL": 300, + "ResourceRecords": [{"Value": domain_name}], + }, + ], + ) + + async def setup_acm(self, zone_id) -> str: + # look for the certificate + certs = json.loads( + await self.sh("aws acm list-certificates --certificate-statuses ISSUED") + )["CertificateSummaryList"] + for cert in certs: + if cert["DomainName"] == "pitcrew.io": + return cert["CertificateArn"] + + # if it doesn't exist, create it + arn = json.loads( + await self.sh( + f"aws acm request-certificate --domain-name pitcrew.io --validation-method DNS --subject-alternative-names {self.esc('*.pitcrew.io')}" + ) + )["CertificateArn"] + cert_description = json.loads( + await self.sh( + f"aws acm describe-certificate --certificate-arn {self.esc(arn)}" + ) + ) + + validation = cert_description["Certificate"]["DomainValidationOptions"][0] + await self.ensure.aws.route53.has_records( + zone_id, + [ + { + "Name": validation["ResourceRecord"]["Name"], + "Type": validation["ResourceRecord"]["Type"], + "TTL": 60, + "ResourceRecords": [ + {"Value": validation["ResourceRecord"]["Value"]} + ], + } + ], + ) + + await self.sh( + f"aws acm wait certificate-validated --certificate-arn {self.esc(arn)}" + ) + return arn + + async def setup_cloudfront(self, zone_id, cert_arn) -> str: + s3_origin = "pitcrew-site.s3.amazonaws.com" + + list_distributions = json.loads( + await self.sh(f"aws cloudfront list-distributions") + ) + for dist in list_distributions["DistributionList"]["Items"]: + if dist["Origins"]["Items"][0]["DomainName"] == s3_origin: + return dist["Id"] + + config = { + "DefaultRootObject": "index.html", + "Aliases": {"Quantity": 2, "Items": ["pitcrew.io", "www.pitcrew.io"]}, + "Origins": { + "Quantity": 1, + "Items": [ + { + "Id": "pitcrew-origin", + "DomainName": s3_origin, + "S3OriginConfig": {"OriginAccessIdentity": ""}, + } + ], + }, + "DefaultCacheBehavior": { + "TargetOriginId": "pitcrew-origin", + "ForwardedValues": { + "QueryString": True, + "Cookies": {"Forward": "none"}, + }, + "TrustedSigners": {"Enabled": False, "Quantity": 0}, + "ViewerProtocolPolicy": "redirect-to-https", + "MinTTL": 180, + }, + "CallerReference": str(uuid4()), + "Comment": "Created by crew", + "Enabled": True, + "ViewerCertificate": { + "ACMCertificateArn": cert_arn, + "SSLSupportMethod": "sni-only", + }, + } + create_distribution = json.loads( + await self.sh( + f"aws cloudfront create-distribution --distribution-config {self.esc(json.dumps(config))}" + ) + ) + cf_id = create_distribution["Distribution"]["Id"] + await self.sh(f"aws cloudfront wait distribution-deployed --id {cf_id}") + return cf_id + + async def build_and_sync(self): + await self.examples.deploy_pitcrew.build() + await self.sh("aws s3 sync --acl public-read out/ s3://pitcrew-site/") diff --git a/code/train/Python/0063702_mass_path_distance.py b/code/train/Python/0063702_mass_path_distance.py new file mode 100644 index 0000000000000000000000000000000000000000..2a98a46e5b6517f869b8a1eb4434e1e520aa2129 --- /dev/null +++ b/code/train/Python/0063702_mass_path_distance.py @@ -0,0 +1,76 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed May 15 19:23:23 2013 + +@author: andres +""" +import networkx as nx +import networkb, numpy, json +from scipy import spatial +import logging +logger = logging.getLogger('networkb.algorithms.mass_path_distance') + +def mass_path_distance(bn,N_clus,op='first',correlation='both'): + """ + Returns mass, maximun radio, maximun path length and average path + length for all clusters at critical threshold. If op='first' the + critical threshold is the nearest to 1 and if op='biggest' the + threshold is the one with the biggest jump in the percolation curve. + """ + N=[] + lmean=[] + lmax=[] + rmax=[] + voxels=bn.get_node2voxel() + affine=bn.get_affine() + + jumps=networkb.find_th_jumps(bn,N_clus) + if op=='first': + if len(jumps)==0: + print 'no jumps' + return {'N':[],'rmax':[],'lmax':[],'lmean':[]} + pc=max([jump[0] for jump in jumps]) + elif op=='biggest': + gap=0 + pc=1 + gc=bn.get_gc()[0] + th=bn.get_th() + if len(jumps)==0: + print 'no jumps' + return {'N':[],'rmax':[],'lmax':[],'lmean':[]} + for jump in jumps: + j=th.index(jump) + if gc[j-1]-gc[j]>gap: + pc=jump[0] + gap=gc[j-1]-gc[j] + logger.info('pc=%f',pc) + G=bn.get_Graph(pc,correlation=correlation) + logger.info('number of nodes in network at pc: %i',G.number_of_nodes()) + cluster_list=nx.connected_components(G) + edge_list=G.edges() + logger.info('number of clusters: %i',len(cluster_list)) + N=[len(x) for x in cluster_list] + for i,nodelist in enumerate(cluster_list): + if i<10: + logger.info('procesing cluster %i of mass %i',i,N[i]) + else: + logger.debug('procesing cluster %i of mass %i',i,N[i]) + Gsub=bn.get_SubGraph(float(pc),nodelist,edge_list) + A=numpy.zeros([N[i],3]) + pos=numpy.array([0,0,0,1]) + path_length=[] + H = Gsub.copy() + for j,node in enumerate(H): + temp=[x for x in nx.single_source_shortest_path_length(Gsub, node).values() if x>0] + path_length.extend(temp) + pos[0:3]=voxels[str(node)] + A[j,:]=numpy.dot(affine, numpy.transpose(pos))[0:3] + Gsub.remove_node(node) + D=spatial.distance.cdist(A,A) + rmax.append(numpy.max(D)) + lmax.append(max(path_length)) + lmean.append(numpy.mean(path_length)) + del Gsub, D, A, pos, path_length + json.dump({'N':N,'rmax':rmax,'lmax':lmax,'lmean':lmean}, + open(bn.cluster_properties_file,'w')) + return {'N':N,'rmax':rmax,'lmax':lmax,'lmean':lmean} diff --git a/code/train/Python/0063710_parser_test.py b/code/train/Python/0063710_parser_test.py new file mode 100644 index 0000000000000000000000000000000000000000..281557b5f13ed01c8826ab652fd4a107e08724bb --- /dev/null +++ b/code/train/Python/0063710_parser_test.py @@ -0,0 +1,114 @@ +from sqlite3 import dbapi2 +from os.path import dirname +from unittest import main, TestCase +from sqlalchemy.engine.url import URL +from datetime import date + +from medic import orm +from medic.parser import MedlineXMLParser, PubMedXMLParser + +__author__ = 'Florian Leitner' + + +class ParserTest(TestCase): + MEDLINE_STRUCTURE_FILE = dirname(__file__) + '/medline.xml' + PMID = 123 + + ITEMS = [ + orm.Identifier(PMID, 'doi', 'valid doi'), + orm.Identifier(PMID, 'pii', 'invalid pii'), + orm.Abstract(PMID, 'NLM', 'copyright info'), + orm.Section(PMID, 'NLM', 1, 'Background', 'background text', 'background label'), + orm.Section(PMID, 'NLM', 2, 'Objective', 'objective text', 'objective label'), + orm.Section(PMID, 'NLM', 3, 'Methods', 'methods text', 'methods label'), + orm.Section(PMID, 'NLM', 4, 'Methods', 'duplicate methods', 'methods label'), + orm.Section(PMID, 'NLM', 5, 'Results', 'results text', 'results label'), + orm.Section(PMID, 'NLM', 6, 'Conclusions', 'conclusions text', 'conclusions label'), + orm.Section(PMID, 'NLM', 7, 'Unlabelled', 'unlabelled text with\xa0encoding\x96errors'), + orm.Section(PMID, 'NLM', 8, 'Unassigned', 'abstract text', 'abstract label'), + orm.Section(PMID, 'NLM', 9, 'Abstract', 'default text'), + orm.Author(PMID, 1, 'Author', forename='First'), + orm.Author(PMID, 2, 'Middle', suffix='Suf'), + orm.Author(PMID, 3, 'Author', forename='P Last', initials='PL'), + orm.Database(PMID, 'db1', 'acc1'), + orm.Database(PMID, 'db1', 'acc2'), + orm.Database(PMID, 'db1', 'acc3'), + orm.Database(PMID, 'db2', 'acc'), + orm.PublicationType(PMID, 'publication type 1'.upper()), + orm.PublicationType(PMID, 'publication type 2'.upper()), + orm.Chemical(PMID, 1, "chemical substance 1"), + orm.Chemical(PMID, 2, "chemical substance 2", "EC 1.1.1.1"), + orm.Descriptor(PMID, 1, 'minor geographic descriptor'), + orm.Qualifier(PMID, 1, 1, 'minor qualifier'), + orm.Descriptor(PMID, 2, 'major descriptor', True), + orm.Qualifier(PMID, 2, 1, 'major qualifier', True), + orm.Qualifier(PMID, 2, 2, 'another qualifier'), + orm.Descriptor(PMID, 3, 'major descriptor', True), + orm.Qualifier(PMID, 3, 1, 'minor qualifier'), + orm.Descriptor(PMID, 4, 'minor descriptor'), + orm.Qualifier(PMID, 4, 1, 'major qualifier', True), + orm.Identifier(PMID, 'pmc', 'PMC12345'), + orm.Abstract(PMID, 'Publisher'), + orm.Section(PMID, 'Publisher', 1, 'Unassigned', 'explanation for publisher abstract', + truncated=True), + orm.Abstract(PMID, 'NASA', 'NASA copyright'), + orm.Section(PMID, 'NASA', 1, 'Conclusions', 'NASA conclusions', 'NASA label'), + orm.Keyword(PMID, 'NLM', 1, 'NLM minor keyword'), + orm.Keyword(PMID, 'NLM', 2, 'major keyword', True), + orm.Keyword(PMID, 'NLM', 3, 'minor keyword'), + orm.Keyword(PMID, 'NASA', 1, 'NASA keyword'), + orm.Citation(PMID, 'MEDLINE', '[a translated title].', 'NLM Jour Abbrev', '1950 some random date string', + date(1974, 2, 19), date(1974, 11, 19), date(2006, 2, 14), + 'vol 1(no 1)', '100-10'), + orm.Citation(987, 'MEDLINE', 'title', 'NLM Jour Abbrev', '1990 season', + date(1974, 2, 19), date(1974, 11, 19), date(2006, 2, 14)), + orm.Identifier(987, 'doi', 'some doi'), + ] + def setUp(self): + self.stream = open(ParserTest.MEDLINE_STRUCTURE_FILE) + + def parse(self, parser, items): + reps = sorted(str(i) for i in items) + recv = [] + to_delete = [123, 987] + last_item = None + count = -1 + + for item in parser.parse(self.stream): + if type(item) == int: + # DeleteCitation elements + assert item in to_delete, item + to_delete.remove(item) + else: + count += 1 + recv.append(str(item)) + self.assertTrue(item in items, "\n" + str(item) + str(items[count])) + last_item = item + yield item + + self.assertEqual(len(items), count + 1, repr(last_item)) + + for expected, received in zip(reps, sorted(recv)): + self.assertEqual(expected, received) + + def testParseToDB(self): + orm.InitDb(URL('sqlite'), module=dbapi2) + self.sess = orm.Session() + parser = PubMedXMLParser(unique=False) # do not skip records with versions + + for item in self.parse(parser, ParserTest.ITEMS): + self.sess.add(item) + + self.sess.commit() + + def testParseAll(self): + parser = PubMedXMLParser(unique=False) # do not skip records with versions + list(self.parse(parser, ParserTest.ITEMS)) + + def testParseSkipVersion(self): + parser = MedlineXMLParser(unique=True) # skip records with versions + list(self.parse(parser, ParserTest.ITEMS[:-2])) + + +if __name__ == '__main__': + main() diff --git a/code/train/Python/0064061_accuracytest.py b/code/train/Python/0064061_accuracytest.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c682e00ee99a70306cf43a7ac79f3d6a86728d --- /dev/null +++ b/code/train/Python/0064061_accuracytest.py @@ -0,0 +1,165 @@ +from __future__ import print_function + +import os +import math +import string +import random +import unittest +import tempfile + +import pybloomfilter + + +class TestAccuracyMixin(object): + FILTER_SIZE = 1000 + + def _gen_random_items(self, n, exclude=None): + # Yield n unique random items; if an existing set is provided, + # items already in that set will not be yielded. + if exclude is not None: + yielded = exclude + else: + yielded = set() + + yield_count = 0 + while yield_count < n: + random_item = self._random_item() + if random_item not in yielded: + yield random_item + yielded.add(random_item) + yield_count += 1 + + def test_false_pos_degredation(self): + # we'll check 10% to 0.01% + for error_rate in (0.1, 0.01, 0.001, 0.0001): + bf = self._bf(error_rate) + items_in_filter = set( + self._gen_random_items(bf.capacity)) + + items_in_filter_list = list(items_in_filter) + n = 0 + chunk_count = 10 + chunk_size = int(math.ceil(float(bf.capacity) / chunk_count)) + print('error_rate = %.4f' % error_rate) + print(' %6s %9s %s' % ('n', 'false_pos', + 'estimated error_rate')) + for i in range(chunk_count): + chunk = items_in_filter_list[i*chunk_size:(i+1)*chunk_size] + n += len(chunk) + bf.update(chunk) + pos_test_count = int(5 * 1.0 / error_rate) + false_pos = len(list(filter(bf.__contains__, + self._gen_random_items( + pos_test_count, items_in_filter)))) + est_error_rate = float(false_pos) / pos_test_count + print(' %6d %9d %.8f %s' % ( + n, false_pos, est_error_rate, + '******' if est_error_rate > error_rate else '')) + + def test_accuracy(self): + print('\n%14s\t%14s\t%17s' % ('pos_test_count', 'false_pos_rate', + 'error_rate_target')) + # we'll check 10% to 0.01% + for error_rate in (0.1, 0.01, 0.001, 0.0001): + bf = self._bf(error_rate) + items_in_filter = set( + self._gen_random_items(bf.capacity)) + bf.update(items_in_filter) + + # sanity check + self.assertEqual(bf.capacity, len(items_in_filter)) + + false_neg = len(items_in_filter) - \ + len(list(filter(bf.__contains__, items_in_filter))) + + pos_test_count = int(10 * (1.0 / error_rate)) + false_pos = len(list(filter(bf.__contains__, self._gen_random_items( + pos_test_count, items_in_filter)))) + false_pos = 0 + for test in self._gen_random_items(pos_test_count, + items_in_filter): + if test in bf: + false_pos += 1 + + false_pos_rate = float(false_pos) / pos_test_count + false_neg_rate = float(false_neg) / len(items_in_filter) + error_rate_target = error_rate * 2 # cut it some slack + + print('%14d\t%14f\t%17f' % (pos_test_count, false_pos_rate, + error_rate_target)) + self.assertTrue( + false_pos_rate <= error_rate_target, + "false_pos: %r / %r = %r > %r" % ( + false_pos, pos_test_count, + false_pos / float(pos_test_count), error_rate_target)) + self.assertEqual(false_neg_rate, 0.0, + "false negative rate is nonzero: %0.6f" % + (false_neg_rate,)) + del bf + + +class StringAccuracyMallocTestCase(unittest.TestCase, TestAccuracyMixin): + CHARS = string.ascii_letters + STR_LEN = 10 + + def _random_item(self): + return ''.join(random.choice(self.CHARS) + for _ in range(self.STR_LEN)) + + def _bf(self, error_rate): + return pybloomfilter.BloomFilter(self.FILTER_SIZE, error_rate) + + +class StringAccuracyMmapTestCase(unittest.TestCase, TestAccuracyMixin): + CHARS = string.ascii_letters + STR_LEN = 10 + + def setUp(self): + self.temp_file = tempfile.NamedTemporaryFile(suffix='.bloom', + delete=False) + + def tearDown(self): + os.unlink(self.temp_file.name) + + def _random_item(self): + return ''.join(random.choice(self.CHARS) + for _ in range(self.STR_LEN)) + + def _bf(self, error_rate): + return pybloomfilter.BloomFilter(self.FILTER_SIZE, error_rate, + self.temp_file.name) + + +class IntegerAccuracyMallocTestCase(unittest.TestCase, TestAccuracyMixin): + + def _random_item(self): + return random.randint(-2**31, 2**31) + + def _bf(self, error_rate): + return pybloomfilter.BloomFilter(self.FILTER_SIZE, error_rate) + + +class IntegerAccuracyMmapTestCase(unittest.TestCase, TestAccuracyMixin): + + def setUp(self): + self.temp_file = tempfile.NamedTemporaryFile(suffix='.bloom', + delete=False) + + def tearDown(self): + os.unlink(self.temp_file.name) + + def _random_item(self): + return random.randint(-2**31, 2**31) + + def _bf(self, error_rate): + return pybloomfilter.BloomFilter(self.FILTER_SIZE, error_rate, + self.temp_file.name) + + +def suite(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(StringAccuracyMmapTestCase)) + suite.addTest(unittest.makeSuite(StringAccuracyMallocTestCase)) + suite.addTest(unittest.makeSuite(IntegerAccuracyMmapTestCase)) + suite.addTest(unittest.makeSuite(IntegerAccuracyMallocTestCase)) + return suite diff --git a/code/train/Python/0065151_list1.py b/code/train/Python/0065151_list1.py new file mode 100644 index 0000000000000000000000000000000000000000..e58415023884cceb038c1c43b311403e973421d4 --- /dev/null +++ b/code/train/Python/0065151_list1.py @@ -0,0 +1,102 @@ +#!/usr/bin/python -tt +# Copyright 2010 Google Inc. +# Licensed under the Apache License, Version 2.0 +# http://www.apache.org/licenses/LICENSE-2.0 + +# Google's Python Class +# http://code.google.com/edu/languages/google-python-class/ + +# Basic list exercises +# Fill in the code for the functions below. main() is already set up +# to call the functions with a few different inputs, +# printing 'OK' when each function is correct. +# The starter code for each function includes a 'return' +# which is just a placeholder for your code. +# It's ok if you do not complete all the functions, and there +# are some additional functions to try in list2.py. + + +# A. match_ends +# Given a list of strings, return the count of the number of +# strings where the string length is 2 or more and the first +# and last chars of the string are the same. +# Note: python does not have a ++ operator, but += works. +def match_ends(words): + count = 0 + for word in words: + if len(word) >= 2 and word[0] == word[-1]: + count += 1 + return count + + +# B. front_x +# Given a list of strings, return a list with the strings +# in sorted order, except group all the strings that begin with 'x' first. +# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields +# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] +# Hint: this can be done by making 2 lists and sorting each of them +# before combining them. +def front_x(words): + a = [] + x = [] + for word in words: + if word[0] == "x": + x.append(word) + else: + a.append(word) + a.sort() + x.sort() + return x + a + + +# C. sort_last +# Given a list of non-empty tuples, return a list sorted in increasing +# order by the last element in each tuple. +# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields +# [(2, 2), (1, 3), (3, 4, 5), (1, 7)] +# Hint: use a custom key= function to extract the last element form each tuple. +def sort_last(tuples): + def ultimo(tuple): + return tuple[-1] + tuples.sort(key=ultimo) + return tuples + + +# Simple provided test() function used in main() to print +# what each function returns vs. what it's supposed to return. +def test(got, expected): + if got == expected: + prefix = ' OK ' + else: + prefix = ' X ' + print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected))) + + +# Calls the above functions with interesting inputs. +def main(): + print('match_ends') + test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3) + test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2) + test(match_ends(['aaa', 'be', 'abc', 'hello']), 1) + + print() + print('front_x') + test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']), + ['xaa', 'xzz', 'axx', 'bbb', 'ccc']) + test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']), + ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']) + test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']), + ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']) + + print() + print('sort_last') + test(sort_last([(1, 3), (3, 2), (2, 1)]), + [(2, 1), (3, 2), (1, 3)]) + test(sort_last([(2, 3), (1, 2), (3, 1)]), + [(3, 1), (1, 2), (2, 3)]) + test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]), + [(2, 2), (1, 3), (3, 4, 5), (1, 7)]) + + +if __name__ == '__main__': + main() diff --git a/code/train/Python/0065512_course_grade.py b/code/train/Python/0065512_course_grade.py new file mode 100644 index 0000000000000000000000000000000000000000..d1dca3f1314be9736b0c1c4b47a6fb310a05bffb --- /dev/null +++ b/code/train/Python/0065512_course_grade.py @@ -0,0 +1,209 @@ +""" +CourseGrade Class +""" + +from collections import defaultdict +from django.conf import settings +from lazy import lazy +from logging import getLogger +from lms.djangoapps.course_blocks.api import get_course_blocks +from openedx.core.djangoapps.signals.signals import GRADES_UPDATED +from xmodule import block_metadata_utils + +from .subsection_grade import SubsectionGradeFactory + + +log = getLogger(__name__) + + +class CourseGrade(object): + """ + Course Grade class + """ + def __init__(self, student, course, course_structure): + self.student = student + self.course = course + self.course_structure = course_structure + self.chapter_grades = [] + + @lazy + def subsection_grade_totals_by_format(self): + """ + Returns grades for the subsections in the course in + a dict keyed by subsection format types. + """ + subsections_by_format = defaultdict(list) + for chapter in self.chapter_grades: + for subsection_grade in chapter['sections']: + if subsection_grade.graded: + graded_total = subsection_grade.graded_total + if graded_total.possible > 0: + subsections_by_format[subsection_grade.format].append(graded_total) + return subsections_by_format + + @lazy + def locations_to_weighted_scores(self): + """ + Returns a dict of problem scores keyed by their locations. + """ + locations_to_weighted_scores = {} + for chapter in self.chapter_grades: + for subsection_grade in chapter['sections']: + locations_to_weighted_scores.update(subsection_grade.locations_to_weighted_scores) + return locations_to_weighted_scores + + @property + def has_access_to_course(self): + """ + Returns whether the course structure as seen by the + given student is non-empty. + """ + return len(self.course_structure) > 0 + + @lazy + def summary(self): + """ + Returns the grade summary as calculated by the course's grader. + """ + # Grading policy might be overriden by a CCX, need to reset it + self.course.set_grading_policy(self.course.grading_policy) + grade_summary = self.course.grader.grade( + self.subsection_grade_totals_by_format, + generate_random_scores=settings.GENERATE_PROFILE_SCORES + ) + + # We round the grade here, to make sure that the grade is a whole percentage and + # doesn't get displayed differently than it gets grades + grade_summary['percent'] = round(grade_summary['percent'] * 100 + 0.05) / 100 + grade_summary['grade'] = self._compute_letter_grade(grade_summary['percent']) + grade_summary['totaled_scores'] = self.subsection_grade_totals_by_format + grade_summary['raw_scores'] = list(self.locations_to_weighted_scores.itervalues()) + + return grade_summary + + def compute(self): + """ + Computes the grade for the given student and course. + """ + subsection_grade_factory = SubsectionGradeFactory(self.student) + for chapter_key in self.course_structure.get_children(self.course.location): + chapter = self.course_structure[chapter_key] + subsection_grades = [] + for subsection_key in self.course_structure.get_children(chapter_key): + subsection_grades.append( + subsection_grade_factory.create( + self.course_structure[subsection_key], + self.course_structure, self.course + ) + ) + + self.chapter_grades.append({ + 'display_name': block_metadata_utils.display_name_with_default_escaped(chapter), + 'url_name': block_metadata_utils.url_name_for_block(chapter), + 'sections': subsection_grades + }) + + self._signal_listeners_when_grade_computed() + + def score_for_module(self, location): + """ + Calculate the aggregate weighted score for any location in the course. + This method returns a tuple containing (earned_score, possible_score). + + If the location is of 'problem' type, this method will return the + possible and earned scores for that problem. If the location refers to a + composite module (a vertical or section ) the scores will be the sums of + all scored problems that are children of the chosen location. + """ + if location in self.locations_to_weighted_scores: + score = self.locations_to_weighted_scores[location] + return score.earned, score.possible + children = self.course_structure.get_children(location) + earned = 0.0 + possible = 0.0 + for child in children: + child_earned, child_possible = self.score_for_module(child) + earned += child_earned + possible += child_possible + return earned, possible + + def _compute_letter_grade(self, percentage): + """ + Returns a letter grade as defined in grading_policy (e.g. 'A' 'B' 'C' for 6.002x) or None. + + Arguments + - grade_cutoffs is a dictionary mapping a grade to the lowest + possible percentage to earn that grade. + - percentage is the final percent across all problems in a course + """ + + letter_grade = None + grade_cutoffs = self.course.grade_cutoffs + + # Possible grades, sorted in descending order of score + descending_grades = sorted(grade_cutoffs, key=lambda x: grade_cutoffs[x], reverse=True) + for possible_grade in descending_grades: + if percentage >= grade_cutoffs[possible_grade]: + letter_grade = possible_grade + break + + return letter_grade + + def _signal_listeners_when_grade_computed(self): + """ + Signal all listeners when grades are computed. + """ + responses = GRADES_UPDATED.send_robust( + sender=None, + user=self.student, + grade_summary=self.summary, + course_key=self.course.id, + deadline=self.course.end + ) + + for receiver, response in responses: + log.info( + 'Signal fired when student grade is calculated. Receiver: %s. Response: %s', + receiver, response + ) + + +class CourseGradeFactory(object): + """ + Factory class to create Course Grade objects + """ + def __init__(self, student): + self.student = student + + def create(self, course): + """ + Returns the CourseGrade object for the given student and course. + """ + course_structure = get_course_blocks(self.student, course.location) + return ( + self._get_saved_grade(course, course_structure) or + self._compute_and_update_grade(course, course_structure) + ) + + def _compute_and_update_grade(self, course, course_structure): + """ + Freshly computes and updates the grade for the student and course. + """ + course_grade = CourseGrade(self.student, course, course_structure) + course_grade.compute() + return course_grade + + def _get_saved_grade(self, course, course_structure): # pylint: disable=unused-argument + """ + Returns the saved grade for the given course and student. + """ + if settings.FEATURES.get('ENABLE_SUBSECTION_GRADES_SAVED') and course.enable_subsection_grades_saved: + # TODO LATER Retrieve the saved grade for the course, if it exists. + _pretend_to_save_course_grades() + + +def _pretend_to_save_course_grades(): + """ + Stub to facilitate testing feature flag until robust grade work lands. + """ + pass diff --git a/code/train/Python/0065884_E4.py b/code/train/Python/0065884_E4.py new file mode 100644 index 0000000000000000000000000000000000000000..97210b7564408b2f2c325821984dc3f8bb71a09a --- /dev/null +++ b/code/train/Python/0065884_E4.py @@ -0,0 +1,43 @@ +__author__ = 'shawnmehan' + +""" two digit products 91*99 = 9009, largest palindrome of such multiples. +What is largest 3-digits palindrome +""" + +import itertools + +def get_list(n): + l = [] # set up output list + n_string = str(n) # convert number to string + for c in n_string: + l.append(c) + return l + + +def get_reverse_list(l): + r = [] # set up output list + for c in range(0,len(l)): # flip the list + r.append(l[-(c+1)]) + return r + + +def is_palindrome(l1, l2): + if l1 == l2: + return True + else: + return False + + +def largest_product(): + max_product = 0 + for i, j in itertools.product(range(1, 100000), range(1, 100000)): + product = i * j + if max_product > product: # smaller than what we already found so skip + continue + front = get_list(product) + back = get_reverse_list(front) + if (is_palindrome(front, back)): + max_product = product + return max_product + +print largest_product() diff --git a/code/train/Python/0066105_pascal_voc.py b/code/train/Python/0066105_pascal_voc.py new file mode 100644 index 0000000000000000000000000000000000000000..0afaf69d597e0af85e391d96af85e3f82bd00f9c --- /dev/null +++ b/code/train/Python/0066105_pascal_voc.py @@ -0,0 +1,173 @@ +from __future__ import division + +import os +from math import ceil, floor +from xml.dom.minidom import parse + +import numpy as np +from skimage.io import imread +from skimage.transform import rescale + +from .dataset import Datasets +from .download import maybe_download_and_extract + + +URL = 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/'\ + 'VOCtrainval_11-May-2012.tar' +CLASSES = [ + 'person', 'bird', 'cat', 'cow', 'dog', 'horse', 'sheep', 'aeroplane', + 'bicycle', 'boat', 'bus', 'car', 'motorbike', 'train', 'bottle', 'chair', + 'diningtable', 'pottedplant', 'sofa', 'tvmonitor' +] + + +class PascalVOC(Datasets): + def __init__(self, data_dir, val_size=1500, fixed_size=None): + self._fixed_size = fixed_size + + maybe_download_and_extract(URL, data_dir) + + data_dir = os.path.join(data_dir, 'VOCdevkit', 'VOC2012') + names = os.listdir(os.path.join(data_dir, 'Annotations')) + names = [name.split('.')[0] for name in names] + names = sorted(names) + + # PascalVOC didn't release the full test annotations yet, use the + # validation set instead :( + train = Dataset(names[val_size:], data_dir, fixed_size) + val = Dataset(names[:val_size], data_dir, fixed_size) + test = Dataset(names[:val_size], data_dir, fixed_size) + + super(PascalVOC, self).__init__(train, val, test) + + @property + def classes(self): + return CLASSES + + @property + def width(self): + return self._fixed_size + + @property + def height(self): + return self._fixed_size + + @property + def num_channels(self): + return 3 + + +class Dataset(object): + def __init__(self, names, data_dir, fixed_size=None): + self.epochs_completed = 0 + + self._data_dir = data_dir + self._fixed_size = fixed_size + self._names = names + self._index_in_epoch = 0 + + @property + def num_examples(self): + return len(self._names) + + def _random_shuffle_examples(self): + perm = np.arange(self.num_examples) + np.random.shuffle(perm) + self._names = [self._names[i] for i in perm] + + def next_batch(self, batch_size, shuffle=True): + # This code is nearly complete identical to the default next_batch + # method of the default dataset class, but instead of shuffling the + # examples in memory, we shuffle just the filenames. + # + # Therefore the duplication check of this file is diabled in + # .codeclimate.yml. + + start = self._index_in_epoch + + # Shuffle for the first epoch. + if self.epochs_completed == 0 and start == 0 and shuffle: + self._random_shuffle_examples() + + if start + batch_size > self.num_examples: + # Finished epoch. + self.epochs_completed += 1 + + # Get the rest examples in this epoch. + rest_num_examples = self.num_examples - start + names_rest = self._names[start:self.num_examples] + + # Shuffle the examples. + if shuffle: + self._random_shuffle_examples() + + # Start next epoch. + start = 0 + self._index_in_epoch = batch_size - rest_num_examples + end = self._index_in_epoch + names = names_rest + self._names[start:end] + else: + # Just slice the examples. + self._index_in_epoch += batch_size + end = self._index_in_epoch + names = self._names[start:end] + + if self._fixed_size is None: + images = [self._read_image(name) for name in names] + else: + images = np.stack([self._read_image(name) for name in names]) + labels = np.stack([self._read_label(name) for name in names]) + + return images, labels + + def _read_image(self, name): + path = os.path.join(self._data_dir, 'JPEGImages', + '{}.jpg'.format(name)) + image = imread(path) + + if self._fixed_size is None: + image = (1 / 255) * image.astype(np.float32) + return image.astype(np.float32) + else: + height, width, _ = image.shape + + scale_y = self._fixed_size / height + scale_x = self._fixed_size / width + scale = min(scale_y, scale_x) + + image = rescale(image, (scale, scale), mode='constant') + + pad_y = self._fixed_size - image.shape[0] + pad_x = self._fixed_size - image.shape[1] + + image = np.pad(image, + ((int(ceil(pad_y / 2)), int(floor(pad_y / 2))), + (int(ceil(pad_x / 2)), + int(floor(pad_x / 2))), (0, 0)), 'constant') + return image + + def _read_label(self, name): + path = os.path.join(self._data_dir, 'Annotations', + '{}.xml'.format(name)) + annotation = parse(path) + + label = np.zeros((len(CLASSES)), np.uint8) + + # Get the label to the greatest bounding box. + max_area = 0 + max_name = '' + for obj in annotation.getElementsByTagName('object'): + name = obj.getElementsByTagName('name')[0].firstChild.nodeValue + bbox = obj.getElementsByTagName('bndbox')[0] + xmin = bbox.getElementsByTagName('xmin')[0].firstChild.nodeValue + xmax = bbox.getElementsByTagName('xmax')[0].firstChild.nodeValue + ymin = bbox.getElementsByTagName('ymin')[0].firstChild.nodeValue + ymax = bbox.getElementsByTagName('ymax')[0].firstChild.nodeValue + area = (float(xmax) - float(xmin)) * (float(ymax) - float(ymin)) + if area > max_area: + max_area = area + max_name = name + + label[CLASSES.index(max_name)] = 1 + + return label diff --git a/code/train/Python/0066263_test_extensions.py b/code/train/Python/0066263_test_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..d81197572a53595b68914f697d9370828ff8abfc --- /dev/null +++ b/code/train/Python/0066263_test_extensions.py @@ -0,0 +1,155 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright (c) 2011 X.commerce, a business unit of eBay Inc. +# Copyright 2011 OpenStack LLC. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import iso8601 +from lxml import etree +import webob + +from manila.api.v1 import router +from manila.api import xmlutil + +from manila.openstack.common import jsonutils +from manila import test +from oslo.config import cfg + +CONF = cfg.CONF +NS = "{http://docs.openstack.org/common/api/v1.0}" + + +class ExtensionTestCase(test.TestCase): + def setUp(self): + super(ExtensionTestCase, self).setUp() + ext_list = CONF.osapi_share_extension[:] + fox = ('manila.tests.api.extensions.foxinsocks.Foxinsocks') + if fox not in ext_list: + ext_list.append(fox) + self.flags(osapi_share_extension=ext_list) + + +class ExtensionControllerTest(ExtensionTestCase): + + def setUp(self): + super(ExtensionControllerTest, self).setUp() + self.ext_list = [] + self.ext_list.sort() + + def test_list_extensions_json(self): + app = router.APIRouter() + request = webob.Request.blank("/fake/extensions") + response = request.get_response(app) + self.assertEqual(200, response.status_int) + + # Make sure we have all the extensions, extra extensions being OK. + data = jsonutils.loads(response.body) + names = [str(x['name']) for x in data['extensions'] + if str(x['name']) in self.ext_list] + names.sort() + self.assertEqual(names, self.ext_list) + + # Ensure all the timestamps are valid according to iso8601 + for ext in data['extensions']: + iso8601.parse_date(ext['updated']) + + # Make sure that at least Fox in Sox is correct. + (fox_ext, ) = [ + x for x in data['extensions'] if x['alias'] == 'FOXNSOX'] + self.assertEqual( + fox_ext, {'namespace': 'http://www.fox.in.socks/api/ext/pie/v1.0', + 'name': 'Fox In Socks', + 'updated': '2011-01-22T13:25:27-06:00', + 'description': 'The Fox In Socks Extension', + 'alias': 'FOXNSOX', + 'links': []}, ) + + for ext in data['extensions']: + url = '/fake/extensions/%s' % ext['alias'] + request = webob.Request.blank(url) + response = request.get_response(app) + output = jsonutils.loads(response.body) + self.assertEqual(output['extension']['alias'], ext['alias']) + + def test_get_extension_json(self): + app = router.APIRouter() + request = webob.Request.blank("/fake/extensions/FOXNSOX") + response = request.get_response(app) + self.assertEqual(200, response.status_int) + + data = jsonutils.loads(response.body) + self.assertEqual( + data['extension'], + {"namespace": "http://www.fox.in.socks/api/ext/pie/v1.0", + "name": "Fox In Socks", + "updated": "2011-01-22T13:25:27-06:00", + "description": "The Fox In Socks Extension", + "alias": "FOXNSOX", + "links": []}) + + def test_get_non_existing_extension_json(self): + app = router.APIRouter() + request = webob.Request.blank("/fake/extensions/4") + response = request.get_response(app) + self.assertEqual(404, response.status_int) + + def test_list_extensions_xml(self): + app = router.APIRouter() + request = webob.Request.blank("/fake/extensions") + request.accept = "application/xml" + response = request.get_response(app) + self.assertEqual(200, response.status_int) + + root = etree.XML(response.body) + self.assertEqual(root.tag.split('extensions')[0], NS) + + # Make sure we have all the extensions, extras extensions being OK. + exts = root.findall('{0}extension'.format(NS)) + self.assert_(len(exts) >= len(self.ext_list)) + + # Make sure that at least Fox in Sox is correct. + (fox_ext, ) = [x for x in exts if x.get('alias') == 'FOXNSOX'] + self.assertEqual(fox_ext.get('name'), 'Fox In Socks') + self.assertEqual( + fox_ext.get('namespace'), + 'http://www.fox.in.socks/api/ext/pie/v1.0') + self.assertEqual(fox_ext.get('updated'), '2011-01-22T13:25:27-06:00') + self.assertEqual( + fox_ext.findtext('{0}description'.format(NS)), + 'The Fox In Socks Extension') + + xmlutil.validate_schema(root, 'extensions') + + def test_get_extension_xml(self): + app = router.APIRouter() + request = webob.Request.blank("/fake/extensions/FOXNSOX") + request.accept = "application/xml" + response = request.get_response(app) + self.assertEqual(200, response.status_int) + xml = response.body + + root = etree.XML(xml) + self.assertEqual(root.tag.split('extension')[0], NS) + self.assertEqual(root.get('alias'), 'FOXNSOX') + self.assertEqual(root.get('name'), 'Fox In Socks') + self.assertEqual( + root.get('namespace'), + 'http://www.fox.in.socks/api/ext/pie/v1.0') + self.assertEqual(root.get('updated'), '2011-01-22T13:25:27-06:00') + self.assertEqual( + root.findtext('{0}description'.format(NS)), + 'The Fox In Socks Extension') + + xmlutil.validate_schema(root, 'extension') diff --git a/code/train/Python/0068007_utils.py b/code/train/Python/0068007_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff7b73d6bf4b43ce49bf8ddce7eb07a63c8313c --- /dev/null +++ b/code/train/Python/0068007_utils.py @@ -0,0 +1,79 @@ +from math import sqrt + + +def eigh(a, tol=1.0e-9): + """ + Calculates the eigenValues and vectors using jacobi method. + Code configured without numpy from http://goo.gl/U3m7nX + + Returns: + (list of 3 floats) EigenValues + (3x3 list of floats) EigenVectors + + Raises: + None + """ + # Find largest off-diag. element a[k][l] + def maxElem(a): + n = len(a) + aMax = 0.0 + for i in range(n - 1): + for j in range(i + 1, n): + if abs(a[i][j]) >= aMax: + aMax = abs(a[i][j]) + k = i + l = j + return aMax, k, l + + # Rotate to make a[k][l] = 0 + def rotate(a, p, k, l): + n = len(a) + aDiff = a[l][l] - a[k][k] + if abs(a[k][l]) < abs(aDiff) * 1.0e-36: + t = a[k][l] / aDiff + else: + phi = aDiff / (2.0 * a[k][l]) + t = 1.0 / (abs(phi) + sqrt(phi ** 2 + 1.0)) + if phi < 0.0: + t = -t + c = 1.0 / sqrt(t ** 2 + 1.0) + s = t * c + tau = s / (1.0 + c) + temp = a[k][l] + a[k][l] = 0.0 + a[k][k] = a[k][k] - t * temp + a[l][l] = a[l][l] + t * temp + for i in range(k): # Case of i < k + temp = a[i][k] + a[i][k] = temp - s * (a[i][l] + tau * temp) + a[i][l] = a[i][l] + s * (temp - tau * a[i][l]) + for i in range(k + 1, l): # Case of k < i < l + temp = a[k][i] + a[k][i] = temp - s * (a[i][l] + tau * a[k][i]) + a[i][l] = a[i][l] + s * (temp - tau * a[i][l]) + for i in range(l + 1, n): # Case of i > l + temp = a[k][i] + a[k][i] = temp - s * (a[l][i] + tau * temp) + a[l][i] = a[l][i] + s * (temp - tau * a[l][i]) + for i in range(n): # Update transformation matrix + temp = p[i][k] + p[i][k] = temp - s * (p[i][l] + tau * p[i][k]) + p[i][l] = p[i][l] + s * (temp - tau * p[i][l]) + + # Set limit on number of rotations + n = len(a) + maxRot = 5 * (n ** 2) + + p = [[1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0]] + + # Jacobi rotation loop + for i in range(maxRot): + + aMax, k, l = maxElem(a) + + if aMax < tol: + return [a[i][i] for i in range(len(a))], p + + rotate(a, p, k, l) diff --git a/code/train/Python/0068360_462._Minimum_Moves_to_Equal_Array_Elements_II.py b/code/train/Python/0068360_462._Minimum_Moves_to_Equal_Array_Elements_II.py new file mode 100644 index 0000000000000000000000000000000000000000..94139251b8a56901e163de6abd21302362c4b351 --- /dev/null +++ b/code/train/Python/0068360_462._Minimum_Moves_to_Equal_Array_Elements_II.py @@ -0,0 +1,40 @@ +class Solution(object): + def step(self, pre_sums, nums, x): + from bisect import bisect_left, bisect_right + ret = 0 + left_pos = bisect_left(nums, x) + if left_pos > 0: + ret += x * (left_pos) - pre_sums[left_pos-1] + right_pos = bisect_right(nums, x) + if right_pos > 0 and right_pos < len(nums): + ret += pre_sums[-1] - pre_sums[right_pos-1] - x * (len(nums)-right_pos) + # print pre_sums, nums, x, ret + return ret + + + def minMoves2(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums = sorted(nums) + pre_sums = [nums[0]] + for i in nums[1:]: + pre_sums.append(pre_sums[-1]+i) + l, r = nums[0], nums[-1]+1 + ret = 1e9 + while l < r: + mid = (l+r) / 2 + mid_val = self.step(pre_sums, nums, mid) + ret = min(ret, mid_val) + right_val = self.step(pre_sums, nums, mid+1) + if mid_val == right_val: + return mid_val + elif mid_val < right_val: + r = mid + else: + l = mid+1 + return ret + + +print Solution().minMoves2([1,1,1,2,2,3]) \ No newline at end of file diff --git a/code/train/Python/0069275_flotilla.py b/code/train/Python/0069275_flotilla.py new file mode 100644 index 0000000000000000000000000000000000000000..0a05b632318ed40f337a417c707e4ab858a430bd --- /dev/null +++ b/code/train/Python/0069275_flotilla.py @@ -0,0 +1,201 @@ +""" +============== +FlotillaClient +============== + +This is the core Python code for connecting to, processing input from, and +sending messages to the Flotilla itself. + +""" + + +from serial import SerialException + +from twisted.internet import defer +from twisted.internet.serialport import SerialPort +from twisted.protocols.basic import LineReceiver + +from .hardware import Colour +from .hardware import Dial +from .hardware import Joystick +from .hardware import Light +from .hardware import Matrix +from .hardware import Motion +from .hardware import Motor +from .hardware import Number +from .hardware import Rainbow +from .hardware import Slider +from .hardware import Touch +from .hardware import Weather + + +class FlotillaClient(LineReceiver): + + MODULES = {'matrix': Matrix, + 'number': Number, + 'rainbow': Rainbow, + 'motor': Motor, + 'touch': Touch, + 'dial': Dial, + 'slider': Slider, + 'joystick': Joystick, + 'motion': Motion, + 'light': Light, + 'colour': Colour, + 'weather': Weather, + } + + def _resetModules(self): + self.modules = { x: None for x in range(1, 9) } + + def run(self, project, reactor): + self.project = project + self.reactor = reactor + self._ready = False + self._connected = False + flotilla_port = self.project._flotilla_port + baudrate = self.project._baudrate + try: + SerialPort(self, flotilla_port, reactor, baudrate) + except SerialException as e: + if not hasattr(self, '_count'): + self._count = 0 + print("Trying to connect to Flotilla. This may take up to 30 seconds") + self._count += 1 + if self._count <= 30: + if self._count % 5 == 0: + print("Trying... {} seconds".format(self._count)) + def runner(arg): + self.run(project, reactor) + d = defer.Deferred() + d.addCallback(runner) + reactor.callLater(1, d.callback, None) + return defer.waitForDeferred(d) + else: + # It took more than 30 seconds (I've never seen this) + raise e + + def connectionLost(self, reason): + self._resetModules() + print('Flotilla is disconnected.') + + @defer.deferredGenerator + def connectionMade(self): + self._resetModules() + self._lines = [] + print('Flotilla is connected.') + self.flotillaCommand(b'v') + def check(arg): + self.flotillaCommand(b'v') + while not self._ready: + d = defer.Deferred() + d.addCallback(check) + self.reactor.callLater(1, d.callback, None) + wfd = defer.waitForDeferred(d) + yield wfd + + def flotillaCommand(self, cmd): + self.delimiter = b'\r' + self.sendLine(cmd) + self.delimiter = b'\r\n' + + def handle_hash(self, line): + + self.project.log("INFO", line) + + if self._ready: + # We are all good. No action required. + return + + if line.startswith(b'# Flotilla'): + # Occasional case where the first line gets missed off the first + # time, so reset. + self._lines = [] + + self._lines.append(line) + + if len(self._lines) == 5 and not self._connected: + # We have issued our first b'v' + ready = [False, False, False, False, False,] + starts = [b'# Flotilla', b'# Version', b'# Serial', b'# User', b'# Dock',] + for i in range(5): + ready[i] = self._lines[i].startswith(starts[i]) + if all(ready): + self._connected = True + self._lines = [] + self.flotillaCommand(b'd') + + if len(self._lines) == 11 and not self._ready: + # We're connected, and have issued a b'd' + ready = [False,] * 11 + starts = [b'# SRAM', b'# Loop', b'# Channels', b'# - 0', b'# - 1', + b'# - 2', b'# - 3', b'# - 4', b'# - 5', b'# - 6', b'# - 7',] + for i in range(11): + ready[i] = self._lines[i].startswith(starts[i]) + if all(ready): + self._ready = True + self._lines = [] + self.project.connectModules() + self.flotillaCommand(b'e') + + def handle_C(self, channel, module): + print("Found a {} on channel {}".format(module, channel)) + new_module = self.MODULES[module](self, channel) + self.modules[channel] = new_module + self.project.connect() + + def handle_D(self, channel, module): + self.modules[channel] = None + # TODO we should send a message to the project that a new module + # has been deleted + + def handle_U(self, channel, module, data): + if self.modules[channel] is None: + # It's possible to get input from a hardware module before + # everything is connected up. Ignore it until we're ready + # Rather than using ``self._ready`` we check for ``None`` to avoid + # any unhandled exceptions. + return + j = self.modules[channel].change(data) + + def message(self, data): + self.project.message(data) + + def connectedModules(self, type_=None): + if type_ is None: + return self.modules.values() + return [ m for m in self.modules.values() if m is not None and m.module == type_ ] + + def firstOf(self, type_): + modules = self.connectedModules(type_) + if len(modules) == 0: + return None + l = [ (m.channel, m) for m in modules ] + l.sort() + return l[0][1] + + def lineReceived(self, line): + parts = line.split(b" ") + cmd = parts[0] + if cmd == b'#': + self.handle_hash(line) + return + try: + channel, module = parts[1].decode('ascii').split('/') + except IndexError as e: + # Sometimes, if the Flotilla is particularly overloaded, we get + # malformed lines. Ignore them. + print(line) + return + channel = int(channel) + if cmd == b'c': + self.handle_C(channel, module) + return + if cmd == b'd': + self.handle_D(channel, module) + return + if cmd == b'u': + data = parts[2] + self.handle_U(channel, module, data) + return + diff --git a/code/train/Python/0069309_dsatur.py b/code/train/Python/0069309_dsatur.py new file mode 100644 index 0000000000000000000000000000000000000000..7a097c2907fe3a2a0fba534a40d4c6f95cbee0e4 --- /dev/null +++ b/code/train/Python/0069309_dsatur.py @@ -0,0 +1,87 @@ +''' +@author: Dallas Fraser +@id: 20652186 +@class: CS686 +@date: 2016-04-05 +@note: coloring_aux with a greedy algorithm +''' +import logging +from inducer.graph import available_color,\ + color_vertex,\ + copy_graph,\ + chromatic_number,\ + is_colored, get_color + + +def inducer_coloring(G): + (H, chromatic) = coloring(G) + colors = [[] for __ in range(0, chromatic)] + for node in H.nodes(): + colors[get_color(H, node)].append(node) + return colors + + +def coloring(G, logger=None): + """Returns a coloring and chromatic number""" + if logger is None: + logging.basicConfig(level=logging.DEBUG, + format='%(asctime)s %(message)s') + logger = logging.getLogger(__name__) + H = dsatur(G, logger) + return (H, chromatic_number(H)) + + +def dsatur(G, logger): + """Returns a coloring using dsatur + + Parameters: + G: the graph to color (networkx) + logger: the logger to use + Returns: + H: a colored copy of the G (networkx) + Note: + used the networkx implementaiton as a starting base but made changes + """ + H = copy_graph(G) + len_g = len(H) + no_colored = 0 + distinct_colors = {} + for node in H.nodes(): + distinct_colors[node] = set() + while no_colored != len_g: + if no_colored == 0: + # When sat. for all nodes is 0, yield the node with highest degree + node = max([x for x in H.nodes()], + key=lambda x: len(list(H.neighbors(x)))) + else: + # want the vertex with the highest saturation + highest_saturation = -1 + highest_saturation_nodes = [] + for node, distinct in distinct_colors.items(): + # If the node is not already colored + if not is_colored(H, node): + saturation = len(distinct) + if saturation > highest_saturation: + highest_saturation = saturation + highest_saturation_nodes = [node] + elif saturation == highest_saturation: + highest_saturation_nodes.append(node) + if len(highest_saturation_nodes) == 1: + node = highest_saturation_nodes[0] + else: + # Return the node with highest degree + max_node = max([x for x in highest_saturation_nodes], + key=lambda x: len(list(H.neighbors(x)))) + node = max_node + color = 0 + # find some color can use for it + while not available_color(H, node, color): + color += 1 + # color the vertex + color_vertex(H, node, color) + logger.debug("Colored {} to {}".format(node, color)) + no_colored += 1 + # tells it neighbors what is up + for neighbour in H.neighbors(node): + distinct_colors[neighbour].add(color) + return H diff --git a/code/train/Python/0070347_config.py b/code/train/Python/0070347_config.py new file mode 100644 index 0000000000000000000000000000000000000000..da3df08ac74307833e3f8b2581be5122ea0394d4 --- /dev/null +++ b/code/train/Python/0070347_config.py @@ -0,0 +1,239 @@ +# -*- coding: UTF-8 -*- +# Copyright 2009-2017 Luc Saffre +# License: BSD (see file COPYING for details) + +"""This defines the :class:`ConfigDirCache` which Lino instantiates +and installs as :attr:`SITE.confdirs +`. + +It creates a list `config_dirs` of all configuration directories by +looping through :attr:`lino.core.site.Site.installed_plugins` and taking those +whose source directory has a :xfile:`config` subdir. + +The mechanism in this module emulates the behaviour of Django's and +Jinja's template loaders. + +We cannot use the Jinja loader because Jinja's `get_template` method +returns a `Template`, and Jinja templates don't know their filename. +One possibility might be to write a special Jinja Template class... + +""" + +from __future__ import unicode_literals +from builtins import object + +import logging +logger = logging.getLogger(__name__) + +import os +from os.path import join, abspath, dirname, isdir +import sys +import codecs +from fnmatch import fnmatch +import six + +fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() + +from lino.utils import iif + +SUBDIR_NAME = 'config' # we might change this to "templates" + + +class ConfigDir(object): + + """A directory that may contain configuration files. + + """ + + def __init__(self, name, writeable): + self.name = abspath(name) + self.writeable = writeable + + def __repr__(self): + return "ConfigDir %s" % self.name + iif( + self.writeable, " (writeable)", "") + + +class ConfigDirCache(object): + _init = False + + def __init__(self, site): + if self._init: + raise Exception("Oops, ConfigDirCache was already instantiated!") + self._init = True + self.site = site + self.scan_config_dirs() + + def scan_config_dirs(self): + """Scan the file system and populate :attr:`config_dirs`.""" + config_dirs = [] + + for pth in self.site.get_settings_subdirs(SUBDIR_NAME): + if six.PY2: + pth = pth.decode(fs_encoding) + config_dirs.append(ConfigDir(pth, False)) + + def add_config_dir(name, mod): + pth = join(dirname(mod.__file__), SUBDIR_NAME) + if isdir(pth): + # logger.info("add_config_dir %s %s", name, pth) + # config_dirs.append(ConfigDir(pth.decode(fs_encoding), False)) + config_dirs.append(ConfigDir(pth, False)) + + self.site.for_each_app(add_config_dir) + + self.LOCAL_CONFIG_DIR = None + + p = self.site.cache_dir.child(SUBDIR_NAME) + if isdir(p): + self.LOCAL_CONFIG_DIR = ConfigDir(p, True) + config_dirs.append(self.LOCAL_CONFIG_DIR) + + config_dirs.reverse() + self.config_dirs = tuple(config_dirs) + + # logger.info('config_dirs:\n%s', '\n'.join([ + # repr(cd) for cd in config_dirs])) + + def find_config_file(self, fn, *groups): + """ + Return the full path of the first occurence within the + :class:`lino.utils.config.ConfigDirCache` of a file named + `filename` + + """ + if os.path.isabs(fn): + return fn + if len(groups) == 0: + groups = [''] + for group in groups: + if group: + prefix = join(*(group.split('/'))) + else: + prefix = '' + for cd in self.config_dirs: + ffn = join(cd.name, prefix, fn) + if os.path.exists(ffn): + return ffn + + def find_config_files(self, pattern, *groups): + """ + Returns a dict of `filename` -> `config_dir` entries for each config + file on this site that matches the pattern. Loops through + `config_dirs` and collects matching files. When a filename is + provided by more than one app, then the latest app gets it. + + `groups` is a tuple of strings, e.g. '', 'foo', 'foo/bar', ... + + """ + files = {} + for group in groups: + if group: + prefix = os.path.sep + join(*(group.split('/'))) + else: + prefix = '' + for cd in self.config_dirs: + pth = cd.name + prefix + if isdir(pth): + for fn in os.listdir(pth): + if fnmatch(fn, pattern): + files.setdefault(fn, cd) + return files + + def find_template_config_files(self, template_ext, *groups): + """ + Like :func:`find_config_files`, but ignore babel variants: + e.g. ignore "foo_fr.html" if "foo.html" exists. + Note: but don't ignore "my_template.html" + """ + files = self.find_config_files('*' + template_ext, *groups) + l = [] + template_ext + for name in list(files.keys()): + basename = name[:-len(template_ext)] + chunks = basename.split('_') + if len(chunks) > 1: + basename = '_'.join(chunks[:-1]) + if basename + template_ext in files: + continue + l.append(name) + l.sort() + if not l: + logger.warning( + "find_template_config_files() : no matches for (%r, %r)", + '*' + template_ext, groups) + return l + + def load_config_files(self, loader, pattern, *groups): + """ + Currently not used. + Naming conventions for :xfile:`*.dtl` files are: + + - the first detail is called appname.Model.dtl + - If there are more Details, then they are called + appname.Model.2.dtl, appname.Model.3.dtl etc. + + The `sort()` below must remove the filename extension (".dtl") + because otherwise the frist Detail would come last. + """ + files = list(self.find_config_files(pattern, *groups).items()) + + def fcmp(a): + return a[0][:-4] + files.sort(key=fcmp) + for group in groups: + prefix = group.replace("/", os.sep) + for filename, cd in files: + filename = join(prefix, filename) + ffn = join(cd.name, filename) + logger.debug("Loading %s...", ffn) + s = codecs.open(ffn, encoding='utf-8').read() + loader(s, cd, filename) + + +IGNORE_TIMES = False +MODIFY_WINDOW = 2 + + +def must_make(src, target): + "returns True if src is newer than target" + try: + src_st = os.stat(src) + src_mt = src_st.st_mtime + except OSError: + # self.error("os.stat() failed: ",e) + return False + + try: + target_st = os.stat(target) + target_mt = target_st.st_mtime + except OSError: + # self.error("os.stat() failed: %s", e) + return True + + if src_mt - target_mt > MODIFY_WINDOW: + return True + return False + + +def make_dummy_messages_file(src_fn, messages): + """ + Write a dummy `.py` source file containing + translatable messages that getmessages will find. + """ + raise Exception("Never used") + target_fn = src_fn + '.py' + if not must_make(src_fn, target_fn): + logger.debug("%s is up-to-date.", target_fn) + return + try: + f = file(target_fn, 'w') + except IOError as e: + logger.warning("Could not write file %s : %s", target_fn, e) + return + f.write("# this file is generated by Lino\n") + f.write("from django.utils.translation import ugettext\n") + for m in messages: + f.write("ugettext(%r)\n" % m) + f.close() + logger.info("Wrote %d dummy messages to %s.", len(messages), target_fn) diff --git a/code/train/Python/0070419_config.py b/code/train/Python/0070419_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2426694d5f19582142d1434ce11bce8994958742 --- /dev/null +++ b/code/train/Python/0070419_config.py @@ -0,0 +1,177 @@ +""" +module: radmin.confg +Config file logic + +Created by Ian Starnes 2007-11-27 + +""" + +class Config(object): + """The Config class.""" + def __init__(self, filename): + self.filename = filename + self._items = {} + execfile(filename, globals(), self._items) + + def add(self, key, value): + self._items[key] = value + + def has_key(self, key): + return self._items.has_key(key) + + def get(self, field, default=None, required=False): + "returns the field as a string" + if self._items.has_key(field): + return self._items[field] + if required: + raise Exception("missing required field(%s)!" % field) + return default + +class IniFile(object): + """docstring for IniFile""" + SYNTAX_COMMENTS = ['#', ';'] + SYNTAX_DELIMITER = '=' + + def __init__(self, filename): + self.filename = filename + self.sections = [] + self._section_dict = {} + + def hasSection(self, section): + return section in self.sections + + def getSection(self, section): + if section not in self.sections: + self._section_dict[section] = {} + self.sections.append(section) + return self._section_dict[section] + + def load(self): + f = open(self.filename, 'r') + section = self.getSection("") + quote = None + key = None + value = None + for line in f.readlines(): + # if inside a quote read anything until end quote + if quote != None: + new_value = line.strip() + if new_value[-1] == quote: + value += new_value[:-1] + quote = None + section[key] = value + continue + value += new_value + + # ignore comments or empty lines + if line[0] in IniFile.SYNTAX_COMMENTS or len(line) < 3: + continue + + # check for new section + if line[0] == '[': + section = self.getSection(line[1:line.find("]")]) + continue + + # check for delimiter + if line.count(IniFile.SYNTAX_DELIMITER) >= 1: + #key, value = line.split('=') + pos = line.find(IniFile.SYNTAX_DELIMITER) + key = line[:pos].strip() + value = line[pos+len(IniFile.SYNTAX_DELIMITER):].strip() + if value[0] == '"': + quote = '"' + elif value[0] == "'": + quote = "'" + + # parse the string + if quote != None: + if value[-1] == quote: + value = value[1:-1] + quote = None + else: + value = value[1:] + continue + else: + if value.count('.') == 1: + flt = value.split('.') + if flt[0].isdigit() and flt[1].isdigit(): + value = float(value) + elif value.isdigit(): + value = int(value) + section[key] = value + + else: + print "no delimiter found in line: %s" % line + + def _write(self, writer, comment=None): + f = writer + if comment: + f.write("# %s\n\n" % self.comment) + for name in self.sections: + section = self._section_dict[name] + if len(section) > 0: + f.write("[%s]\n" % name) + sorted_keys = section.keys() + sorted_keys.sort() + for key in sorted_keys: + value = section[key] + if type(value) is str: + if value.count('\n') > 0 or value.count('"') > 0: + f.write('%s="""%s"""\n\n' % (key, value)) + else: + f.write('%s="%s"\n' % (key, value)) + else: + f.write('%s=%s\n' % (key, value)) + f.write("\n") + + def save(self, comment=None): + f = open(self.filename, 'w') + self._write(f, comment) + f.close() + + def __str__(self): + import StringIO + writer = StringIO.StringIO() + self._write(writer) + out = writer.getvalue() + writer.close() + return out + + def asHTML(self): + """generate html output""" + import StringIO, cgi + f = StringIO.StringIO() + f.write("
\n") + for name in self.sections: + section = self._section_dict[name] + if len(section) > 0: + error_summary = False + if name.lower().count("error") > 0: + error_summary = True + f.write("
\n") + + count = 0 + f.write("

%s

\n" % name) + if error_summary: + f.write("
\n") + sorted_keys = section.keys() + sorted_keys.sort() + for key in sorted_keys: + value = section[key] + if not error_summary: + f.write("%s: %s\n" %(key, value)) + else: + f.write("%s\n" % cgi.escape(value)) + count += 1 + if count == 3 or error_summary: + f.write("
\n") + count = 0 + if error_summary: + f.write("
\n") + f.write("
\n") + f.write("
\n") + content = f.getvalue() + f.close() + return content + + \ No newline at end of file diff --git a/code/train/Python/0070625_index.py b/code/train/Python/0070625_index.py new file mode 100644 index 0000000000000000000000000000000000000000..5720f4c7996bf45461565229c8b98b1e0cf6de58 --- /dev/null +++ b/code/train/Python/0070625_index.py @@ -0,0 +1,255 @@ +"""UserAvatarRequestHandlerFunction + +Fetches the Gravatar of a user. + +Using this Lambda-backed API Gateway endpoint as a proxy, we avoid having to +expose the plain MD5 hash of each user's e-mail address. This allows for more +realistic e-mail address privacy. + +""" + +from __future__ import print_function + +import os +import json +import time +import base64 +import hashlib +from datetime import datetime +import requests +import boto3 +import botocore +from apigateway_helpers.exception import APIGatewayException +from apigateway_helpers.headers import get_response_headers as get_base_response_headers + +cognito_identity_client = boto3.client("cognito-identity") +cognito_idp_client = boto3.client("cognito-idp") +cognito_sync_client = boto3.client("cognito-sync") +s3_client = boto3.client("s3") + +shared_bucket_name = os.environ["SHARED_BUCKET"] +identity_pool_id = os.environ["COGNITO_IDENTITY_POOL_ID"] +user_pool_id = os.environ["COGNITO_USER_POOL_ID"] +user_profile_dataset_name = os.environ["COGNITO_USER_PROFILE_DATASET_NAME"] + +cached_gravatars_prefix = "cached-gravatars/" +http_strftime_format = "%a, %d %b %Y %H:%M:%S %Z" + +def lambda_handler(event, context): + + print("Event: {}".format(json.dumps(event))) + + if "warming" in event and "{}".format(event["warming"]).lower() == "true": + return { + "message": "Warmed!" + } + + identity_id = event["pathParameters"].get("user-id", "") + + if identity_id == "": + raise APIGatewayException("Parameter \"user-id\" specified in path must be longer than zero characters.", 400) + + user_specified_author_avatar_hash = event["queryStringParameters"].get("hash") + + # Pixels + image_size = 80 + + if "s" in event["queryStringParameters"]: + try: + image_size = int(event["queryStringParameters"]["s"]) + if image_size < 1: + raise Exception + if image_size > 2048: + raise Exception + except: + raise APIGatewayException("Parameter \"s\" must be a positive integer up to 2048.", 400) + + cached_avatar_available = False + cached_avatar_last_modified_string = None + force_fresh_gravatar_pull = False + + try: + response = s3_client.head_object( + Bucket = shared_bucket_name, + Key = get_cached_gravatar_s3_key(identity_id, image_size) + ) + + expires_datetime = datetime.strptime(response["Metadata"]["expires"], http_strftime_format) + + current_datetime = datetime.utcnow().replace(tzinfo=expires_datetime.tzinfo) + + seconds_until_expiration = int((expires_datetime - current_datetime).total_seconds()) + + if seconds_until_expiration > 0: + cached_avatar_available = True + print("Expires in {} second(s).".format(seconds_until_expiration)) + else: + print("Cached avatar expired {} second(s) ago.".format(-1 * seconds_until_expiration)) + + cached_avatar_last_modified_string = response["Metadata"].get("source-last-modified") + + if "author-avatar-hash" in response["Metadata"] and user_specified_author_avatar_hash is not None: + if user_specified_author_avatar_hash != response["Metadata"]["author-avatar-hash"]: + cached_avatar_available = False + force_fresh_gravatar_pull = True + print("Cached avatar is for a different e-mail address than user requested.") + + except botocore.exceptions.ClientError as e: + if e.response['Error']['Code'] == '404': + pass + else: + raise + + if cached_avatar_available: + print("Cached avatar not yet expired. Returning it.") + + return return_cached_object(identity_id, image_size) + + + try: + response = cognito_sync_client.list_records( + IdentityPoolId = identity_pool_id, + IdentityId = identity_id, + DatasetName = user_profile_dataset_name + ) + except botocore.exceptions.ClientError as e: + if e.response['Error']['Code'] == 'ValidationException': + raise APIGatewayException("Parameter \"user-id\" specified in path does not correspond to a valid user.", 400) + else: + raise + + user_pool_user_id = None + + for each_record in response.get("Records", []): + if each_record["Key"] == "user-id": + user_pool_user_id = each_record["Value"] + break + + if user_pool_user_id is None: + raise APIGatewayException("Parameter \"user-id\" specified in path does not correspond to a valid user.", 400) + + response = cognito_idp_client.admin_get_user( + UserPoolId = user_pool_id, + Username = user_pool_user_id + ) + + user_email_address = None + user_email_address_verified = False + user_sub = None + + for each_attribute_set in response.get("UserAttributes", []): + if each_attribute_set["Name"] == "email": + user_email_address = each_attribute_set["Value"] + elif each_attribute_set["Name"] == "email_verified": + user_email_address_verified = each_attribute_set["Value"] + elif each_attribute_set["Name"] == "sub": + user_sub = each_attribute_set["Value"] + + author_avatar_hash = hashlib.md5("{}{}".format(user_sub, user_email_address)).hexdigest() + + if user_email_address is None: + raise Exception("Unable to find e-mail address in Cogito User Pool record.") + elif not user_email_address_verified: + raise Exception("User's e-mail address is not yet verified.") + + print("Request is for avatar of user with e-mail address: {}".format(user_email_address)) + + # http://en.gravatar.com/site/implement/hash/ + email_address_gravatar_hash = hashlib.md5(user_email_address.strip().lower()).hexdigest() + + request_kwargs = { + "params": { + "s": str(image_size), + "r": "pg", + "d": "identicon" + }, + "headers": {} + } + + if cached_avatar_last_modified_string is not None and not force_fresh_gravatar_pull: + print("Last modified: {}".format(cached_avatar_last_modified_string)) + request_kwargs["headers"]["If-Modified-Since"] = cached_avatar_last_modified_string + + r = requests.get( + "https://www.gravatar.com/avatar/{}".format(email_address_gravatar_hash), + **request_kwargs + ) + + r.raise_for_status() + + if r.status_code == 304: + + print("Gravatar not modified since cached version. Returning cached version.") + + response = s3_client.copy_object( + Bucket = shared_bucket_name, + Key = get_cached_gravatar_s3_key(identity_id, image_size), + CopySource = { + "Bucket": shared_bucket_name, + "Key": get_cached_gravatar_s3_key(identity_id, image_size) + }, + MetadataDirective = "REPLACE", + Metadata = { + "Author-Avatar-Hash": author_avatar_hash, + "Expires": r.headers["Expires"], + "Source-Last-Modified": r.headers["Last-Modified"] + } + ) + + # We can keep serving our cached version. + return return_cached_object(identity_id, image_size) + + else: + # Save this new version. + + print("Caching Gravatar response image and returning live result.") + + s3_client.put_object( + Bucket = shared_bucket_name, + Key = get_cached_gravatar_s3_key(identity_id, image_size), + Body = r.content, + Metadata = { + "Author-Avatar-Hash": author_avatar_hash, + "Expires": r.headers["Expires"], + "Source-Last-Modified": r.headers["Last-Modified"] + } + ) + + return base64.b64encode(r.content) + +def get_cached_gravatar_s3_key(identity_id, image_size): + return "{}{}/{}.png".format( + cached_gravatars_prefix, + identity_id, + image_size + ) + +def return_cached_object(identity_id, image_size): + + response = s3_client.get_object( + Bucket = shared_bucket_name, + Key = get_cached_gravatar_s3_key(identity_id, image_size) + ) + + return base64.b64encode(response["Body"].read()) + +def proxy_lambda_handler(event, context): + + response_headers = get_response_headers(event, context) + + try: + return_var = lambda_handler(event, context) + except APIGatewayException as e: + return { + "statusCode": e.http_status_code, + "headers": response_headers, + "body": json.dumps({ + "message": e.http_status_message + }) + } + + return { + "statusCode": 200, + "headers": response_headers, + "body": return_var + } \ No newline at end of file diff --git a/code/train/Python/0070718_http.py b/code/train/Python/0070718_http.py new file mode 100644 index 0000000000000000000000000000000000000000..d94280e8cd7d4867823c8a48f7d170b91e39ad9b --- /dev/null +++ b/code/train/Python/0070718_http.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +# +# Stac - Smarter Travel Artifactory Client +# +# Copyright 2015-2016 Smarter Travel +# +# Available under the MIT license. See LICENSE for details. +# + +""" +stac.http +~~~~~~~~~ + +Clients and functionality for interacting with portions of the Artifactory JSON +API. It is typically not required for users of the Stac library to interact +with this module directly. +""" + +from __future__ import absolute_import +# pylint: disable=import-error,no-name-in-module +import distutils.version +import stac.exceptions +import stac.util + + +class VersionApiDao(object): + """HTTP DAO to get one or multiple versions of a particular artifact. + + This DAO interacts with the Artifactory API over HTTP or HTTPS. + + This class is thread safe. + """ + _logger = stac.util.get_log() + + def __init__(self, session, base_url, repo): + """Set the factory for requests session and factory for API urls. + + :param requests.Session session: Session for making HTTP requests to + the Artifactory API. This session should be configured with any required + credentials for accessing the API. + :param str|unicode base_url: Base URL to the Artifactory installation + :param str|unicode repo: Name of repository to search against. + """ + self._session = session + self._base_url = base_url + self._repo = repo + + def get_most_recent_release(self, group, artifact, remote=False): + """Get the version number of the most recent release (non-integration version) + of a particular group and artifact combination. + + :param str group: Group of the artifact to get the version of + :param str artifact: Name of the artifact to get the version of + :param bool remote: Should remote repositories be searched to find the latest + version? Note this can make the request much slower. Default is false. + :return: Version number of the most recent release + :rtype: str + :raises requests.exceptions.HTTPError: For any non-success HTTP responses + from the Artifactory API. + """ + url = self._base_url + '/api/search/latestVersion' + params = {'g': group, 'a': artifact, 'repos': self._repo, 'remote': int(remote)} + self._logger.debug("Using latest version API at %s - params %s", url, params) + + response = self._session.get(url, params=params) + response.raise_for_status() + return response.text.strip() + + def get_most_recent_versions(self, group, artifact, limit, remote=False, integration=False): + """Get a list of the version numbers of the most recent artifacts (integration + or non-integration), ordered by the version number, for a particular group and + artifact combination. + + :param str group: Group of the artifact to get versions of + :param str artifact: Name of the artifact to get versions of + :param int limit: Fetch only this many of the most recent releases + :param bool remote: Should remote repositories be searched to find the latest + versions? Note this can make the request much slower. Default is false. + :param bool integration: If true, fetch only "integration versions", otherwise + fetch only non-integration versions. + :return: Version numbers of the most recent artifacts + :rtype: list + :raises requests.exceptions.HTTPError: For any non-success HTTP responses + from the Artifactory API. + :raises ValueError: If limit is 0 or negative. + """ + if limit < 1: + raise ValueError("Releases limit must be positive") + + url = self._base_url + '/api/search/versions' + params = {'g': group, 'a': artifact, 'repos': self._repo, 'remote': int(remote)} + self._logger.debug("Using all version API at %s - params %s", url, params) + + response = self._session.get(url, params=params) + response.raise_for_status() + + json = response.json() + versions = [ + item['version'] for item in json['results'] if item['integration'] is integration] + # pylint: disable=no-member + versions.sort(key=distutils.version.LooseVersion, reverse=True) + return versions[:limit] diff --git a/code/train/Python/0070953_font_table_ttf.py b/code/train/Python/0070953_font_table_ttf.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe5dc1fc98531a4fe84bc0758eb128a374b20ae --- /dev/null +++ b/code/train/Python/0070953_font_table_ttf.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# -*- noplot -*- +""" +matplotlib has support for freetype fonts. Here's a little example +using the 'table' command to build a font table that shows the glyphs +by character code. + +Usage python font_table_ttf.py somefile.ttf +""" + +import sys +import os + +import matplotlib +from matplotlib.ft2font import FT2Font +from matplotlib.font_manager import FontProperties +from pylab import figure, table, show, axis, title + +import six +from six import unichr + +# the font table grid + +labelc = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'B', 'C', 'D', 'E', 'F'] +labelr = ['00', '10', '20', '30', '40', '50', '60', '70', '80', '90', + 'A0', 'B0', 'C0', 'D0', 'E0', 'F0'] + +if len(sys.argv) > 1: + fontname = sys.argv[1] +else: + fontname = os.path.join(matplotlib.get_data_path(), + 'fonts', 'ttf', 'Vera.ttf') + +font = FT2Font(fontname) +codes = list(font.get_charmap().items()) +codes.sort() + +# a 16,16 array of character strings +chars = [['' for c in range(16)] for r in range(16)] +colors = [[(0.95, 0.95, 0.95) for c in range(16)] for r in range(16)] + +figure(figsize=(8, 4), dpi=120) +for ccode, glyphind in codes: + if ccode >= 256: + continue + r, c = divmod(ccode, 16) + s = unichr(ccode) + chars[r][c] = s + +lightgrn = (0.5, 0.8, 0.5) +title(fontname) +tab = table(cellText=chars, + rowLabels=labelr, + colLabels=labelc, + rowColours=[lightgrn]*16, + colColours=[lightgrn]*16, + cellColours=colors, + cellLoc='center', + loc='upper left') + +for key, cell in tab.get_celld().items(): + row, col = key + if row > 0 and col > 0: + cell.set_text_props(fontproperties=FontProperties(fname=fontname)) +axis('off') +show() diff --git a/code/train/Python/0071722_common2.py b/code/train/Python/0071722_common2.py new file mode 100644 index 0000000000000000000000000000000000000000..214407aa8964c0bd6d1f3efef84bbdd8c233c437 --- /dev/null +++ b/code/train/Python/0071722_common2.py @@ -0,0 +1,76 @@ +from __future__ import print_function +import numpy as np +from random import shuffle, random,seed +from time import time +from heapq import nlargest +from collections import deque,Counter +from itertools import cycle + +import marshal +from pprint import pprint +import sys + +def combinations(n,k): + "return k from n combination" + out = list(range(n)) + shuffle(out) + return out[:k] + +def random_vector(n,lo=0,hi=1): + "return 1d uniform random vector" + return np.random.randint(lo,hi+1,n) + +def random_sparse_vector(n,lo=0,hi=1,d=0.1,k=None): + "return 1d random vector with some of its values set to zero" + sparse = np.zeros(n) + k = k or int(d*n) + positions = combinations(n,k) + sparse[list(positions)] = random_vector(k,lo+1,hi) + return sparse + +def top(k,d,items=False,values=False): + "return k elements with largest values from dictionary" + if items: + return nlargest(k,((x,d[x]) for x in d),key=lambda x:x[1]) + elif values: + return nlargest(k,d.values()) + else: + return nlargest(k,d,key=lambda x:d[x]) + +def clock(label,t0,t1=None): + "print execution time" + dt = time()-t0 if t1==None else t1-t0 + print("{:.3f}\t{}".format(dt,label)) + +def avg(v): + "average" + return 1.0*sum(v)/len(v) + +def gini(data): + "gini index" + g = 0 + for a in data: + for b in data: + g += abs(a-b) + return float(g)/(2.0*len(data)*sum(data)) + +def pick(v_set,n): + "select n random values from a set" + if n<=0: return [] + out = list(v_set) + shuffle(out) + return out[:n] + +if __name__=="__main__": + x = random_vector(30,0,1) + print(x) + y = random_vector(30,0,1) + print(y) + print(x+y) + print(combinations(10,5)) + d = dict(enumerate(x+y)) + print(top(3,d,values=True)) + print(top(2,dict(a=1,b=2,c=3),values=True)) + print(top(2,dict(a=1,b=2,c=3),values=False)) + print(random_sparse_vector(20,d=0.2)) + print(random_sparse_vector(20,k=10)) diff --git a/code/train/Python/0071770_common.py b/code/train/Python/0071770_common.py new file mode 100644 index 0000000000000000000000000000000000000000..1dd84205a6baf5542284ae7a3504c52e5153a2be --- /dev/null +++ b/code/train/Python/0071770_common.py @@ -0,0 +1,233 @@ +import json +from architectures.SampleNet import SampleNet +from keras.applications import ResNet50, VGG16, VGG19, InceptionV3 +from keras.models import load_model +from keras.optimizers import SGD +from keras.utils import np_utils + +def default_path(): + + # Config your default root path according to your folder + root_path = '/Users/gustavo/Documents/LibKeras' + + return root_path + +def preprocess_inception(x): + x /= 255. + x -= 0.5 + x *= 2. + return x + +class ConvNet: + """ + Keras wrapper for Convolutional Neural Networks + """ + def __init__(self): + + # Defining initial flags + self.model = None + self._trained = False + self._history = None + self._to_categorical = False + + return + + def build_resnet50(self, include_top=True, weights=None, input_shape=None, classes=1000): + + # Creating ResNet50 Model + model = ResNet50(include_top=include_top, weights=weights, classes=classes) + if weights != None: + self._trained = True + + # Print model summary + model.summary() + + # Applying model to ConvNet class + self.model = model + + return + + def build_vgg16(self, include_top=True, weights=None, input_shape=None, classes=1000): + + # Creating VGG16 Model + model = VGG16(include_top=include_top, weights=weights, classes=classes) + if weights != None: + self._trained = True + + # Print model summary + model.summary() + + # Applying model to ConvNet class + self.model = model + + return + + def build_vgg19(self, include_top=True, weights=None, input_shape=None, classes=1000): + + # Creating VGG19 Model + model = VGG19(include_top=include_top, weights=weights, classes=classes) + if weights != None: + self._trained = True + + # Print model summary + model.summary() + + # Applying model to ConvNet class + self.model = model + + return + + def build_inception3(self, include_top=True, weights=None, input_shape=None, classes=1000): + + # Creating InceptionV3 Model + model = InceptionV3(include_top=include_top, weights=weights, classes=classes) + if weights != None: + self._trained = True + + # Print model summary + model.summary() + + # Applying model to ConvNet class + self.model = model + + return + + def build_samplenet(self, include_top=True, weights=None, input_shape=None, classes=2): + + # Creating SampleNet Model + model = SampleNet(include_top=include_top, weights=weights, input_shape=input_shape, classes=classes) + if weights != None: + self._trained = True + + # Print model summary + model.summary() + + # Applying model to ConvNet class + self.model = model + + return + + def compile(self, learning_rate=0.001, momentum=0.9, decay=0.0005, nesterov=True, metric='binary_accuracy', loss_func='binary_crossentropy'): + + # Check if model has been built + if self.model is None: + print("Error: the model has not been built.") + return + + # Initialise the optimizer + opt = SGD(lr=learning_rate, momentum=momentum, decay=decay, nesterov=nesterov) + + # Compiling model + print("\n[INFO] compiling...") + self.model.compile(loss=loss_func, optimizer=opt, metrics=[metric]) + + return + + def train(self, data_train, labels_train, n_classes, batch_size=32, n_epochs=20, validation_size=0.05, loss_func='binary_crossentropy'): + + # Check if model has been built + if self.model is None: + print("Error: the model has not been built.") + return + + # Apply categorical format for labels + if n_classes > 2 or loss_func == 'categorical_crossentropy': + labels_train = np_utils.to_categorical(labels_train, n_classes) + self._to_categorical = True + + # Training model + print("\n[INFO] training...") + history = self.model.fit(data_train, labels_train, batch_size=batch_size, validation_split=validation_size, epochs=n_epochs, verbose=1) + + # Applying post-train flags + self._trained = True + self._history = history.history + + return + + def evaluate(self, data_test, labels_test, n_classes, batch_size=32): + + if self._trained == False: + print("Error: the model has not been trained.") + return + + # Switch to categorical labels if this is not a binary classification task + if self._to_categorical == True: + labels_test = np_utils.to_categorical(labels_test, n_classes) + + # Evaluating model on test set + print("\n[INFO] evaluating...") + (loss, acc) = self.model.evaluate(data_test, labels_test, batch_size=batch_size, verbose=1) + + # Displaying final accuracy and loss + print("\n[INFO] test_accuracy: {:.2f}% test_loss: {:.4f}".format(acc * 100, loss)) + + return acc + + def predict(self, x, batch_size=32, verbose=0): + + # Check if the network is already pre-trained or not + if self._trained == False: + print("Error: the model has not been trained.") + return + + # Predicting numpy input 'x' + print("[INFO] predicting...") + + return self.model.predict(x, batch_size=batch_size, verbose=verbose) + + def decode_predictions(self, preds, path=None, top=None): + + # Decodes the predictions into readable inputs from path file + CLASS_INDEX = json.load(open(path)) + results = [] + for pred in preds: + top_indices = pred.argsort()[-top:][::-1] + result = [tuple(CLASS_INDEX[str(i)]) + (pred[i],) for i in top_indices] + result.sort(key=lambda x: x[2], reverse=True) + results.append(result) + + return results + + def save_model(self, fpath): + + # Saving trained model + self.model.save(fpath, overwrite=True) + + return + + def load_model(self, fpath): + + # Loading trained model + self.model = load_model(fpath) + self._trained = True + + return + + def save_weight(self, fpath): + + # Saving trained weights + self.model.save_weights(fpath, overwrite=True) + + return + + def load_weight(self, fpath): + + # Loading trained weights + self.model.load_weights(fpath) + self._trained = True + + return + + def get_history(self): + + # Returning network history + if self._history is None: + print("Error: the model has no history.") + return + + return self._history + +# Test the ConvNet class +if __name__ == "__main__": + print("Main") diff --git a/code/train/Python/0072360_page_set_archive_info.py b/code/train/Python/0072360_page_set_archive_info.py new file mode 100644 index 0000000000000000000000000000000000000000..0a03efee409e43c9abb95961cad3330cf01ba4fa --- /dev/null +++ b/code/train/Python/0072360_page_set_archive_info.py @@ -0,0 +1,155 @@ +# Copyright (c) 2013 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import json +import logging +import os +import re +import shutil + +from telemetry.page import cloud_storage + + +class PageSetArchiveInfo(object): + def __init__(self, file_path, data): + self._file_path = file_path + self._base_dir = os.path.dirname(file_path) + + # Ensure directory exists. + if not os.path.exists(self._base_dir): + os.makedirs(self._base_dir) + + # Download all .wpr files. + for archive_path in data['archives']: + archive_path = self._WprFileNameToPath(archive_path) + try: + cloud_storage.GetIfChanged(archive_path) + except (cloud_storage.CredentialsError, + cloud_storage.PermissionError): + if os.path.exists(archive_path): + # If the archive exists, assume the user recorded their own and + # simply warn. + logging.warning('Need credentials to update WPR archive: %s', + archive_path) + + # Map from the relative path (as it appears in the metadata file) of the + # .wpr file to a list of page names it supports. + self._wpr_file_to_page_names = data['archives'] + + # Map from the page name to a relative path (as it appears in the metadata + # file) of the .wpr file. + self._page_name_to_wpr_file = dict() + # Find out the wpr file names for each page. + for wpr_file in data['archives']: + page_names = data['archives'][wpr_file] + for page_name in page_names: + self._page_name_to_wpr_file[page_name] = wpr_file + self.temp_target_wpr_file_path = None + + @classmethod + def FromFile(cls, file_path): + if os.path.exists(file_path): + with open(file_path, 'r') as f: + data = json.load(f) + return cls(file_path, data) + return cls(file_path, {'archives': {}}) + + def WprFilePathForPage(self, page): + if self.temp_target_wpr_file_path: + return self.temp_target_wpr_file_path + wpr_file = self._page_name_to_wpr_file.get(page.display_name, None) + if wpr_file is None: + # Some old page sets always use the URL to identify a page rather than the + # display_name, so try to look for that. + wpr_file = self._page_name_to_wpr_file.get(page.url, None) + if wpr_file: + return self._WprFileNameToPath(wpr_file) + return None + + def AddNewTemporaryRecording(self, temp_target_wpr_file_path): + self.temp_target_wpr_file_path = temp_target_wpr_file_path + + def AddRecordedPages(self, page_names): + (target_wpr_file, target_wpr_file_path) = self._NextWprFileName() + for page_name in page_names: + self._SetWprFileForPage(page_name, target_wpr_file) + shutil.move(self.temp_target_wpr_file_path, target_wpr_file_path) + + # Update the hash file. + with open(target_wpr_file_path + '.sha1', 'wb') as f: + f.write(cloud_storage.GetHash(target_wpr_file_path)) + f.flush() + + self._WriteToFile() + self._DeleteAbandonedWprFiles() + + def _DeleteAbandonedWprFiles(self): + # Update the metadata so that the abandoned wpr files don't have empty page + # name arrays. + abandoned_wpr_files = self._AbandonedWprFiles() + for wpr_file in abandoned_wpr_files: + del self._wpr_file_to_page_names[wpr_file] + # Don't fail if we're unable to delete some of the files. + wpr_file_path = self._WprFileNameToPath(wpr_file) + try: + os.remove(wpr_file_path) + except Exception: + logging.warning('Failed to delete file: %s' % wpr_file_path) + + def _AbandonedWprFiles(self): + abandoned_wpr_files = [] + for wpr_file, page_names in self._wpr_file_to_page_names.iteritems(): + if not page_names: + abandoned_wpr_files.append(wpr_file) + return abandoned_wpr_files + + def _WriteToFile(self): + """Writes the metadata into the file passed as constructor parameter.""" + metadata = dict() + metadata['description'] = ( + 'Describes the Web Page Replay archives for a page set. Don\'t edit by ' + 'hand! Use record_wpr for updating.') + metadata['archives'] = self._wpr_file_to_page_names.copy() + # Don't write data for abandoned archives. + abandoned_wpr_files = self._AbandonedWprFiles() + for wpr_file in abandoned_wpr_files: + del metadata['archives'][wpr_file] + + with open(self._file_path, 'w') as f: + json.dump(metadata, f, indent=4) + f.flush() + + def _WprFileNameToPath(self, wpr_file): + return os.path.abspath(os.path.join(self._base_dir, wpr_file)) + + def _NextWprFileName(self): + """Creates a new file name for a wpr archive file.""" + # The names are of the format "some_thing_number.wpr". Read the numbers. + highest_number = -1 + base = None + for wpr_file in self._wpr_file_to_page_names: + match = re.match(r'(?P.*)_(?P[0-9]+)\.wpr', wpr_file) + if not match: + raise Exception('Illegal wpr file name ' + wpr_file) + highest_number = max(int(match.groupdict()['NUMBER']), highest_number) + if base and match.groupdict()['BASE'] != base: + raise Exception('Illegal wpr file name ' + wpr_file + + ', doesn\'t begin with ' + base) + base = match.groupdict()['BASE'] + if not base: + # If we're creating a completely new info file, use the base name of the + # page set file. + base = os.path.splitext(os.path.basename(self._file_path))[0] + new_filename = '%s_%03d.wpr' % (base, highest_number + 1) + return new_filename, self._WprFileNameToPath(new_filename) + + def _SetWprFileForPage(self, page_name, wpr_file): + """For modifying the metadata when we're going to record a new archive.""" + old_wpr_file = self._page_name_to_wpr_file.get(page_name, None) + if old_wpr_file: + self._wpr_file_to_page_names[old_wpr_file].remove(page_name) + self._page_name_to_wpr_file[page_name] = wpr_file + if wpr_file not in self._wpr_file_to_page_names: + self._wpr_file_to_page_names[wpr_file] = [] + self._wpr_file_to_page_names[wpr_file].append(page_name) diff --git a/code/train/Python/0072712_kegboard_daemon.py b/code/train/Python/0072712_kegboard_daemon.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8d6b498d068e5839de445c97ddd9065f5e9452 --- /dev/null +++ b/code/train/Python/0072712_kegboard_daemon.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python +# +# Copyright 2009 Mike Wakerly +# +# This file is part of the Pykeg package of the Kegbot project. +# For more information on Pykeg or Kegbot, see http://kegbot.org/ +# +# Pykeg is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# Pykeg is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Pykeg. If not, see . + +"""Kegboard daemon. + +The kegboard daemon is the primary interface between a kegboard devices and a +kegbot system. The process is responsible for several tasks, including: + - discovering kegboards available locally + - connecting to the kegbot core and registering the individual boards + - accumulating data if the kegbot core is offline + +The kegboard daemon is compatible with any device that speaks the Kegboard +Serial Protocol. See http://kegbot.org/docs for the complete specification. + +The daemon should run on any machine which is attached to kegboard hardware. + +The daemon must connect to a Kegbot Core in order to publish data (such as flow +and temperature events). This is a TCP connection, using the Kegnet Protocol to +exchange data. +""" + +import Queue + +import gflags +import serial +import os +import time + +from pykeg.core import importhacks +from pykeg.core import kb_app +from pykeg.core import kb_common +from pykeg.core import util +from pykeg.core.net import kegnet +from pykeg.hw.kegboard import kegboard + +FLAGS = gflags.FLAGS + +gflags.DEFINE_string('kegboard_name', 'kegboard', + 'Name of this kegboard that will be used when talking to the core. ' + 'If you are using multiple kegboards, you will want to run different ' + 'daemons with different names. Otherwise, the default is fine.') + +gflags.DEFINE_boolean('show_messages', True, + 'Print all messages going to and from the kegboard. Useful for ' + 'debugging.') + +gflags.DEFINE_integer('required_firmware_version', 7, + 'Minimum firmware version required. If the device has an older ' + 'firmware version, the daemon will refuse to service it. This ' + 'value should probably not be changed.') + +FLAGS.SetDefault('tap_name', kb_common.ALIAS_ALL_TAPS) + +class KegboardKegnetClient(kegnet.SimpleKegnetClient): + def __init__(self, reader, addr=None): + kegnet.SimpleKegnetClient.__init__(self, addr) + self._reader = reader + + def onSetRelayOutput(self, event): + self._logger.debug('Responding to relay event: %s' % event) + if not event.output_name: + return + try: + output_id = int(event.output_name[-1]) + except ValueError: + return + if event.output_mode == event.Mode.ENABLED: + output_mode = 1 + else: + output_mode = 0 + + # TODO(mikey): message.SetValue is lame, why doesn't attr access work as in + # other places? Fix it. + message = kegboard.SetOutputCommand() + message.SetValue('output_id', output_id) + message.SetValue('output_mode', output_mode) + self._reader.WriteMessage(message) + +class KegboardManagerApp(kb_app.App): + def __init__(self, name='core'): + kb_app.App.__init__(self, name) + + def _Setup(self): + kb_app.App._Setup(self) + + serial_fd = serial.Serial(FLAGS.kegboard_device, FLAGS.kegboard_speed) + reader = kegboard.KegboardReader(serial_fd) + + self._client = KegboardKegnetClient(reader=reader) + + self._manager_thr = KegboardManagerThread('kegboard-manager', + self._client) + self._AddAppThread(self._manager_thr) + + self._device_io_thr = KegboardDeviceIoThread('device-io', self._manager_thr, + reader) + self._AddAppThread(self._device_io_thr) + + self._client_thr = kegnet.KegnetClientThread('kegnet', self._client) + self._AddAppThread(self._client_thr) + + +class KegboardManagerThread(util.KegbotThread): + """Manager of local kegboard devices.""" + + def __init__(self, name, client): + util.KegbotThread.__init__(self, name) + self._client = client + self._message_queue = Queue.Queue() + + def _DeviceName(self, base_name): + return '%s.%s' % (FLAGS.kegboard_name, base_name) + + def PostDeviceMessage(self, device_name, device_message): + """Receive a message from a device, for processing.""" + self._message_queue.put((device_name, device_message)) + + def run(self): + self._logger.info('Starting main loop.') + initialized = False + + while not self._quit: + try: + device_name, device_message = self._message_queue.get(timeout=1.0) + except Queue.Empty: + continue + + if FLAGS.show_messages: + self._logger.info('RX: %s' % str(device_message)) + self._HandleDeviceMessage(device_name, device_message) + + self._logger.info('Exiting main loop.') + + def _HandleDeviceMessage(self, device_name, msg): + if isinstance(msg, kegboard.MeterStatusMessage): + meter_name = self._DeviceName(msg.meter_name) + curr_val = msg.meter_reading + self._client.SendMeterUpdate(meter_name, curr_val) + + elif isinstance(msg, kegboard.TemperatureReadingMessage): + sensor_name = self._DeviceName(msg.sensor_name) + sensor_value = msg.sensor_reading + self._client.SendThermoUpdate(sensor_name, sensor_value) + + elif isinstance(msg, kegboard.OnewirePresenceMessage): + strval = '%016x' % msg.device_id + if msg.status == 1: + self._client.SendAuthTokenAdd(FLAGS.tap_name, + kb_common.AUTH_MODULE_CORE_ONEWIRE, strval) + else: + self._client.SendAuthTokenRemove(FLAGS.tap_name, + kb_common.AUTH_MODULE_CORE_ONEWIRE, strval) + + elif isinstance(msg, kegboard.AuthTokenMessage): + # For legacy reasons, a kegboard-reported device name of 'onewire' is + # translated to 'core.onewire'. Any other device names are reported + # verbatim. + device = msg.device + if device == 'onewire': + device = kb_common.AUTH_MODULE_CORE_ONEWIRE + + # Convert the token byte field to little endian string representation. + bytes_be = msg.token + bytes_le = '' + for b in bytes_be: + bytes_le = '%02x%s' % (ord(b), bytes_le) + + if msg.status == 1: + self._client.SendAuthTokenAdd(FLAGS.tap_name, device, bytes_le) + else: + self._client.SendAuthTokenRemove(FLAGS.tap_name, device, bytes_le) + + +class KegboardDeviceIoThread(util.KegbotThread): + """Manages all device I/O. + + This thread continuously reads from attached kegboard devices and passes + messages to the KegboardManagerThread. + """ + def __init__(self, name, manager, reader): + util.KegbotThread.__init__(self, name) + self._manager = manager + self._reader = reader + + def Ping(self): + ping_message = kegboard.PingCommand() + self._reader.WriteMessage(ping_message) + + def ThreadMain(self): + self._logger.info('Starting reader loop...') + + # Ping the board a couple of times before going into the listen loop. + for i in xrange(2): + self.Ping() + + initialized = False + while not self._quit: + try: + msg = self._reader.GetNextMessage() + except kegboard.UnknownMessageError: + self._logger.warning('Read unknown message, skipping') + continue + + # Check the reported firmware version. If it is not acceptable, then + # drop all messages until it is updated. + # TODO(mikey): kill the application when this happens? It isn't strictly + # necessary, but is probably the most obvious way to get the point across. + if isinstance(msg, kegboard.HelloMessage): + version = msg.firmware_version + if version >= FLAGS.required_firmware_version: + if not initialized: + self._logger.info('Found a Kegboard! Firmware version %i' % version) + initialized = True + else: + self._logger.error('Attached kegboard firmware version (%s) is ' + 'less than the required version (%s); please update this ' + 'kegboard.' % (version, FLAGS.required_firmware_version)) + os._exit(1) + + if not initialized: + self.Ping() + time.sleep(0.1) + continue + + self._manager.PostDeviceMessage('kegboard', msg) + self._logger.info('Reader loop ended.') + + +if __name__ == '__main__': + KegboardManagerApp.BuildAndRun() diff --git a/code/train/Python/0073006_GPFDIST.py b/code/train/Python/0073006_GPFDIST.py new file mode 100644 index 0000000000000000000000000000000000000000..aad24910fbe37b411a812cc50821d411eb78b0b8 --- /dev/null +++ b/code/train/Python/0073006_GPFDIST.py @@ -0,0 +1,209 @@ +""" +Copyright (c) 2004-Present Pivotal Software, Inc. + +This program and the accompanying materials are made available under +the terms of the 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. +""" + +import os +import platform +import time + +import tinctest + +from gppylib.commands.base import Command +from tinctest.lib import run_shell_command + +class GPFDISTError(Exception): + pass + +class GPFDIST: + + def __init__(self, port, hostname, directory=None): + "init" + self.port = port + self.hostname = hostname + self.secure = False + self.ssl_cert = "" + if directory is None: + directory = os.getcwd() + self.directory = directory + self.gphome = os.environ.get("GPHOME") + + # Ensure we use compatible ps command on Solaris platform + self.ps_command = 'ps' + if platform.system() in ['SunOS']: + self.ps_command = '/bin/ps' + + def gethost(self): + return self.hostname + + def getport(self): + return self.port + + def getdir(self): + return self.directory + + def startGpfdist(self, options="", port=None, raise_assert=True, ssl=None): + """ + start hosting the data + @comment: Why do we need to ssh to a host that is localhost + killGpfdist does not support kill process on other host + @note: If we are to use ssh subprocess, we will go to the home folder, + let's revisit this with remote command so that it works for starting + gpfdist on remote host + """ + if port is None: + port = self.port + else: + port = str(port) + if ssl is None: + ssl = "" + else: + self.secure = True + self.ssl_cert = ssl + ssl = "--ssl %s" % self.ssl_cert + + directory = self.directory + + gpfdist_cmd = "gpfdist -p %s -d %s %s %s" % (port, directory, options, ssl) + cmd = "gpssh -h %s 'source %s/greenplum_path.sh; %s > /dev/null &'" % (self.hostname, self.gphome, gpfdist_cmd) + + res = {'rc':0, 'stderr':'', 'stdout':''} + run_shell_command(cmd, 'gpfdist', res) + if res['rc'] > 0: + raise Exception("Failed to start gpfdist on host %s and port %s with non-zero rc" %(self.hostname, port)) + return self.check_gpfdist_process(port=port, raise_assert=raise_assert) + + def check_gpfdist_process(self, wait=60, port=None, raise_assert=True): + """ + Check for the gpfdist process + Wait at least 60s until gpfdist starts, else raise an exception + """ + if port is None: + port = self.port + process_started = False + count = 0 + while (not process_started and count0: + if content.find("gpfdist -p %s" % port)>0: + process_started = self.is_gpfdist_connected(port) + if process_started: + return True + count = count + 1 + time.sleep(1) + if raise_assert: + raise GPFDISTError("Could not start gpfdist process") + else: + tinctest.logger.warning("Could not start gpfdist process") + + def is_gpfdist_connected(self, port=None): + """ + Check gpfdist by connecting after starting process + @return: True or False + @todo: Need the absolute path + """ + if port is None: + port = self.port + + url = "http://%s:%s" % (self.hostname, port) + if self.secure: + url = url.replace("http:", "https:") + " -k" + + cmd_str = "curl %s" %url + res = {'rc':0, 'stderr':'', 'stdout':''} + run_shell_command(cmd_str, 'gpfdist process check', res) + content = res['stdout'] + if content.find("couldn't")>=0: + return False + return True + + def is_port_released(self, port=None): + """ + Check whether the port is released after stopping gpfdist + @return: True or False + """ + if port is None: + port = self.port + cmd_str = "netstat -an | grep %s" % port + cmd = "gpssh -h %s '%s'" %(self.hostname, cmd_str) + res = {'rc':0, 'stderr':'', 'stdout':''} + run_shell_command(cmd, 'gpfdist port check', res) + content = res['stdout'] + # strip hostname prefix from gpssh output + content = content.replace(self.hostname, '').strip('[]').strip() + if len(content)>0: + return False + return True + + def is_gpfdist_killed(self, port=None, wait=1): + """ + Check whether the gpfdist process is killed + """ + if port is None: + port = self.port + process_killed = False + count = 0 + while (not process_killed and count < wait): + cmd_str = " | ".join([ + self.ps_command + ' -ef', + 'grep \"[g]pfdist -p %s\"' % (port)]) + cmd = "gpssh -h %s '%s'" %(self.hostname, cmd_str) + res = {'rc':0, 'stderr':'', 'stdout':''} + run_shell_command(cmd, 'gpfdist process check', res) + content = res['stdout'] + # strip hostname prefix from gpssh output + content = content.replace(self.hostname, '').strip('[]').strip() + if len(content)>0 or content.find("gpfdist -p %s" %port) > 0: + tinctest.logger.warning("gpfdist process still exists on %s:%s" %(self.hostname, self.port)) + else: + return True + count = count + 1 + time.sleep(1) + tinctest.logger.warning("gpfdist process not killed on %s:%s" %(self.hostname, self.port)) + return False + + def killGpfdist(self, wait=60, port=None): + """ + kill the gpfdist process + @change: Johnny Soedomo, check from netstat whether the system has released the process rather than waiting a flat 10s + @todo: Support for stopping gpfdist process on remote host + """ + if port is None: + port = self.port + + cmd_str = ' | '.join([self.ps_command + " -ef", + "grep \"[g]pfdist -p %s\"" % (port), + "awk '\"'\"'{print $2}'\"'\"'", + "xargs kill"]) + cmd = "gpssh -h %s '%s'" %(self.hostname, cmd_str) + + res = {'rc':0, 'stderr':'', 'stdout':''} + run_shell_command(cmd, 'kill gpfdist', res) + + if not self.is_gpfdist_killed(): + raise GPFDISTError("Could not kill gpfdist process on %s:%s" %(self.hostname, self.port)) + # Make sure the port is released + is_released = False + count = 0 + while (not is_released and count < wait): + is_released = self.is_port_released() + count = count + 1 + time.sleep(1) diff --git a/code/train/Python/0073157_016.py b/code/train/Python/0073157_016.py new file mode 100644 index 0000000000000000000000000000000000000000..679875898a2940a0a7478c6e9057938a156027ac --- /dev/null +++ b/code/train/Python/0073157_016.py @@ -0,0 +1,31 @@ +import sys + +class Solution(object): + def threeSumClosest(self, nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + nums.sort() + result = 0 + diff = sys.maxsize + for index, a in enumerate(nums): + left = index + 1 + right = len(nums) -1 + + while left < right: + b = nums[left] + c = nums[right] + total = a + b + c + if total == target: + return total + if abs(total-target) < diff: + diff = abs(total-target) + result = total + if total < target: + left += 1 + if total > target: + right -=1 + return result + \ No newline at end of file diff --git a/code/train/Python/0073784_wiz_stock_planning.py b/code/train/Python/0073784_wiz_stock_planning.py new file mode 100644 index 0000000000000000000000000000000000000000..0e638032982c8e874bde7b8ffcb176c161c47fcc --- /dev/null +++ b/code/train/Python/0073784_wiz_stock_planning.py @@ -0,0 +1,145 @@ +# -*- coding: utf-8 -*- +############################################################################## +# For copyright and license notices, see __openerp__.py file in root directory +############################################################################## +from openerp import models, fields, api, _ +from dateutil.relativedelta import relativedelta + + +class WizStockPlanning(models.TransientModel): + + _name = 'wiz.stock.planning' + _description = 'Wiz Stock Planning' + + @api.multi + def _def_company(self): + return self.env.user.company_id.id + + company = fields.Many2one( + 'res.company', 'Company', default=_def_company, required=True) + from_date = fields.Date( + 'From date', required=True, + help='Date from which the interval starts counting days') + days = fields.Integer( + 'Days interval', required=True, + help='Increase number of days starting from the date from') + to_date = fields.Date('To date', required=True, + help='Deadline for calculating periods') + category = fields.Many2one( + 'product.category', 'Category', + help='Enter this field if you want to filter by category') + template = fields.Many2one( + 'product.template', 'Template', + help='Enter this field if you want to filter by template') + product = fields.Many2one( + 'product.product', 'Product', + help='Enter this field if you want to filter by product') + + @api.multi + def calculate_stock_planning(self): + self.ensure_one() + move_obj = self.env['stock.move'] + procurement_obj = self.env['procurement.order'] + planning_obj = self.env['stock.planning'] + planning = planning_obj.search([]) + planning.unlink() + fdate = self.from_date + from_date = False + while fdate < self.to_date: + product_datas = {} + cond = [('company_id', '=', self.company.id), + ('date', '<=', fdate), + ('state', 'not in', ('done', 'cancel'))] + if from_date: + cond.append(('date', '>', from_date)) + if self.product: + cond.append(('product_id', '>', self.product_id.id)) + moves = move_obj.search(cond).filtered( + lambda x: x.location_id.usage == 'internal' or + x.location_dest_id.usage == 'internal') + if self.category: + moves = moves.filtered( + lambda x: x.product_id.product_tmpl_id.categ_id.id == + self.category.id) + if self.template: + moves = moves.filtered( + lambda x: x.product_id.product_tmpl_id.id == + self.template.id) + for move in moves: + if move.location_id.usage == 'internal': + product_datas = self._find_product_in_table( + product_datas, move.product_id, move.location_id, + move.warehouse_id) + if move.location_dest_id.usage == 'internal': + product_datas = self._find_product_in_table( + product_datas, move.product_id, + move.location_dest_id, move.warehouse_id) + cond = [('company_id', '=', self.company.id), + ('date_planned', '<=', fdate), + ('state', 'in', ('confirmed', 'running'))] + if from_date: + cond.append(('date_planned', '>', from_date)) + if self.product: + cond.append(('product_id', '>', self.product_id.id)) + procurements = procurement_obj.search(cond).filtered( + lambda x: x.location_id.usage == 'internal') + if self.category: + procurements = procurements.filtered( + lambda x: x.product_id.product_tmpl_id.categ_id.id == + self.category.id) + if self.template: + procurements = procurements.filtered( + lambda x: x.product_id.product_tmpl_id.id == + self.template.id) + for procurement in procurements: + product_datas = self._find_product_in_table( + product_datas, procurement.product_id, + procurement.location_id, procurement.warehouse_id) + for data in product_datas: + datos_array = product_datas[data] + vals = {'company': self.company.id, + 'location': datos_array['location'].id, + 'scheduled_date': fdate, + 'product': datos_array['product'].id} + if from_date: + vals['from_date'] = from_date + if datos_array['warehouse']: + vals['warehouse'] = datos_array['warehouse'].id + else: + cond = [('company_id', '=', self.company.id), + ('lot_stock_id', '=', datos_array['location'].id)] + warehouses = self.env['stock.warehouse'].search(cond) + if warehouses: + vals['warehouse'] = warehouses[0].id + planning_obj.create(vals) + from_date = fdate + fdate = fields.Date.to_string(fields.Date.from_string(fdate) + + relativedelta(days=self.days)) + return {'name': _('Stock Planning'), + 'type': 'ir.actions.act_window', + 'view_type': 'form', + 'view_mode': 'tree', + 'res_model': 'stock.planning', + } + + def _find_product_in_table(self, product_datas, product, location, + warehouse): + found = False + for data in product_datas: + datos_array = product_datas[data] + dproduct = datos_array['product'] + dlocation = datos_array['location'] + dwarehouse = datos_array['warehouse'] + if dproduct.id == product.id and dlocation.id == location.id: + found = True + if not dwarehouse and warehouse: + product_datas[data].update({'warehouse': warehouse}) + break + if not found: + my_vals = {'product': product, + 'location': location, + 'warehouse': warehouse, + } + ind = product.id + location.id + (warehouse.id or 0) + product_datas[(ind)] = my_vals + return product_datas diff --git a/code/train/Python/0074419_query_process.py b/code/train/Python/0074419_query_process.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f3953094ce9b1a1d4d65e155b1baa39e63c7f1 --- /dev/null +++ b/code/train/Python/0074419_query_process.py @@ -0,0 +1,131 @@ +# [START imports] +import os +from google.appengine.ext import ndb +import cloudstorage as gcs +import numpy as np +import array +import math +import sys +from jpeg_bs_decoder import JpegDecoder +my_default_retry_params = gcs.RetryParams(initial_delay=0.2, + max_delay=5.0, + backoff_factor=2, + max_retry_period=15) +gcs.set_default_retry_params(my_default_retry_params) + +#default data path +BUCKET = '/nsidc-0051' +MONTH_RP = '/monthly' +DAILY_RP = '/daily' +MONTH_CP = '/monthly_cmp' +DAILY_CP = '/daily_cmp' + +class QueryProc(object): + + def blk_total_seaice(self,blk): + thr1 = 250 + thr2 = 37.5 + cell_size = 25#km + seaice_area = len(blk[np.where(blk<=thr1)]) - len(blk[np.where(blk= max_seaice: + max_id = filename[20:] + max_seaice = total_seaice + min_seaice = max_seaice + if total_seaice <= min_seaice: + min_id = filename[20:] + min_seaice = total_seaice + + gcs_file.close() + #for testing, DeadlineExceededError + if i > 5: + break + + result.append(max_seaice) + result.append(max_id) + result.append(min_seaice) + result.append(min_id) + #debugging + return result + + def maxmin_proc_cmp(self): + #get files list from gs + objs = gcs.listbucket(BUCKET+MONTH_CP) + filelist = [] + for obj in objs: + filelist.append(obj.filename) + + #go through and calculate, need refine into modules later + max_seaice = -float('inf') + min_seaice = float('inf') + result = [] + i = 0 + max_id = None + min_id = None + gcs_file = [] + raw_data = [] + dclist = [] + + for file in filelist: + i = i + 1 + filename = file + gcs_file = gcs.open(filename,mode='r') + + jd = JpegDecoder() + dclist = jd.jpdecode(gcs_file) + gcs_file.close() + + #a new function + ###parsed_dc = np.asarray(dclist) + total_seaice = sum(dclist) + if total_seaice >= max_seaice: + max_id = filename[20:] + max_seaice = total_seaice + min_seaice = max_seaice + if total_seaice <= min_seaice: + min_id = filename[20:] + min_seaice = total_seaice + + gcs_file.close() + #for testing, DeadlineExceededError + if i > 5: + break + + result.append(max_seaice) + result.append(max_id) + result.append(min_seaice) + result.append(min_id) + + return result #a list or dict + + + + diff --git a/code/train/Python/0075625_word_count.py b/code/train/Python/0075625_word_count.py new file mode 100644 index 0000000000000000000000000000000000000000..0437c9f886cc9f823d290ae17f91de93692a90cb --- /dev/null +++ b/code/train/Python/0075625_word_count.py @@ -0,0 +1,128 @@ +""" +description: Word Count Program for CSCI 141 +file: word_count.py +language: python3 +author: sps@cs.rit.edu Sean Strout +author: jeh@cs.rit.edu James Heliotis +author: bks@cs.rit.edu ben k steele +author: jsb@cs.rit.edu Jeremy Brown +author: anh@cs.rit.edu Arthur Nunes-Harwitt +author: scj@cs.rit.edu Scott Johnson +""" + +# import the functions needed from the hashtable.py module. + +from hashtable import * + + +def word_count( hTable, filename ): + """ + Record the frequency of all words in the named file in the hashtable. + word_count : HashTable String -> HashTable + """ + + # Read the words of the text file into the word count table. + fd = open( filename ) + for line in fd: + for word in line.split(): + # using a regular expression argument to strip(), + # strip out punctuation and convert token to lower-case. + word = word.strip(",.\"\';:-!?").lower() + if hTable.has( word ): + count = hTable.get( word ) + hTable.put( word, count + 1 ) + else: + hTable.put( word, 1 ) + + fd.close() # closing the file is a 'good practice'. + return hTable + +def printSummary( theTable ): + """ + printSummary prints a summary of information about the hash table contents. + printSummary : HashTable -> NoneType + """ + + # Display the entire table! + print( "Unique words:", theTable.size ) + + # Find the most common word in the text file. + total = 0 + maxWord = "" + maxCount = 0 + for key in theTable.keys( ): + thisCount = theTable.get( key ) + total += thisCount + if thisCount > maxCount: + maxCount = thisCount + maxWord = key + + print( "There are " + str( len( theTable.keys( ) ) ) + " words." ) + print( "Total words:", total ) + print( '"' + maxWord + "\" appeared ", str( maxCount ), + " times, more than any other word." ) + +def printTable( hTable ): + """ + Print the contents of the given hash table. + Each key/value pair is displayed in parentheses, tuple-style. + All pairs appear on a single line. + printTable : HashTable -> NoneType + """ + print( "Word Count Data ---------------" ) + lcount = 0 + ltext = 0 + for key in hTable.keys( ): + # print( "(" + key + "," + str( hTable.get( key ) ) + ")", end=" " ) + txt = "(" + key + "," + str( hTable.get( key ) ) + ")" + ltext += len( txt ) + if ltext > 51: + print( txt ) + ltext = 0 + else: + print( txt, end=" " ) + print() + +def main(): + capacity = int( input( "Enter capacity (-1 for default): " ) ) + if capacity < 0: + hTable = createHashTable() + else: + hTable = createHashTable( capacity ) + filename = input( "Enter filename: " ) + + wordTable = word_count( hTable, filename ) + printSummary( wordTable ) + + while True: + + print( "Commands: k[ey] f[ind] q[uit] ? ", end=" " ) + response = input( ":- " ) # the displayed prompt + query = response.split() + + if len( response ) == 0 or not response[0] in "fkq": + print( response + " invalid. Please enter a command and a word." ) + response = "" + continue + + if query[0] == "k": + print( "( " + query[1] + " in text ) is " \ + + str( wordTable.has( query[1] ) ) + "." ) + + if query[0] == "f": + if wordTable.has( query[1] ): + print( query[1] + " appears " \ + + str( wordTable.get( query[1] ) ) + " times." ) + else: + print( query[1] + " in not in the text." ) + + if query[0] == "q": + break + # + answer = input( "Do you want to see the entire table?(y/n) " ) + if answer != "y": + return + printTable( wordTable ) + +# run the main program +main() diff --git a/code/train/Python/0076184_3_LogestSubstringWithoutRepeatingCharacters.py b/code/train/Python/0076184_3_LogestSubstringWithoutRepeatingCharacters.py new file mode 100644 index 0000000000000000000000000000000000000000..ab664ffb4e74ece68d0a09959992a67ef3bc9622 --- /dev/null +++ b/code/train/Python/0076184_3_LogestSubstringWithoutRepeatingCharacters.py @@ -0,0 +1,24 @@ +class Solution: + # @param {string} s + # @return {integer} + def lengthOfLongestSubstring(self, s): + maxLength = 0 + start = 0 + substring = {} + idx = 0 + while idx < len(s): + if s[i] not in substring: + substrings[i] = idx + else: + maxLength = max(i - start, maxLength) + start = i + substring = set(s[i]) + print start, maxLength + return max(len(s) - start, maxLength) + + +if __name__ == "__main__": + sol = Solution() +# print sol.lengthOfLongestSubstring("c") +# print sol.lengthOfLongestSubstring("abcabcbb") + print sol.lengthOfLongestSubstring("dvdf") diff --git a/code/train/Python/0076888_cardDeck.py b/code/train/Python/0076888_cardDeck.py new file mode 100644 index 0000000000000000000000000000000000000000..56e59a190e71e164d705810e2200cf6f4171fc69 --- /dev/null +++ b/code/train/Python/0076888_cardDeck.py @@ -0,0 +1,34 @@ +__author__ = 'Rico' + +from lang.language import translation + + +class CardDeck: + symbols = ["♥", "♦", "♣", "♠"] + valueInt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] + + @staticmethod + def create_deck(): + from random import shuffle + deck = list(range(1, 52)) #TODO currently only one deck ... maybe i should add another one. + shuffle(deck) + return deck[:] + + def pick_one_card(self): + card = self.deck[0] + self.deck.pop(0) + return card + + def get_card_name(self, card): + symbol = self.symbols[card//13] + value = self.value_str[card % 13] + card_name = "|"+symbol+" "+value+"|" + return card_name + + def get_card_value(self, card): + return self.valueInt[card % 13] + + def __init__(self, lang_id): + self.deck = self.create_deck() + self.value_str = [translation("ace", lang_id), "2", "3", "4", "5", "6", "7", "8", "9", "10", + translation("jack", lang_id), translation("queen", lang_id), translation("king", lang_id)] diff --git a/code/train/Python/0077207_sakakibara_tools.py b/code/train/Python/0077207_sakakibara_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..59b0f0b4e1ff46c4f094a3bc85b2c4af377f0b9f --- /dev/null +++ b/code/train/Python/0077207_sakakibara_tools.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python +# Standard modules +import os, bisect +import subprocess as sp + +# Nonstandard modules +import pandas as pd + +# My modules +from fasta_tools import get_absolute_positions + +def murasaki_pairwise(pair, outdir, outprefix, weight = 28, length = 36): + anchors = '{}/{}.anchors'.format(outdir, outprefix) + if not os.path.isfile(anchors): + genomes = ' '.join(list(pair.values())) + command = "murasaki -p[{}:{}] -d {} -n {} -H2 {}".format(weight, length, outdir, outprefix, genomes) + # if it's taking forever try -m [int] to skip hashes that appear [int] times + sp.Popen(command, shell=True).wait() + else: + print('Murasaki output already present at {}: using existing file.'.format(anchors)) + return anchors + +def abs_to_rel(anchors, outfile, verbose = True): + # Converts Murasaki output format using genome-based positions to OSFinder input format using chromosome/scaffold/contig-based positions + stub = anchors[:-len('.anchors')] + + if not os.path.isfile(outfile): + genome_file = stub + '.seqs' + genomes, intab = read_sakakibara(anchors, genome_file, 'murasaki') + out_header, sep = sakakibara_header(genomes, 'osfinder') + outtab = pd.DataFrame(index = intab.index, columns=out_header) + + if verbose: + print('Munging {} genomes from Murasaki format to OSFinder format.'.format(len(genomes))) + + for genome in genomes: + genome_positions = sorted(get_absolute_positions(genome).values()) + scaf = genome+'.scaf' + start = genome+'.start' + stop = genome+'.stop' + sign = genome+'.sign' + + # Convert Murasaki signed coordinates to OSFinder unsigned coordinates. + # Murasaki position -1 is complementary to 1 + # -2 is complementary to 2, . . . -SIZE is comp to SIZE + # -1 is NOT complementary to SIZE + + intab[start] = intab[start].apply(abs) + intab[stop] = intab[stop].apply(abs) + + def order(row): + # If the coord is negative need to swap start and stop + # such that start < stop. + if row[start] > row[stop]: + row[start], row[stop] = row[stop], row[start] + return row + + intab = intab.apply(order, axis=1) + + #for index, row in intab.iterrows(): + # if intab.loc[index, start] > intab.loc[index, stop]: + # intab.set_value(index, start, intab.loc[index, stop]) + # intab.set_value(index, stop, intab.loc[index, start]) + + # get number of scaffold and position adjustment for scaffold + outtab[scaf] = intab[start].apply(scaffold_number, args = (genome_positions, )) + delta = outtab[scaf].apply(lambda x: genome_positions[x-1] - 1) + + # delta converts to relative position + outtab[start] = intab[start] - delta + outtab[stop] = intab[stop] - delta + + outtab[sign] = intab[sign] + + if verbose: + print("\tFinished munging " + genome) + + outtab.to_csv(outfile, sep = sep, header = False, index = False) + print('OSFinder format written to {}.'.format(outfile)) + else: + print('OSFinder input found at {}: using existing file.'.format(outfile)) + + return outfile + +def read_sakakibara(file_name, genome_file, fmt): + # Reads Murasaki and OSFinder formated coordinate files into pandas dataframes + genomes = [line.strip() for line in open(genome_file, 'r')] + header, sep = sakakibara_header(genomes, fmt) + table = pd.read_csv(file_name, sep = sep, names = header, header = None, index_col = False) + return genomes, table + +def sakakibara_header(genomes, fmt): + header = [] + if fmt == 'murasaki': + [header.extend([genome+'.start', genome+'.stop', genome+'.sign']) for genome in genomes] + sep = '\t' + elif fmt == 'osfinder': + [header.extend([genome+'.scaf', genome+'.start', genome+'.stop', genome+'.sign']) for genome in genomes] + sep = ' ' + else: + raise ValueError("fmt must be 'murasaki' or 'osfinder'") + + return header, sep + +def scaffold_number(position, genome_positions): + return bisect.bisect(genome_positions, position) + +def osfinder_pairwise(anchors, outprefix, min_len = 1000): + segments = outprefix + '.os.txt' + + if not os.path.isfile(segments): + command = 'osfinder -i {} -o {} -n 2 -s {}'.format(anchors, outprefix, min_len) + sp.Popen(command, shell=True).wait() + else: + print('OSFinder output already present at {}: using existing file.'.format(segments)) + return segments + +def osfinder_to_grimm(osfinder_results, genome_file, outfile, genome_abbreviations): + genomes, tab = read_sakakibara(osfinder_results, genome_file, 'osfinder') + + grimm_genomes = {genome: [] for genome in genomes} + for genome in genomes: + scaf = genome+'.scaf' + start = genome+'.start' + sign = genome+'.sign' + + tab = tab.sort_values([scaf, start]) + + current_scaf = tab.iloc[0][scaf] + for i, segment in tab.iterrows(): + if segment[scaf] != current_scaf: + # End of the scaffold + grimm_genomes[genome].append('$') + current_scaf = segment[scaf] + + grimm_genomes[genome].append(str(eval(segment[sign]+str(i+1)))) # i+1 because GRIMM cannot start from 0 + + outfh = open(outfile, 'w') + for genome, segs in list(grimm_genomes.items()): + outfh.write(' '.join(['>', genome_abbreviations[genome], '\n'])) + outfh.write(' '.join(segs) + '\n') + outfh.write('\n') + outfh.close() diff --git a/code/train/Python/0077716_game_controller.py b/code/train/Python/0077716_game_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..6212d6efaf1c7e661bbdaa070d47e21f8232beb7 --- /dev/null +++ b/code/train/Python/0077716_game_controller.py @@ -0,0 +1,245 @@ +# Copyright 2018 Google Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +"""A high level DM Lab controller class.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import numpy as np +import six + +from python.tests.utils import math_utils + +# Tolerance used when changing player orientation. +ROTATION_TOLERANCE = 2. + +# Tolerance used when changing player position. +POSITION_TOLERANCE = 5. + +_FPS = 60 +_TURN_ACTION_NAME = 'LOOK_LEFT_RIGHT_PIXELS_PER_FRAME' +_MOVE_ACTION_NAME = 'MOVE_BACK_FORWARD' +_JUMP_ACTION_NAME = 'JUMP' +_NOOP_ACTION = np.array([0, 0, 0, 0, 0, 0, 0], dtype=np.intc) +_MIN_BRAKING_SPEED = 50. +_VELOCITY_TOLERANCE = 1e-08 +_INTERNAL_ROTATION_TOLERANCE = ROTATION_TOLERANCE * .5 +_INTERNAL_POSITION_TOLERANCE = POSITION_TOLERANCE * .7 +_SLOW_MOVE_DISTANCE = 10. + + +class ControllerException(Exception): + """Base class for all game controller exceptions.""" + + +class EpisodeFinishedError(ControllerException): + """Raised when an episode is finished while controller is running.""" + + +class PathBlockedError(ControllerException): + """Raised when player path is blocked.""" + + +class GameController(object): + """A high level game controller class. + + The class allows interacting with DMLab environment using high level actions, + such as look at specific direction, move to specific coordinates etc. + """ + + def __init__(self, env): + """Initialize the controller.""" + self._env = env + + action_spec = env.action_spec() + self._action_index = { + action['name']: i + for i, action in enumerate(action_spec) + } + + def look_at_2d(self, target_orientation, steps=10): + """Rotate the player in horizontal plane towards the angle.""" + delta_angle = math_utils.delta_angle_degrees(self.orientation[1], + target_orientation) + self.rotate(delta_angle, steps=steps) + + def rotate(self, delta_angle, steps=10): + """Rotate the player delta_angle degrees in horizontal plane.""" + start = self.orientation + target = np.array([start[0], start[1] + delta_angle, 0.0]) + + speed = self._rotation_speed(delta_angle, steps=steps) + + if np.abs(speed) < 1.: + return + + actions = self._get_actions(_TURN_ACTION_NAME, speed) + + error_message = ('Failed to reach requested orientation. Start: {0}, ' + 'target: {1}, current: {2}.') + for _ in six.moves.range(steps): + if self._env.is_running(): + self._step(actions, 1) + else: + raise AssertionError( + error_message.format(start[1], target[1], self.orientation[1])) + + if abs(math_utils.delta_angle_degrees( + self.orientation[1], target[1])) >= _INTERNAL_ROTATION_TOLERANCE: + if steps == 1: + raise AssertionError( + error_message.format(start[1], target[1], self.orientation[1])) + else: + self.rotate( + math_utils.delta_angle_degrees(self.orientation[1], target[1]), + steps=1) + + def move_to(self, + target_x, + target_y, + max_steps=2000, + max_speed=None): + """Move the player to the target location.""" + pos = self.position + target = np.array([target_x, target_y, pos[2]]) + + if max_speed is None: + max_speed = float('inf') + + direction = (target - pos)[:2] + last_pos = np.array([float('inf'), float('inf'), float('inf')]) + target_orientation = np.degrees(np.arctan2(direction[1], direction[0])) + self.look_at_2d(target_orientation) + + blocked_frames_count = 0 + for _ in six.moves.range(max_steps): + move_action_value = 1 + pos = self.position + direction = (target - pos)[:2] + distance = np.linalg.norm(direction) + speed = np.linalg.norm(self.velocity[:2]) + + if distance < _SLOW_MOVE_DISTANCE: + if speed > 0.0: + self.stop() + elif speed > max_speed: + move_action_value = 0 + + if distance < _INTERNAL_POSITION_TOLERANCE: + break + + if np.linalg.norm(last_pos - pos) < .1: + blocked_frames_count += 1 + if blocked_frames_count > 10: + raise PathBlockedError( + 'Failed to reach target. The path might be blocked.') + else: + blocked_frames_count = 0 + last_pos = pos + + target_orientation = np.degrees(np.arctan2(direction[1], direction[0])) + rotation_speed = self._rotation_speed( + math_utils.delta_angle_degrees(self.orientation[1], + target_orientation), + steps=1) + actions = self._get_empty_actions() + self._set_action_value(actions, _TURN_ACTION_NAME, rotation_speed) + self._set_action_value(actions, _MOVE_ACTION_NAME, move_action_value) + self._step(actions, 1) + else: + raise AssertionError('Failed to reach target in max steps.') + + def stop(self, max_steps=2000): + """Stops the player as soon as possible.""" + start_orientation = self.orientation[1] + for _ in six.moves.range(max_steps): + speed = np.linalg.norm(self.velocity[:2]) + if speed < _VELOCITY_TOLERANCE and np.allclose( + self.rotation_velocity, [0.0, 0.0, 0.0], + atol=_VELOCITY_TOLERANCE): + break + if speed < _MIN_BRAKING_SPEED: + self._step(_NOOP_ACTION, 1) + else: + self.look_at_2d( + self.orientation[1] + + np.degrees(np.arctan2(self.velocity[1], self.velocity[0])), + steps=1) + + self._step(self._get_actions(_MOVE_ACTION_NAME, -1), 1) + else: + raise AssertionError('Failed to stop in max steps.') + self.look_at_2d(start_orientation, steps=1) + + def jump(self): + self._step(self._get_actions(_JUMP_ACTION_NAME, 1), 1) + self.stop() + + def _step(self, actions, steps): + try: + return self._env.step(actions, steps) + except RuntimeError: + if self._env.is_running(): + raise + else: + raise EpisodeFinishedError() + + @property + def position(self): + return self._observations['DEBUG.POS.TRANS'] + + @property + def orientation(self): + return self._observations['DEBUG.POS.ROT'] + + @property + def velocity(self): + return self._observations['VEL.TRANS'] + + @property + def rotation_velocity(self): + return self._observations['VEL.ROT'] + + @property + def _observations(self): + try: + return self._env.observations() + except RuntimeError: + if self._env.is_running(): + raise + else: + raise EpisodeFinishedError() + + def _get_empty_actions(self): + return np.zeros([len(self._action_index)], dtype=np.intc) + + def _set_action_value(self, actions, action_name, action_value): + actions[self._action_index[action_name]] = action_value + + def _get_actions(self, action_name, action_value): + actions = self._get_empty_actions() + self._set_action_value(actions, action_name, action_value) + return actions + + def _rotation_speed(self, delta_angle, steps=10): + start = self.orientation + target = np.array([start[0], start[1] + delta_angle, 0.0]) + + if math_utils.angles_within_tolerance(self.orientation, target): + return 0.0 + + return math_utils.calculate_speed(_FPS, start, target, steps)[1] diff --git a/code/train/Python/0078409_asciimation.py b/code/train/Python/0078409_asciimation.py new file mode 100644 index 0000000000000000000000000000000000000000..4406b432d110172996f972597c8595d55a756601 --- /dev/null +++ b/code/train/Python/0078409_asciimation.py @@ -0,0 +1,118 @@ +import codecs +import json + +class ASCIImation(object): + def __init__(self, font_family="courier new", font_size=12, + font_bold=False, speed=100, looped=True, size=[20, 10], + filename=None): + if filename is None: + self.font_family = font_family + self.font_size = font_size + self.font_bold = font_bold + self.speed = speed + self.looped = looped + self.size = size + self.frames = [] + else: + # Open and load the file + f = codecs.open(filename, 'rb', 'utf-8') + data = json.load(f) + f.close() + + # Get properties of the ASCIImation + self.font_family = data["style"]["family"] + self.font_size = int(data["style"]["size"]) + self.font_bold = True if data["style"]["weight"] == "bold" else \ + False + self.speed = int(data["speed"]) + self.looped = data["loop"] + self.size = [int(data["width"]), int(data["height"])] + self.frames = [] + + # Add all the frames + text = "" + repeat = 1 + foreground_color = "#000000" + background_color = "#ffffff" + for frame in data["content"]: + if "text" in frame: + text = frame["text"] + if "repeat" in frame: + repeat = int(frame["repeat"]) + if "fontColor" in frame: + foreground_color = str(frame["fontColor"]) + if "backgroundColor" in frame: + background_color = str(frame["backgroundColor"]) + self.frames.append(Frame( + text=text, + repeat=repeat, + foreground_color=foreground_color, + background_color=background_color + )) + + def __getitem__(self, key): + if key < 0 or key > len(self): + raise IndexError("Index outside length of ASCIImation") + current_frame = 0 + while key >= self.frames[current_frame].repeat: + key -= self.frames[current_frame].repeat + current_frame += 1 + return self.frames[current_frame] + + def __len__(self): + length = 0 + for f in self.frames: + length += f.repeat + return length + + def __str__(self): + # Construct a dict from this ASCIImation to convert to JSON + ascii_dict = {} + ascii_dict["style"] = {} + ascii_dict["style"]["family"] = self.font_family + ascii_dict["style"]["size"] = self.font_size + ascii_dict["style"]["weight"] = "bold" if self.font_bold else "normal" + ascii_dict["style"]["lineHeight"] = "120%" + ascii_dict["style"]["color"] = "#000000" + ascii_dict["style"]["backgroundColor"] = "#FFFFFF" + + ascii_dict["speed"] = self.speed + ascii_dict["loop"] = self.looped + ascii_dict["width"] = self.size[0] + ascii_dict["height"] = self.size[1] + + ascii_dict["content"] = [] + f_prev = None + for f in self.frames: + ascii_dict["content"].append({"text": f.text}) + + if f_prev is None or f.repeat != f_prev.repeat: + ascii_dict["content"][-1]["repeat"] = f.repeat + if f_prev is None or f.foreground_color != f_prev.foreground_color: + ascii_dict["content"][-1]["fontColor"] = f.foreground_color + if f_prev is None or f.background_color != f_prev.background_color: + ascii_dict["content"][-1]["backgroundColor"] = \ + f.background_color + + f_prev = f + + ascii_dict["metadata"] = {} + ascii_dict["metadata"]["duration"] = len(self) + ascii_dict["metadata"]["frames"] = len(self.frames) + + return json.dumps(ascii_dict, separators=(',',':')) + +class Frame(object): + def __init__(self, text="", repeat=1, foreground_color="#000000", + background_color="#ffffff"): + self.text = text + self.repeat = repeat + self.foreground_color = foreground_color + self.background_color = background_color + + def __str__(self): + s = "repeat: {0}\n".format(self.repeat) + s += "foreground_color: {0}\n".format(self.foreground_color) + s += "background_color: {0}\n".format(self.background_color) + s += self.text + return s diff --git a/code/train/Python/0079218_tree_convert.py b/code/train/Python/0079218_tree_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..8112befe9a053db524dcc90b46ef0bda47bcf2f1 --- /dev/null +++ b/code/train/Python/0079218_tree_convert.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +TAG = "| " +INDENT = 1 + +def level(line): + i = 0 + while line.startswith(TAG): + line = line[4:] + i += 1 + return i + +def strip(line): + return line.replace(TAG, "") + +def parse(lines, start, stop): + if start >= stop: + return + + if ":" in strip(lines[start]): + # has a class label + lev = level(lines[start]) + strs = strip(lines[start]).split(":") + print " "*4*(lev+INDENT) + "if " + strs[0] + ":" + label = strs[1] + label = label[1:label.index("(")-1] + print " "*4*(lev+1+INDENT) + "return \"" + label + "\"" + parse(lines, start+1, stop) + return + + # no class label expend + lev = level(lines[start]) + print " "*4*(lev+INDENT) + "if " + strip(lines[start]) + ":" + + middle = None + for i in xrange(start+1,stop): + if level(lines[i]) == lev: + middle = i + break + if middle == None: + parse(lines, start+1,stop) + # # no else + # print " "*4*lev + "TODO" + # if start+1 < middle: + # parse(lines, start+1, middle) + else: + # with else + parse(lines, start+1, middle) + #print " "*4*lev + "else:" + parse(lines, middle, stop) + +fname = "tree.log" +f = open(fname, "r") +lines = [line.strip() for line in f] +f.close() + +del lines[len(lines) - 1] + +parse(lines, 0, len(lines)) + + + diff --git a/code/train/Python/0079331_steering_dashlet.py b/code/train/Python/0079331_steering_dashlet.py new file mode 100644 index 0000000000000000000000000000000000000000..007be7e3ad8a693dd899ab38070afd9bf2829776 --- /dev/null +++ b/code/train/Python/0079331_steering_dashlet.py @@ -0,0 +1,61 @@ +# rFactor Remote LCD +# Copyright (C) 2014 Ingo Ruhnke +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + + +import rfactorlcd +import math + + +class SteeringDashlet(rfactorlcd.Dashlet): + + def __init__(self, *args): + super(SteeringDashlet, self).__init__(*args) + self.steering = 0 + self.rotation = math.pi / 2 + + def update_state(self, state): + if self.steering != state.steering: + self.steering = state.steering + + def draw(self, cr): + r = min(self.w, self.h)/2.0 + + cr.set_source_rgb(*self.lcd_style.shadow_color) + cr.save() + cr.translate(self.w/2, self.h/2) + cr.rotate(self.rotation * self.steering) + + cr.move_to(-r, 0) + cr.line_to(r, 0) + + cr.move_to(0, 0) + cr.line_to(0, r) + cr.stroke() + cr.restore() + + cr.set_source_rgb(*self.lcd_style.foreground_color) + cr.new_path() + cr.arc(self.w/2, self.h/2, + r, 0, 2.0 * math.pi) + cr.stroke() + + cr.new_path() + cr.arc(self.w/2, self.h/2, + r/5.0, 0, 2.0 * math.pi) + cr.fill() + + +# EOF # diff --git a/code/train/Python/0079404_s3-mp-upload.py b/code/train/Python/0079404_s3-mp-upload.py new file mode 100644 index 0000000000000000000000000000000000000000..dfdcbf98bacd7c102004144d07da381879aa2dbe --- /dev/null +++ b/code/train/Python/0079404_s3-mp-upload.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python +import argparse +from cStringIO import StringIO +import logging +from math import ceil +from multiprocessing import Pool +import time +import urlparse + +import boto + +parser = argparse.ArgumentParser(description="Transfer large files to S3", + prog="s3-mp-upload") +parser.add_argument("src", type=file, help="The file to transfer") +parser.add_argument("dest", help="The S3 destination object") +parser.add_argument("-np", "--num-processes", help="Number of processors to use", + type=int, default=2) +parser.add_argument("-f", "--force", help="Overwrite an existing S3 key", + action="store_true") +parser.add_argument("-s", "--split", help="Split size, in Mb", type=int, default=50) +parser.add_argument("-rrs", "--reduced-redundancy", help="Use reduced redundancy storage. Default is standard.", default=False, action="store_true") +parser.add_argument("--insecure", dest='secure', help="Use HTTP for connection", + default=True, action="store_false") +parser.add_argument("-t", "--max-tries", help="Max allowed retries for http timeout", type=int, default=5) +parser.add_argument("-v", "--verbose", help="Be more verbose", default=False, action="store_true") +parser.add_argument("-q", "--quiet", help="Be less verbose (for use in cron jobs)", default=False, action="store_true") + +logger = logging.getLogger("s3-mp-upload") + +def do_part_upload(args): + """ + Upload a part of a MultiPartUpload + + Open the target file and read in a chunk. Since we can't pickle + S3Connection or MultiPartUpload objects, we have to reconnect and lookup + the MPU object with each part upload. + + :type args: tuple of (string, string, string, int, int, int) + :param args: The actual arguments of this method. Due to lameness of + multiprocessing, we have to extract these outside of the + function definition. + + The arguments are: S3 Bucket name, MultiPartUpload id, file + name, the part number, part offset, part size + """ + # Multiprocessing args lameness + bucket_name, mpu_id, fname, i, start, size, secure, max_tries, current_tries = args + logger.debug("do_part_upload got args: %s" % (args,)) + + # Connect to S3, get the MultiPartUpload + s3 = boto.connect_s3() + s3.is_secure = secure + bucket = s3.lookup(bucket_name) + mpu = None + for mp in bucket.list_multipart_uploads(): + if mp.id == mpu_id: + mpu = mp + break + if mpu is None: + raise Exception("Could not find MultiPartUpload %s" % mpu_id) + + # Read the chunk from the file + fp = open(fname, 'rb') + fp.seek(start) + data = fp.read(size) + fp.close() + if not data: + raise Exception("Unexpectedly tried to read an empty chunk") + + def progress(x,y): + logger.debug("Part %d: %0.2f%%" % (i+1, 100.*x/y)) + + try: + # Do the upload + t1 = time.time() + mpu.upload_part_from_file(StringIO(data), i+1, cb=progress) + + # Print some timings + t2 = time.time() - t1 + s = len(data)/1024./1024. + logger.info("Uploaded part %s (%0.2fM) in %0.2fs at %0.2fMBps" % (i+1, s, t2, s/t2)) + except Exception, err: + logger.debug("Retry request %d of max %d times" % (current_tries, max_tries)) + if (current_tries > max_tries): + logger.error(err) + else: + time.sleep(3) + current_tries += 1 + do_part_upload((bucket_name, mpu_id, fname, i, start, size, secure, max_tries, current_tries)) + +def main(src, dest, num_processes=2, split=50, force=False, reduced_redundancy=False, verbose=False, quiet=False, secure=True, max_tries=5): + # Check that dest is a valid S3 url + split_rs = urlparse.urlsplit(dest) + if split_rs.scheme != "s3": + raise ValueError("'%s' is not an S3 url" % dest) + + s3 = boto.connect_s3() + s3.is_secure = secure + bucket = s3.lookup(split_rs.netloc) + if bucket == None: + raise ValueError("'%s' is not a valid bucket" % split_rs.netloc) + key = bucket.get_key(split_rs.path) + # See if we're overwriting an existing key + if key is not None: + if not force: + raise ValueError("'%s' already exists. Specify -f to overwrite it" % dest) + + # Determine the splits + part_size = max(5*1024*1024, 1024*1024*split) + src.seek(0,2) + size = src.tell() + num_parts = int(ceil(float(size) / part_size)) + + logger.debug("Part Size: {0}".format(part_size)) + logger.debug("File Size: {0}".format(size)) + logger.debug("Num Parts: {0}".format(num_parts)) + + # If file is less than 5M, just upload it directly + if size < 5*1024*1024: + src.seek(0) + t1 = time.time() + k = boto.s3.key.Key(bucket,split_rs.path) + k.set_contents_from_file(src) + t2 = time.time() - t1 + s = size/1024./1024. + logger.info("Finished uploading %0.2fM in %0.2fs (%0.2fMBps)" % (s, t2, s/t2)) + return + + # Create the multi-part upload object + mpu = bucket.initiate_multipart_upload(split_rs.path, reduced_redundancy=reduced_redundancy) + logger.info("Initialized upload: %s" % mpu.id) + + # Generate arguments for invocations of do_part_upload + def gen_args(num_parts, fold_last): + for i in range(num_parts): + part_start = part_size*i + if i == (num_parts-1) and fold_last is True: + yield (bucket.name, mpu.id, src.name, i, part_start, part_size*2, secure, max_tries, 0) + break + else: + yield (bucket.name, mpu.id, src.name, i, part_start, part_size, secure, max_tries, 0) + + + # If the last part is less than 5M, just fold it into the previous part + fold_last = ((size % part_size) < 5*1024*1024) + + # Do the thing + try: + # Create a pool of workers + pool = Pool(processes=num_processes) + t1 = time.time() + pool.map_async(do_part_upload, gen_args(num_parts, fold_last)).get(9999999) + # Print out some timings + t2 = time.time() - t1 + s = size/1024./1024. + # Finalize + src.close() + mpu.complete_upload() + logger.info("Finished uploading %0.2fM in %0.2fs (%0.2fMBps)" % (s, t2, s/t2)) + except KeyboardInterrupt: + logger.warn("Received KeyboardInterrupt, canceling upload") + pool.terminate() + mpu.cancel_upload() + raise + except Exception, err: + logger.error("Encountered an error, canceling upload") + logger.error(err) + mpu.cancel_upload() + raise + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + args = parser.parse_args() + arg_dict = vars(args) + if arg_dict['quiet'] == True: + logger.setLevel(logging.WARNING) + if arg_dict['verbose'] == True: + logger.setLevel(logging.DEBUG) + logger.debug("CLI args: %s" % args) + main(**arg_dict) diff --git a/code/train/Python/0079585_CompareSampleLogs.py b/code/train/Python/0079585_CompareSampleLogs.py new file mode 100644 index 0000000000000000000000000000000000000000..1cb7c10154cfbe2672ab27f249261abfb177b079 --- /dev/null +++ b/code/train/Python/0079585_CompareSampleLogs.py @@ -0,0 +1,195 @@ +# Mantid Repository : https://github.com/mantidproject/mantid +# +# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI, +# NScD Oak Ridge National Laboratory, European Spallation Source +# & Institut Laue - Langevin +# SPDX - License - Identifier: GPL - 3.0 + +from __future__ import (absolute_import, division, print_function) + +from mantid.api import PythonAlgorithm, AlgorithmFactory, WorkspaceGroup, MatrixWorkspace +from mantid.kernel import Direction, StringArrayLengthValidator, StringArrayProperty, FloatBoundedValidator +import mantid.simpleapi as api +import numpy as np + + +class CompareSampleLogs(PythonAlgorithm): + """ + Compares specified sample logs for a given list of workspaces + """ + + def __init__(self): + """ + Init + """ + PythonAlgorithm.__init__(self) + self.tolerance = 0.0 + self.wslist = [] + + def category(self): + """ + Returns category + """ + return "Utility\\Workspaces" + + def seeAlso(self): + return [ "CompareWorkspaces","CheckForSampleLogs","CopySample" ] + + def name(self): + """ + Returns name + """ + return "CompareSampleLogs" + + def summary(self): + return "Compares specified sample logs for a given list of workspaces." + + def PyInit(self): + validator = StringArrayLengthValidator() + validator.setLengthMin(1) # one group may be given + self.declareProperty(StringArrayProperty(name="InputWorkspaces", direction=Direction.Input, validator=validator), + doc="Comma separated list of workspaces or groups of workspaces.") + + self.declareProperty(StringArrayProperty(name="SampleLogs", direction=Direction.Input, validator=validator), + doc="Comma separated list of sample logs to compare.") + self.declareProperty("Tolerance", 1e-3, validator=FloatBoundedValidator(lower=1e-7), + doc="Tolerance for comparison of numeric values.") + self.declareProperty("Result", "A string that will be empty if all the logs match, " + "otherwise will contain a comma separated list of not matching logs", Direction.Output) + + return + + def validateInputs(self): + # given workspaces must exist + # and must be public of ExperimentInfo + issues = dict() + workspaces = self.getProperty("InputWorkspaces").value + for wsname in workspaces: + if not api.AnalysisDataService.doesExist(wsname): + issues["InputWorkspaces"] = "Workspace " + wsname + " does not exist." + else: + wks = api.AnalysisDataService.retrieve(wsname) + if isinstance(wks, WorkspaceGroup): + for idx in range(wks.getNumberOfEntries()): + if not isinstance(wks.getItem(idx), MatrixWorkspace): + issues["InputWorkspaces"] = "Group " + wsname + " contains workspaces of unsupported type." + elif not isinstance(wks, MatrixWorkspace): + issues["InputWorkspaces"] = "Type of workspace " + wsname + " is not supported by this algorithm." + + return issues + + def _expand_groups(self): + workspaces = self.getProperty("InputWorkspaces").value + input_workspaces = [] + for wsname in workspaces: + wks = api.AnalysisDataService.retrieve(wsname) + if isinstance(wks, WorkspaceGroup): + input_workspaces.extend(wks.getNames()) + else: + input_workspaces.append(wsname) + + return input_workspaces + + def do_match(self, pname, properties, isnum): + wsnum = len(self.wslist) + nprop = len(properties) + # if some workspaces do not have this property, return False + if nprop != wsnum: + message = "Number of properties " + str(nprop) + " for property " + pname +\ + " is not equal to number of workspaces " + str(wsnum) + self.log().information(message) + return False + + match = True + if isnum: + # check for nan + idx_nan = np.where(np.isnan(properties))[0] + if len(idx_nan) > 0: + message = "Sample log " + pname + " contains nan values. \n" +\ + "Workspaces: " + ", ".join(self.wslist) + "\n Values: " + str(properties) + self.log().information(message) + return False + + if max(properties) - min(properties) > self.tolerance: + match = False + else: + pvalue = properties[0] + if properties.count(pvalue) != nprop: + match = False + if not match: + message = "Sample log " + pname + " is not identical in the given list of workspaces. \n" +\ + "Workspaces: " + ", ".join(self.wslist) + "\n Values: " + str(properties) + self.log().information(message) + return match + + def compare_properties(self, plist): + """ + Compares properties which are required to be the same. + Produces error message and throws exception if difference is observed + or if one of the sample logs is not found. + Important: exits after the first difference is observed. No further check is performed. + @param plist List of properties to compare + """ + # retrieve the workspaces, form dictionary {wsname: run} + runs = {} + does_not_match = [] + for wsname in self.wslist: + wks = api.AnalysisDataService.retrieve(wsname) + runs[wsname] = wks.getRun() + + for prop in plist: + properties = [] + isnum = False + for wsname in self.wslist: + run = runs[wsname] + if not run.hasProperty(prop): + message = "Workspace " + wsname + " does not have sample log " + prop + self.log().warning(message) + else: + curprop = run.getProperty(prop) + if curprop.type == 'string' or curprop.type == 'number': + properties.append(curprop.value) + + else: + message = "Comparison of " + str(curprop.type) + " properties is not yet supported. Property " +\ + prop + " in the workspace " + wsname + self.log().warning(message) + + # sometimes numbers are presented as strings + try: + properties = [float(val) for val in properties] + except ValueError: + pass + else: + isnum = True + + # check whether number of properties and workspaces match + match = self.do_match(prop, properties, isnum) + if not match: + does_not_match.append(prop) + + return does_not_match + + def PyExec(self): + self.wslist = self._expand_groups() + + # no sence to compare sample logs for one workspace + if len(self.wslist) < 2: + message = "At least 2 workspaces must be given as an input." + self.log().error(message) + raise RuntimeError(message) + + lognames = self.getProperty("SampleLogs").value + self.tolerance = self.getProperty("Tolerance").value + result = '' + do_not_match = self.compare_properties(lognames) + + # return list of not matching properties + if len(do_not_match) > 0: + result = ",".join(do_not_match) + + self.setProperty("Result", result) + return + + +# Register algorithm with Mantid +AlgorithmFactory.subscribe(CompareSampleLogs) diff --git a/code/train/Python/0079592_regspace.py b/code/train/Python/0079592_regspace.py new file mode 100644 index 0000000000000000000000000000000000000000..8d5f8eb1f90f0ddf2ceca24fcad699198beada1d --- /dev/null +++ b/code/train/Python/0079592_regspace.py @@ -0,0 +1,166 @@ + +# This file is part of PyEMMA. +# +# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER) +# +# PyEMMA is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . + + +''' +Created on 26.01.2015 + +@author: marscher +''' + +from __future__ import absolute_import + +import warnings + +from pyemma.coordinates.clustering import regspatial +from pyemma.coordinates.clustering.interface import AbstractClustering +from pyemma.util.annotators import doc_inherit +from pyemma.util.exceptions import NotConvergedWarning + +import numpy as np + + +__all__ = ['RegularSpaceClustering'] + + +class RegularSpaceClustering(AbstractClustering): + r"""Regular space clustering""" + + def __init__(self, dmin, max_centers=1000, metric='euclidean', stride=1, n_jobs=None): + """Clusters data objects in such a way, that cluster centers are at least in + distance of dmin to each other according to the given metric. + The assignment of data objects to cluster centers is performed by + Voronoi partioning. + + Regular space clustering [Prinz_2011]_ is very similar to Hartigan's leader + algorithm [Hartigan_1975]_. It consists of two passes through + the data. Initially, the first data point is added to the list of centers. + For every subsequent data point, if it has a greater distance than dmin from + every center, it also becomes a center. In the second pass, a Voronoi + discretization with the computed centers is used to partition the data. + + + Parameters + ---------- + dmin : float + minimum distance between all clusters. + metric : str + metric to use during clustering ('euclidean', 'minRMSD') + max_centers : int + if this cutoff is hit during finding the centers, + the algorithm will abort. + n_jobs : int or None, default None + Number of threads to use during assignment of the data. + If None, all available CPUs will be used. + + References + ---------- + + .. [Prinz_2011] Prinz J-H, Wu H, Sarich M, Keller B, Senne M, Held M, Chodera JD, Schuette Ch and Noe F. 2011. + Markov models of molecular kinetics: Generation and Validation. + J. Chem. Phys. 134, 174105. + .. [Hartigan_1975] Hartigan J. Clustering algorithms. + New York: Wiley; 1975. + + """ + super(RegularSpaceClustering, self).__init__(metric=metric, n_jobs=n_jobs) + + self.set_params(dmin=dmin, metric=metric, max_centers=max_centers, stride=stride) + + @doc_inherit + def describe(self): + return "[RegularSpaceClustering dmin=%f, inp_dim=%i]" % (self._dmin, self.data_producer.dimension()) + + @property + def dmin(self): + """Minimum distance between cluster centers.""" + return self._dmin + + @dmin.setter + def dmin(self, d): + if d < 0: + raise ValueError("d has to be positive") + + self._dmin = float(d) + self._estimated = False + + @property + def max_centers(self): + """ + Cutoff during clustering. If reached no more data is taken into account. + You might then consider a larger value or a larger dmin value. + """ + return self._max_centers + + @max_centers.setter + def max_centers(self, value): + if value < 0: + raise ValueError("max_centers has to be positive") + + self._max_centers = int(value) + self._estimated = False + + @property + def n_clusters(self): + return self.max_centers + + @n_clusters.setter + def n_clusters(self, val): + self.max_centers = val + + def _estimate(self, iterable, **kwargs): + ######## + # Calculate clustercenters: + # 1. choose first datapoint as centroid + # 2. for all X: calc distances to all clustercenters + # 3. add new centroid, if min(distance to all other clustercenters) >= dmin + ######## + # temporary list to store cluster centers + clustercenters = [] + it = iterable.iterator(return_trajindex=False) + used_frames = 0 + try: + with iterable.iterator(return_trajindex=False, stride=self.stride, chunk=self.chunksize) as it: + for X in it: + used_frames += len(X) + regspatial.cluster(X.astype(np.float32, order='C', copy=False), + clustercenters, self.dmin, + self.metric, self.max_centers) + except RuntimeError: + msg = 'Maximum number of cluster centers reached.' \ + ' Consider increasing max_centers or choose' \ + ' a larger minimum distance, dmin.' + self._logger.warning(msg) + warnings.warn(msg) + # finished anyway, because we have no more space for clusters. Rest of trajectory has no effect + clustercenters = np.array(clustercenters) + self.update_model_params(clustercenters=clustercenters, + n_cluster=len(clustercenters)) + # pass amount of processed data + used_data = used_frames / float(it.n_frames_total()) * 100.0 + raise NotConvergedWarning("Used data for centers: %.2f%%" % used_data) + + clustercenters = np.array(clustercenters) + self.update_model_params(clustercenters=clustercenters, + n_clusters=len(clustercenters)) + + if len(clustercenters) == 1: + self._logger.warning('Have found only one center according to ' + 'minimum distance requirement of %f' % self.dmin) + + return self diff --git a/code/train/Python/0079701_ComparisonManager.py b/code/train/Python/0079701_ComparisonManager.py new file mode 100644 index 0000000000000000000000000000000000000000..fd769343a27eeeb2c4ce6d4432db68e8159c6a82 --- /dev/null +++ b/code/train/Python/0079701_ComparisonManager.py @@ -0,0 +1,94 @@ +# +# Copyright (C) 2010 GSyC/LibreSoft +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +# Author : Raul Roman Lopez +# +from opencv import cv +from math import sqrt + +class ComparisonManager: + + + def __init__(self): + self.matched_id = -1 + self.matched_goodness = 1000 + + ## Decision constants + self.MATCH_THRESHOLD = 0.2 + self.GOODNESS_THRESHOLD = 0.2 + + ## SURF constants + self.EXTENDED = 0 + self.HESSIAN_THRESHOLD = 3000 + self.NOCTAVES = 3 + self.NOCTAVELAYERS = 1 + + + def getResults(self): + return self.matched_id, self.matched_goodness + + def extractSURFPoints(self, path): + print path + image = cv.LoadImage(path, cv.CV_LOAD_IMAGE_GRAYSCALE) + (keypoints, descriptors) = cv.ExtractSURF(image, None, cv.CreateMemStorage(), (self.EXTENDED, self.HESSIAN_THRESHOLD, self.NOCTAVES, self.NOCTAVELAYERS)) + return keypoints, descriptors + + def compareTwoPhotos(self, path1, path2, data=None): + ''' This function returns the number of matching points and the goodness of the election (their mean) ''' + kp1, dp1 = self.extractSURFPoints(path1) + if data: + kp2 = data[0] + dp2 = data[1] + else: + kp2, dp2 = self.extractSURFPoints(path2) + + npoints2 = 0 + mean = 0 + for i in range(len(kp1)): + last_value1 = 500000 + last_value2 = 500000 + dsc1 = dp1[i] + lapl1 = kp1[i][1] + for k in range(len(kp2)): + # if laplacian signs doesn't match, discard the point + lapl2 = kp2[k][1] + if lapl1 != lapl2: + continue + + dsc2 = dp2[k] + value = 0 + for j in range(len(dsc1)): + value = value + pow(dsc1[j] - dsc2[j], 2) + value = sqrt(value) + if value < last_value1: + last_value2 = last_value1 + last_value1 = value + point = kp2[k][0] + elif value < last_value2: + last_value2 = value + if (abs(last_value1 - last_value2) > self.MATCH_THRESHOLD): + npoints2 += 1 + mean += last_value1 + print "Matched: %d" % (npoints2) + if npoints2 < 2: + return None, None + else: + mean = mean/npoints2 + print "Matched: %d; Mean: %f" % (npoints2, mean) + if mean < self.GOODNESS_THRESHOLD: + return (npoints2, mean) + return None, None + diff --git a/code/train/Python/0079938_smoothness_controller.py b/code/train/Python/0079938_smoothness_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..3bcd285bf5a810ac0f41c3590e3e41a8ec670c84 --- /dev/null +++ b/code/train/Python/0079938_smoothness_controller.py @@ -0,0 +1,104 @@ +# Copyright 2014 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +import sys + +from measurements import smooth_gesture_util +from telemetry.timeline.model import TimelineModel +from telemetry.page import page_measurement +from telemetry.page.actions import action_runner +from telemetry.web_perf import timeline_interaction_record as tir_module +from telemetry.web_perf.metrics import smoothness + + +RUN_SMOOTH_ACTIONS = 'RunSmoothAllActions' + + +class MissingDisplayFrameRateError(page_measurement.MeasurementFailure): + def __init__(self, name): + super(MissingDisplayFrameRateError, self).__init__( + 'Missing display frame rate metrics: ' + name) + +class SmoothnessController(object): + def __init__(self): + self._timeline_model = None + self._tracing_timeline_data = None + self._interaction = None + + def Start(self, page, tab): + # FIXME: Remove webkit.console when blink.console lands in chromium and + # the ref builds are updated. crbug.com/386847 + custom_categories = ['webkit.console', 'blink.console', 'benchmark'] + custom_categories += page.GetSyntheticDelayCategories() + tab.browser.StartTracing(','.join(custom_categories), 60) + if tab.browser.platform.IsRawDisplayFrameRateSupported(): + tab.browser.platform.StartRawDisplayFrameRateMeasurement() + # Start the smooth marker for all smooth actions. + runner = action_runner.ActionRunner(tab) + self._interaction = runner.BeginInteraction( + RUN_SMOOTH_ACTIONS, is_smooth=True) + + def Stop(self, tab): + # End the smooth marker for all smooth actions. + self._interaction.End() + # Stop tracing for smoothness metric. + if tab.browser.platform.IsRawDisplayFrameRateSupported(): + tab.browser.platform.StopRawDisplayFrameRateMeasurement() + self._tracing_timeline_data = tab.browser.StopTracing() + self._timeline_model = TimelineModel( + timeline_data=self._tracing_timeline_data) + + def AddResults(self, tab, results): + # Add results of smoothness metric. This computes the smoothness metric for + # the time ranges of gestures, if there is at least one, else the the time + # ranges from the first action to the last action. + + renderer_thread = self._timeline_model.GetRendererThreadFromTabId( + tab.id) + run_smooth_actions_record = None + smooth_records = [] + for event in renderer_thread.async_slices: + if not tir_module.IsTimelineInteractionRecord(event.name): + continue + r = tir_module.TimelineInteractionRecord.FromAsyncEvent(event) + if r.logical_name == RUN_SMOOTH_ACTIONS: + assert run_smooth_actions_record is None, ( + 'SmoothnessController cannot issue more than 1 %s record' % + RUN_SMOOTH_ACTIONS) + run_smooth_actions_record = r + elif r.is_smooth: + smooth_records.append( + smooth_gesture_util.GetAdjustedInteractionIfContainGesture( + self._timeline_model, r)) + + # If there is no other smooth records, we make measurements on time range + # marked smoothness_controller itself. + # TODO(nednguyen): when crbug.com/239179 is marked fixed, makes sure that + # page sets are responsible for issueing the markers themselves. + if len(smooth_records) == 0: + if run_smooth_actions_record is None: + sys.stderr.write('Raw tracing data:\n') + sys.stderr.write(repr(self._tracing_timeline_data.EventData())) + sys.stderr.write('\n') + raise Exception('SmoothnessController failed to issue markers for the ' + 'whole interaction.') + else: + smooth_records = [run_smooth_actions_record] + + # Create an interaction_record for this legacy measurement. Since we don't + # wrap the results that is sent to smoothnes metric, the logical_name will + # not be used. + smoothness_metric = smoothness.SmoothnessMetric() + smoothness_metric.AddResults( + self._timeline_model, renderer_thread, smooth_records, results) + if tab.browser.platform.IsRawDisplayFrameRateSupported(): + for r in tab.browser.platform.GetRawDisplayFrameRateMeasurements(): + if r.value is None: + raise MissingDisplayFrameRateError(r.name) + results.Add(r.name, r.unit, r.value) + + def CleanUp(self, tab): + if tab.browser.platform.IsRawDisplayFrameRateSupported(): + tab.browser.platform.StopRawDisplayFrameRateMeasurement() + if tab.browser.is_tracing_running: + tab.browser.StopTracing() diff --git a/code/train/Python/0080114_ps4b.py b/code/train/Python/0080114_ps4b.py new file mode 100644 index 0000000000000000000000000000000000000000..ec5c214ff04a000831db74687bb101b253235394 --- /dev/null +++ b/code/train/Python/0080114_ps4b.py @@ -0,0 +1,165 @@ +from ps4a import * +import time + +# +# +# Problem #6: Computer chooses a word +# +# +def compChooseWord(hand, wordList, n): + """ + Given a hand and a wordList, find the word that gives + the maximum value score, and return it. + + This word should be calculated by considering all the words + in the wordList. + + If no words in the wordList can be made from the hand, return None. + + hand: dictionary (string -> int) + wordList: list (string) + n: integer (HAND_SIZE; i.e., hand size required for additional points) + + returns: string or None + """ + # Create a new variable to store the maximum score seen so far (initially 0) + max_score = 0 + # Create a new variable to store the best word seen so far (initially None) + best_word = None + # For each word in the wordList + for word in wordList: + # If you can construct the word from your hand + if isValidWord(word, hand, wordList): + # (hint: you can use isValidWord, or - since you don't really need to test if the word is in the wordList - you can make a similar function that omits that test) + + # Find out how much making that word is worth + candidate_to_be_best = getWordScore(word, n) + # If the score for that word is higher than your best score + if candidate_to_be_best > max_score: + max_score = candidate_to_be_best + best_word = word + # Update your best score, and best word accordingly + return best_word + # return the best word you found. + +# +# Problem #7: Computer plays a hand +# +def compPlayHand(hand, wordList, n): + """ + Allows the computer to play the given hand, following the same procedure + as playHand, except instead of the user choosing a word, the computer + chooses it. + + 1) The hand is displayed. + 2) The computer chooses a word. + 3) After every valid word: the word and the score for that word is + displayed, the remaining letters in the hand are displayed, and the + computer chooses another word. + 4) The sum of the word scores is displayed when the hand finishes. + 5) The hand finishes when the computer has exhausted its possible + choices (i.e. compChooseWord returns None). + + hand: dictionary (string -> int) + wordList: list (string) + n: integer (HAND_SIZE; i.e., hand size required for additional points) + """ + # Keep track of the total score + total = 0 + # As long as there are still letters left in the hand: + #end_reason = 'Run out of letters.' + while calculateHandlen(hand) > 0: + # Display the hand + print 'Current Hand: ', + displayHand(hand) + comp_inp = compChooseWord(hand, wordList, n) + if comp_inp == None: + break + erned_points = getWordScore(comp_inp, n) + total += erned_points + hand = updateHand(hand, comp_inp) + print '"%s" erned %s points. Total: %s points' %(comp_inp,erned_points, total ) + print '' + + print 'Total score: %s points.' %(total) + +# +# Problem #8: Playing a game +# +# +def playGame(wordList): + """ + Allow the user to play an arbitrary number of hands. + + 1) Asks the user to input 'n' or 'r' or 'e'. + * If the user inputs 'e', immediately exit the game. + * If the user inputs anything that's not 'n', 'r', or 'e', keep asking them again. + + 2) Asks the user to input a 'u' or a 'c'. + * If the user inputs anything that's not 'c' or 'u', keep asking them again. + + 3) Switch functionality based on the above choices: + * If the user inputted 'n', play a new (random) hand. + * Else, if the user inputted 'r', play the last hand again. + + * If the user inputted 'u', let the user play the game + with the selected hand, using playHand. + * If the user inputted 'c', let the computer play the + game with the selected hand, using compPlayHand. + + 4) After the computer or user has played the hand, repeat from step 1 + + wordList: list (string) + """ + game = True + hand = None + while game: + here = True + user_inp = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ') + if user_inp == 'e': + game = False + return + elif user_inp not in ['n','r','e']: + print 'Invalid command.' + continue + elif user_inp == 'r': + if hand == None: + print 'You have not played a hand yet. Please play a new hand first!' + continue + print '' + while here: + user_inp2 = raw_input('Enter u to have yourself play, c to have the computer play: ') + #print '' + if user_inp2 not in ['u','c']: + print 'Invalid command.' + continue + else: + user_inp += user_inp2 + here = False + + if user_inp[0] == 'n': + hand = dealHand(HAND_SIZE) + if user_inp[1] == 'u': + playHand(hand, wordList, HAND_SIZE) + elif user_inp[1] == 'c': + compPlayHand(hand, wordList, HAND_SIZE) + elif user_inp[0] == 'r': + if hand == None: + print 'You have not played a hand yet. Please play a new hand first!' + elif hand: + if user_inp[1] == 'u': + playHand(hand, wordList, HAND_SIZE) + elif user_inp[1] == 'c': + compPlayHand(hand, wordList, HAND_SIZE) + + return + + +# +# Build data structures used for entire session and play game +# +if __name__ == '__main__': + wordList = loadWords() + playGame(wordList) + + diff --git a/code/train/Python/0080337_selection.py b/code/train/Python/0080337_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..2c3dfebd7855eacef781d9327775c4d526be615e --- /dev/null +++ b/code/train/Python/0080337_selection.py @@ -0,0 +1,21 @@ +# selection.py +# This is an selection sort example +# + +def selection_sort(list2): + for i in range(0, len (list2)): # Step through entire list + min = i # Minimum value equals outside range + for j in range(i + 1, len(list2)): # Step through everything above first loop incrementer + if list2[j] < list2[min]: # If the compared number is lower than the minimum, make it the minimum + min = j + list2[i], list2[min] = list2[min], list2[i] # After going through list, swap the outer list position number with the found lowest number + return(list2) + +def main(): + print("Insertion Sort") + list1 = [4,7,3,2,9,0,4,2,1,6,7] + print(list1) + list2 = selection_sort(list1) + print(list2) + +main() diff --git a/code/train/Python/0080520_transcript_orientations.py b/code/train/Python/0080520_transcript_orientations.py new file mode 100644 index 0000000000000000000000000000000000000000..921494c4bc3bfee3a8b7360cc8536ad6becd5b7a --- /dev/null +++ b/code/train/Python/0080520_transcript_orientations.py @@ -0,0 +1,171 @@ +# Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia +# This file is part of ngs_crumbs. +# ngs_crumbs is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. + +# ngs_crumbs is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with ngs_crumbs. If not, see . + + +from itertools import compress +import os.path + +from crumbs.seq.annotation import (PolyaAnnotator, EstscanOrfAnnotator, + BlastAnnotator) +from crumbs.seq.utils.seq_utils import append_to_description +from crumbs.utils.tags import SEQRECORD +from crumbs.seq.seq import SeqWrapper + + +class TranscriptOrientator(object): + '''This class orientates the transcripts + + It can take into account: poly-A, ORFs and blast matches''' + + def __init__(self, polya_params=None, estscan_params=None, + blast_params=None): + self._polya_params = polya_params + self._estscan_params = estscan_params + self._blast_params = blast_params + + self._annotators = self._create_pipeline() + + def _create_pipeline(self): + 'It creates the annotation pipeline' + # pylint: disable=W0142 + annotators = [] + if self._polya_params: + annotators.append({'name': 'polyA'}) + if self._estscan_params: + annotators.append({'name': 'estscan_orf'}) + if self._blast_params: + for blast_param in self._blast_params: + annotators.append({'name': 'blast', + 'blastdb': blast_param['blastdb']}) + return annotators + + @staticmethod + def _select_features_by_type(features, kind): + 'it selects features by type' + return [feat for feat in features if feat.type == kind] + + def _polya_selector(self, features): + 'It selects the polya' + # pylint: disable=W0613 + feats = self._select_features_by_type(features, 'polyA_sequence') + if feats: + return feats[0] + + def _orf_selector(self, features): + 'it returns the longest feature' + # pylint: disable=W0613 + features = self._select_features_by_type(features, 'ORF') + if not features: + return None + + lengths = [len(feat) for feat in features] + return features[lengths.index(max(lengths))] + + def _match_part_selector(self, features, blastdb): + 'it return the match_part with the best e-value' + blastdb = os.path.basename(blastdb) + features = self._select_features_by_type(features, 'match_part') + features = [f for f in features if f.qualifiers['blastdb'] == blastdb] + + if not features: + return None + scores = [feat.qualifiers['score'] for feat in features] + return features[scores.index(min(scores))] + + def _guess_orientations(self, seqs, annotator_name, blastdb): + '''It returns the orientation of the annotated transcripts.''' + orientations = [] + for seq in seqs: + if annotator_name == 'polyA': + feature = self._polya_selector(seq.object.features) + elif annotator_name == 'estscan_orf': + feature = self._orf_selector(seq.object.features) + elif annotator_name == 'blast': + feature = self._match_part_selector(seq.object.features, + blastdb=blastdb) + else: + raise NotImplementedError('This annotator type not supported') + + orientation = None if feature is None else feature.strand + orientations.append(orientation) + return orientations + + def _get_annotator(self, annotator_name, blastdb): + 'It prepares and returns the annotator' + if annotator_name == 'polyA': + annotator = PolyaAnnotator(**self._polya_params) + elif annotator_name == 'estscan_orf': + annotator = EstscanOrfAnnotator(**self._estscan_params) + elif annotator_name == 'blast': + blast_param = None + for blast_param_ in self._blast_params: + if blastdb == blast_param_['blastdb']: + blast_param = blast_param_ + break + annotator = BlastAnnotator(**blast_param) + else: + raise NotImplementedError('This annotator type not supported') + return annotator + + def __call__(self, seqs): + 'It orientates seqs, that should have a SeqRecord in it' + orientations = None + orientation_log = [None] * len(seqs) + + for annotator in self._annotators: + if orientations: + to_annalyze = [not o for o in orientations] + seqs_to_analyze = list(compress(seqs, to_annalyze)) + else: + orientations = [None] * len(seqs) + seqs_to_analyze = seqs + + annotator_name = annotator['name'] + blastdb = annotator.get('blastdb', None) + annotator = self._get_annotator(annotator_name, blastdb) + + annot_seqrecords = annotator(seqs_to_analyze) + annot_strands = self._guess_orientations(annot_seqrecords, + annotator_name, + blastdb=blastdb) + + if blastdb: + annotator_name += ' ' + os.path.basename(blastdb) + + analyzed_seqs_index = 0 + for index, orientation in enumerate(orientations): + if orientation is None: + orientations[index] = annot_strands[analyzed_seqs_index] + if annot_strands[analyzed_seqs_index] == -1: # reverse + orientation_log[index] = annotator_name + analyzed_seqs_index += 1 + # Now we reverse the seqs that we have guess that are reversed + reorientated_seqrecords = [] + for orientation, seq, reason in zip(orientations, seqs, + orientation_log): + if orientation == -1: + rev_seqrecord = seq.object.reverse_complement(id=True, + description=True, + annotations=True, + features=True, + dbxrefs=True, + name=True) + seq = SeqWrapper(SEQRECORD, rev_seqrecord, None) + # we mark the reason why it has been reversed + text = '(reversed because of: {})'.format(reason) + append_to_description(seq, text) + + reorientated_seqrecords.append(seq) + return reorientated_seqrecords diff --git a/code/train/Python/0080654_compareResult.py b/code/train/Python/0080654_compareResult.py new file mode 100644 index 0000000000000000000000000000000000000000..24f8c31d2d3ca6df1cce0e11dc6bca5ac5878978 --- /dev/null +++ b/code/train/Python/0080654_compareResult.py @@ -0,0 +1,172 @@ +accuracy = 1e-8 + +class Cell: + def __init__(self, vtkCell, bounds, q): + self.vtkCell = vtkCell + self.bounds = bounds + self.q = q + + def __eq__(self, other): + global accuracy + if abs(self.q - other.q) > accuracy: + return false + + if len(sel.bounds) != len(other.bounds): + return false + + for i in xrange(len(self.bounds)): + if abs(self.bounds[i] - other.bounds[i]) > accuracy: + return false + + return true + + def __cmp__(self, other): + global accuracy + if self.q - other.q > accuracy: + return 1 + elif other.q - self.q > accuracy: + return -1 + + if len(self.bounds) != len(other.bounds): + return false + + for i in xrange(len(self.bounds)): + if self.bounds[i] - other.bounds[i] > accuracy: + return 1 + elif other.bounds[i] - self.bounds[i] > accuracy: + return -1 + + return 0 + + def __str__(self): + return "q: " + str(self.q) + " bounds: " + str(self.bounds) + +def parseRange(argument): + if ':' in argument: + return range(*map(int, argument.split(':'))) + return range(int(argument), int(argument)+1) + +def readCellsFromFile(cells, path, iteration, rank): + import vtk + import os.path + filename = path.replace('__ITERATION__', str(iteration)).replace('__RANK__', str(rank)) + + if os.path.exists(filename): + reader = vtk.vtkDataSetReader() + reader.SetFileName(filename) + reader.SetReadAllScalars(True) + reader.Update() + + grid = reader.GetOutput() + + numberOfCells = grid.GetNumberOfCells() + cellData = grid.GetCellData() + qs = cellData.GetScalars("q0") + + for cellId in xrange(numberOfCells): + vtkCell = grid.GetCell(cellId) + + q = qs.GetTuple(cellId)[0] + cells.append(Cell(vtkCell, vtkCell.GetBounds()[:], q)) + + return numberOfCells + else: + return 0 + + +def findClosestMatch(cell, cells): + bestIndex = -1 + minDistance = 1000000 + import math + for index in xrange(len(cells)): + c = cells[index] + distance = 0 + for i in xrange(len(cell.bounds)): + distance += (cell.bounds[i] - c.bounds[i])**2 + distance = math.sqrt((c.q - cell.q)**2 * 10 + distance) + + if distance < minDistance: + minDistance = distance + bestIndex = index + return bestIndex + +def findCellInList(cell, cells): + lower = 0 + upper = len(cells) + + while(upper > lower): + middle = (upper + lower) / 2 + middleCell = cells[middle] + if middleCell < cell: + lower = middle + 1 + elif middleCell > cell: + upper = middle + else: + return middle + + return -1 + +def main(): + from argparse import ArgumentParser + parser = ArgumentParser(description='Tool for comparing vtk output of parallel runs.') + parser.add_argument('path1', help='The path to the first set of vtk files. Use __ITERATION__ for iteration number and __RANK__ for rank number.') + parser.add_argument('path2', help='The path to the second set of vtk files. Use __ITERATION__ for iteration number and __RANK__ for rank number.') + parser.add_argument('iteration1', type=int, help='The iteration number of the first set of vtk files.') + parser.add_argument('ranks1', help='The range of ranks for the first set of vtk files. Define single number or min:max.') + parser.add_argument('iteration2', type=int, help='The iteration number of the second set of vtk files.') + parser.add_argument('ranks2', help='The range of ranks for the second set of vtk files. Define single number or min:max.') + parser.add_argument('accuracy', help='The accuracy for numerical equality.', type=float, nargs='?', const='1e-5') + arguments = parser.parse_args() + + global accuracy + accuracy = arguments.accuracy + if arguments.path2 == 'SameAsPath1': + path2 = arguments.path1 + else: + path2 = arguments.path2 + + #Loop through ranks1 + cells1 = [] #set() + ranks1 = parseRange(arguments.ranks1) + for rank in ranks1: + print "1: Parsing rank...", rank + numberOfCells = readCellsFromFile(cells1, arguments.path1, arguments.iteration1, rank) + print "Read", numberOfCells, "cells." + print "1: Total number of cells:", len(cells1) + + #Loop through ranks2 + cells2 = [] #set() + ranks2 = parseRange(arguments.ranks2) + + print ranks2 + + for rank in ranks2: + print "2: Parsing rank", rank + numberOfCells = readCellsFromFile(cells2, path2, arguments.iteration2, rank) + print "Read", numberOfCells, "cells." + print "2: Total number of cells:", len(cells2) + + #Compare lists + if len(cells1) != len(cells2): + raise Exception("Number of cells do not match!") + + cells1.sort() + cells2.sort() + + for cell in cells1: + index = findCellInList(cell, cells2) + + if index == -1: + bestMatch = findClosestMatch(cell, cells2) + if bestMatch == -1: + bestMatchString = "" + else: + bestMatchString = "Best match is " + str(cells2[bestMatch]) + raise Exception("No matching cell for " + str(cell) + ". " + bestMatchString) + else: + del cells2[index] + + print "All cells match" + +if __name__=="__main__": + main() diff --git a/code/train/Python/0080728_environment.py b/code/train/Python/0080728_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..969139a80d12617cbb10f35533511826d382ae49 --- /dev/null +++ b/code/train/Python/0080728_environment.py @@ -0,0 +1,198 @@ +# This file is part of Rubber and thus covered by the GPL +# (c) Emmanuel Beffara, 2002--2006 +# vim: noet:ts=4 +""" +This module contains the code for formatted message output (the Message class) +and the class Environment, which contains all information about a given +building process. +""" + +import os, os.path, sys, subprocess, thread +import re, string +from subprocess import Popen + +from rubber.util import _ +from rubber.util import * +import rubber.converters +import rubber.depend +from rubber.convert import Converter + +re_kpse = re.compile("kpathsea: Running (?P[^ ]*).* (?P[^ ]*)$") + +class Environment: + """ + This class contains all state information related to the building process + for a whole document, the dependency graph and conversion rules. + """ + def __init__ (self, cwd=None): + """ + Initialize the environment. The optional argument is the path to the + reference directory for compilation, by default it is the current + working directory. + """ + self.kpse_msg = { + "mktextfm" : _("making font metrics for \\g"), + "mktexmf" : _("making font \\g"), + "mktexpk" : _("making bitmap for font \\g") + } + + if cwd is None: cwd = os.getcwd() + self.vars = Variables(items = { 'cwd': cwd, '_environment': self }) + self.path = [cwd] + self.conv_prefs = {} + + # Represents a set of dependency nodes. Nodes can be accessed by absolute + # path name using the dictionary interface. + self.depends = dict() + self.converter = Converter(self.depends) + self.converter.read_ini (os.path.join (rubber.__path__[0], 'rules.ini')) + + self.is_in_unsafe_mode_ = False + self.doc_requires_shell_ = False + self.synctex = False + self.main = None + self.final = None + + def find_file (self, name, suffix=None): + """ + Look for a source file with the given name, and return either the + complete path to the actual file or None if the file is not found. + The optional argument is a suffix that may be added to the name. + """ + for path in self.path: + test = os.path.join(path, name) + if suffix and os.path.exists(test + suffix) and os.path.isfile(test + suffix): + return test + suffix + elif os.path.exists(test) and os.path.isfile(test): + return test + return None + + def conv_set (self, file, vars): + """ + Define preferences for the generation of a given file. The argument + 'file' is the name of the target and the argument 'vars' is a + dictionary that contains imposed values for some variables. + """ + self.conv_prefs[file] = vars + + def convert (self, target, prefixes=[""], suffixes=[""], check=None, context=None): + """ + Use conversion rules to make a dependency tree for a given target + file, and return the final node, or None if the file does not exist + and cannot be built. The optional arguments 'prefixes' and 'suffixes' + are lists of strings that can be added at the beginning and the end of + the name when searching for the file. Prefixes are tried in order, and + for each prefix, suffixes are tried in order; the first file from this + order that exists or can be made is kept. The optional arguments + 'check' and 'context' have the same meaning as in + 'Converter.best_rule'. + """ + # Try all suffixes and prefixes until something is found. + + last = None + for t in [p + target + s for s in suffixes for p in prefixes]: + + # Define a check function, according to preferences. + + if self.conv_prefs.has_key(t): + prefs = self.conv_prefs[t] + def do_check (vars, prefs=prefs): + if prefs is not None: + for key, val in prefs.items(): + if not (vars.has_key(key) and vars[key] == val): + return 0 + return 1 + else: + prefs = None + do_check = check + + # Find the best applicable rule. + + ans = self.converter.best_rule(t, check=do_check, context=context) + if ans is not None: + if last is None or ans["cost"] < last["cost"]: + last = ans + + # Check if the target exists. + + if prefs is None and os.path.exists(t): + if last is not None and last["cost"] <= 0: + break + msg.log(_("`%s' is `%s', no rule applied") % (target, t)) + return rubber.depend.Leaf(self.depends, t) + + if last is None: + return None + msg.log(_("`%s' is `%s', made from `%s' by rule `%s'") % + (target, last["target"], last["source"], last["name"])) + return self.converter.apply(last) + + def may_produce (self, name): + """ + Return true if the given filename may be that of a file generated by + any of the converters. + """ + return self.converter.may_produce(name) + + def execute (self, prog, env={}, pwd=None, out=None, kpse=0): + """ + Silently execute an external program. The `prog' argument is the list + of arguments for the program, `prog[0]' is the program name. The `env' + argument is a dictionary with definitions that should be added to the + environment when running the program. The standard output is passed + line by line to the `out' function (or discarded by default). If the + optional argument `kpse' is true, the error output is parsed and + messages from Kpathsea are processed (to indicate e.g. font + compilation), otherwise the error output is kept untouched. + """ + msg.info(_("executing: %s") % string.join(prog)) + if pwd: + msg.log(_(" in directory %s") % pwd) + if env != {}: + msg.log(_(" with environment: %r") % env) + + progname = prog_available(prog[0]) + if not progname: + msg.error(_("%s not found") % prog[0]) + return 1 + + penv = os.environ.copy() + for (key,val) in env.items(): + penv[key] = val + + if kpse: + stderr = subprocess.PIPE + else: + stderr = None + + process = Popen(prog, + executable = progname, + env = penv, + cwd = pwd, + stdin = devnull(), + stdout = subprocess.PIPE, + stderr = stderr) + + if kpse: + def parse_kpse (): + for line in process.stderr: + line = line.rstrip() + match = re_kpse.match(line) + if not match: + continue + cmd = match.group("cmd") + if self.kpse_msg.has_key(cmd): + msg.progress(match.expand(self.kpse_msg[cmd])) + else: + msg.progress(_("kpathsea running %s") % cmd) + thread.start_new_thread(parse_kpse, ()) + + if out is not None: + for line in process.stdout: + out(line) + else: + process.stdout.readlines() + + ret = process.wait() + msg.log(_("process %d (%s) returned %d") % (process.pid, prog[0],ret)) + return ret diff --git a/code/train/Python/0080847_mongo_doc_manager.py b/code/train/Python/0080847_mongo_doc_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..f686dd9bb130916b09db4b8b1673b772628eb752 --- /dev/null +++ b/code/train/Python/0080847_mongo_doc_manager.py @@ -0,0 +1,144 @@ +# Copyright 2012 10gen, Inc. +# +# 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. + +# This file will be used with PyPi in order to package and distribute the final +# product. + +"""Receives documents from the oplog worker threads and indexes them + into the backend. + + This file is a document manager for MongoDB, but the intent + is that this file can be used as an example to add on different backends. + To extend this to other systems, simply implement the exact same class and + replace the method definitions with API calls for the desired backend. + """ + +import pymongo + +class DocManager(): + """The DocManager class creates a connection to the backend engine and + adds/removes documents, and in the case of rollback, searches for them. + + The reason for storing id/doc pairs as opposed to doc's is so that + multiple updates to the same doc reflect the most up to date version as + opposed to multiple, slightly different versions of a doc. + + We are using MongoDB native fields for _id and ns, but we also store + them as fields in the document, due to compatibility issues. + """ + + def __init__(self, url, unique_key='_id'): + """ Verify URL and establish a connection. + """ + try: + self.mongo = pymongo.Connection(url) + except pymongo.errors.InvalidURI: + raise SystemError + except pymongo.errors.ConnectionFailure: + raise SystemError + self.unique_key = unique_key + + def stop(self): + """Stops any running threads + """ + pass + + def upsert(self, doc): + """Update or insert a document into Mongo + """ + database, coll = doc['ns'].split('.', 1) + try: + self.mongo[database][coll].save(doc) + except pymongo.errors.OperationFailure: + raise SystemError + + def remove(self, doc): + """Removes document from Mongo + + The input is a python dictionary that represents a mongo document. + The documents has ns and _ts fields. + """ + database, coll = doc['ns'].split('.', 1) + self.mongo[database][coll].remove( + {self.unique_key: doc[self.unique_key]}) + + def search(self, start_ts, end_ts): + """Called to query Mongo for documents in a time range. + """ + search_set = [] + db_list = self.mongo.database_names() + for database in db_list: + if database == "config" or database == "local": + continue + coll_list = self.mongo[database].collection_names() + for coll in coll_list: + if coll.startswith("system"): + continue + namespace = str(database) + "." + str(coll) + search_set.append(namespace) + + res = [] + for namespace in search_set: + database, coll = namespace.split('.', 1) + target_coll = self.mongo[database][coll] + res.extend(list(target_coll.find({'_ts': {'$lte': end_ts, + '$gte': start_ts}}))) + + return res + + def commit(self): + """ Performs a commit + """ + return + + def get_last_doc(self): + """Returns the last document stored in Mongo. + """ + search_set = [] + db_list = self.mongo.database_names() + for database in db_list: + if database == "config" or database == "local": + continue + coll_list = self.mongo[database].collection_names() + for coll in coll_list: + if coll.startswith("system"): + continue + namespace = str(database) + "." + str(coll) + search_set.append(namespace) + + res = [] + for namespace in search_set: + database, coll = namespace.split('.', 1) + target_coll = self.mongo[database][coll] + res.extend(list(target_coll.find().sort('_ts', -1))) + + max_ts = 0 + max_doc = None + for item in res: + if item['_ts'] > max_ts: + max_ts = item['_ts'] + max_doc = item + + return max_doc + + def _remove(self): + """For test purposes only. Removes all documents in test.test + """ + self.mongo['test']['test'].remove() + + def _search(self): + """For test purposes only. Performs search on Elastic with empty query. + Does not have to be implemented. + """ + return list(self.mongo['test']['test'].find()) diff --git a/code/train/Python/0081227_borderlayout.py b/code/train/Python/0081227_borderlayout.py new file mode 100644 index 0000000000000000000000000000000000000000..59b3574a922038cc44347ab6d581fd6288693435 --- /dev/null +++ b/code/train/Python/0081227_borderlayout.py @@ -0,0 +1,181 @@ +# This file is part of the Frescobaldi project, http://www.frescobaldi.org/ +# +# Copyright (c) 2008 - 2014 by Wilbert Berendsen +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# See http://www.gnu.org/licenses/ for more information. + +""" +Manages widgets in the borders of a QScrollArea. +""" + +from PyQt4.QtCore import QEvent, QObject, QPoint, QRect, QSize + + +LEFT, TOP, RIGHT, BOTTOM = 0, 1, 2, 3 + +class BorderLayout(QObject): + + # order in which the widget spaces are filled. + # if top and bottom are first, they get the full width. + order = TOP, BOTTOM, LEFT, RIGHT + + def __init__(self, scrollarea): + super(BorderLayout, self).__init__(scrollarea) + self._resizing = False + self._margins = 0, 0, 0, 0 + self._widgets = ([], [], [], []) + scrollarea.viewport().installEventFilter(self) + + @classmethod + def get(cls, scrollarea): + """Gets the BorderLayout for the given scrollarea. + + If None exists, creates and returns a new instance. + + """ + for c in scrollarea.children(): + if type(c) is cls: + return c + return cls(scrollarea) + + def scrollarea(self): + """Returns our scrollarea instance (our parent).""" + return self.parent() + + def addWidget(self, widget, side): + """Adds a widget to our scrollarea.""" + self.insertWidget(widget, side, -1) + + def insertWidget(self, widget, side, position): + """Inserts a widget in a specific position.""" + assert side in (LEFT, TOP, RIGHT, BOTTOM) + new = False + for l in self._widgets: + if widget in l: + l.remove(widget) + break + else: + new = True + widget.setParent(self.scrollarea()) + widget.installEventFilter(self) + if position == -1: + self._widgets[side].append(widget) + else: + self._widgets[side].insert(widget, position) + if new: + widget.show() + self.updateGeometry() + + def removeWidget(self, widget): + """Removes the widget, it is not deleted.""" + for l in self._widgets: + if widget in l: + l.remove(widget) + widget.removeEventFilter(self) + widget.setParent(None) + self.updateGeometry() + + def setViewportMargins(self, left, top, right, bottom): + """(Internal) Sets the viewport margins and remembers them.""" + self._margins = (left, top, right, bottom) + try: + self.scrollarea().setViewportMargins(left, top, right, bottom) + except RuntimeError: + # this can happen when the scrollarea already is deleted by Python + # because setViewportMargins is a protected method + pass + + def viewportGeometry(self): + """(Internal) Returns the viewport geometry as if with 0 margins.""" + g = self.scrollarea().viewport().geometry() + left, top, right, bottom = self._margins + return g.adjusted(-left, -top, right, bottom) + + def eventFilter(self, obj, ev): + """Reimplemented to handle resizes and avoid resize loops.""" + if self._resizing: + return False + elif ev.type() == QEvent.Resize and obj is self.scrollarea().viewport(): + self.updateGeometry() + elif ev.type() in (QEvent.Resize, QEvent.ShowToParent, QEvent.HideToParent): + self.updateGeometry() + elif ev.type() in (QEvent.ParentChange, QEvent.DeferredDelete) and obj is not self.scrollarea().viewport(): + for l in self._widgets: + if obj in l: + l.remove(obj) + obj.removeEventFilter(self) + self.updateGeometry() + break + return False + + def updateGeometry(self): + """(Internal) Positions all widgets in the scrollarea edges.""" + self._resizing = True + g = self.viewportGeometry() + pos = g.topLeft() + size = g.size() + left, right, top, bottom = 0, 0, 0, 0 + + for side in self.order: + def widgets(): + for w in self._widgets[side][::-1]: + if w.isVisibleTo(self.scrollarea()): + yield w + if side is LEFT: + for widget in widgets(): + w = widget.sizeHint().width() + h = size.height() - top - bottom + x = left + y = top + g = QRect(pos + QPoint(x, y), QSize(w, h)) + widget.setGeometry(g) + left += w + elif side is RIGHT: + for widget in widgets(): + w = widget.sizeHint().width() + h = size.height() - top - bottom + x = size.width() - right - w + y = top + g = QRect(pos + QPoint(x, y), QSize(w, h)) + widget.setGeometry(g) + right += w + elif side is TOP: + for widget in widgets(): + w = size.width() - left - right + h = widget.heightForWidth(w) + if h == -1: + h = widget.sizeHint().height() + x = left + y = top + g = QRect(pos + QPoint(x, y), QSize(w, h)) + widget.setGeometry(g) + top += h + elif side is BOTTOM: + for widget in widgets(): + w = size.width() - left - right + h = widget.heightForWidth(w) + if h == -1: + h = widget.sizeHint().height() + x = left + y = size.height() - bottom - h + g = QRect(pos + QPoint(x, y), QSize(w, h)) + widget.setGeometry(g) + bottom += h + self.setViewportMargins(left, top, right, bottom) + self._resizing = False + + + diff --git a/code/train/Python/0081256_text.py b/code/train/Python/0081256_text.py new file mode 100644 index 0000000000000000000000000000000000000000..0e0ca1cae6cb1613582e34f5d0a32cc5c48d461f --- /dev/null +++ b/code/train/Python/0081256_text.py @@ -0,0 +1,86 @@ +from toast.scene_graph import GameObject + + +class Text(GameObject): + def __init__(self, font, message): + """Class Constructor + + font: A BitmapFont object. + message: A string. + """ + super(Text, self).__init__() + + self.font = font + self.__position = (0, 0) + self.__time = 0 + self.visible = True + self.__message = message + + self.char_list = [] + self.position_list = [] + + self.__update_char_list() + self._update_chars() + + def update(self, time=0.1667): + super(Text, self).update(time) + + self.time += time + + def _update_chars(self, time=0.1667): + left = 0 + index = 0 + for (_, rect) in self.char_list: + rect.left = self.position[0] + self.position_list[index][0] + rect.top = self.position[1] + self.position_list[index][1] + left += rect.width + index += 1 + + def render(self, surface, offset=(0, 0)): + if not self.visible: + return + + for (image, rect) in self.char_list: + surface.blit(image, rect) + + @property + def message(self): + return self.__message + + @message.setter + def message(self, message): + self.__message = message + self.__update_char_list() + + def __update_char_list(self): + self.char_list = [] + self.position_list = [] + + left = 0 + top = 0 + + # Build the list of characters + for char in self.__message: + image = self.font.render(char) + rect = image.get_rect() + rect.left = left + rect.top = top + self.char_list.append((image, rect)) + self.position_list.append((left, top)) + left += rect.width + + def GetPosition(self): + return self.__position + + def SetPosition(self, position): + self.__position = position + + position = property(GetPosition, SetPosition) + + def GetTime(self): + return self.__time + + def SetTime(self, time): + self.__time = time + + time = property(GetTime, SetTime) diff --git a/code/train/Python/0081368_filename.py b/code/train/Python/0081368_filename.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb63844b665011c02e2957c327be846038f0ef3 --- /dev/null +++ b/code/train/Python/0081368_filename.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- + +import os +import re +import logging +import glob +import itertools +from completor import Completor, LIMIT + +from .utils import test_subseq + + +logger = logging.getLogger('completor') +PAT = re.compile(r'(\w{2,}:(//?[^\s]*)?)|(]*>?)|(//)') +START_NO_DIRNAME = re.compile(r'^(\.{0,2}/|~/|[a-zA-Z]:/|\$)') + + +def gen_entry(pat, dirname, basename, offset): + prefix = len(dirname) + if os.path.dirname(dirname) != dirname: + prefix += 1 + for fname in glob.iglob(pat): + entry = fname[prefix:] + score = test_subseq(basename, entry) + if score is None: + continue + + abbr = '' + if os.path.isdir(os.path.join(dirname, entry)): + abbr = ''.join([entry, os.sep]) + if entry.startswith('.'): + score += 100000 + entry = { + 'word': entry, + 'abbr': abbr, + 'menu': '[F]', + 'offset': offset, + } + yield entry, score + + +def find(current_dir, input_data, offset): + path_dir = os.path.expanduser(os.path.expandvars(input_data)) + if not path_dir: + return [] + + dirname, basename = os.path.split(path_dir) + if not dirname: + dirname = '.' + + if not os.path.isabs(dirname): + dirname = os.path.join(current_dir, dirname) + + def _pat(p): + return os.path.join(dirname, p) + + hidden = gen_entry(_pat('.*'), dirname, basename, offset) + chain = gen_entry(_pat('*'), dirname, basename, offset), hidden + + entries = list(itertools.islice(itertools.chain(*chain), LIMIT)) + entries.sort(key=lambda x: x[1]) + return entries + + +class Filename(Completor): + filetype = 'filename' + + sync = True + trigger = re.compile(r""" + # Head part + (?: + # '/', './', '../', or '~' + \.{0,2}/|~| + + # '$var/' + \$[A-Za-z0-9{}_]+/| + + # 'c:/' + (?= N: + respuesta.append(N-x) + condicion = False + else: + while S[paso]: + paso -= 1 + if paso == x: + respuesta = [-1] + break + respuesta.append(paso-x) + x = paso +respuesta.reverse() +print(*respuesta) \ No newline at end of file diff --git a/code/train/Python/0083300_namelist.py b/code/train/Python/0083300_namelist.py new file mode 100644 index 0000000000000000000000000000000000000000..17fca270ef4b5d1e2ccbad54727abf2928009e3c --- /dev/null +++ b/code/train/Python/0083300_namelist.py @@ -0,0 +1,89 @@ +# Copyright (C) British Crown (Met Office) & Contributors. +# This file is part of Rose, a framework for meteorological suites. +# +# Rose is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Rose is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Rose. If not, see . +# ----------------------------------------------------------------------------- +"""Process namelist: sections in a metomi.rose.config.ConfigNode matching a +name.""" + + +from functools import cmp_to_key +import re + +import metomi.rose.config +from metomi.rose.config_processor import ConfigProcessError +from metomi.rose.env import UnboundEnvironmentVariableError, env_var_process +from metomi.rose.reporter import Event + +RE_NAMELIST_GROUP = re.compile(r"\Anamelist:(\w+).*\Z") + + +class NamelistEvent(Event): + + LEVEL = Event.VV + + +class NamelistLocHandler: + """Handler of namelists.""" + + SCHEME = "namelist" + + def __init__(self, manager): + self.manager = manager + + def can_pull(self, loc): + return loc.name.startswith(self.SCHEME + ":") + + def parse(self, loc, conf_tree): + """Set loc.scheme, loc.loc_type.""" + loc.scheme = self.SCHEME + loc.loc_type = loc.TYPE_BLOB + if loc.name.endswith("(:)"): + name = loc.name[0:-2] + sections = [ + k for k in list(conf_tree.node.value) if k.startswith(name) + ] + else: + sections = [k for k in list(conf_tree.node.value) if k == loc.name] + for section in list(sections): + section_value = conf_tree.node.get_value([section]) + if section_value is None: + sections.remove(section) + if not sections: + raise ValueError(loc.name) + return sections + + async def pull(self, loc, conf_tree): + """Write namelist to loc.cache.""" + sections = self.parse(loc, conf_tree) + if loc.name.endswith("(:)"): + sections.sort(key=cmp_to_key(metomi.rose.config.sort_settings)) + with open(loc.cache, "wb") as handle: + for section in sections: + section_value = conf_tree.node.get_value([section]) + group = RE_NAMELIST_GROUP.match(section).group(1) + nlg = "&" + group + "\n" + for key, node in sorted(section_value.items()): + if node.state: + continue + try: + value = env_var_process(node.value) + except UnboundEnvironmentVariableError as exc: + raise ConfigProcessError( + [section, key], node.value, exc + ) + nlg += "%s=%s,\n" % (key, value) + nlg += "/" + "\n" + handle.write(nlg.encode('UTF-8')) + self.manager.handle_event(NamelistEvent(nlg)) diff --git a/code/train/Python/0083420_async_iterator.py b/code/train/Python/0083420_async_iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..b59689bdb8df1120a6ce9ea6fa4190e5b9e68332 --- /dev/null +++ b/code/train/Python/0083420_async_iterator.py @@ -0,0 +1,43 @@ +from queue import Queue +from threading import Thread + +import asyncio + +class AsyncIterator: + + POLL_INTERVAL = .5 + + def __init__(self): + self.queue = Queue() + self.thread = None + self.done = False + self.stop_iteration_cls = StopAsyncIteration + + def start(self, call, *args, **kwargs): + + def run(): + for line in call(*args, **kwargs): + self.queue.put(line) + self.done = True + + self.thread = Thread(target=run) + self.thread.start() + + return self + + def throw(self, cls): + self.stop_iteration_cls = cls + + async def __aiter__(self): + return self + + async def __anext__(self): + while self.queue.empty(): + if self.done: + raise self.stop_iteration_cls + + await asyncio.sleep(AsyncIterator.POLL_INTERVAL) + + item = self.queue.get() + self.queue.task_done() + return item diff --git a/code/train/Python/0083554_parallel_runner.py b/code/train/Python/0083554_parallel_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..1505d85138404f374352e2ec4c81ee1529040f81 --- /dev/null +++ b/code/train/Python/0083554_parallel_runner.py @@ -0,0 +1,227 @@ +from lettuce.core import Feature, TotalResult + +from lettuce.terrain import after +from lettuce.terrain import before +from lettuce.terrain import world + +from lettuce.decorators import step +from lettuce.registry import call_hook +from lettuce.registry import STEP_REGISTRY +from lettuce.registry import CALLBACK_REGISTRY +from lettuce.exceptions import StepLoadingError +from lettuce.plugins import ( + xunit_output, + autopdb +) +from lettuce import fs +from lettuce import exceptions + +from multiprocessing import Pool +from cStringIO import StringIO +from itertools import chain +import os.path +import sys +import traceback +import copy + +from importlib import import_module + +try: + from colorama import init as ms_windows_workaround + ms_windows_workaround() +except ImportError: + pass + +try: + terrain = fs.FileSystem._import("terrain") + reload(terrain) +except Exception, e: + if not "No module named terrain" in str(e): + string = 'Lettuce has tried to load the conventional environment ' \ + 'module "terrain"\nbut it has errors, check its contents and ' \ + 'try to run lettuce again.\n\nOriginal traceback below:\n\n' + + sys.stderr.write(string) + sys.stderr.write(exceptions.traceback.format_exc(e)) + raise SystemExit(1) + + +class ParallelRunner(object): + """Parallel lettuce test runner. Runs each feature in a separate process, + up to a fixed number in parallel. + + Takes a base path as parameter (string), so that it can look for + features and step definitions on there. + """ + def __init__(self, base_path, parallelization=5, scenarios=None, + verbosity=0, random=False, enable_xunit=False, + xunit_filename=None, tags=None, failfast=False, + auto_pdb=False): + """ lettuce.Runner will try to find a terrain.py file and + import it from within `base_path` + """ + + self.tags = tags + self.explicit_features = [] + + if isinstance(base_path, list): + self.explicit_features = base_path + base_path = os.path.dirname(base_path[0]) + + sys.path.insert(0, base_path) + self.loader = fs.FeatureLoader(base_path) + self.verbosity = verbosity + self.scenarios = scenarios and map(int, scenarios.split(",")) or None + self.failfast = failfast + if auto_pdb: + autopdb.enable(self) + + sys.path.remove(base_path) + + if verbosity is 0: + output = 'non_verbose' + elif verbosity is 1: + output = 'dots' + elif verbosity is 2: + output = 'scenario_names' + elif verbosity is 3: + output = 'shell_output' + else: + output = 'colored_shell_output' + + self.random = random + + if enable_xunit: + xunit_output.enable(filename=xunit_filename) + + self._output = output + + self.parallelization = parallelization + + @property + def output(self): + module = import_module('.' + self._output, 'lettuce.plugins') + reload(module) + return module + + def run(self): + """ Find and load step definitions, and them find and load + features under `base_path` specified on constructor + """ + try: + self.loader.find_and_load_step_definitions() + except StepLoadingError, e: + print "Error loading step definitions:\n", e + return + + results = [] + if self.explicit_features: + features_files = self.explicit_features + else: + features_files = self.loader.find_feature_files() + if self.random: + random.shuffle(features_files) + + if not features_files: + self.output.print_no_features_found(self.loader.base_dir) + return + + processes = Pool(processes=self.parallelization) + test_results_it = processes.imap_unordered( + worker_process, [(self, filename) for filename in features_files] + ) + + all_total = ParallelTotalResult() + for result in test_results_it: + all_total += result['total'] + sys.stdout.write(result['stdout']) + sys.stderr.write(result['stderr']) + + return all_total + +def worker_process(args): + self, filename = args + sys.stdout = StringIO() + sys.stderr = StringIO() + + failed = False + results = [] + try: + self.output + call_hook('before', 'all') + feature = Feature.from_file(filename) + results.append( + feature.run(self.scenarios, + tags=self.tags, + random=self.random, + failfast=self.failfast)) + + except exceptions.LettuceSyntaxError, e: + sys.stderr.write(e.msg) + failed = True + except: + if not self.failfast: + e = sys.exc_info()[1] + print "Died with %s" % str(e) + traceback.print_exc() + else: + print + print ("Lettuce aborted running any more tests " + "because was called with the `--failfast` option") + + failed = True + + finally: + total = TotalResult(results) + call_hook('after', 'all', total) + + return { + 'stdout': sys.stdout.getvalue(), + 'stderr': sys.stderr.getvalue(), + 'failed': failed, + 'total': ParallelTotalResult(total), + } + +class ParallelTotalResult(object): + def __init__(self, total=None): + self.steps_passed = 0 + self.steps_failed = 0 + self.steps_skipped = 0 + self.steps_undefined = 0 + self.steps = 0 + scenario_results = [] + if total: + feature_results = total.feature_results + self.features_ran = len(feature_results) + self.features_passed = len([result for result in feature_results if result.passed]) + for feature_result in feature_results: + for scenario_result in feature_result.scenario_results: + self.steps_passed += len(scenario_result.steps_passed) + self.steps_failed += len(scenario_result.steps_failed) + self.steps_skipped += len(scenario_result.steps_skipped) + self.steps_undefined += len(scenario_result.steps_undefined) + self.steps += scenario_result.total_steps + scenario_results.append(scenario_result) + self.scenarios_ran = len(scenario_results) + self.scenarios_passed = len([result for result in scenario_results if result.passed]) + else: + self.features_ran = 0 + self.features_passed = 0 + self.scenarios_ran = 0 + self.scenarios_passed = 0 + + def _filter_proposed_definitions(self): + raise NotImplementedError() + + @property + def proposed_definitions(self): + raise NotImplementedError() + + def __add__(self, other): + new_ptr = copy.copy(self) + for attr in new_ptr.__dict__: + if isinstance(getattr(new_ptr, attr), int): + setattr(new_ptr, attr, + getattr(new_ptr, attr) + getattr(other, attr)) + return new_ptr + diff --git a/code/train/Python/0083792_wordCountReducer_Sliding_StdDev.py b/code/train/Python/0083792_wordCountReducer_Sliding_StdDev.py new file mode 100644 index 0000000000000000000000000000000000000000..71f4d0e760b8e5cfee8639ece12ddf812edc17ab --- /dev/null +++ b/code/train/Python/0083792_wordCountReducer_Sliding_StdDev.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python + +from operator import itemgetter +import sys +import math + +current_word = None +current_count = 0 +word = None + +wordcount = {} +count_list = [] + +wordcountByFile = {} +extrawordcount = {} +wordAvg = {} +wordStdDev = {} + +def addToDictionary(current_word, current_count): + wordkey = current_word.split("_")[0] + if wordcount.get(wordkey) == None: + count_list = [] + count_list.append(current_count) + wordcount[wordkey] = count_list + else: + wordcount.get(wordkey).append(current_count) + +def addToDictByFile(current_word): + if wordcountByFile.get(current_word) == None: + wordcountByFile[current_word] = 1 + else: + count_val = wordcountByFile.get(current_word) + wordcountByFile[current_word] = count_val + 1 + +def addToWordCount(current_word): + if wordcount.get(current_word) == None: + wordcount[current_word] = 1 + else: + count_val = wordcount.get(current_word) + wordcount[current_word] = count_val + 1 + +def addToExtraWordCount(word): + if extrawordcount.get(word) == None: + extrawordcount[word] = 1 + else: + extrawordcount[word] = extrawordcount[word] + 1 + +def calculateMinMaxAvg(): + average = -1 + minimum = -1 + maximum = -1 + for word in wordcount: + #print wordcount.get(word) + minimum = min(wordcount.get(word)) + maximum = max(wordcount.get(word)) + average = sum(wordcount.get(word))/229.0 + print '%s\t%s\t%s\t%s' % (word, minimum, maximum, average) + +def calculateAverage(): + average = -1 + for word in wordcount: + average = sum(wordcount.get(word))/5.0 + return average + +def calculateStdDev(): + stdDev = -1 + average = -1 + for word in wordcount: + partialSquare = -1 + sumOfSquare = -1 + average = sum(wordcount.get(word))/5.0 + countlist = wordcount.get(word) + for count in countlist: + partialSquare = (count-average)**2 + sumOfSquare += partialSquare + stdDev = math.sqrt(sumOfSquare/5.0) + print '%s\t%s\t%s' % (word, average, stdDev) + +#def slicedict(d, s): +# return {k:v for k,v in d.iteritems() if k.startswith(s)} +def slicedict(sourcedict, string): + #print sourcedict + #print string + newdict = {} + for key in sourcedict.keys(): + if key.startswith(string): + newdict[key] = sourcedict[key] + return newdict + +def calculateStdDev2(): + #stdDev = 0 + average = 0 + for word in wordcount: + #print word + #print "WordAverageWondow: " + word + "\t" + "wordcount: " + str(wordcount.get(word)) + "avg: " + "\t" + str(average) + average = (wordcount.get(word)/5.0) + #print "WordAverageWondow: " + word + "\t" + "wordcount: " + str(wordcount.get(word)) + "avg: " + "\t" + str(average) + partialSquare = 0 + sumOfSquare = 0 + stdDev = 0 + tempdict = slicedict(wordcountByFile, word+"_") + #print tempdict + for tempkey in tempdict: + partialSquare = (int(tempdict.get(tempkey))-average)*(int(tempdict.get(tempkey))-average) + #print partialSquare + sumOfSquare += partialSquare + stdDev = math.sqrt(sumOfSquare/5.0) + #print "WordAverageWondow: " + word + "\t" + str(average) + wordAvg[word] = average + wordStdDev[word] = stdDev + #print '%s\t%s\t%s' % (word, average, stdDev) + +def calculateTwoStdDev(): + calculateStdDev2() + for word in wordcount: + if wordAvg.get(word) == None or wordStdDev.get(word) == None: + continue + nWordAverage = wordAvg.get(word) + nWordStdDev = wordStdDev.get(word) + nTwoStdDev = nWordAverage + 2*nWordStdDev + nExtraWordCount = extrawordcount.get(word) + if nExtraWordCount == None: + continue + elif nExtraWordCount > nTwoStdDev: + print '%s\t%s\t%s\t%s\t%s' % (word, nExtraWordCount, nWordAverage, nWordStdDev, nTwoStdDev) + + +# input comes from STDIN +for line in sys.stdin: + # remove leading and trailing whitespace + line = line.strip() + + # parse the input we got from mapper.py + word, count = line.split('\t', 1) + + dict_word = "" + dic_count = "" + # convert count (currently a string) to int + try: + dict_word = word + "_" + count.split("_")[1] + dic_count = count.split("_")[0] + dic_count = int(dic_count) + except ValueError: + # count was not a number, so silently + # ignore/discard this line + continue + + if "_file6" in dict_word: + addToExtraWordCount(word) + else: + addToDictByFile(dict_word) + addToWordCount(word) + +#calculateStdDev2() +calculateTwoStdDev() + + +''' + # convert count (currently a string) to int + try: + word = word + count.split("_")[1] + count = count.split("_")[0] + count = int(count) + except ValueError: + # count was not a number, so silently + # ignore/discard this line + continue + + # this IF-switch only works because Hadoop sorts map output + # by key (here: word) before it is passed to the reducer + if current_word == word: + current_count += count + else: + if current_word: + # write result to STDOUT + #print '%s\t%s' % (current_word, current_count) + addToDictionary(current_word, current_count) + current_count = count + current_word = word + +# do not forget to output the last word if needed! +if current_word == word: + #print '%s\t%s' % (current_word, current_count) + addToDictionary(current_word, current_count) +''' + +#calculateStdDev(calculateAverage()) diff --git a/code/train/Python/0083845_zmq_client.py b/code/train/Python/0083845_zmq_client.py new file mode 100644 index 0000000000000000000000000000000000000000..246b76fca7e3abd87b6adc89225358c2850da664 --- /dev/null +++ b/code/train/Python/0083845_zmq_client.py @@ -0,0 +1,186 @@ +import base64 +import os + +import zmq +from zmq.eventloop.zmqstream import ZMQStream + +from pyblinktrade.message_builder import MessageBuilder +from pyblinktrade.message import JsonMessage, InvalidMessageException + +class TradeClientException(Exception): + def __init__(self, error_message, detail = None): + self.error_message = error_message + self.detail = None + super(TradeClientException, self).__init__() + + def __str__(self): + if self.detail: + return self.error_message + '( detail:%s)'%self.detail + return self.error_message + + + +class TradeClient(object): + def __init__(self, zmq_context, trade_in_socket, trade_pub = None, reopen=True): + self.zmq_context = zmq_context + self.connection_id = None + self.trade_in_socket = trade_in_socket + self.is_logged = False + self.user_id = None + self.reopen = reopen + self.trade_pub = trade_pub + + self.trade_pub_socket = None + self.trade_pub_socket_stream = None + + if self.trade_pub: + self.trade_pub_socket = self.zmq_context.socket(zmq.SUB) + self.trade_pub_socket.connect(self.trade_pub) + self.trade_pub_socket_stream = ZMQStream(self.trade_pub_socket) + self.trade_pub_socket_stream.on_recv(self._on_trade_publish) + + def _on_trade_publish(self, message): + self.on_trade_publish(message) + + def on_trade_publish(self, message): + pass + + def connect(self): + if not self.trade_pub_socket and self.trade_pub: + self.trade_pub_socket = self.zmq_context.socket(zmq.SUB) + self.trade_pub_socket.connect(self.trade_pub) + self.trade_pub_socket_stream = ZMQStream(self.trade_pub_socket) + self.trade_pub_socket_stream.on_recv(self._on_trade_publish) + + self.trade_in_socket.send( "OPN," + base64.b32encode(os.urandom(10))) + response_message = self.trade_in_socket.recv() + opt_code = response_message[:3] + raw_message = response_message[4:] + + if opt_code != 'OPN': + if opt_code == 'ERR': + raise TradeClientException( error_message = raw_message ) + + raise TradeClientException( error_message = 'Protocol Error: Unknow message opt_code received' ) + + self.connection_id = raw_message + + + def close(self): + if self.trade_pub_socket_stream: + self.trade_pub_socket_stream.close() + self.trade_pub_socket_stream = None + self.trade_pub_socket.close() + self.trade_pub_socket = None + + if self.connection_id: + self.trade_in_socket.send( "CLS," + self.connection_id ) + response_message = self.trade_in_socket.recv() + self.connection_id = None + + def isConnected(self): + return self.connection_id is not None + + def getBrokerList(self, status_list): + page = 0 + page_size = 100 + + broker_list = [] + columns = [] + while True: + res = self.sendJSON(MessageBuilder.getBrokerList( status_list, None, page, page_size )) + columns = res.get('Columns') + broker_list.extend(res.get('BrokerListGrp')) + if len(res.get('BrokerListGrp')) < page_size: + break + page += 1 + + return broker_list, columns + + def getLastTrades(self, last_trade_id, page=0): + + if last_trade_id is None: + last_trade_id = 1 + + rep_msg = self.sendJSON({ 'MsgType': 'U32', + 'TradeHistoryReqID': -1, + 'Page': page, + 'PageSize': 100 }) + + result_list = [] + + if rep_msg.isTradeHistoryResponse(): + last_processed = 0 + trade_list = rep_msg.get('TradeHistoryGrp') + if not trade_list : + return result_list + for trade in trade_list: + if last_trade_id <= trade[0]: + last_processed = trade[0] + if last_processed != last_trade_id: + result_list.append(trade) + + + if last_processed != last_trade_id: + return result_list + self.getLastTrades(last_trade_id, page+1) + + return result_list + + + def getSecurityList(self): + resp = self.sendJSON({ 'MsgType' : 'x', + 'SecurityReqID': 'getSecurityList', + 'SecurityListRequestType': 0}) + return resp + + + + def sendString(self, string_msg): + if not self.isConnected() and self.reopen: + self.connect() + + self.trade_in_socket.send_unicode( "REQ," + self.connection_id + ',' + string_msg) + + response_message = self.trade_in_socket.recv() + raw_resp_message_header = response_message[:3] + raw_resp_message = response_message[4:].strip() + + rep_msg = None + if raw_resp_message: + try: + rep_msg = JsonMessage(raw_resp_message) + except Exception: + pass + + if raw_resp_message_header == 'CLS' and rep_msg and not rep_msg.isErrorMessage(): + self.close() + if self.reopen: + self.connect() + return rep_msg + + if raw_resp_message_header != 'REP': + self.close() + if self.reopen: + self.connect() + + if rep_msg and rep_msg.isErrorMessage(): + raise TradeClientException(rep_msg.get('Description'), rep_msg.get('Detail')) + raise TradeClientException('Invalid request: ' + raw_resp_message ) + + + if rep_msg and rep_msg.isUserResponse(): + if rep_msg.get("UserStatus") == 1: + self.user_id = rep_msg.get("UserID") + self.is_logged = True + + if self.trade_pub_socket: + self.trade_pub_socket.setsockopt(zmq.SUBSCRIBE, '^' + str(self.user_id) + '$') + + return rep_msg + + def sendJSON(self, json_msg): + import json + return self.sendString(json.dumps(json_msg)) + + def sendMessage(self, msg): + return self.sendString(msg.raw_message) \ No newline at end of file diff --git a/code/train/Python/0084540_max_product_subarray.py b/code/train/Python/0084540_max_product_subarray.py new file mode 100644 index 0000000000000000000000000000000000000000..8b9b4020998a4e9babfa6e6c5c2ec4d3cd414d42 --- /dev/null +++ b/code/train/Python/0084540_max_product_subarray.py @@ -0,0 +1,53 @@ +from typing import List + + +class Solution: + def maxProductV1(self, nums: List[int]) -> int: + if len(nums) == 0: + return 0 + ans, prod = float("-Inf"), 1 + for n in nums: + prod *= n + ans = max(ans, prod) + if prod == 0: + prod = 1 + prod = 1 + for n in nums[::-1]: + prod *= n + ans = max(ans, prod) + if prod == 0: + prod = 1 + return ans + + def maxProductV2(self, nums: List[int]) -> int: + if len(nums) == 0: + return 0 + prod_fwd, prod_back = nums, nums[::-1] + for i in range(1, len(nums)): + prod_fwd[i] *= prod_fwd[i - 1] or 1 + prod_back[i] *= prod_back[i - 1] or 1 + return max(prod_fwd + prod_back) + + +# TESTS +for nums, expected in [ + ([2, 3, -2, 4], 6), + ([-2, 0, -1], 0), + ([], 0), + ([1], 1), + ([-2], -2), + ([1, -2], 1), + ([-1, -3], 3), + ([3, -1, 4], 4), + ([3, -1, 2, 6], 12), + ([-2, -3, 0, -4], 6), + ([-2, 1, -3, -4], 12), + ([-2, 1, -3, 1, -4], 12), + ([-2, 1, -3, 1, -4, -2], 48), + ([-2, 1, -3, 1, -4, -2, 0, 49], 49), +]: + sol = Solution() + actual = sol.maxProductV1(nums) + print("Max subarray product of", nums, "->", actual) + assert actual == expected + assert expected == sol.maxProductV2(nums) diff --git a/code/train/Python/0084844_tilt_tests.py b/code/train/Python/0084844_tilt_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..02d4a9c5c686e9df280ba15473c7f204aeca8390 --- /dev/null +++ b/code/train/Python/0084844_tilt_tests.py @@ -0,0 +1,182 @@ +import os, subprocess, sys +import pkg_resources + +import fermentrack_django.settings + +try: + from packaging import version + has_packaging = True +except: + has_packaging = False + + +# This function is used to check if an apt package is installed on Raspbian, Ubuntu, Debian, etc. +def apt_package_installed(package_name: str) -> bool: + devnull = open(os.devnull,"w") + retval = subprocess.call(["dpkg", "-s", package_name],stdout=devnull,stderr=subprocess.STDOUT) + devnull.close() + if retval != 0: + return False + return True + + +# This is just a means to check if apt (dpkg) is installed at all +def has_apt() -> bool: + try: + devnull = open(os.devnull,"w") + retval = subprocess.call(["dpkg", "--version"],stdout=devnull,stderr=subprocess.STDOUT) + devnull.close() + if retval != 0: + return False + return True + except: + # dpkg doesn't exist + return False + + +def check_apt_packages() -> (bool, list): + package_list = ["bluez", "libcap2-bin", "libbluetooth3", "libbluetooth-dev"] + + if not fermentrack_django.settings.USE_DOCKER: + # For non-docker installs, we assume that redis-server is installed on the same host as Fermentrack + package_list.append("redis-server") + + test_results = [] + all_packages_ok = True + + for package in package_list: + result = {'package': package, 'result': True} + if apt_package_installed(package): + result['result'] = True + else: + result ['result'] = False + all_packages_ok = False + test_results.append(result) + + return all_packages_ok, test_results + + +def check_python_packages() -> (bool, bool, list): + # Returns has_packaging, all_packages_ok, test_results[] + if not has_packaging: + return has_packaging, False, [] + + if sys.platform == "darwin": + # The MacOS support uses different packages from the support for Linux + package_list = [ + {'name': 'pyobjc', 'version': version.parse("6.2")}, + {'name': 'redis', 'version': version.parse("3.4.1")}, + ] + else: + package_list = [ + {'name': 'aioblescan', 'version': version.parse("0.2.6")}, + {'name': 'redis', 'version': version.parse("3.4.1")}, + ] + + test_results = [] + all_packages_ok = True + + for package_to_find in package_list: + result_stub = { + 'package': package_to_find['name'], + 'required_version': package_to_find['version'], + 'installed_version': None, + 'ok': False, + } + + for package in pkg_resources.working_set: + if package.project_name == package_to_find['name']: + result_stub['installed_version'] = package.parsed_version + if result_stub['installed_version'].public == result_stub['required_version'].public: + result_stub['ok'] = True + + if result_stub['ok'] is False: + all_packages_ok = False + test_results.append(result_stub) + + return has_packaging, all_packages_ok, test_results + + +def check_python_setcap() -> (bool, str, str): + try: + base_executable = subprocess.check_output(["readlink", "-e", sys.executable]).strip().decode("utf-8") + except FileNotFoundError: + # readlink doesn't exist + return False, "", "" + except subprocess.CalledProcessError: + # readlink failed + return False, "", "" + + try: + getcap_values = subprocess.check_output(["getcap", base_executable]).strip().decode("utf-8") + except FileNotFoundError: + # getcap doesn't exist on this system (e.g. MacOS) + return False, base_executable, "" + except subprocess.CalledProcessError: + # setcap -v failed + return False, base_executable, "" + + # We have to check for three things: + # 1. That the executable has cap_net_admin + # 2. That the executable has cap_net_raw + # 3. That the executable has +eip (inheritable permissions) + # The output of getcap should look like this: b'/usr/bin/python3.6 = cap_net_admin,cap_net_raw+eip\n' + + cap_net_admin_missing = True + cap_net_raw_missing = True + cap_eip_unset = True + if getcap_values.find("cap_net_admin") != -1: + cap_net_admin_missing = False + if getcap_values.find("cap_net_raw") != -1: + cap_net_raw_missing = False + if getcap_values.find("+eip") != -1: + cap_eip_unset = False + + if cap_net_admin_missing or cap_net_raw_missing or cap_eip_unset: + return False, base_executable, getcap_values + return True, base_executable, getcap_values + + +# The following was used for testing during development +if __name__ == "__main__": + if has_apt(): + apt_ok, apt_test_results = check_apt_packages() + + if apt_ok: + print("All apt packages found. Package status:") + else: + print("Missing apt packages. Package status:") + + for this_test in apt_test_results: + print("Package {}: {}".format(this_test['package'], + ("Installed" if this_test['result'] else "Not Installed"))) + else: + print("dpkg not installed - not checking to see if system packages are installed") + print("") + + + # Next, check the python packages + python_ok, python_test_results = check_python_packages() + + if python_ok: + print("All required python packages found. Package status:") + else: + print("Missing/incorrect python packages. Package status:") + + for this_test in python_test_results: + print("Package {} - Required Version {} - Installed Version {} - OK? {}".format( + this_test['package'], this_test['required_version'], this_test['installed_version'], this_test['ok'])) + print("") + + # Check that Python has the correct capabilities set + has_caps, python_path, getcap_values = check_python_setcap() + + if has_caps: + print("Python executable has all necessary cap flags. Current flags: ") + else: + print("Missing cap flags on python executable. Current flags: ") + print(getcap_values) + print("") + + + diff --git a/code/train/Python/0084865_countries_sort.py b/code/train/Python/0084865_countries_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..80d4df5edcc6c8c8fb6d65b0cab16ae36644dd87 --- /dev/null +++ b/code/train/Python/0084865_countries_sort.py @@ -0,0 +1,90 @@ +from selenium import webdriver + + +# check that a country list is sorted +def check_country_list(): + countries = [] + + # list of countries + countries_list = driver.find_elements_by_css_selector("table.dataTable tr.row td:nth-child(5)") + # list of zones + zones_list = driver.find_elements_by_css_selector("table.dataTable tr.row td:nth-child(6)") + + for i in range(len(countries_list)): + s = countries_list[i].get_attribute("textContent") + # creating a list of country names (strings) + countries.append(s) + + # check that a sub-country list for each country with Zone number != 0 is sorted + subcountries = [] + if zones_list[i].get_attribute("textContent") != "0": + countries_list[i].find_element_by_css_selector("a").click() + + subcountries_list = driver.find_elements_by_css_selector("table#table-zones tbody td:nth-child(3)") + for j in range(len(subcountries_list)): + sub = subcountries_list[j].get_attribute("textContent") + # creating a list of sub-counties with removing the last empty element + if sub != '': + subcountries.append(sub) + + # go back + driver.execute_script("window.history.go(-1)") + countries_list = driver.find_elements_by_css_selector("table.dataTable tr.row td:nth-child(5)") + zones_list = driver.find_elements_by_css_selector("table.dataTable tr.row td:nth-child(6)") + + subcountries_sorted = list(subcountries) + subcountries_sorted.sort() +# print(subcountries_sorted) +# print(subcountries) + print("Sub-country list is sorted: ", subcountries_sorted == subcountries) + + countries_sorted = list(countries) + countries_sorted.sort() + print("Country list is sorted: ", countries_sorted == countries) + + return countries_sorted == countries + + +# check that a geo zone list is sorted for each country +def check_geozones(): + + # list of countries + countries_list = driver.find_elements_by_css_selector("table.dataTable tr.row td:nth-child(3) a") + for i in range(len(countries_list)): + countries_list[i].click() + geozones = [] + + # list of geo zones for a selected country + geozones_list = driver.find_elements_by_css_selector("#table-zones tbody td:nth-child(3) [selected]") + for j in range(len(geozones_list)): + sub = geozones_list[j].get_attribute("textContent") + geozones.append(sub) + + geozones_sorted = list(geozones) + geozones_sorted.sort() +# print(geozones_sorted) +# print(geozones) + print("Geozone list is sorted: ",geozones_sorted == geozones) + + # go back + driver.execute_script("window.history.go(-1)") + countries_list = driver.find_elements_by_css_selector("table.dataTable tr.row td:nth-child(3) a") + + +# main block +driver = webdriver.Chrome() + +# login +driver.get("http://localhost/litecart/admin/?app=countries&doc=countries") +driver.find_element_by_name("username").send_keys("admin") +driver.find_element_by_name("password").send_keys("admin") +driver.find_element_by_name("login").click() + +# task 9_1: check a country list and sub-country lists +check_country_list() + +# task 9_2: check geo zones lists +driver.get("http://localhost/litecart/admin/?app=geo_zones&doc=geo_zones") +check_geozones() + +driver.quit() \ No newline at end of file diff --git a/code/train/Python/0085506_me.py b/code/train/Python/0085506_me.py new file mode 100644 index 0000000000000000000000000000000000000000..edfb1785b6751c1e8fe943ceba1cab7c816db6cd --- /dev/null +++ b/code/train/Python/0085506_me.py @@ -0,0 +1,155 @@ +''' +Created on May 20, 2017 + +@author: jamie +''' +from copy import deepcopy +import scipy as np +import scipy.linalg as linalg +import sys + +class MeData(object): + ''' + Mixture of Experts Data Structure + ''' + u = None + g = None + h = None + a = None + learningRate = None + z = None + S = None + d = None + fz = None + fz_g = None + +class MixtureOfExperts(object): + ''' + Mixture of Experts + ''' + dataList = None + learningRate = None + expDecayFactor = None + minLearnRate = None + simTime = None + currTime = None + initLearningRate = None + dt = None + max_g_idx = None + prev_max_g_idx = None + + + def __init__(self, dataList, learningRate, expDecayFactor, minLearnRate, + simTime): + ''' + Constructor + ''' + self.dataList = deepcopy(dataList) + self.initLearningRate = learningRate + self.learningRate = learningRate + self.expDecayFactor = expDecayFactor + self.minLearnRate = minLearnRate + self.simTime = simTime + self.currTime = 0.0 + + self.reset() + + def reset(self): + ''' + reset the HME - everything except the learning rate + ''' + numNodes = len(self.dataList) + numNodesInv = 1./numNodes + for node in self.dataList: + node.u = numNodesInv + node.g = numNodesInv + node.h = numNodesInv + node.a = numNodesInv + + self.max_g_idx = -1 + self.prev_max_g_idx = -1 + + def run(self, simTime): + ''' + Run the HME algorithm + ''' + self.dt = simTime - self.simTime + self.currTime = self.currTime + self.dt + self.simTime = simTime + + self.processNodes() + + self.prev_max_g_idx = self.max_g_idx + + def processNodes(self): + ''' + Process all of the nodes + ''' + self.computeU() + self.computeG() + self.computeH() + self.updateLearningRate() + self.updateA() + + def computeU(self): + ''' + Compute the pre-activiation per the synaptic neuron + ''' + for node in self.dataList: + node.u = node.a + + def computeG(self): + ''' + Compute the softmax function + The softmax function computes the gating weights + ''' + sum_gi = 0. + self.max_g_idx = 0 + for node in self.dataList: + sum_gi = sum_gi + np.exp(node.u) + + idx = 0 + max_g = 0 + + for node in self.dataList: + node.g = np.exp(node.u)/sum_gi + if node.g > max_g: + self.max_g_idx = idx + max_g = node.g + idx = idx + 1 + + def computeH(self): + ''' + Compute the aposteriori probability of the ith filter + ''' + sum_fz_g = 0. + for node in self.dataList: + Sinv = linalg.inv(node.S) + Sk = 2.*np.pi*node.S + denom = np.sqrt(linalg.det(Sk)) + tmpDot = -0.5 * np.dot(np.dot(node.z, Sinv), node.z) + if tmpDot > -700.: + fz = np.exp(tmpDot)/denom + else: + fz = 9.85967654376e-305 + fz_g = fz * node.g + sum_fz_g = sum_fz_g + fz_g + + node.fz = fz + node.fz_g = fz_g + + for node in self.dataList: + node.h = node.fz_g / sum_fz_g + + def updateLearningRate(self): + for node in self.dataList: + node.learningRate = (self.initLearningRate - self.minLearnRate) \ + * np.exp(-self.expDecayFactor * self.dt) + self.minLearnRate + + def updateA(self): + for node in self.dataList: + node.a = node.a + node.learningRate * (node.h - node.g) + + + + \ No newline at end of file diff --git a/code/train/Python/0085859_string.py b/code/train/Python/0085859_string.py new file mode 100644 index 0000000000000000000000000000000000000000..2610b7777207f8fffc000c25da51831352b485e0 --- /dev/null +++ b/code/train/Python/0085859_string.py @@ -0,0 +1,215 @@ +""" +Module for formatting output data in console (to string). +""" +from __future__ import annotations + +from shutil import get_terminal_size +from typing import Iterable + +import numpy as np + +from pandas.io.formats.format import DataFrameFormatter +from pandas.io.formats.printing import pprint_thing + + +class StringFormatter: + """Formatter for string representation of a dataframe.""" + + def __init__(self, fmt: DataFrameFormatter, line_width: int | None = None): + self.fmt = fmt + self.adj = fmt.adj + self.frame = fmt.frame + self.line_width = line_width + + def to_string(self) -> str: + text = self._get_string_representation() + if self.fmt.should_show_dimensions: + text = "".join([text, self.fmt.dimensions_info]) + return text + + def _get_strcols(self) -> list[list[str]]: + strcols = self.fmt.get_strcols() + if self.fmt.is_truncated: + strcols = self._insert_dot_separators(strcols) + return strcols + + def _get_string_representation(self) -> str: + if self.fmt.frame.empty: + return self._empty_info_line + + strcols = self._get_strcols() + + if self.line_width is None: + # no need to wrap around just print the whole frame + return self.adj.adjoin(1, *strcols) + + if self._need_to_wrap_around: + return self._join_multiline(strcols) + + return self._fit_strcols_to_terminal_width(strcols) + + @property + def _empty_info_line(self) -> str: + return ( + f"Empty {type(self.frame).__name__}\n" + f"Columns: {pprint_thing(self.frame.columns)}\n" + f"Index: {pprint_thing(self.frame.index)}" + ) + + @property + def _need_to_wrap_around(self) -> bool: + return bool(self.fmt.max_cols is None or self.fmt.max_cols > 0) + + def _insert_dot_separators(self, strcols: list[list[str]]) -> list[list[str]]: + str_index = self.fmt._get_formatted_index(self.fmt.tr_frame) + index_length = len(str_index) + + if self.fmt.is_truncated_horizontally: + strcols = self._insert_dot_separator_horizontal(strcols, index_length) + + if self.fmt.is_truncated_vertically: + strcols = self._insert_dot_separator_vertical(strcols, index_length) + + return strcols + + @property + def _adjusted_tr_col_num(self) -> int: + return self.fmt.tr_col_num + 1 if self.fmt.index else self.fmt.tr_col_num + + def _insert_dot_separator_horizontal( + self, strcols: list[list[str]], index_length: int + ) -> list[list[str]]: + strcols.insert(self._adjusted_tr_col_num, [" ..."] * index_length) + return strcols + + def _insert_dot_separator_vertical( + self, strcols: list[list[str]], index_length: int + ) -> list[list[str]]: + n_header_rows = index_length - len(self.fmt.tr_frame) + row_num = self.fmt.tr_row_num + for ix, col in enumerate(strcols): + cwidth = self.adj.len(col[row_num]) + + if self.fmt.is_truncated_horizontally: + is_dot_col = ix == self._adjusted_tr_col_num + else: + is_dot_col = False + + if cwidth > 3 or is_dot_col: + dots = "..." + else: + dots = ".." + + if ix == 0 and self.fmt.index: + dot_mode = "left" + elif is_dot_col: + cwidth = 4 + dot_mode = "right" + else: + dot_mode = "right" + + dot_str = self.adj.justify([dots], cwidth, mode=dot_mode)[0] + col.insert(row_num + n_header_rows, dot_str) + return strcols + + def _join_multiline(self, strcols_input: Iterable[list[str]]) -> str: + lwidth = self.line_width + adjoin_width = 1 + strcols = list(strcols_input) + + if self.fmt.index: + idx = strcols.pop(0) + # error: Argument 1 to "__call__" of "_NumberOp" has incompatible type + # "None"; expected "Union[int, float, complex, number, bool_]" + # error: Incompatible types in assignment (expression has type "number", + # variable has type "Optional[int]") + lwidth -= ( # type: ignore[assignment,arg-type] + np.array([self.adj.len(x) for x in idx]).max() + adjoin_width + ) + + col_widths = [ + np.array([self.adj.len(x) for x in col]).max() if len(col) > 0 else 0 + for col in strcols + ] + + assert lwidth is not None + # error: Argument 1 to "_binify" has incompatible type "List[object]"; expected + # "List[int]" + col_bins = _binify(col_widths, lwidth) # type: ignore[arg-type] + nbins = len(col_bins) + + if self.fmt.is_truncated_vertically: + assert self.fmt.max_rows_fitted is not None + nrows = self.fmt.max_rows_fitted + 1 + else: + nrows = len(self.frame) + + str_lst = [] + start = 0 + for i, end in enumerate(col_bins): + row = strcols[start:end] + if self.fmt.index: + row.insert(0, idx) + if nbins > 1: + if end <= len(strcols) and i < nbins - 1: + row.append([" \\"] + [" "] * (nrows - 1)) + else: + row.append([" "] * nrows) + str_lst.append(self.adj.adjoin(adjoin_width, *row)) + start = end + return "\n\n".join(str_lst) + + def _fit_strcols_to_terminal_width(self, strcols: list[list[str]]) -> str: + from pandas import Series + + lines = self.adj.adjoin(1, *strcols).split("\n") + max_len = Series(lines).str.len().max() + # plus truncate dot col + width, _ = get_terminal_size() + dif = max_len - width + # '+ 1' to avoid too wide repr (GH PR #17023) + adj_dif = dif + 1 + col_lens = Series([Series(ele).apply(len).max() for ele in strcols]) + n_cols = len(col_lens) + counter = 0 + while adj_dif > 0 and n_cols > 1: + counter += 1 + mid = round(n_cols / 2) + mid_ix = col_lens.index[mid] + col_len = col_lens[mid_ix] + # adjoin adds one + adj_dif -= col_len + 1 + col_lens = col_lens.drop(mid_ix) + n_cols = len(col_lens) + + # subtract index column + max_cols_fitted = n_cols - self.fmt.index + # GH-21180. Ensure that we print at least two. + max_cols_fitted = max(max_cols_fitted, 2) + self.fmt.max_cols_fitted = max_cols_fitted + + # Call again _truncate to cut frame appropriately + # and then generate string representation + self.fmt.truncate() + strcols = self._get_strcols() + return self.adj.adjoin(1, *strcols) + + +def _binify(cols: list[int], line_width: int) -> list[int]: + adjoin_width = 1 + bins = [] + curr_width = 0 + i_last_column = len(cols) - 1 + for i, w in enumerate(cols): + w_adjoined = w + adjoin_width + curr_width += w_adjoined + if i_last_column == i: + wrap = curr_width + 1 > line_width and i > 0 + else: + wrap = curr_width + 2 > line_width and i > 0 + if wrap: + bins.append(i) + curr_width = w_adjoined + + bins.append(len(cols)) + return bins diff --git a/code/train/Python/0086061_validate_json_format.py b/code/train/Python/0086061_validate_json_format.py new file mode 100644 index 0000000000000000000000000000000000000000..2d63117f957ce0c6d707bc7f602750161a79eeee --- /dev/null +++ b/code/train/Python/0086061_validate_json_format.py @@ -0,0 +1,231 @@ +""" +Validate JSON format. + +Licensed under MIT +Copyright (c) 2012-2015 Isaac Muse +""" +import re +import codecs +import json + +RE_LINE_PRESERVE = re.compile(r"\r?\n", re.MULTILINE) +RE_COMMENT = re.compile( + r'''(?x) + (?P + /\*[^*]*\*+(?:[^/*][^*]*\*+)*/ # multi-line comments + | [ \t]*//(?:[^\r\n])* # single line comments + ) + | (?P + "(?:\\.|[^"\\])*" # double quotes + | .[^/"']* # everything else + ) + ''', + re.DOTALL +) +RE_TRAILING_COMMA = re.compile( + r'''(?x) + ( + (?P + , # trailing comma + (?P[\s\r\n]*) # white space + (?P\]) # bracket + ) + | (?P + , # trailing comma + (?P[\s\r\n]*) # white space + (?P\}) # bracket + ) + ) + | (?P + "(?:\\.|[^"\\])*" # double quoted string + | .[^,"']* # everything else + ) + ''', + re.DOTALL +) +RE_LINE_INDENT_TAB = re.compile(r'^(?:(\t+)?(?:(/\*)|[^ \t\r\n])[^\r\n]*)?\r?\n$') +RE_LINE_INDENT_SPACE = re.compile(r'^(?:((?: {4})+)?(?:(/\*)|[^ \t\r\n])[^\r\n]*)?\r?\n$') +RE_TRAILING_SPACES = re.compile(r'^.*?[ \t]+\r?\n?$') +RE_COMMENT_END = re.compile(r'\*/') +PATTERN_COMMENT_INDENT_SPACE = r'^(%s *?[^\t\r\n][^\r\n]*)?\r?\n$' +PATTERN_COMMENT_INDENT_TAB = r'^(%s[ \t]*[^ \t\r\n][^\r\n]*)?\r?\n$' + + +E_MALFORMED = "E0" +E_COMMENTS = "E1" +E_COMMA = "E2" +W_NL_START = "W1" +W_NL_END = "W2" +W_INDENT = "W3" +W_TRAILING_SPACE = "W4" +W_COMMENT_INDENT = "W5" + + +VIOLATION_MSG = { + E_MALFORMED: 'JSON content is malformed.', + E_COMMENTS: 'Comments are not part of the JSON spec.', + E_COMMA: 'Dangling comma found.', + W_NL_START: 'Unnecessary newlines at the start of file.', + W_NL_END: 'Missing a new line at the end of the file.', + W_INDENT: 'Indentation Error.', + W_TRAILING_SPACE: 'Trailing whitespace.', + W_COMMENT_INDENT: 'Comment Indentation Error.' +} + + +class CheckJsonFormat(object): + """ + Test JSON for format irregularities. + + - Trailing spaces. + - Inconsistent indentation. + - New lines at end of file. + - Unnecessary newlines at start of file. + - Trailing commas. + - Malformed JSON. + """ + + def __init__(self, use_tabs=False, allow_comments=False): + """Setup the settings.""" + + self.use_tabs = use_tabs + self.allow_comments = allow_comments + self.fail = False + + def index_lines(self, text): + """Index the char range of each line.""" + + self.line_range = [] + count = 1 + last = 0 + for m in re.finditer('\n', text): + self.line_range.append((last, m.end(0) - 1, count)) + last = m.end(0) + count += 1 + + def get_line(self, pt): + """Get the line from char index.""" + + line = None + for r in self.line_range: + if pt >= r[0] and pt <= r[1]: + line = r[2] + break + return line + + def check_comments(self, text): + """ + Check for JavaScript comments. + + Log them and strip them out so we can continue. + """ + + def remove_comments(group): + return ''.join([x[0] for x in RE_LINE_PRESERVE.findall(group)]) + + def evaluate(m): + text = '' + g = m.groupdict() + if g["code"] is None: + if not self.allow_comments: + self.log_failure(E_COMMENTS, self.get_line(m.start(0))) + text = remove_comments(g["comments"]) + else: + text = g["code"] + return text + + content = ''.join(map(lambda m: evaluate(m), RE_COMMENT.finditer(text))) + return content + + def check_dangling_commas(self, text): + """ + Check for dangling commas. + + Log them and strip them out so we can continue. + """ + + def check_comma(g, m, line): + # ,] -> ] or ,} -> } + self.log_failure(E_COMMA, line) + if g["square_comma"] is not None: + return g["square_ws"] + g["square_bracket"] + else: + return g["curly_ws"] + g["curly_bracket"] + + def evaluate(m): + g = m.groupdict() + return check_comma(g, m, self.get_line(m.start(0))) if g["code"] is None else g["code"] + + return ''.join(map(lambda m: evaluate(m), RE_TRAILING_COMMA.finditer(text))) + + def log_failure(self, code, line=None): + """ + Log failure. + + Log failure code, line number (if available) and message. + """ + + if line: + print("%s: Line %d - %s" % (code, line, VIOLATION_MSG[code])) + else: + print("%s: %s" % (code, VIOLATION_MSG[code])) + self.fail = True + + def check_format(self, file_name): + """Initiate the check.""" + + self.fail = False + comment_align = None + with codecs.open(file_name, encoding='utf-8') as f: + count = 1 + for line in f: + indent_match = (RE_LINE_INDENT_TAB if self.use_tabs else RE_LINE_INDENT_SPACE).match(line) + end_comment = ( + (comment_align is not None or (indent_match and indent_match.group(2))) and + RE_COMMENT_END.search(line) + ) + # Don't allow empty lines at file start. + if count == 1 and line.strip() == '': + self.log_failure(W_NL_START, count) + # Line must end in new line + if not line.endswith('\n'): + self.log_failure(W_NL_END, count) + # Trailing spaces + if RE_TRAILING_SPACES.match(line): + self.log_failure(W_TRAILING_SPACE, count) + # Handle block comment content indentation + if comment_align is not None: + if comment_align.match(line) is None: + self.log_failure(W_COMMENT_INDENT, count) + if end_comment: + comment_align = None + # Handle general indentation + elif indent_match is None: + self.log_failure(W_INDENT, count) + # Enter into block comment + elif comment_align is None and indent_match.group(2): + alignment = indent_match.group(1) if indent_match.group(1) is not None else "" + if not end_comment: + comment_align = re.compile( + (PATTERN_COMMENT_INDENT_TAB if self.use_tabs else PATTERN_COMMENT_INDENT_SPACE) % alignment + ) + count += 1 + f.seek(0) + text = f.read() + + self.index_lines(text) + text = self.check_comments(text) + self.index_lines(text) + text = self.check_dangling_commas(text) + try: + json.loads(text) + except Exception as e: + self.log_failure(E_MALFORMED) + print(e) + return self.fail + + +if __name__ == "__main__": + import sys + cjf = CheckJsonFormat(False, True) + cjf.check_format(sys.argv[1]) diff --git a/code/train/Python/0087245_gpstandbywatch.py b/code/train/Python/0087245_gpstandbywatch.py new file mode 100644 index 0000000000000000000000000000000000000000..a4285b17dd505b29d1e5017ca787aca9fb66b4c8 --- /dev/null +++ b/code/train/Python/0087245_gpstandbywatch.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python +# Line too long - pylint: disable=C0301 +# Invalid name - pylint: disable=C0103 + +""" + gpstandbywatch.py + Copyright (c) EMC/Greenplum Inc 2011. All Rights Reserved. + + Check actual contents and process state of syncmaster + in order to properly return accurate information back to + gpinitstandby via gpstart. +""" + +import os +import sys +import glob +import time + +from gppylib.gplog import setup_tool_logging, get_default_logger +from gppylib.commands import gp, unix + + +def matching_files(pglogdir, ignore=None, setlimit=False): + """ + Generate a series of file names corresponding to files + in 'pglogdir' which are not in the specified 'ignore' map. + + Note that startup.log is always returned if present. + + If 'setlimit' is not false, files whose modification time + exceeds the ctime of startup.log will also be ignored. + """ + mlimit = None + pattern = os.path.join(pglogdir, 'startup.log') + for path in glob.glob(pattern): + if setlimit: + mlimit = os.stat(path).st_ctime + yield path + + pattern = os.path.join(pglogdir, '*.csv') + for path in glob.glob(pattern): + if ignore is not None and path in ignore: + continue + if mlimit is not None and os.stat(path).st_mtime >= mlimit: + continue + yield path + + +def updated_files(pglogdir, ignore, prev): + """ + Generate a series of (time, path) tuples corresponding to files + in 'pglogdir' and not in 'ignore' which were also modified + after 'prev' (or all files if 'prev' is None). + """ + for path in matching_files(pglogdir, ignore): + ts = os.stat(path).st_mtime + if prev is None or prev < ts: + yield (ts, path) + + +def updated_handles(pglogdir, ignore, prev, handles): + """ + Generate a series of (time, handle) tuples corresponding to files + in 'pglogdir' and not in 'ignore' modified after 'prev' + (or all files if 'prev' is None). + """ + for ts, path in updated_files(pglogdir, ignore, prev): + h = handles.get(path, None) + if h is None: + h = open(path, 'r') + handles[path] = h + yield (ts, h) + + + +class SyncmasterWatcher: + """ + Watch changes to files in the pg_log directory recorded by the gpsyncmaster. + """ + + def __init__(self, datadir): + """ + Build a map containing the existing contents of the pg_log + directory so that we can avoid getting confused by them + after we start the syncmaster. + """ + self.datadir = datadir + self.pglogdir = os.path.join(self.datadir, 'pg_log') + + # note use of setlimit=True here to prevent any files created + # after startup.log from becoming ignored. + self.ignore = {} + for path in matching_files( self.pglogdir, setlimit=True ): + self.ignore[path] = True + + self.handles = {} + self.maxlines = 1000 + self.timelimit = 10 + self.delay = 0.1 + + + def tail_briefly(self): + """ + Generate lines recently added to log files in the pg_log directory + updated after our __init__ constructor was called. + """ + start = time.time() # starting time + elapsed = 0 # time elapsed so far + count = 0 # number of lines we've seen + tp = None + + # until we're out of time or have returned enough lines + while elapsed < self.timelimit and count < self.maxlines: + + # for each file modified since we last checked + tn = None + for ts, h in updated_handles(self.pglogdir, self.ignore, tp, self.handles): + + # track the last file modification time + if tn is None or tn < ts: + tn = ts + + # yield the new lines to the caller + while count < self.maxlines: + line = h.readline() + if not line: + break + yield line + count += 1 + + # update the elapsed time + elapsed = time.time() - start + + # if any new lines, update prev and keep checking for more + if tn is not None: + tp = tn + continue + + # if we get here it means none of the files were updated in + # our last iteration. sleep a moment before checking for + # more updates + time.sleep(self.delay) + + + + def monitor_logs(self): + """ + Read the syncmaster log files for a few seconds, looking for + potential problems. + + Returns 0 if no problems were seen or or 1 if the startup log + contained an error or if the gpsyncmaster process exited before + we were done watching. + """ + logger.info("Monitoring logs") + + # now scan some of the syncmaster output for a moment + for line in self.tail_briefly(): + + if line.startswith('Traceback'): # gpsyncmaster traceback recorded + logger.warning(line) + return 1 + + # MPP-13212 - since the syncmaster reports rejected client connections + # as 'FATAL' errors, the presence of a 'FATAL' error need not indicate + # a problem in the syncmaster so we comment out the following logic: + # + # if line.find('FATAL') >= 0: # fatal error recorded + # logger.warning(line) + # return 1 + # + # This is especially important for health monitoring clients which may + # rely on the difference between a rejected connection and a TCP failure. + + if line.find('could not bind IPv4 socket') >= 0: # syncmaster used IPv6 by mistake + logger.warning(line) + return 1 + + if line.find('QDSYNC: scan forward') >= 0: # syncmaster appears to be working + logger.info(line) + break + + logger.info("checking if syncmaster is running") + pid = gp.getSyncmasterPID('localhost', self.datadir) + if not pid > 0: + logger.warning("syncmaster not running") + return 1 + + # syncmaster is running and there are no obvious errors in the log + logger.info("syncmaster appears ok, pid %s" % pid) + return 0 + + + def close(self): + """ + Closes all handles to the logs we're watching. + """ + for h in self.handles.values(): + h.close() + self.handles = {} + + + +if __name__ == '__main__': + + # setup gpAdminLogs logging + execname = os.path.split(sys.argv[0])[-1] + hostname = unix.getLocalHostname() + username = unix.getUserName() + setup_tool_logging(execname, hostname, username) + logger = get_default_logger() + + # watch syncmaster logs + watcher = SyncmasterWatcher( sys.argv[1] ) + rc = watcher.monitor_logs() + watcher.close() + + # report final status + logger.info("exiting with %s" % rc) + sys.exit( rc ) diff --git a/code/train/Python/0087586_a.py b/code/train/Python/0087586_a.py new file mode 100644 index 0000000000000000000000000000000000000000..871379c31fdff86098c35d03819f4b6b4181e615 --- /dev/null +++ b/code/train/Python/0087586_a.py @@ -0,0 +1,77 @@ +#!/usr/bin/python + +import sys + +def get_file(argv): + if len(argv) == 1: + return "a.in" + else: + return "a_%s.in" % (argv[1]) + +def get_file_out(argv): + if len(argv) == 1: + return "a.out" + else: + return "a_%s.out" % (argv[1]) + +def print_answer(t, answer, f): + answer = "Case #%d: %s" % (t, answer) + print answer + f.write(answer) + f.write("\n") + +def get_number(S): + L = list(S) + M = {} + for c in S: + if c in M: + M[c] = M[c] + 1 + else: + M[c] = 1 + O = ['Z', 'W', 'U', 'X', 'G', 'FI', 'SV', 'HR', 'NI', 'ON'] + uniques = { + 'Z': ['Z', 'E', 'R', 'O'], + 'W': ['T', 'W', 'O'], + 'U': ['F', 'O', 'U', 'R'], + 'X': ['S', 'I', 'X'], + 'G': ['E', 'I', 'G', 'H', 'T'], + 'FI': ['F', 'I', 'V', 'E'], + 'SV': ['S', 'E', 'V', 'E', 'N'], + 'HR': ['T', 'H', 'R', 'E', 'E'], + 'NI': ['N', 'I', 'N', 'E'], + 'ON': ['O', 'N', 'E'], + } + assert len(uniques) == 10 + mapping = [0, 2, 4, 6, 8, 5, 7, 3, 9, 1] + assert len(mapping) == 10 + numbers = [] + for check in xrange(0, len(O)): + uc = O[check] + found_all = True + for test in uc: + if test not in M or M[test] < 1: + found_all = False + break + if found_all: + to_remove = len(S) + for test in uc: + to_remove = min(M[test], to_remove) + for i in xrange(0, to_remove): + numbers.append(str(mapping[check])) + for c in uniques[uc]: + M[c] = M[c] - 1 + numbers.sort() + return ''.join(numbers) + +def main(argv): + f = open(get_file(argv), 'r') + f_out = open(get_file_out(argv), 'w') + T = int(f.readline()) + for t in xrange(1, T+1): + S = f.readline().strip() + number = get_number(S) + print_answer(t, number, f_out) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/code/train/Python/0088177_append.py b/code/train/Python/0088177_append.py new file mode 100644 index 0000000000000000000000000000000000000000..ddab79a14f87bf7285f3fde06bd02b939398abd2 --- /dev/null +++ b/code/train/Python/0088177_append.py @@ -0,0 +1,51 @@ +#!@PYTHON_EXECUTABLE@ +# -*- coding: utf-8 -*- + +import sys +import cf +import os + +INPUT_FILE = 'indent.png' + +FORMATS = ( + 'text', + 'smarttext', + 'textdebug' +) + +def removeOutput(): + fmtTest = cf.Tester('format') + fmtTest.removeOutput(INPUT_FILE, FORMATS) + +def test(): + fmtTest = cf.Tester('format') + fmtTest.addArg('--append') + + for format in FORMATS: + file_size = 0 + + for i in range(0, 2): + fmtTest.setFormat(format) + fmtTest.cuneiformTest(fmtTest.makeFullImageName(INPUT_FILE)) + + new_file_size = os.path.getsize(fmtTest.output()) + + if new_file_size <= file_size: + fmtTest.printError("Append failed") + fmtTest.addFail() + else: + file_size = new_file_size + + fmtTest.removeArg('--append') + + if fmtTest.passed(): + return True + else: + if __name__ == '__main__': + sys.exit(1) + else: + return False + +if __name__ == '__main__': + test() + diff --git a/code/train/Python/0088251_nmapRunner.py b/code/train/Python/0088251_nmapRunner.py new file mode 100644 index 0000000000000000000000000000000000000000..1c7e06b9bc2a070571896f8de70a1f595e75a2cb --- /dev/null +++ b/code/train/Python/0088251_nmapRunner.py @@ -0,0 +1,160 @@ +# Copyright (c) 2013 KernelSanders +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 +# USA + + +import os +import threading +import subprocess, shlex +import signal +import time +import re + +GATEWAY = '' +IFACE = '' +MYIP = '' + +''' +Return the default gateway's IP and the interface name used to connect to it as a tuple. +This function works with both Linux and OSX versions of netstat to retrieve the information. +''' +def setDefaultGatewayAndInterface(): + global GATEWAY, IFACE + if GATEWAY == '' or IFACE == '': + file=os.popen("netstat -nr") + data=file.read() + file.close() + lines=data.strip().split('\n') + entriesList = [] + osx = False + for line in lines: + if line[:7] == 'default' or line[:7] == '0.0.0.0': + if line[:7] == 'default': + osx = True + for entries in line.split(' '): + if entries != '': + entriesList.append(entries) + try: + GATEWAY = entriesList[1] + except: + print 'No network detected' + os.system('killall python') + os._exit(1) + + if osx: + IFACE = entriesList[5] + return entriesList[1], entriesList[5] + else: + IFACE = entriesList[7] + return entriesList[1], entriesList[7] + else: + return GATEWAY, IFACE + +''' +Return our own IP. This allows us to exclude it from the scan so we don't accidentally +ARP spoof ourselves. +''' +def getOwnIP(): + global MYIP + if MYIP == '': + f = os.popen("ifconfig en0") + data = f.read() + f.close() + IPs = re.findall(r"""inet\s[0-9]+(?:\.[0-9]+){3}""", data) + if len(IPs) < 1: + print 'No network detected' + os._exit(1) + MYIP = IPs[0][5:] + return IPs[0][5:] + else: + return MYIP + +#===================================================================================== +''' +The code below works on iOS 5, but for some reason nmap throws a segfault on iOS 6. +Therefore the pig module is used to conduct all scans. The following code is left in +for those interested, but is unused. +''' + + +''' +Using the default gateway's ip, create the IP arg for nmap. Currently only supports /24 +which is subnet 255.255.255.0. Subnet detection and better nmap arg creation is a possible +area of improvement. For now, if you know you are on a different subnet, manually change the /24 +the correct / notation. +''' +def setArgForNmap(router): + parts = router.split('.') + arg = parts[0]+'.'+parts[1]+'.'+parts[2]+'.0/24' + return arg + +''' +This class runs the nmap scan. It currently runs a simple ping scan (-sP), and parses the results +into a list of IPs that is returned when the returnHosts() is called. +''' +class nmap(threading.Thread): + def __init__(self, subnet): + self.subnet = subnet + self.scanning = True + self.returnList = [] + self._stop = threading.Event() + super(nmap,self).__init__() + + def run(self): + self.p1 = subprocess.Popen(shlex.split('nmap -sP ' + self.subnet + ' --system-dns'), stdout=subprocess.PIPE) + me = getOwnIP() + router, iface = setDefaultGatewayAndInterface() + while self.scanning: + out = self.p1.stdout.readline() + if len(out) > 0: + if 'Nmap done' in out: + self.stop() + elif 'up' in out: + ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', out )[0] + if ip != me and ip != router: + self.returnList.append(ip) + + def returnHosts(self): + return self.returnList + + def stop(self): + self._stop.set() + self.scanning = False + os.kill(self.p1.pid,signal.SIGKILL) + # super(nmap,self).join(None) + + def stopped(self): + return self._stop.isSet() + +''' +Set up the nmap scan, run it, and return the parsed list of hosts. +(kill it after 30 seconds no matter what) +''' +def getHosts(): + router, iface = setDefaultGatewayAndInterface() + subnet = setArgForNmap(router) + myNmap = nmap(subnet) + myNmap.start() + startTime = time.time() + while not myNmap.stopped() and time.time() - startTime < 30: + time.sleep(.2) + myNmap.stop() + myNmap.join() + hosts = myNmap.returnHosts() + return hosts + + + diff --git a/code/train/Python/0088696_encrypt.py b/code/train/Python/0088696_encrypt.py new file mode 100644 index 0000000000000000000000000000000000000000..28b4302d01c77db0605d928913b4da3b7ea3db08 --- /dev/null +++ b/code/train/Python/0088696_encrypt.py @@ -0,0 +1,132 @@ +#Brian Stamm +#CSC - 110 +#Howework 8 - Encryption/Decryption +#11.18.14 + +import sys +import os + +INSTRUCTION_CHOICE = 1 #GLOBAL CHOICES +DECRYPT_CHOICE = 2 +ENCRYPT_CHOICE = 3 +QUIT_CHOICE = 4 + +LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.!?,\'\";:-' #GLOBAL LIST - contains all letters/numbers/symbols encrypted + +def main(): + my_key = 'HIJKLMNOPQRSTUVWXYZ0123456789.!?,\'\";:-abcdefghijklmnopqrstuvwxyzABCDEFG' #KEY for LETTERS + choice = 0 + pre_instruction(my_key) #Instructing on menu selection, also contains check to make sure my_key and LETTERS line up accurately + + while choice != QUIT_CHOICE: #MENU Loop + display_menu() + + choice = int(input("Enter the number of your choice: ")) + + if choice == INSTRUCTION_CHOICE: + print() + instruction() + elif choice == DECRYPT_CHOICE: + print() + decrypt(my_key) + elif choice == ENCRYPT_CHOICE: + print() + encrypt(my_key) + elif choice == QUIT_CHOICE: + closure() + sys.exit() + else: + print("Sorry, I didn't understant that. Please try again.") + print() + +def pre_instruction(key): + print("Welcome to Little Orphan Annie's Encrpytion Program, brought to you by Ovaltine.") + print("Be sure to pick one of the numbers from the menu:") + keyList = list(key) #Following checks to ensure both LETTERS and my_list have all same characters within it. if not, shuts down. + lettersList = list(LETTERS) + keyList.sort() + lettersList.sort() + if keyList != lettersList: + print("There's an error with the program's key. Please contact Olvatine.") + sys.exit() + else: + print() + +def instruction(): #Detailed instructions + print("This program is designed to either encrypt a simple text file,") + print("or it will decrypt a file it has encrypted. It uses a special key designed") + print("only for this program, so it cannot decipher a code it does not have the key for.") + print() + print("A menu will display various options. Currently, you are in the \"Detailed") + print("Instructions\" Section. In the \"Decrypt file\", it will walk you through") + print("how to decrypt a selected file. The \"Encrypt file\" will help with encrypting.") + print() + print("After either encrypting or decrypting the file, this program creates a new") + print("file in the same folder as the initial program. To help distinguish from") + print("the original, the new file will either have a 'E' at the end of the file") + print("named for \"Encrypted,\", or 'D' for \"Decrypted.\"") + print() + print("Be sure when you are asked to write the file name, be sure to to put the") + print("extention at the end as well. For example, if your file is named \"Program\",") + print("you will need to remember to write out \"Program.txt\"") + print() + print("That's all for now! Back to the menu -") + print() + +def display_menu(): #Displays menu + print("Display menu:") + print() + print("1) Detailed Instructions") + print("2) Decrypt file") + print("3) Encrypt file") + print("4) Quit") + print('') + +def decrypt(my_key): #Decyption + file_name = input("What is the name of the file we are decrypting, with extension? ") + infile = open(file_name, 'r') + temp_file = open('temp.txt', 'w') #Creates temp file + new_name = rename_d(file_name) #Function to create new name for decrypted file, with D at end + line = infile.readline() + while line != '': + temp_file.write(line.translate({ord(x):y for (x,y) in zip(my_key,LETTERS)})) #LOOP that deciphers (same in Encryption, but my_key and LETTERS flipped + line=infile.readline() + infile.close() + temp_file.close() + os.rename('temp.txt', new_name) #Renames the temp file as something permnament + +def encrypt(my_key): #Encryption, same as previous, except + file_name = input("What is the name of the file we are encrpyting, with extension? ") + infile = open(file_name, 'r') + temp_file = open('temp.txt', 'w') + new_name = rename_e(file_name) #HERE, different function used for naming the file + line = infile.readline() + while line != '': + temp_file.write(line.translate({ord(x):y for (x,y) in zip(LETTERS,my_key)})) #And here, loop is basically same, except LETTERS and my_key are flipped + line=infile.readline() + infile.close() + temp_file.close() + os.rename('temp.txt', new_name) + +def rename_d(file): #Creates new file name for DECRYPTION + new_name = file[0:(len(file)-4)]+'D.txt' + print("Your decrypted file is named: ",new_name) + print("And back to the main menu.") + print() + return new_name + +def rename_e(file): #Creates new file name for ENCRYPTION + new_name = file[0:(len(file)-4)]+'E.txt' + print("Your encrypted file is named: ",new_name) + print("And bakc to the main menu.") + print() + return new_name + +def closure(): #Farewell + print() + print("Thanks for using Little Orphan Annie's Encrpytion Program!") + print("And don't forget, More Ovaltine, Please!") + sys.exit() + +main() + diff --git a/code/train/Python/0088719_liaCLI.py b/code/train/Python/0088719_liaCLI.py new file mode 100644 index 0000000000000000000000000000000000000000..a491b4c31e4eb0078ae9d587e47e4156f7412b62 --- /dev/null +++ b/code/train/Python/0088719_liaCLI.py @@ -0,0 +1,116 @@ +#import sys +import argparse +import os +import readline + + +import lialib.liaBackend as backend +import lialib.autoRules as rules + +## All the CLI Code +def rlinput(prompt, prefill='', promptColor = False): + if(promptColor): + colorTags = ['\x1b[0;32m', '\033[1;m'] + else: + colorTags = ['',''] + readline.set_startup_hook(lambda: readline.insert_text(prefill)) + try: + return input(colorTags[0] + prompt + colorTags[1]) + finally: + readline.set_startup_hook() + +def getUserInput(promptStr, prefill= '', defaultValue = False, force= False, promptColor=False): + """Gets the input from use. Returns False if no input""" + response = rlinput(promptStr, prefill= prefill, promptColor=promptColor) + if(force): + while(response == ""): + print("Sorry, a value must be provided for this. Please try again.") + response = rlinput(promptStr, prefill= prefill, promptColor= promptColor) + return(response) + else: + if(response == ""): + return(defaultValue) + else: + return(response) + +def modifyLinePrompt(lineData, editList= ["description", "date", "amount"], promptColor=False): + """Loops through and prompts user of any data modifications to line""" + print("\nAdding new entry: " + backend.entryInfo(lineData)) + + for dataType in editList: + editPrompt = dataType.capitalize() + ": " + response = getUserInput(editPrompt, prefill= lineData[dataType], promptColor= promptColor) + if(response): + backend.modifyData(lineData, dataType, response) + return(lineData) + +def setAccountsPrompt(lineData, ruleList= False, importAccount = "", promptColor = False): + """Calls the prompts to set the accounts (will also check rules when added)""" + + ## In the future, here is where the rules will be checked/called to see if + ## there is anything to pass as a secondary account's default name. + + ## For now, just enjoy the nested return call :P + lineData = mainAccountPrompt(lineData, importAccount = importAccount, promptColor= promptColor) + lineData = secondAccountsPrompt(lineData, ruleList = ruleList, promptColor= promptColor) + return(lineData) + +def mainAccountPrompt(lineData, importAccount = "", promptColor=False): + """Prompts the user for information to set the main account""" + editPrompt = "Main account: " + editImportAccount = getUserInput(editPrompt, prefill= importAccount, defaultValue = importAccount, force= True, promptColor= promptColor) + + return(backend.setMainAccount(lineData, editImportAccount)) + + +def secondAccountsPrompt(lineData, ruleList=False, promptColor=False): + """Prompts the user for the secondary account(s) information""" + secondAccounts = [] + + if(ruleList): + prefill = rules.matchRuleData(lineData, ruleList) + else: + prefill = "" + + force = True + accountAmount = True ## Ugh this is such a hack... + while(accountAmount != ""): + accountAmount = "" + accountAdd = getUserInput("Secondary account(s): ", prefill = prefill, defaultValue = "", force= force, promptColor= promptColor) + if(accountAdd != ""): + accountAmount = getUserInput("'" + accountAdd + "'" + " amount: ", defaultValue = "", promptColor= promptColor) + secondAccounts.append((accountAdd, accountAmount)) + force = False + return(backend.setSecondAccounts(lineData, secondAccounts)) + + + +def cacheProcess(queueData,ruleList, importAccount, outputFile, cacheFileSRC, promptColor= False): + """CLI for processing input files or cached items""" + for i in range(0,len(queueData)): + lineData = modifyLinePrompt(queueData[0], promptColor= promptColor) + lineData = setAccountsPrompt(lineData, ruleList = ruleList, importAccount = importAccount, promptColor= promptColor) + backend.writeLedgerStatement(lineData, outputFile) + queueData.pop(0) + ## If loop through all, delete cache file + if(os.path.exists(cacheFileSRC)): + os.remove(cacheFileSRC) + +def manualAddProcess(importAccount, outputFile, dateFormat, ruleList= False, orderList= ["description", "date", "amount"], promptColor= False): + """CLI sequence for manually adding entries""" + head, tail = orderList[0], orderList[1:] + userInput = getUserInput("Enter in transaction " + head + ": ", promptColor= promptColor) + lineData = {} + while userInput: + lineData["mainAccount"] = importAccount + lineData[head] = userInput + for inputType in tail: + lineData[inputType] = getUserInput("Enter in " + inputType + ": ", force=True, promptColor= promptColor) + lineData = backend.cleanLineData(lineData, dateFormat) + lineData = secondAccountsPrompt(lineData, ruleList = ruleList) + backend.writeLedgerStatement(lineData, outputFile) + print("'" + lineData[head] + "'" + " added to ledger journal.\n") + + userInput = getUserInput("Enter in transaction " + head + ": ", promptColor= promptColor) + + diff --git a/code/train/Python/0089329_subset.py b/code/train/Python/0089329_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..fb8c8daba4fb2fb48e20cc25a95d16796b5383e0 --- /dev/null +++ b/code/train/Python/0089329_subset.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python +# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai +from __future__ import (unicode_literals, division, absolute_import, + print_function) + +__license__ = 'GPL v3' +__copyright__ = '2013, Kovid Goyal ' +__docformat__ = 'restructuredtext en' + +import os, sys + +from calibre import prints, as_unicode +from calibre.ebooks.oeb.base import OEB_STYLES, OEB_DOCS, XPath +from calibre.ebooks.oeb.polish.container import OEB_FONTS +from calibre.ebooks.oeb.polish.utils import guess_type +from calibre.utils.fonts.sfnt.subset import subset +from calibre.utils.fonts.sfnt.errors import UnsupportedFont +from calibre.utils.fonts.utils import get_font_names + +def remove_font_face_rules(container, sheet, remove_names, base): + changed = False + for rule in tuple(sheet.cssRules): + if rule.type != rule.FONT_FACE_RULE: + continue + try: + uri = rule.style.getProperty('src').propertyValue[0].uri + except (IndexError, KeyError, AttributeError, TypeError, ValueError): + continue + name = container.href_to_name(uri, base) + if name in remove_names: + sheet.deleteRule(rule) + changed = True + return changed + +def subset_all_fonts(container, font_stats, report): + remove = set() + total_old = total_new = 0 + changed = False + for name, mt in container.mime_map.iteritems(): + if (mt in OEB_FONTS or name.rpartition('.')[-1].lower() in {'otf', 'ttf'}) and mt != guess_type('a.woff'): + chars = font_stats.get(name, set()) + with container.open(name, 'rb') as f: + f.seek(0, os.SEEK_END) + total_old += f.tell() + if not chars: + remove.add(name) + report('Removed unused font: %s'%name) + continue + with container.open(name, 'r+b') as f: + raw = f.read() + font_name = get_font_names(raw)[-1] + warnings = [] + container.log('Subsetting font: %s'%(font_name or name)) + try: + nraw, old_sizes, new_sizes = subset(raw, chars, + warnings=warnings) + except UnsupportedFont as e: + container.log.warning( + 'Unsupported font: %s, ignoring. Error: %s'%( + name, as_unicode(e))) + continue + + for w in warnings: + container.log.warn(w) + olen = sum(old_sizes.itervalues()) + nlen = sum(new_sizes.itervalues()) + total_new += len(nraw) + if nlen == olen: + report('The font %s was already subset'%font_name) + else: + report('Decreased the font %s to %.1f%% of its original size'% + (font_name, nlen/olen * 100)) + changed = True + f.seek(0), f.truncate(), f.write(nraw) + + for name in remove: + container.remove_item(name) + changed = True + + if remove: + for name, mt in container.mime_map.iteritems(): + if mt in OEB_STYLES: + sheet = container.parsed(name) + if remove_font_face_rules(container, sheet, remove, name): + container.dirty(name) + elif mt in OEB_DOCS: + for style in XPath('//h:style')(container.parsed(name)): + if style.get('type', 'text/css') == 'text/css' and style.text: + sheet = container.parse_css(style.text, name) + if remove_font_face_rules(container, sheet, remove, name): + style.text = sheet.cssText + container.dirty(name) + if total_old > 0: + report('Reduced total font size to %.1f%% of original'%( + total_new/total_old*100)) + else: + report('No embedded fonts found') + return changed + +if __name__ == '__main__': + from calibre.ebooks.oeb.polish.container import get_container + from calibre.ebooks.oeb.polish.stats import StatsCollector + from calibre.utils.logging import default_log + default_log.filter_level = default_log.DEBUG + inbook = sys.argv[-1] + ebook = get_container(inbook, default_log) + report = [] + stats = StatsCollector(ebook).font_stats + subset_all_fonts(ebook, stats, report.append) + outbook, ext = inbook.rpartition('.')[0::2] + outbook += '_subset.'+ext + ebook.commit(outbook) + prints('\nReport:') + for msg in report: + prints(msg) + print() + prints('Output written to:', outbook) + diff --git a/code/train/Python/0089369_14-Longest_Collatz_sequence.py b/code/train/Python/0089369_14-Longest_Collatz_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..9b29a25a65d95b49954b1baae6e20527ab5d81a6 --- /dev/null +++ b/code/train/Python/0089369_14-Longest_Collatz_sequence.py @@ -0,0 +1,52 @@ +""" +The following iterative sequence is defined for the set of positive integers: + +n -> n/2 (n is even) +n -> 3n + 1 (n is odd) + +Using the rule above and starting with 13, we generate the following sequence: + +13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 +It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. +Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. + +Which starting number, under one million, produces the longest chain? + +NOTE: Once the chain starts the terms are allowed to go above one million. +""" + +chainLengths = {} +longestChain = 0 +longestChainStartingNumber = 0 + +def get_next_collatz_number(number): + if number % 2 == 0: + return number / 2 + else: + return number * 3 + 1 + + +def get_collatz_chain_length(number): + chain_length = 0 + original_number = number + + while number > 1: + if number in chainLengths: + chain_length += chainLengths[number] + break + else: + number = get_next_collatz_number(number) + chain_length += 1 + + chainLengths[original_number] = chain_length + return chain_length + + +for i in xrange(2, 1000 * 1000): + currentLength = get_collatz_chain_length(i) + + if currentLength > longestChain: + longestChain = currentLength + longestChainStartingNumber = i + +print str(longestChainStartingNumber) \ No newline at end of file diff --git a/code/train/Python/0090453_dht11.py b/code/train/Python/0090453_dht11.py new file mode 100644 index 0000000000000000000000000000000000000000..ec770ad98144ad1d7c24c312f65277a8922095e6 --- /dev/null +++ b/code/train/Python/0090453_dht11.py @@ -0,0 +1,193 @@ +import time +import RPi + + +class DHT11Result: + 'DHT11 sensor result returned by DHT11.read() method' + + ERR_NO_ERROR = 0 + ERR_MISSING_DATA = 1 + ERR_CRC = 2 + + error_code = ERR_NO_ERROR + temperature = -1 + humidity = -1 + + def __init__(self, error_code, temperature, humidity): + self.error_code = error_code + self.temperature = temperature + self.humidity = humidity + + def is_valid(self): + return self.error_code == DHT11Result.ERR_NO_ERROR + + +class DHT11: + 'DHT11 sensor reader class for Raspberry' + + __pin = 0 + + def __init__(self, pin): + self.__pin = pin + + def read(self): + RPi.GPIO.setup(self.__pin, RPi.GPIO.OUT) + + # send initial high + self.__send_and_sleep(RPi.GPIO.HIGH, 0.05) + + # pull down to low + self.__send_and_sleep(RPi.GPIO.LOW, 0.02) + + # change to input using pull up + RPi.GPIO.setup(self.__pin, RPi.GPIO.IN, RPi.GPIO.PUD_UP) + + # collect data into an array + data = self.__collect_input() + + # parse lengths of all data pull up periods + pull_up_lengths = self.__parse_data_pull_up_lengths(data) + + # if bit count mismatch, return error (4 byte data + 1 byte checksum) + if len(pull_up_lengths) != 40: + return DHT11Result(DHT11Result.ERR_MISSING_DATA, 0, 0) + + # calculate bits from lengths of the pull up periods + bits = self.__calculate_bits(pull_up_lengths) + + # we have the bits, calculate bytes + the_bytes = self.__bits_to_bytes(bits) + + # calculate checksum and check + checksum = self.__calculate_checksum(the_bytes) + if the_bytes[4] != checksum: + return DHT11Result(DHT11Result.ERR_CRC, 0, 0) + + # ok, we have valid data, return it + return DHT11Result(DHT11Result.ERR_NO_ERROR, the_bytes[2], the_bytes[0]) + + def __send_and_sleep(self, output, sleep): + RPi.GPIO.output(self.__pin, output) + time.sleep(sleep) + + def __collect_input(self): + # collect the data while unchanged found + unchanged_count = 0 + + # this is used to determine where is the end of the data? + max_unchanged_count = 100 + + last = -1 + data = [] + while True: + current = RPi.GPIO.input(self.__pin) + data.append(current) + if last != current: + unchanged_count = 0 + last = current + else: + unchanged_count += 1 + if unchanged_count > max_unchanged_count: + break + + return data + + def __parse_data_pull_up_lengths(self, data): + STATE_INIT_PULL_DOWN = 1 + STATE_INIT_PULL_UP = 2 + STATE_DATA_FIRST_PULL_DOWN = 3 + STATE_DATA_PULL_UP = 4 + STATE_DATA_PULL_DOWN = 5 + + state = STATE_INIT_PULL_DOWN + + lengths = [] # will contain the lengths of data pull up periods + current_length = 0 # will contain the length of the previous period + + for i in range(len(data)): + + current = data[i] + current_length += 1 + + if state == STATE_INIT_PULL_DOWN: + if current == RPi.GPIO.LOW: + # ok, we got the initial pull down + state = STATE_INIT_PULL_UP + continue + else: + continue + if state == STATE_INIT_PULL_UP: + if current == RPi.GPIO.HIGH: + # ok, we got the initial pull up + state = STATE_DATA_FIRST_PULL_DOWN + continue + else: + continue + if state == STATE_DATA_FIRST_PULL_DOWN: + if current == RPi.GPIO.LOW: + # we have the initial pull down, the next will be the data pull up + state = STATE_DATA_PULL_UP + continue + else: + continue + if state == STATE_DATA_PULL_UP: + if current == RPi.GPIO.HIGH: + # data pulled up, the length of this pull up will determine whether it is 0 or 1 + current_length = 0 + state = STATE_DATA_PULL_DOWN + continue + else: + continue + if state == STATE_DATA_PULL_DOWN: + if current == RPi.GPIO.LOW: + # pulled down, we store the length of the previous pull up period + lengths.append(current_length) + state = STATE_DATA_PULL_UP + continue + else: + continue + + return lengths + + def __calculate_bits(self, pull_up_lengths): + # find shortest and longest period + shortest_pull_up = 1000 + longest_pull_up = 0 + + for i in range(0, len(pull_up_lengths)): + length = pull_up_lengths[i] + if length < shortest_pull_up: + shortest_pull_up = length + if length > longest_pull_up: + longest_pull_up = length + + # use the halfway to determine whether the period it is long or short + halfway = shortest_pull_up + (longest_pull_up - shortest_pull_up) / 2 + bits = [] + + for i in range(0, len(pull_up_lengths)): + bit = False + if pull_up_lengths[i] > halfway: + bit = True + bits.append(bit) + + return bits + + def __bits_to_bytes(self, bits): + the_bytes = [] + byte = 0 + + for i in range(0, len(bits)): + byte = byte << 1 + if (bits[i]): + byte = byte | 1 + else: + byte = byte | 0 + if ((i + 1) % 8 == 0): + the_bytes.append(byte) + byte = 0 + + return the_bytes + + def __calculate_checksum(self, the_bytes): + return the_bytes[0] + the_bytes[1] + the_bytes[2] + the_bytes[3] & 255 \ No newline at end of file diff --git a/code/train/Python/0090470_hmmm.py b/code/train/Python/0090470_hmmm.py new file mode 100644 index 0000000000000000000000000000000000000000..c0e25a89fadafc98efb2a8202f852529df7a49c0 --- /dev/null +++ b/code/train/Python/0090470_hmmm.py @@ -0,0 +1,150 @@ +from mpl_toolkits.mplot3d import axes3d +import matplotlib.pyplot as plt +from matplotlib import rcParams +import numpy as np +rcParams['axes.labelsize'] = 14 +rcParams['axes.titlesize'] = 16 +rcParams['xtick.labelsize'] = 14 +rcParams['ytick.labelsize'] = 14 +rcParams['legend.fontsize'] = 14 +rcParams['font.family'] = 'serif' +rcParams['font.serif'] = ['Computer Modern Roman'] +rcParams['text.usetex'] = True +rcParams['grid.alpha'] = 0.0 + +def make_cube(): + """ A Cube consists of a bunch of planes...""" + + planes = { + "top" : np.asarray( [[[0,1],[0,1]], [[0,0],[1,1]], [[1,1],[1,1]]] ), + "bottom" : np.asarray( [[[0,1],[0,1]], [[0,0],[1,1]], [[0,0],[0,0]]] ), + "left" : np.asarray( [[[0,0],[0,0]], [[0,1],[0,1]], [[0,0],[1,1]]] ), + "right" : np.asarray( [[[1,1],[1,1]], [[0,1],[0,1]], [[0,0],[1,1]]] ), + "front" : np.asarray( [[[0,1],[0,1]], [[0,0],[0,0]], [[0,0],[1,1]]] ), + "back" : np.asarray( [[[0,1],[0,1]], [[1,1],[1,1]], [[0,0],[1,1]]] ) + } + return planes + +def skew(space, column, row, recipe=None): + """Position of array elements in relation to each other.""" + + if recipe is None: + return (0,0,0) + elif recipe == "layered_tight": + return (space*0.1, space*0.5, -(space*0.5)) + elif recipe == "layered_loose": + return (space*1.0, space*1.25, -(space*1.25)) + elif recipe == "layered": + return (space*0.75, space*0.75, -(space*0.75)) + else: + raise TypeError("Unknown recipe[%s]" % recipe) + +class NDArrayPlotter(object): + + def __init__(self, shape, color="blue", alpha="0.6"): + self.defaults = { + "color": color, + "alpha": alpha, + "shape": shape + } + self.set_shape(shape) + self.set_color(color) + self.set_alpha(alpha) + + def set_shape(self, shape): + self.shape = shape + + def set_color(self, color): + self.colors = np.zeros(self.shape, dtype=('a10')) + self.colors[:] = color + + def set_alpha(self, alpha): + self.alphas = np.empty(self.shape, dtype=np.float32) + self.alphas[:] = alpha + + def render(self, ary, highlight=None, color=None, alpha=None): + + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + + cube = make_cube() + + scale = (0.01, 0.75, 0.75) + for space in xrange(0, ary.shape[0]): + for column in xrange(0, ary.shape[1]): + for row in xrange(0, ary.shape[2]): + + # Extract settings that apply to all sides of the cube + alpha = self.alphas[space,column,row] + color = self.colors[space,column,row] + + if highlight and highlight[space,column,row] == 1: + alpha = 1 + + relative_pos = skew(space, column, row, 'layered') + + for side in cube: + (Xs, Ys, Zs) = ( + scale[0]*(cube[side][0] + space ) +relative_pos[0], + scale[1]*(cube[side][1] + row ) +relative_pos[1], + scale[2]*(cube[side][2] + column ) +relative_pos[2] + ) + ax.plot_surface( + Xs, Ys, Zs, + rstride=1, cstride=1, + alpha=alpha, + color=color + ) + + highest = 0 # Make it look cubic + for size in ary.shape: + if size > highest: + highest = size + ax.set_xlim((0,highest)) + ax.set_ylim((0,highest)) + ax.set_zlim((0,highest)) + + + ax.set_xlabel('Third dimension' ) # Meant to visualize ROW-MAJOR ordering + ax.set_ylabel('Row(s)') + ax.set_zlabel('Column(s)') + + #plt.axis('off') # This also removes the axis labels... i want those... + #ax.set_axis_off() # this removes too much (also the labels) + + # So I try this instead... + ax.set_xticks([]) # removes the ticks... great now the rest of it + ax.set_yticks([]) + ax.set_zticks([]) + #ax.grid(False) # this does nothing.... + #ax.set_frame_on(False) # this does nothing.... + plt.show() + +def main(): + + subject = np.ones((5,5,5)) + + #highlight = np.zeros(subject.shape) # Highlight a row + #highlight[ 0, :, :] = 1 + #highlight[-1, :, :] = 1 + #highlight[ :, 0, :] = 1 + #highlight[ :, -1, :] = 1 + #highlight[ :, :, 0] = 1 + #highlight[ :, :,-1] = 1 + + + plotter = NDArrayPlotter(subject.shape) + + colors = plotter.colors + colors[:] = "#00FF00" + colors[ 0, :, :] = "#FF0000" + colors[-1, :, :] = "#FF0000" + colors[ :, 0, :] = "#FF0000" + colors[ :, -1, :] = "#FF0000" + colors[ :, :, 0] = "#FF0000" + colors[ :, :,-1] = "#FF0000" + + plotter.render(subject) + +if __name__ == "__main__": + main() diff --git a/code/train/Python/0090538_OpenInVisualStudio.py b/code/train/Python/0090538_OpenInVisualStudio.py new file mode 100644 index 0000000000000000000000000000000000000000..2ebb5be824399dc1e840b31ecacb80274a733bc2 --- /dev/null +++ b/code/train/Python/0090538_OpenInVisualStudio.py @@ -0,0 +1,141 @@ + +import prj.main.Prj as Prj + +import mtm.util.MiscUtil as MiscUtil +import os +import mtm.ioc.Container as Container +from mtm.ioc.Inject import Inject +import mtm.ioc.IocAssertions as Assertions +import sys +import argparse + +from mtm.log.LogStreamConsole import LogStreamConsole + +from mtm.util.Platforms import Platforms +import mtm.util.PlatformUtil as PlatformUtil +from mtm.util.Assert import * + +class Runner: + _scriptRunner = Inject('ScriptRunner') + _log = Inject('Logger') + _sys = Inject('SystemHelper') + _varMgr = Inject('VarManager') + _vsSolutionHelper = Inject('VisualStudioHelper') + _prjVsSolutionHelper = Inject('ProjenyVisualStudioHelper') + + def run(self, args): + self._args = args + success = self._scriptRunner.runWrapper(self._runInternal) + + if not success: + sys.exit(1) + + def _runInternal(self): + self._log.debug("Started OpenInVisualStudio with arguments: {0}".format(" ".join(sys.argv[1:]))) + + project, platform = self._getProjectAndPlatformFromFilePath(self._args.filePath) + + self._log.debug("Determined Project = {0}, Platform = {1}", project, platform) + + lineNo = 1 + if self._args.lineNo: + lineNo = int(self._args.lineNo) + + if platform == None: + solutionPath = None + else: + solutionPath = self._prjVsSolutionHelper.getCustomSolutionPath(project, platform) + + self._vsSolutionHelper.openFile( + self._args.filePath, lineNo, solutionPath) + + def _getProjectAndPlatformFromFilePath(self, filePath): + unityProjectsDir = self._sys.canonicalizePath(self._varMgr.expand('[UnityProjectsDir]')) + filePath = self._sys.canonicalizePath(filePath) + + if not filePath.startswith(unityProjectsDir): + raise Exception("The given file path is not within the UnityProjects directory") + + relativePath = filePath[len(unityProjectsDir)+1:] + dirs = relativePath.split(os.path.sep) + + projectName = dirs[0] + + try: + platformProjectDirName = dirs[1] + platformDirName = platformProjectDirName[platformProjectDirName.rfind('-')+1:] + + platform = PlatformUtil.fromPlatformFolderName(platformDirName) + except: + platform = None + + return projectName, platform + +def addArguments(parser): + parser.add_argument("filePath", help="") + parser.add_argument("lineNo", nargs='?', help="") + +def findConfigPath(filePath): + lastParentDir = None + parentDir = os.path.dirname(filePath) + + while parentDir and parentDir != lastParentDir: + configPath = os.path.join(parentDir, Prj.ConfigFileName) + + if os.path.isfile(configPath): + return configPath + + lastParentDir = parentDir + parentDir = os.path.dirname(parentDir) + + assertThat(False, "Could not find Prj config path starting at path {0}", filePath) + +def installBindings(args): + + Container.bind('LogStream').toSingle(LogStreamConsole, True, False) + + Prj.installBindings(findConfigPath(args.filePath)) + +def _main(): + parser = argparse.ArgumentParser(description='Projeny Visual Studio Opener') + addArguments(parser) + + argv = sys.argv[1:] + + # If it's 2 then it only has the -cfg param + if len(argv) == 0: + parser.print_help() + sys.exit(2) + + args = parser.parse_args(sys.argv[1:]) + + installBindings(args) + + Runner().run(args) + +if __name__ == '__main__': + if (sys.version_info < (3, 0)): + print('Wrong version of python! Install python 3 and try again') + sys.exit(2) + + succeeded = True + + try: + _main() + + except KeyboardInterrupt as e: + print('Operation aborted by user by hitting CTRL+C') + succeeded = False + + except Exception as e: + sys.stderr.write(str(e) + '\n') + + if not MiscUtil.isRunningAsExe(): + sys.stderr.write('\n' + traceback.format_exc()) + + succeeded = False + + if not succeeded: + sys.exit(1) + + diff --git a/code/train/Python/0090736_build.py b/code/train/Python/0090736_build.py new file mode 100644 index 0000000000000000000000000000000000000000..79a703c1409126f2831db2d8d0f873016d2f9121 --- /dev/null +++ b/code/train/Python/0090736_build.py @@ -0,0 +1,209 @@ +# Copyright 2015 Dietrich Epp. +# +# This file is part of Dash and the Jetpack Space Pirates. The Dash +# and the Jetpack Space Pirates source code is distributed under the +# terms of the MIT license. See LICENSE.txt for details. +import base64 +import hashlib +import json +import os +import pipes +import subprocess +import sys + +class BuildFailure(Exception): + pass + +def all_files(root, *, exts=None): + """List all files below the given root.""" + if exts is not None: + if not exts: + return + exts = set(exts) + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = [x for x in dirnames + if not x.startswith('.')] + for filename in filenames: + if filename.startswith('.'): + continue + if exts: + ext = os.path.splitext(filename)[1] + if ext not in exts: + continue + yield os.path.join(dirpath, filename) + +def latest_mtime(files): + """Get the latest modification timestamp of the given files.""" + mtime = -1 + for file in files: + mtime = max(mtime, os.stat(file).st_mtime) + return mtime + +def format_pipe(cmds): + return ' | '.join(' '.join(pipes.quote(arg) for arg in cmd) for cmd in cmds) + +def run_pipe(cmd, data=None): + """Pipe data through a single command.""" + print(' ' + format_pipe([cmd]), file=sys.stderr) + proc = subprocess.Popen( + cmd, + stdin=None if data is None else subprocess.PIPE, + stdout=subprocess.PIPE) + stdout, stderr = proc.communicate(data) + if proc.returncode != 0: + raise BuildFailure('Command failed: {}'.format(cmd[0])) + return stdout + +class CachedFile(object): + __slots__ = ['path', 'hash', 'key'] + +def sort_key(path): + base, ext = os.path.splitext(path) + return ext, base + +class BuildSystem(object): + """The application build system.""" + __slots__ = ['cache'] + + def __init__(self): + self.cache = {} + + def copy(self, path, src, *, bust=False): + """Copy a file and return the path.""" + def get_data(): + with open(src, 'rb') as fp: + return fp.read() + return self.build(path, get_data, deps=[src], bust=bust) + + def write(self, path, data, *, bust=False): + """Write data and return the path.""" + return self.build(path, lambda x: x, args=[data], bust=bust) + + def build(self, path, builder, *, + deps=[], args=(), kw={}, bust=False): + """Build a file and return the corrected path.""" + mtime = latest_mtime(deps) + key = mtime, args, kw + try: + cached = self.cache[path] + except KeyError: + cached = None + else: + if key == cached.key: + return cached.path + print('Rebuilding {}'.format(path), file=sys.stderr) + data = builder(*args, **kw) + obj = hashlib.new('SHA256') + obj.update(data) + hash = obj.digest() + if cached is not None and cached.hash == hash: + return cached.path + dirname, basename = os.path.split(path) + if bust: + out_name = '{0[0]}.{1}{0[1]}'.format( + os.path.splitext(basename), + base64.b16encode(hash)[:8].lower().decode('UTF-8')) + out_path = os.path.join(dirname, out_name) + else: + out_path = path + cached = CachedFile() + cached.path = out_path + cached.hash = hash + cached.key = key + if dirname: + os.makedirs(dirname, exist_ok=True) + with open(out_path, 'wb') as fp: + fp.write(data) + self.cache[path] = cached + return out_path + + def build_module(self, path, name, builder): + """Build a file from an NPM module.""" + with open(os.path.join('node_modules', name, 'package.json')) as fp: + data = json.load(fp) + version = data['version'] + dirname, basename = os.path.split(path) + out_name = '{0[0]}-{1}{0[1]}'.format( + os.path.splitext(basename), version) + out_path = os.path.join(dirname, out_name) + if not os.path.isfile(out_path): + data = builder() + if dirname: + os.makedirs(dirname, exist_ok=True) + with open(out_path, 'wb') as fp: + fp.write(data) + return out_path + + def package(self, out_path, directory): + """Create a package for all of the files.""" + if not directory: + files = [c.path for c in self.cache.values()] + else: + if not directory.endswith('/'): + directory += '/' + files = [c.path[len(directory):] for c in self.cache.values() + if c.path.startswith(directory)] + if not files: + raise BuildFailure('No files') + files.sort(key=sort_key) + try: + with open(out_path, 'wb') as fp: + subprocess.check_call(['tar', 'cz'] + files, + stdout=fp, cwd=directory) + except: + try: + os.unlink(out_path) + except FileNotFoundError: + pass + raise + print('Created {}'.format(out_path)) + +def browserify(config, modules): + """Bundle a JavaScript application using browserify.""" + try: + env = dict(config['environment']) + except KeyError: + env = None + sec = config['browserify'] + cmd = [sec.get('path', './node_modules/.bin/browserify')] + cmd.extend(sec.get('flags', '').split()) + if env: + cmd.extend(('-t', '[', 'envify')) + for k, v in env.items(): + cmd.extend(('--' + k.upper(), v)) + cmd.append(']') + cmd.extend(modules) + return run_pipe(cmd) + +def minify_js(config, data): + """Minify a JavaScript document.""" + sec = config['uglifyjs'] + if sec.getboolean('enable', True): + cmd = [sec.get('path', './node_modules/.bin/uglifyjs')] + cmd.extend(sec.get('flags', '').split()) + data = run_pipe(cmd, data) + return data + +def minify_css(config, data): + """Minify a CSS document.""" + sec = config['cleancss'] + if sec.getboolean('enable', True): + cmd = [sec.get('path', './node_modules/.bin/cleancss')] + cmd.extend(sec.get('flags', '').split()) + data = run_pipe(cmd, data) + return data + +def minify_html(config, data): + """Minify an HTML document.""" + sec = config['html_minifier'] + if sec.getboolean('enable', True): + cmd = [sec.get('path', './node_modules/.bin/html-minifier')] + cmd.extend(sec.get('flags', '').split()) + data = run_pipe(cmd, data) + return data + +def minify_json(config, path): + """Minify a JSON document.""" + with open(path) as fp: + obj = json.load(fp) + return json.dumps(obj, separators=(',', ':')).encode('UTF-8') diff --git a/code/train/Python/0091103_ArnoldCatPeriod.py b/code/train/Python/0091103_ArnoldCatPeriod.py new file mode 100644 index 0000000000000000000000000000000000000000..81bece69c6f66c1743c8862f66c8e40d0f9edf36 --- /dev/null +++ b/code/train/Python/0091103_ArnoldCatPeriod.py @@ -0,0 +1,62 @@ +from ArnoldCat import ArnoldCat +import matplotlib.pyplot as plt +import math + +def tracerT(Nmax, Nmin=1, p=1, q=1): + file = open('store.txt', 'w') + for i in xrange(Nmin,Nmax+1): + arnoldCat = ArnoldCat(i, None, None, p, q) + T = arnoldCat.calculerT() + print>>file, T + print('N = '+str(i)+' , T = '+ str(T)) + file.close() + +def plotPeriode(lien, borne = None): + with open(lien) as f: + lines = f.read().splitlines() + x = xrange(1,len(lines)+1) + c = math.log10((1+math.sqrt(5))/2) + if borne == None : + plt.plot(x, lines, 'b-') + else : + plt.plot(x, lines, 'b-', x, [3*i for i in x], 'r-', x, [math.log10(i)/c for i in x], 'r-') + +def plotPeriodeRatio(lien): + with open(lien) as f: + lines = f.read().splitlines() + x = xrange(1,len(lines)+1) + for i in xrange(len(lines)): + lines[i]=float(int(lines[i]))/(i+1) + plt.plot(x, lines, 'b-') + +def plotPeriodeFibonacci(lien): + with open(lien) as f: + lines = f.read().splitlines() + F = [1, 1] + T = [1] + while F[1] 0 + + @property + def IsPublished(self): + return self.published > 0 + + @property + def IsPublishedEqual(self): + return self.published_equal == len(self.projects) + + +class Branches(Command): + common = True + helpSummary = "View current topic branches" + helpUsage = """ +%prog [...] + +Summarizes the currently available topic branches. + +Branch Display +-------------- + +The branch display output by this command is organized into four +columns of information; for example: + + *P nocolor | in repo + repo2 | + +The first column contains a * if the branch is the currently +checked out branch in any of the specified projects, or a blank +if no project has the branch checked out. + +The second column contains either blank, p or P, depending upon +the upload status of the branch. + + (blank): branch not yet published by repo upload + P: all commits were published by repo upload + p: only some commits were published by repo upload + +The third column contains the branch name. + +The fourth column (after the | separator) lists the projects that +the branch appears in, or does not appear in. If no project list +is shown, then the branch appears in all projects. + +""" + + def Execute(self, opt, args): + projects = self.GetProjects(args) + out = BranchColoring(self.manifest.manifestProject.config) + all = {} + project_cnt = len(projects) + + for project in projects: + for name, b in project.GetBranches().iteritems(): + b.project = project + if name not in all: + all[name] = BranchInfo(name) + all[name].add(b) + + names = all.keys() + names.sort() + + if not names: + print >>sys.stderr, ' (no branches)' + return + + width = 25 + for name in names: + if width < len(name): + width = len(name) + + for name in names: + i = all[name] + in_cnt = len(i.projects) + + if i.IsCurrent: + current = '*' + hdr = out.current + else: + current = ' ' + hdr = out.local + + if i.IsPublishedEqual: + published = 'P' + elif i.IsPublished: + published = 'p' + else: + published = ' ' + + hdr('%c%c %-*s' % (current, published, width, name)) + out.write(' |') + + if in_cnt < project_cnt and (in_cnt == 1): + fmt = out.write + paths = [] + if in_cnt < project_cnt - in_cnt: + type = 'in' + for b in i.projects: + paths.append(b.project.relpath) + else: + fmt = out.notinproject + type = 'not in' + have = set() + for b in i.projects: + have.add(b.project) + for p in projects: + paths.append(p.relpath) + + s = ' %s %s' % (type, ', '.join(paths)) + if width + 7 + len(s) < 80: + fmt(s) + else: + out.nl() + fmt(' %s:' % type) + for p in paths: + out.nl() + fmt(' %s' % p) + out.nl() diff --git a/code/train/Python/0092348_rules.py b/code/train/Python/0092348_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..6d3e615d10ef4587e8a0e3bcb64ba502ce9a8f6c --- /dev/null +++ b/code/train/Python/0092348_rules.py @@ -0,0 +1,65 @@ +from cloudbot import hook + +ruleslist = {"spam": "Your issue was too long. Go to http://pastebin.com and link your issue from there.", +"nick": "Please change your nick by entering /nick newnick", +"nocoop": "You've been helped on the matter and will receive no further help or advice. Thank you for your (non-existent) cooperation.", +"abuse": "Please refrain from abusing the bot as it might cause you to be kicked from the channel, thanks.", +"monologue": "Please take your monologue elsewhere other than this channel, maybe you could start a blog..thanks.", +"enter": "Enter is not a spacebar, please try to form complete sentences to avoid being kicked by a bot or appearing as though you're just spamming.", +"pastie": "Please don't paste all that content here, go to https://pastebin.com/ and link your issue instead..thanks.", +"caps": "Please refrain from using all or mostly caps, failure to adhere to this notice may result in your nick being quieted or fbanned.", +"help": "If you need help with channel/nick/network issues please /join #crushandrun and state your issue."} + +# Generate the rules list reply. +# Beginning phrase. +ruleslistreply = "The rules I have loaded are: " +# Make the list of entries. +rulesactuallist = list(ruleslist.keys()) +# Alphabetize it. +rulesactuallist.sort() +# Generate the reply. +for i in rulesactuallist: + # Probably a better way of handling this... Don't need a comma at the start. + if ruleslistreply.endswith(": ") == True: + ruleslistreply = ruleslistreply+i + # The rest of the list. + else: + ruleslistreply = ruleslistreply+", "+i +# Finish phrase. +ruleslistreply = ruleslistreply+"." + +@hook.command(permissions=["rules"]) +def rules(text, nick, chan, conn): + # Check for a category name. + if text: + # Split by spaces if they exist. + text = text.split(" ") + # Make category name lowercase. + command = text[0].lower().strip() + # Check if there's a target nick. + try: + targetnick = text[1] + except IndexError: + targetnick = None + # Check to see if category exists. + try: + reply = ruleslist[command] + except KeyError: + reply = ruleslistreply + # Category doesn't exist: + if reply == ruleslistreply: + conn.cmd("PRIVMSG " + nick + " :"+ruleslistreply) + # Category exists: + else: + # Target nick exists: + if targetnick !=None: + conn.cmd("PRIVMSG " + chan + " :"+targetnick+": "+reply) + else: + return reply + # No category name, return list of categories. + else: + conn.cmd("PRIVMSG " + nick + " :"+ruleslistreply) + +@hook.command(permissions=["rules"]) +def listrules(conn, nick): + conn.cmd("PRIVMSG " + nick + " :"+ruleslistreply) diff --git a/code/train/Python/0092434_check.py b/code/train/Python/0092434_check.py new file mode 100644 index 0000000000000000000000000000000000000000..0d5306541482d5bb035737e6a438321001cf52da --- /dev/null +++ b/code/train/Python/0092434_check.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# check.py +# +# This file was forked from Cnchi (graphical installer from Antergos) +# Check it at https://github.com/antergos +# +# Copyright 2013 Antergos (http://antergos.com/) +# Copyright 2013 Manjaro (http://manjaro.org) +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301, USA. + +""" Check screen (detects if Manjaros prerequisites are meet) """ + +from gi.repository import Gtk, GObject +import subprocess +import os +import logging +import canonical.gtkwidgets as gtkwidgets +import canonical.misc as misc + +from rank_mirrors import AutoRankmirrorsThread + +# Constants +NM = 'org.freedesktop.NetworkManager' +NM_STATE_CONNECTED_GLOBAL = 70 +UPOWER = 'org.freedesktop.UPower' +UPOWER_PATH = '/org/freedesktop/UPower' +MIN_ROOT_SIZE = 6000000000 + +_next_page = "timezone" +_prev_page = "location" + +class Check(Gtk.Box): + """ Check class """ + def __init__(self, params): + """ Init class ui """ + self.title = params['title'] + self.settings = params['settings'] + self.forward_button = params['forward_button'] + self.backwards_button = params['backwards_button'] + self.testing = params['testing'] + + super().__init__() + + self.ui = Gtk.Builder() + + self.ui_dir = self.settings.get('ui') + self.ui.add_from_file(os.path.join(self.ui_dir, "check.ui")) + self.ui.connect_signals(self) + + self.remove_timer = False + + self.thread = None + + self.prepare_power_source = None + self.prepare_network_connection = None + self.prepare_enough_space = None + self.timeout_id = None + self.prepare_best_results = None + + super().add(self.ui.get_object("check")) + + def translate_ui(self): + txt = _("System Check") + txt = '%s' % txt + self.title.set_markup(txt) + + self.prepare_enough_space = self.ui.get_object("prepare_enough_space") + txt = _("has at least %dGB available storage space") % int(MIN_ROOT_SIZE / 1000000000) + txt += " (*)" + self.prepare_enough_space.props.label = txt + + self.label_space = self.ui.get_object("label_space") + txt = _("This highly depends on which desktop environment you choose, so you might need more space.") + txt = "(*) %s" % txt + self.label_space.set_markup(txt) + + self.prepare_power_source = self.ui.get_object("prepare_power_source") + txt = _("is plugged in to a power source") + self.prepare_power_source.props.label = txt + + self.prepare_network_connection = self.ui.get_object("prepare_network_connection") + txt = _("is connected to the Internet") + self.prepare_network_connection.props.label = txt + + self.prepare_best_results = self.ui.get_object("prepare_best_results") + txt = _("For best results, please ensure that this computer:") + txt = '%s' % txt + self.prepare_best_results.set_markup(txt) + + def check_all(self): + has_internet = misc.has_connection() + self.prepare_network_connection.set_state(has_internet) + + on_power = not self.on_battery() + self.prepare_power_source.set_state(on_power) + + space = self.has_enough_space() + self.prepare_enough_space.set_state(space) + + #if has_internet and space: + if space: + return True + + return False + + def on_battery(self): + import dbus + if self.has_battery(): + bus = dbus.SystemBus() + upower = bus.get_object(UPOWER, UPOWER_PATH) + return misc.get_prop(upower, UPOWER_PATH, 'OnBattery') + + return False + + def has_battery(self): + # UPower doesn't seem to have an interface for this. + path = '/sys/class/power_supply' + if not os.path.exists(path): + return False + for folder in os.listdir(path): + type_path = os.path.join(path, folder, 'type') + if os.path.exists(type_path): + with open(type_path) as power_file: + if power_file.read().startswith('Battery'): + return True + return False + + def has_enough_space(self): + lsblk = subprocess.Popen(["lsblk", "-lnb"], stdout=subprocess.PIPE) + output = lsblk.communicate()[0].decode("utf-8").split("\n") + + max_size = 0 + + for item in output: + col = item.split() + if len(col) >= 5: + if col[5] == "disk" or col[5] == "part": + size = int(col[3]) + if size > max_size: + max_size = size + # we need 5GB + # 5000000000 + if max_size >= MIN_ROOT_SIZE: + return True + + return False + + def on_timer(self, time): + if not self.remove_timer: + self.forward_button.set_sensitive(self.check_all()) + return not self.remove_timer + + def store_values(self): + # remove timer + self.remove_timer = True + + logging.info(_("We have Internet connection.")) + logging.info(_("We're connected to a power source.")) + logging.info(_("We have enough disk space.")) + + # Enable forward button + self.forward_button.set_sensitive(True) + + if not self.testing: + ## Launch rankmirrors script to determine the 5 fastest mirrors + self.thread = AutoRankmirrorsThread() + self.thread.start() + + return True + + def get_prev_page(self): + return _prev_page + + def get_next_page(self): + return _next_page + + def prepare(self, direction): + self.translate_ui() + self.show_all() + + self.forward_button.set_sensitive(self.check_all()) + + # set timer + self.timeout_id = GObject.timeout_add(1000, self.on_timer, None) diff --git a/code/train/Python/0093703_polling.py b/code/train/Python/0093703_polling.py new file mode 100644 index 0000000000000000000000000000000000000000..6b7ae4221f64ffa7785bd2dcc10393ab54d1bf41 --- /dev/null +++ b/code/train/Python/0093703_polling.py @@ -0,0 +1,169 @@ +# Copyright 2017, Google Inc. +# +# 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. + +"""Abstract and helper bases for Future implementations.""" + +import abc +import concurrent.futures +import functools +import operator + +import six +import tenacity + +from google.cloud.future import _helpers +from google.cloud.future import base + + +class PollingFuture(base.Future): + """A Future that needs to poll some service to check its status. + + The :meth:`done` method should be implemented by subclasses. The polling + behavior will repeatedly call ``done`` until it returns True. + + .. note: Privacy here is intended to prevent the final class from + overexposing, not to prevent subclasses from accessing methods. + """ + def __init__(self): + super(PollingFuture, self).__init__() + self._result = None + self._exception = None + self._result_set = False + """bool: Set to True when the result has been set via set_result or + set_exception.""" + self._polling_thread = None + self._done_callbacks = [] + + @abc.abstractmethod + def done(self): + """Checks to see if the operation is complete. + + Returns: + bool: True if the operation is complete, False otherwise. + """ + # pylint: disable=redundant-returns-doc, missing-raises-doc + raise NotImplementedError() + + def running(self): + """True if the operation is currently running.""" + return not self.done() + + def _blocking_poll(self, timeout=None): + """Poll and wait for the Future to be resolved. + + Args: + timeout (int): How long to wait for the operation to complete. + If None, wait indefinitely. + """ + if self._result_set: + return + + retry_on = tenacity.retry_if_result( + functools.partial(operator.is_not, True)) + # Use exponential backoff with jitter. + wait_on = ( + tenacity.wait_exponential(multiplier=1, max=10) + + tenacity.wait_random(0, 1)) + + if timeout is None: + retry = tenacity.retry(retry=retry_on, wait=wait_on) + else: + retry = tenacity.retry( + retry=retry_on, + wait=wait_on, + stop=tenacity.stop_after_delay(timeout)) + + try: + retry(self.done)() + except tenacity.RetryError as exc: + six.raise_from( + concurrent.futures.TimeoutError( + 'Operation did not complete within the designated ' + 'timeout.'), + exc) + + def result(self, timeout=None): + """Get the result of the operation, blocking if necessary. + + Args: + timeout (int): How long to wait for the operation to complete. + If None, wait indefinitely. + + Returns: + google.protobuf.Message: The Operation's result. + + Raises: + google.gax.GaxError: If the operation errors or if the timeout is + reached before the operation completes. + """ + self._blocking_poll(timeout=timeout) + + if self._exception is not None: + # pylint: disable=raising-bad-type + # Pylint doesn't recognize that this is valid in this case. + raise self._exception + + return self._result + + def exception(self, timeout=None): + """Get the exception from the operation, blocking if necessary. + + Args: + timeout (int): How long to wait for the operation to complete. + If None, wait indefinitely. + + Returns: + Optional[google.gax.GaxError]: The operation's error. + """ + self._blocking_poll() + return self._exception + + def add_done_callback(self, fn): + """Add a callback to be executed when the operation is complete. + + If the operation is not already complete, this will start a helper + thread to poll for the status of the operation in the background. + + Args: + fn (Callable[Future]): The callback to execute when the operation + is complete. + """ + if self._result_set: + _helpers.safe_invoke_callback(fn, self) + return + + self._done_callbacks.append(fn) + + if self._polling_thread is None: + # The polling thread will exit on its own as soon as the operation + # is done. + self._polling_thread = _helpers.start_daemon_thread( + target=self._blocking_poll) + + def _invoke_callbacks(self, *args, **kwargs): + """Invoke all done callbacks.""" + for callback in self._done_callbacks: + _helpers.safe_invoke_callback(callback, *args, **kwargs) + + def set_result(self, result): + """Set the Future's result.""" + self._result = result + self._result_set = True + self._invoke_callbacks(self) + + def set_exception(self, exception): + """Set the Future's exception.""" + self._exception = exception + self._result_set = True + self._invoke_callbacks(self) diff --git a/code/train/Python/0093923_8.3.5.2_sort_tuple.py b/code/train/Python/0093923_8.3.5.2_sort_tuple.py new file mode 100644 index 0000000000000000000000000000000000000000..fef06430362881c6cf5d372ea9e452f4c647d494 --- /dev/null +++ b/code/train/Python/0093923_8.3.5.2_sort_tuple.py @@ -0,0 +1,24 @@ +''' + +Sort a tuple by converting it to a list. + +----------------------------------------------------------- +(c) 2013 Allegra Via and Kristian Rother + Licensed under the conditions of the Python License + + This code appears in section 8.3.5 of the book + "Managing Biological Data with Python". +----------------------------------------------------------- +''' + +# sort a tuple +data = (1, 4, 5, 3, 8, 9, 2, 6, 8, 9, 30) +list_data = list(data) +list_data.sort() +new_tup = tuple(list_data) +print(new_tup) + +# sort a tuple using the sorted() built-in function +new_tup = tuple(sorted(data)) +print(new_tup) + diff --git a/code/train/Python/0094269_stiff-linear.py b/code/train/Python/0094269_stiff-linear.py new file mode 100644 index 0000000000000000000000000000000000000000..05c056eb7478ce05b6edee0524d0cea07803c911 --- /dev/null +++ b/code/train/Python/0094269_stiff-linear.py @@ -0,0 +1,267 @@ +# solve the stiff linear system +# +# dY/dt = A Y +# +# / -alpha beta \ +# with A = | | +# \ alpha -beta / +# +# this has the analytic solution for Y_B(0) = 0 of +# +# Y_B/Y_A = [ exp{(alpha+beta) t} - 1 ] / [ (beta/alpha) exp{(alpha+beta) t} + 1] +# +# this shows that a characteristic timescale is t ~ 1/(alpha + beta) +# +# and in the limit t -> infinity, Y_B/Y_A ~ alpha/beta +# +# This example came from Frank Timmes lecture notes +# +# With Backward-Euler, we have the linear system: +# +# (I - dt A) Y^{n+1} = Y^n +# +# also do Runge-Kutta 4th order and VODE +# +# M. Zingale (2013-02-22) + +import numpy +import pylab +from scipy.integrate import ode + +alpha = 1.e9 +beta = 1.e-5 + + +def mkMatrix(dt): + """ return I - dt A """ + return numpy.matrix([[1.0 + dt*alpha, -dt*beta ], + [-dt*alpha, 1.0 + dt*beta]]) + +def rhs(t, Y): + """ RHS of the system for explicit methods """ + return numpy.array([-alpha*Y[0] + beta*Y[1], alpha*Y[0] - beta*Y[1]]) + + +def jac(t, Y): + """ the Jacobian of the system (just the matrix A) """ + return numpy.array([ [-alpha, beta], [alpha, -beta] ]) + + +def integrate(YA_0, YB_0, dt, tmax): + """ perform a backward-Euler integration """ + + YA = YA_0 + YB = YB_0 + + tout = [0.0] + yaout = [YA] + ybout = [YB] + + t = 0.0 + while (t < tmax): + + # create the matrix + J = mkMatrix(dt) + + b = numpy.array([YA, YB]) + + # solve the linear system J x = b + x = numpy.linalg.solve(J, b) + + YA = x[0]; YB = x[1] + + t += dt + + tout.append(t) + yaout.append(YA) + ybout.append(YB) + + return numpy.array(tout), numpy.array(yaout), numpy.array(ybout) + + +def trapIntegrate(YA_0, YB_0, dt, tmax): + """ perform an implicit trapezoid integration: + y^{n+1} = y^n + dt/2 [ f(y^n) + f(y^{n+1}) ] """ + + YA = YA_0 + YB = YB_0 + + tout = [0.0] + yaout = [YA] + ybout = [YB] + + t = 0.0 + while (t < tmax): + + # create the matrix -- using dt/2 + J = mkMatrix(dt/2) + + # create the explicit source term + b = numpy.array([(1.0 - 0.5*dt*alpha)*YA + 0.5*dt*beta*YB, + 0.5*dt*alpha*YA + (1.0 - 0.5*dt*beta)*YB]) + + # solve the linear system J x = b + x = numpy.linalg.solve(J, b) + + YA = x[0]; YB = x[1] + + t += dt + + tout.append(t) + yaout.append(YA) + ybout.append(YB) + + return numpy.array(tout), numpy.array(yaout), numpy.array(ybout) + + +def RK4Integrate(YA_0, YB_0, dt, tmax): + """ 4th-order explicit Runge-Kutta for comparison """ + + YA = YA_0 + YB = YB_0 + + tout = [0.0] + yaout = [YA] + ybout = [YB] + + t = 0.0 + while (t < tmax): + + k1 = rhs(t, numpy.array([YA, YB]) ) + k2 = rhs(t+0.5*dt, numpy.array([YA+0.5*dt*k1[0], YB+0.5*dt*k1[1]]) ) + k3 = rhs(t+0.5*dt, numpy.array([YA+0.5*dt*k2[0], YB+0.5*dt*k2[1]]) ) + k4 = rhs(t+dt, numpy.array([YA+dt*k3[0], YB+dt*k3[1]]) ) + + YA += (dt/6.0)*(k1[0] + 2.0*k2[0] + 2.0*k3[0] + k4[0]) + YB += (dt/6.0)*(k1[1] + 2.0*k2[1] + 2.0*k3[1] + k4[1]) + + t += dt + + tout.append(t) + yaout.append(YA) + ybout.append(YB) + + return numpy.array(tout), numpy.array(yaout), numpy.array(ybout) + + + +def VODEIntegrate(YA_0, YB_0, dt, tmax): + """ integrate using the VODE method, don't take a step smaller than dt """ + + r = ode(rhs, jac).set_integrator("vode", method="bdf", + with_jacobian=True, + atol=1.e-16, rtol=1.e-13, + nsteps = 15000, order=5) #, min_step=dt) + + t = 0.0 + r.set_initial_value([YA_0, YB_0], t) + + tout = [t] + yaout = [YA_0] + ybout = [YB_0] + + while r.successful() and r.t < tmax: + r.integrate(r.t+dt) + + tout.append(r.t) + yaout.append(r.y[0]) + ybout.append(r.y[1]) + + return numpy.array(tout), numpy.array(yaout), numpy.array(ybout) + + +#-------------------------------------------------------------------------- +tref = 1.0/(alpha + beta) # characteristic timescale +yequil = alpha/beta # equilibrium YB/YA ratio + +# R-K works well with a timestep < tref. For dt > tref, it does horrible. +# Backward-Euler always remains stable. + +#-------------------------------------------------------------------------- +# first run, dt = 0.5 tref +dt = 0.5*tref +tmax = 100*tref + +t, YA, YB = integrate(1.0, 0.0, dt, tmax) +t2, YA2, YB2 = trapIntegrate(1.0, 0.0, dt, tmax) +trk, YArk, YBrk = RK4Integrate(1.0, 0.0, dt, tmax) + +pylab.scatter(t/tref, YB/YA/yequil, + marker="x", s=25, color="b", label="backward-Euler") + +pylab.scatter(t2/tref, YB2/YA2/yequil, + marker="o", color="g", label="implicit trapezoid") + +pylab.scatter(trk/tref, YBrk/YArk/yequil, + marker="*", color="r", label="explicit R-K 4") + + +pylab.plot(t/tref, (numpy.exp( (alpha+beta)*t) - 1.0)/ \ + ( (beta/alpha)*numpy.exp( (alpha+beta)*t) + 1.0)/yequil, + ls="-", color="k", label="analytic") + +pylab.legend(loc=2, frameon=False, fontsize="x-small") + + +pylab.xlim(0.0, tmax/tref) + +pylab.xlabel(r"$t \cdot (\alpha + \beta)$") +pylab.ylabel(r"$(Y_B/Y_A) / (\alpha/\beta)$") +pylab.title(r"$\Delta t = 0.5 / (\alpha + \beta)$") + +ax = pylab.gca() +ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) +ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) + +pylab.savefig("stiff-linear-dt0.5tref.png") + + + +#-------------------------------------------------------------------------- +# first run, dt = 5 tref +pylab.clf() +dt = 5*tref +tmax = 500*tref + +t, YA, YB = integrate(1.0, 0.0, dt, tmax) +t2, YA2, YB2 = trapIntegrate(1.0, 0.0, dt, tmax) +trk, YArk, YBrk = RK4Integrate(1.0, 0.0, dt, tmax) + +tvode, YAvode, YBvode = VODEIntegrate(1.0, 0.0, dt, tmax) + + +pylab.scatter(t/tref, YB/YA/yequil, + marker="x", s=25, color="b", label="backward-Euler") + +pylab.scatter(t2/tref, YB2/YA2/yequil, + marker="o", color="g", label="implicit trapezoid") + +pylab.scatter(trk/tref, YBrk/YArk/yequil, + marker="*", color="r", label="explicit R-K 4") + +pylab.plot(t/tref, (numpy.exp( (alpha+beta)*t) - 1.0)/ \ + ( (beta/alpha)*numpy.exp( (alpha+beta)*t) + 1.0)/yequil, + ls="-", color="k", label="analytic") + +pylab.legend(loc=2, frameon=False, fontsize="x-small") + + +pylab.xlim(0.0, tmax/tref) + +pylab.xlabel(r"$t \cdot (\alpha + \beta)$") +pylab.ylabel(r"$(Y_B/Y_A) / (\alpha/\beta)$") +pylab.title(r"$\Delta t = 5 / (\alpha + \beta)$") + +ax = pylab.gca() +ax.xaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) +ax.yaxis.set_major_formatter(pylab.ScalarFormatter(useMathText=True)) + +pylab.savefig("stiff-linear-dt5tref.png") + + +pylab.scatter(tvode/tref, YBvode/YAvode/yequil, + marker="d", color="c", label="VODE (implicit B-D)") + +pylab.legend(loc=2, frameon=False, fontsize="x-small") + +pylab.savefig("stiff-linear-dt5tref-VODE.png") diff --git a/code/train/Python/0094394_gce_cluster_resolver.py b/code/train/Python/0094394_gce_cluster_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..305c53870de3f6f630e7285b6becd0dd0fcf6621 --- /dev/null +++ b/code/train/Python/0094394_gce_cluster_resolver.py @@ -0,0 +1,199 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implementation of Cluster Resolvers for GCE Instance Groups.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import ClusterResolver +from tensorflow.python.training.server_lib import ClusterSpec + +_GOOGLE_API_CLIENT_INSTALLED = True +try: + from googleapiclient import discovery # pylint: disable=g-import-not-at-top + from oauth2client.client import GoogleCredentials # pylint: disable=g-import-not-at-top +except ImportError: + _GOOGLE_API_CLIENT_INSTALLED = False + + +def _format_master_url(master, rpc_layer=None): + return '%s://%s' % (rpc_layer, master) if rpc_layer else master + + +class GceClusterResolver(ClusterResolver): + """Cluster Resolver for Google Compute Engine. + + This is an implementation of cluster resolvers for the Google Compute Engine + instance group platform. By specifying a project, zone, and instance group, + this will retrieve the IP address of all the instances within the instance + group and return a Cluster Resolver object suitable for use for distributed + TensorFlow. + """ + + def __init__(self, + project, + zone, + instance_group, + port, + task_type='worker', + task_id=0, + rpc_layer='grpc', + credentials='default', + service=None): + """Creates a new GceClusterResolver object. + + This takes in a few parameters and creates a GceClusterResolver project. It + will then use these parameters to query the GCE API for the IP addresses of + each instance in the instance group. + + Args: + project: Name of the GCE project. + zone: Zone of the GCE instance group. + instance_group: Name of the GCE instance group. + port: Port of the listening TensorFlow server (default: 8470) + task_type: Name of the TensorFlow job this GCE instance group of VM + instances belong to. + task_id: The task index for this particular VM, within the GCE + instance group. In particular, every single instance should be assigned + a unique ordinal index within an instance group manually so that they + can be distinguished from each other. + rpc_layer: The RPC layer TensorFlow should use to communicate across + instances. + credentials: GCE Credentials. If nothing is specified, this defaults to + GoogleCredentials.get_application_default(). + service: The GCE API object returned by the googleapiclient.discovery + function. (Default: discovery.build('compute', 'v1')). If you specify a + custom service object, then the credentials parameter will be ignored. + + Raises: + ImportError: If the googleapiclient is not installed. + """ + self._project = project + self._zone = zone + self._instance_group = instance_group + self._task_type = task_type + self._task_id = task_id + self._rpc_layer = rpc_layer + self._port = port + self._credentials = credentials + + if credentials == 'default': + if _GOOGLE_API_CLIENT_INSTALLED: + self._credentials = GoogleCredentials.get_application_default() + + if service is None: + if not _GOOGLE_API_CLIENT_INSTALLED: + raise ImportError('googleapiclient must be installed before using the ' + 'GCE cluster resolver') + self._service = discovery.build( + 'compute', 'v1', + credentials=self._credentials) + else: + self._service = service + + def cluster_spec(self): + """Returns a ClusterSpec object based on the latest instance group info. + + This returns a ClusterSpec object for use based on information from the + specified instance group. We will retrieve the information from the GCE APIs + every time this method is called. + + Returns: + A ClusterSpec containing host information retrieved from GCE. + """ + request_body = {'instanceState': 'RUNNING'} + request = self._service.instanceGroups().listInstances( + project=self._project, + zone=self._zone, + instanceGroups=self._instance_group, + body=request_body, + orderBy='name') + + worker_list = [] + + while request is not None: + response = request.execute() + + items = response['items'] + for instance in items: + instance_name = instance['instance'].split('/')[-1] + + instance_request = self._service.instances().get( + project=self._project, + zone=self._zone, + instance=instance_name) + + if instance_request is not None: + instance_details = instance_request.execute() + ip_address = instance_details['networkInterfaces'][0]['networkIP'] + instance_url = '%s:%s' % (ip_address, self._port) + worker_list.append(instance_url) + + request = self._service.instanceGroups().listInstances_next( + previous_request=request, + previous_response=response) + + worker_list.sort() + return ClusterSpec({self._task_type: worker_list}) + + def master(self, task_type=None, task_id=None, rpc_layer=None): + task_type = task_type if task_type is not None else self._task_type + task_id = task_id if task_id is not None else self._task_id + + if task_type is not None and task_id is not None: + master = self.cluster_spec().task_address(task_type, task_id) + if rpc_layer or self._rpc_layer: + return '%s://%s' % (rpc_layer or self._rpc_layer, master) + else: + return master + + return '' + + @property + def task_type(self): + return self._task_type + + @property + def task_id(self): + return self._task_id + + @task_type.setter + def task_type(self, task_type): + raise RuntimeError( + 'You cannot reset the task_type of the GceClusterResolver after it has ' + 'been created.') + + @task_id.setter + def task_id(self, task_id): + self._task_id = task_id + + @property + def environment(self): + """Returns the current environment which TensorFlow is running in. + + For users in the GCE environment, the environment property is always an + empty string, and Google users will not use this ClusterResolver for running + on internal systems. + """ + return '' + + @property + def rpc_layer(self): + return self._rpc_layer + + @rpc_layer.setter + def rpc_layer(self, rpc_layer): + self._rpc_layer = rpc_layer diff --git a/code/train/Python/0094434_application.py b/code/train/Python/0094434_application.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec8689900ba0891c3128da44ce2badcc4fec271 --- /dev/null +++ b/code/train/Python/0094434_application.py @@ -0,0 +1,231 @@ +#!/usr/bin/python +# =========================================================================== +# eXe +# Copyright 2004-2006, University of Auckland +# Copyright 2004-2008 eXe Project, http://eXeLearning.org/ +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# =========================================================================== + +""" +Main application class, pulls together everything and runs it. +""" + +import os +import sys +import shutil + +from tempfile import mkdtemp +# Make it so we can import our own nevow and twisted etc. +if os.name == 'posix' and not ('--standalone' in sys.argv or '--portable' in sys.argv): + sys.path.insert(0, '/usr/share/exe') +from getopt import getopt, GetoptError +from exe.webui.webserver import WebServer +from exe.webui.browser import launchBrowser +from exe.engine.idevicestore import IdeviceStore +from exe.engine.translate import installSafeTranslate +from exe.engine.package import Package +from exe.engine import version +from exe import globals +import logging +from twisted.internet import reactor + +log = logging.getLogger(__name__) + +class Windows_Log(object): + """ + Logging for py2exe application + """ + def __init__(self, level): + self.level = level + def write(self, text): + log.log(self.level, text) +if sys.platform[:3] == "win" and not (sys.argv[0].endswith("exe_do") or \ + sys.argv[0].endswith("exe_do.exe")): + # put stderr and stdout into the log file + sys.stdout = Windows_Log(logging.INFO) + sys.stderr = Windows_Log(logging.ERROR) +del Windows_Log + +# Global application variable +globals.application = None + +class Application: + """ + Main application class, pulls together everything and runs it. + """ + + def __init__(self): + """ + Initialize + """ + self.config = None + self.ideviceStore = None + self.packagePath = None + self.webServer = None + self.standalone = False # Used for the ready to run exe + self.portable = False # FM: portable mode + self.persistNonPersistants = False + self.tempWebDir = mkdtemp('.eXe') + self.resourceDir=None + self.afterUpgradeHandlers = [] + self.preferencesShowed = False + self.loadErrors = [] + assert globals.application is None, "You tried to instantiate two Application objects" + globals.application = self + + def main(self): + """ + Main function, starts eXe + """ + self.processArgs() + self.loadConfiguration() + installSafeTranslate() + self.preLaunch() + # preLaunch() has called find_port() to set config.port (the IP port #) + if self.config.port >= 0: + reactor.callWhenRunning(self.launch) + log.info('serving') + self.serve() + log.info('done serving') + else: + #self.xulMessage(_('eXe appears to already be running')) + log.error('eXe appears to already be running') + log.error('looks like the eXe server was not able to find a valid port; terminating...') + shutil.rmtree(self.tempWebDir, True) + + def processArgs(self): + """ + Processes the command line arguments + """ + try: + options, packages = getopt(sys.argv[1:], + "hV", ["help", "version", "standalone","portable"]) + except GetoptError: + self.usage() + sys.exit(2) + + if len(packages) == 1: + self.packagePath = packages[0] + + elif len(packages) > 1: + self.usage() + sys.exit(2) + + for option in options: + if option[0] in ("-V", "--version"): + print "eXe", version.version + sys.exit() + elif option[0] in ("-h", "--help"): + self.usage() + sys.exit() + elif option[0].lower() == '--standalone': + self.standalone = True + elif option[0].lower() == '--portable': + self.standalone = True + self.portable = True + + + def loadConfiguration(self): + """ + Loads the config file and applies all the settings + """ + if self.standalone: + from exe.engine.standaloneconfig import StandaloneConfig + configKlass = StandaloneConfig + elif sys.platform[:3] == "win": + from exe.engine.winconfig import WinConfig + configKlass = WinConfig + elif sys.platform[:6] == "darwin": + from exe.engine.macconfig import MacConfig + configKlass = MacConfig + else: + from exe.engine.linuxconfig import LinuxConfig + configKlass = LinuxConfig + try: + self.config = configKlass() + except: + configPath = configKlass.getConfigPath() + backup = configPath + '.backup' + configPath.move(backup) + self.config = configKlass() + self.loadErrors.append( + _(u'An error has occurred when loading your config. A backup is saved at %s') % backup) + log.debug("logging set up") + + def preLaunch(self): + """ + Sets ourself up for running + Needed for unit tests + """ + log.debug("preLaunch") + self.ideviceStore = IdeviceStore(self.config) + try: + self.ideviceStore.load() + except: + backup = self.config.configDir / 'idevices.backup' + if backup.exists(): + backup.rmtree() + (self.config.configDir / 'idevices').move(backup) + self.loadErrors.append( + _(u'An error has occurred when loading your Idevice Store. A backup is saved at %s') % backup) + self.ideviceStore.load() + # Make it so jelly can load objects from ~/.exe/idevices + sys.path.append(self.config.configDir/'idevices') + self.webServer = WebServer(self, self.packagePath) + # and determine the web server's port before launching the client, so it can use the same port#: + self.webServer.find_port() + + + def serve(self): + """ + Starts the web server, + this func doesn't return until after the app has finished + """ + print "Welcome to eXe: the eLearning XHTML editor" + log.info("eXe running...") + self.webServer.run() + + def launch(self): + """ + launches the webbrowser + """ + + if self.packagePath: + try: + package = Package.load(self.packagePath) + self.webServer.root.package = package + launchBrowser(self.config, package.name) + except: + self.webServer.root.packagePath = None + launchBrowser(self.config, "") + else: + launchBrowser(self.config, "") + + def usage(self): + """ + Print usage info + """ + self.loadConfiguration() + print _("""Usage: %s [OPTION] [PACKAGE] + -V, --version print version information and exit + -h, --help display this help and exit + --standalone Run totally from current directory + --portable Run in portable mode +Settings are read from exe.conf in $HOME/.exe on Linux/Unix/Mac OS or +in Documents and Settings//Application Data/exe on Windows XP or +Users//AppData/Roaming/exe on Windows 7""") % os.path.basename(sys.argv[0]) + +# =========================================================================== diff --git a/code/train/Python/0094499_MDPObjectLocalizerTask.py b/code/train/Python/0094499_MDPObjectLocalizerTask.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2128ed33efdc5446c96c9ba210e6e7ed0f521a --- /dev/null +++ b/code/train/Python/0094499_MDPObjectLocalizerTask.py @@ -0,0 +1,78 @@ +__author__ = "Juan C. Caicedo, caicedo@illinois.edu" + +from pybrain.rl.environments import Task + +import utils as cu +import libDetection as det + +class MDPObjectLocalizerTask(Task): + + minAcceptableIoU = 0.7 + maxRejectableIoU = 0.2 + + def __init__(self, environment, groundTruthFile): + Task.__init__(self, environment) + self.groundTruth = cu.loadBoxIndexFile(groundTruthFile) + + def getReward(self): + img, state = self.env.getSensors() + gt = self.getGroundTruth(img) + rewards = [] + for s in state: + r = self.computeReward(gt, s) + rewards.append(r) + self.env.updatePostReward() + #actions = [x.lastAction for x in state] + #print 'MDPObjectLocalizerTask::getReward(',img, actions, rewards,')' + return rewards + + def computeReward(self, gt, sensor): + if sensor.lastAction > 1: + # Localizing object with current image-box + maxIoU_0, idx_0 = self.matchBoxes(sensor.currBox, gt) + maxIoU_1, idx_1 = self.matchBoxes(sensor.nextBox, gt) + #if idx_0 != idx_1: print 'Focused object has changed' + if maxIoU_1 >= 0 and maxIoU_0 >= 0: + diff = maxIoU_1 - maxIoU_0 + if diff > 0: + return 1.0 + else: + return -1.0 + else: + return -1.0 + elif sensor.lastAction == 0: + # Current image-box pair has been accepted + maxIoU, idx = self.matchBoxes(sensor.currBox, gt) + if maxIoU >= self.minAcceptableIoU: + return 1.0 #5.0 + else: + return -1.0 #-5.0 + else: + # Current image-box pair has been rejected + maxIoU, idx = self.matchBoxes(sensor.currBox, gt) + if maxIoU <= self.maxRejectableIoU: + return 1.0 #3.0 + else: + return -1.0 #-3.0 + + def performAction(self, action): + #print 'MDPObjectLocalizerTask::performAction(',action,')' + Task.performAction(self, action) + + def getGroundTruth(self, imageName): + try: + gt = self.groundTruth[imageName] + except: + gt = [] + return gt + + def matchBoxes(self, box, gt): + maxIoU = -1. + maxIdx = 0 + for i in range(len(gt)): + iou = det.IoU(box, gt[i]) + if iou > maxIoU: + maxIoU = iou + maxIdx = i + return (maxIoU, maxIdx) + diff --git a/code/train/Python/0095011_test_config_constraints.py b/code/train/Python/0095011_test_config_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..ea68a67a9dddd01b634b510dfe0ed659f621cf27 --- /dev/null +++ b/code/train/Python/0095011_test_config_constraints.py @@ -0,0 +1,36 @@ +import unittest + +from config_constraints import Constraints + + +class ConfigEditorTestCase(unittest.TestCase): + def test_censor_keep_nothing_by_default(self): + constraints = Constraints() + config = {'Foo': None, 'Bar': None} + + censored = list(constraints.censor(config=config).keys()) + + self.assertListEqual(censored, []) + + def test_censor_keep_only_given_key(self): + constraints = Constraints() + only = ['Allowed', 'Uncensored'] + config = { + 'Allowed': None, + 'Uncensored': None, + 'Unauthorized': 'Dangerous' + } + + censored = list(constraints.censor(config=config, keep=only).keys()) + censored.sort() + + self.assertListEqual(censored, ['Allowed', 'Uncensored']) + + def test_censor_empty_dict_stay_empty(self): + constraints = Constraints() + only = ['Allowed'] + config = {} + + censored = list(constraints.censor(config=config, keep=only).keys()) + + self.assertListEqual(censored, []) diff --git a/code/train/Python/0095184_solr_fetcher.py b/code/train/Python/0095184_solr_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..cb037086e76c20872acfb67b53f0b5c050caeb64 --- /dev/null +++ b/code/train/Python/0095184_solr_fetcher.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +import solr +import pysolr +from .fetcher import Fetcher +import urlparse +import requests + + +class SolrFetcher(Fetcher): + def __init__(self, url_harvest, query, **query_params): + super(SolrFetcher, self).__init__(url_harvest, query) + self.solr = solr.Solr(url_harvest) # , debug=True) + self.query = query + self.resp = self.solr.select(self.query) + self.numFound = self.resp.numFound + self.index = 0 + + def next(self): + if self.index < len(self.resp.results): + self.index += 1 + return self.resp.results[self.index - 1] + self.index = 1 + self.resp = self.resp.next_batch() + if not len(self.resp.results): + raise StopIteration + return self.resp.results[self.index - 1] + + +class PySolrFetcher(Fetcher): + def __init__(self, + url_harvest, + query, + handler_path='select', + **query_params): + super(PySolrFetcher, self).__init__(url_harvest, query, **query_params) + self.solr = pysolr.Solr(url_harvest, timeout=1) + self._handler_path = handler_path + self._query_params = { + 'q': query, + 'wt': 'json', + 'sort': 'id asc', + 'rows': 100, + 'cursorMark': '*' + } + self._query_params.update(query_params) + self._nextCursorMark = '*' + self.get_next_results() + self.numFound = self.results['response'].get('numFound') + self.index = 0 + + @property + def _query_path(self): + self._query_params_encoded = pysolr.safe_urlencode(self._query_params) + return '{}?{}'.format(self._handler_path, self._query_params_encoded) + + def get_next_results(self): + self._query_params['cursorMark'] = self._nextCursorMark + resp = self.solr._send_request('get', path=self._query_path) + self.results = self.solr.decoder.decode(resp) + self._nextCursorMark = self.results.get('nextCursorMark') + self.iter = self.results['response']['docs'].__iter__() + + def next(self): + try: + next_result = self.iter.next() + self.index += 1 + return next_result + except StopIteration: + if self.index >= self.numFound: + raise StopIteration + self.get_next_results() + if self._nextCursorMark == self._query_params['cursorMark']: + if self.index >= self.numFound: + raise StopIteration + if len(self.results['response']['docs']) == 0: + raise StopIteration + self.index += 1 + return self.iter.next() + + +class PySolrQueryFetcher(PySolrFetcher): + ''' Use the `select` url path for querying instead of 'query'. This is + more typical for most Solr applications. + ''' + + def __init__(self, url_harvest, query, **query_params): + super(PySolrQueryFetcher, self).__init__( + url_harvest, query, handler_path='query', **query_params) + + +class RequestsSolrFetcher(Fetcher): + '''A fetcher for solr that uses just the requests library + The URL is the URL up to the "select" bit (may change in future) + Extra_data is one of 2 formats: + just a string -- it is the "q" string + URL encoded query string -> + q=&header=:&header=: + The auth parameter will be parsed to figure out type of authentication + needed, right now just deal with "header" token authentication + ''' + + def __init__(self, url_harvest, extra_data, **kwargs): + super(RequestsSolrFetcher, self).__init__(url_harvest, extra_data, + **kwargs) + # will need to change URLs for existing to add /select in general + # the bampfa has NO /select or /query + self._query_iter_template = \ + '?rows={rows}&cursorMark={cursorMark}' + self._query_params = urlparse.parse_qs(extra_data) + if not self._query_params: # Old style, just "q" bit of query + self._query_params = {'q': [extra_data]} + self._page_size = 1000 + self._cursorMark = None + self._nextCursorMark = '*' + self._headers = {} + for name, value in self._query_params.items(): + if name == 'header': + for value in self._query_params[name]: # its a list + header_name, header_value = value.split(':', 1) + self._headers[header_name] = header_value + del self._query_params[name] + if 'wt' not in self._query_params: + self._query_params.update({'wt': ['json']}) + if 'sort' not in self._query_params: + self._query_params.update({'sort': ['id asc']}) + + @property + def end_of_feed(self): + return self._cursorMark == self._nextCursorMark + + @property + def url_request(self): + # build current URL + url_request = ''.join(( + self.url, + self._query_iter_template.format( + rows=self._page_size, cursorMark=self._cursorMark), )) + # join 'q' and all other params + for name, value in self._query_params.items(): + url_request = ''.join((url_request, '&', name, '=', value[0])) + return url_request + + def get_response(self): + '''Get the correct response for the given combo of params''' + return requests.get(self.url_request, headers=self._headers) + + def next(self): + '''get the next page of solr data, using the cursor mark to build + URL + ''' + if (self.end_of_feed): + raise StopIteration + # get resp + self._cursorMark = self._nextCursorMark + resp = self.get_response() + resp.raise_for_status() + resp_obj = resp.json() + self._nextCursorMark = resp_obj['nextCursorMark'] + return resp_obj['response']['docs'] + + +# Copyright © 2017, Regents of the University of California +# All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# - Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# - Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# - Neither the name of the University of California nor the names of its +# contributors may be used to endorse or promote products derived from this +# software without specific prior written permission. +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. diff --git a/code/train/Python/0095250_grid_product.py b/code/train/Python/0095250_grid_product.py new file mode 100644 index 0000000000000000000000000000000000000000..1eae54e57c8b438b0c62600802c0b841f1d07350 --- /dev/null +++ b/code/train/Python/0095250_grid_product.py @@ -0,0 +1,57 @@ +import operator + +from common.matrix import Matrix + + +def _calc_row_product(numbers, start_idx, end_idx_excl): + return reduce(operator.mul, numbers[start_idx:end_idx_excl], 1) + + +def _calculate_max_product_for_vector(vector, length): + max_val = -1 + for j in xrange(len(vector) - length + 1): + product = _calc_row_product(vector, j, j + length) + max_val = max(product, max_val) + return max_val + + +def _create_downwards_diagonal(matrix, startrow, startcol): + indices = zip(range(startrow, matrix.num_rows()), range(startcol, matrix.num_columns())) + return [matrix[x[0]][x[1]] for x in indices] + + +def _calculate_max_row_product(length, matrix): + max_val = -1 + for i in xrange(matrix.num_rows()): + max_val_for_column = _calculate_max_product_for_vector(matrix[i], length) + max_val = max(max_val, max_val_for_column) + return max_val + + +def _calculate_max_downward_diagonal(length, matrix): + max_val = -1 + for i in xrange(matrix.num_rows()): + max_val_for_downwards_diagonal = _calculate_max_product_for_vector(_create_downwards_diagonal(matrix, i, 0), + length) + max_val = max(max_val, max_val_for_downwards_diagonal) + for i in xrange(matrix.num_columns()): + max_val_for_downwards_diagonal = _calculate_max_product_for_vector(_create_downwards_diagonal(matrix, 0, i), + length) + max_val = max(max_val, max_val_for_downwards_diagonal) + return max_val + + +def _flip_horizontally(matrix): + m = Matrix(matrix.num_rows(), matrix.num_columns()) + for i in xrange(m.num_rows()): + for j in xrange(m.num_columns()): + m[i][j] = matrix[m.num_rows() - i - 1][j] + return m + + +def largest_grid_product(matrix, length): + max_val = max(_calculate_max_row_product(length, matrix), + _calculate_max_row_product(length, matrix.transpose()), + _calculate_max_downward_diagonal(length, matrix), + _calculate_max_downward_diagonal(length, _flip_horizontally(matrix))) + return max_val \ No newline at end of file diff --git a/code/train/Python/0095440_subsetFichiers.py b/code/train/Python/0095440_subsetFichiers.py new file mode 100644 index 0000000000000000000000000000000000000000..31fdd517bea3844621df5f5a796acaf79509104d --- /dev/null +++ b/code/train/Python/0095440_subsetFichiers.py @@ -0,0 +1,95 @@ + +import argparse +import logging +import os +import os.path +import sys + + +#ENCODING="ISO-8859-15" +ENCODING="utf-8" + +EXTENSION=".txt" + + +""" +Point d'entree +""" +def main( args ): + + # Parsage des arguments + parser = argparse.ArgumentParser( description='Diff' ) + parser.add_argument( '-e', '--exclure', required=False, help='Pattern de fichiers a exclure' ) + parser.add_argument( '-n', '--nom', required=False, help='Nom du test' ) + parser.add_argument( '-d', '--dir', required=False, help='La reference' ) + parser.add_argument( '-s', '--subset', required=True, help='Le sous-ensemble' ) + arguments = parser.parse_args() + + # Fichier sortie + nomFichierDoublons = 'liste.doublons.' + arguments.nom + EXTENSION if arguments.nom else 'liste.doublons' + EXTENSION + nomFichierUniques = 'liste.uniques.' + arguments.nom + EXTENSION if arguments.nom else 'liste.uniques' + EXTENSION + + nbArgs = len( args ) - 1 + + # Dossier de travail + dossierRacine = arguments.dir if arguments.dir else os.getcwd() + dossierSubset = arguments.subset if arguments.subset else None + + # Ensembles + setRacine = set() + # setSubset = set() + setDoublons = set() + setUniques = set() + + # Parcours arborescence reference + for dirpath, dirnames, filenames in os.walk( dossierRacine ): + for filename in filenames: + if not( arguments.exclure and( arguments.exclure in filename or arguments.exclure in dirpath )): + setRacine.add( filename ) + + # Parcours sous-ensemble + for dirpath, dirnames, filenames in os.walk( dossierSubset ): + for filename in filenames: + if not( arguments.exclure and( arguments.exclure in filename or arguments.exclure in dirpath )): + if filename in setRacine: + setDoublons.add( filename ) + else: + setUniques.add( filename + '\t;\t' + dirpath + os.sep + filename ) + + listeDoublons = list() + listeUniques = list( setUniques ) + + # Parcours arborescence reference + for dirpath, dirnames, filenames in os.walk( dossierRacine ): + for filename in filenames: + if filename in setDoublons: + listeDoublons.append( filename + '\t;\t' + dirpath + os.sep + filename ) + + listeDoublons.sort() + listeUniques.sort() + + # Fichiers presents simultanement dans le sous-ensemble et dans la reference + with open( nomFichierDoublons, mode='w', encoding=ENCODING ) as fichierDoublons: + message = "%d fichiers presents dans les deux dossiers"%( len( listeDoublons )) + print( message ) + fichierDoublons.write( "%s\n"%message ) + + for filename in listeDoublons: + fichierDoublons.write( "%s\n" % filename ) + + # Fichiers du sous-ensemble absents de la reference + with open( nomFichierUniques, mode='w', encoding=ENCODING ) as fichierUniques: + message = "%d fichiers uniquement dans le sous-ensemble %s"%( len( listeUniques ), dossierSubset ) + print( message ) + fichierUniques.write( "%s\n"%message ) + + for filename in listeUniques: + fichierUniques.write( "%s\n" % filename ) + + print( "Resultats ecrits" ) + + +# Execute la fonction main, seulement si le script est appele directement, et non pas depuis un autre script +if( __name__ == "__main__" ): + main( sys.argv ) + diff --git a/code/train/Python/0095506_nurbs.py b/code/train/Python/0095506_nurbs.py new file mode 100644 index 0000000000000000000000000000000000000000..9a4ac6cc3ffea223d72683e2f5f0c58ea0162881 --- /dev/null +++ b/code/train/Python/0095506_nurbs.py @@ -0,0 +1,111 @@ +from math import * + +from bspline import BSplineClass +from elements import PointClass +from geometry import Zero + + +""" +Begin Excerpts from dxf2gcode_b02_nurbs_calc +""" + + +class NURBSClass(object): + + def __init__(self, degree=0, Knots=[], Weights=None, CPoints=None): + self.degree = degree # Spline degree + self.Knots = Knots # Knot Vector + self.CPoints = CPoints # Control points of splines [2D] + self.Weights = Weights # Weighting of the individual points + + # Initializing calculated variables + self.HCPts = [] # Homogeneous points vectors [3D] + + # Convert Points in Homogeneous points + self.CPts_2_HCPts() + + # Creating the BSplineClass to calculate the homogeneous points + self.BSpline = BSplineClass(degree=self.degree, + Knots=self.Knots, + CPts=self.HCPts) + + # Calculate a number of evenly distributed points + def calc_curve_old(self, n=0, cpts_nr=20): + # Initial values for step and u + u = 0 + Points = [] + + step = self.Knots[-1] / (cpts_nr - 1) + while u <= self.Knots[-1]: + Pt = self.NURBS_evaluate(n=n, u=u) + Points.append(Pt) + u += step + return Points + + # Calculate a number points using error limiting + def calc_curve(self, n=0, tol_deg=20): + # Initial values for step and u + u = 0 + Points = [] + + tol = radians(tol_deg) + i = 1 + while self.Knots[i] == 0: + i = i + 1 + step = self.Knots[i] / 3 + + Pt1 = self.NURBS_evaluate(n=n, u=0.0) + Points.append(Pt1) + while u < self.Knots[-1]: + if (u + step > self.Knots[-1]): + step = self.Knots[-1] - u + + Pt2 = self.NURBS_evaluate(n=n, u=u + step) + Pt_test = self.NURBS_evaluate(n=n, u=u + step / 2) + + dx1 = (Pt_test.x - Pt1.x) + dy1 = (Pt_test.y - Pt1.y) + L1 = sqrt(dx1 * dx1 + dy1 * dy1) + + dx2 = (Pt2.x - Pt_test.x) + dy2 = (Pt2.y - Pt_test.y) + L2 = sqrt(dx2 * dx2 + dy2 * dy2) + + if L1 > Zero and L2 > Zero: + cos_angle = dx1 / L1 * dx2 / L2 + dy1 / L1 * dy2 / L2 + if abs(cos_angle) > 1: + cos_angle = int(cos_angle) + angle = acos(cos_angle) + else: + angle = 0.0 + + if angle > tol: + step = step / 2 + else: + u += step + Points.append(Pt2) + step = step * 2 + Pt1 = Pt2 + return Points + + # Calculate a point of NURBS + def NURBS_evaluate(self, n=0, u=0): + + # Calculate the homogeneous points to the n th derivative + HPt = self.BSpline.bspline_ders_evaluate(n=n, u=u) + + # Point back to normal coordinates transform + Point = self.HPt_2_Pt(HPt[0]) + return Point + + # Convert the NURBS control points and weight in a homogeneous vector + def CPts_2_HCPts(self): + for P_nr in range(len(self.CPoints)): + HCPtVec = [self.CPoints[P_nr].x * self.Weights[P_nr], + self.CPoints[P_nr].y * self.Weights[P_nr], + self.Weights[P_nr]] + self.HCPts.append(HCPtVec[:]) + + # Convert a homogeneous vector point in a point + def HPt_2_Pt(self, HPt): + return PointClass(x=HPt[0] / HPt[-1], y=HPt[1] / HPt[-1]) diff --git a/code/train/Python/0095940_amplitude_histogram.py b/code/train/Python/0095940_amplitude_histogram.py new file mode 100644 index 0000000000000000000000000000000000000000..4aaf0e749677be0d9edc22ebbb389889be61fac4 --- /dev/null +++ b/code/train/Python/0095940_amplitude_histogram.py @@ -0,0 +1,269 @@ + +from bokeh.plotting import figure, show, output_file, vplot +from bokeh import palettes +from bokeh.layouts import column,gridplot +from bokeh.models import ranges +from marsyas_util import create, control2array +import numpy as np +import scipy +import json +import os +import math +import sys +from sklearn import svm +from sklearn.model_selection import cross_val_score, cross_val_predict +from sklearn.ensemble import RandomForestClassifier +from sklearn.dummy import DummyClassifier +from sklearn.neural_network import MLPClassifier + + +from sklearn import preprocessing +from sklearn import metrics +import csv + + + +def histo_plot(mydata, wav_fname): + # prepare some data + y0 = mydata[0,:] + + # only plot histogram + y0 = y0[0:len(y0)/2] + x = np.array(range(0, len(y0))) + + sum1 = 0.0; + sum2 = 0.0 + + for i in range(0, len(y0)/2-4): + sum1 = sum1 + y0[i]; + + for i in range(len(y0)/2+4,len(y0)-1): + sum2 = sum2 + y0[i]; + # print(sum1/sum2) + + # output to static HTML file + # create a new plot with a title and axis labels + p = figure(title=wav_fname, x_axis_label=None, y_axis_label=None, + plot_height=150, plot_width=400, toolbar_location=None, + x_range = (150,350)) + + # add a line renderer with legend and line thickness + p.line(x,y0, legend=str(sum1/sum2) ) + return (p,sum1/sum2,mydata[0,:]) + + + +# process collection of wav_fnames using amplitude_histograms as +# features + +def process_collection(wav_fnames): + spec = ["Series/plot", + ["SoundFileSource/src", + ["Fanout/fan", + [ + ["Series/hist", + [ + "Histogram/histo", + "Transposer/trsp", + "TextureStats/tstats1" + ]] + , + ["Series/dlt", + [ + "Spectrum/spk", + "PowerSpectrum/pspk", + "STFT_features", + "TextureStats/tstats2" + ]] + ]] + , + "Transposer/trs" + ]] + + winSize = 4096 + plot_net = create(spec) +# print(plot_net.toString()) + ratios = [] + + inSamples = plot_net.getControl("mrs_natural/inSamples") + inSamples.setValue_natural(winSize) + fname = plot_net.getControl("SoundFileSource/src/mrs_string/filename") + normalize = plot_net.getControl("Fanout/fan/Series/hist/Histogram/histo/mrs_bool/normalize") + # deltaStd = plot_net.getControl("Fanout/fan/Series/hist/Histogram/histo/mrs_real/deltaStd") + memSize1 = plot_net.getControl("Fanout/fan/Series/hist/TextureStats/tstats1/mrs_natural/memSize") + memSize2 = plot_net.getControl("Fanout/fan/Series/dlt/TextureStats/tstats2/mrs_natural/memSize") +# normalize1 = plot_net.getControl("Fanout/fan/Series/dlt/Histogram/histo1/mrs_bool/normalize") + + + memSize1.setValue_natural(50); + memSize2.setValue_natural(50); + reset = plot_net.getControl("Fanout/fan/Series/hist/Histogram/histo/mrs_bool/reset") +# reset1 = plot_net.getControl("Fanout/fan/Series/dlt/Histogram/histo1/mrs_bool/reset") + figs = [] + ratio = 0.0 + avg_ratio = 0.0 + num_glitch = 0 + numFiles = 0 + seconds2process = 15.0 + samples2process = seconds2process * 48000 + iterations2process = int(samples2process * 1.0 / winSize) + + + aggregate_deltas = [] + for wav_fname in wav_fnames: +# print(str(numFiles) + ' - ' + wav_fname); + fname.setValue_string(wav_fname) + reset.setValue_bool(True) +# reset1.setValue_bool(True) + nTicks = 0 + deltas = [] + for i in range(0, iterations2process): + # while plot_net.getControl("SoundFileSource/src/mrs_bool/hasData").to_bool(): + + plot_net.tick() + # print("DELTA", deltaStd.to_real()) + # deltas.append(deltaStd.to_real()) + nTicks = nTicks + 1 + normalize.setValue_bool(True) + # normalize1.setValue_bool(True) + # extra tick to normalize + plot_net.tick() + mydata = control2array(plot_net, "mrs_realvec/processedData") + (fig, ratio, histo) = histo_plot(mydata, wav_fname) + ratios.append(histo) + figs.append(fig) + numFiles = numFiles + 1; + avg_ratio = avg_ratio + abs(1.0-ratio) + #if (abs(1.0-ratio) > 0.2): + # num_glitch = num_glitch+1 + if (scipy.stats.kurtosis(deltas) < 2): + num_glitch = num_glitch+1 + + aggregate_deltas.append(scipy.stats.kurtosis(deltas)) + + + + avg_ratio = avg_ratio / numFiles + print("----------------------") + # print("AVERAGE AGGREGATE = ", np.mean(aggregate_deltas), np.std(aggregate_deltas)) + print(("AVERAGE RATIO=" , avg_ratio)) + print(("NUM GLITCH = ", num_glitch, numFiles)) + print(("GLITCH PERCENTAGE=", int(100 * (num_glitch * 1.0/len(wav_fnames))))) + +# print("AVG DELTA = ", np.mean(deltas)) +# print("STD DELTA = ", np.std(deltas)) +# show(gridplot(*figs, ncols=2)) + return (ratios, wav_fnames) + + +def get_wavs_from_folder(folder): + wav_fnames = [f for f in os.listdir(folder) if f.endswith(".wav")] + wav_fnames = [folder + s for s in wav_fnames] + return wav_fnames + +def main(): + + #playlist_folder = "/Users/georgetzanetakis/data/sound/nonglitch/" + #playlist_folder = "/Users/georgetzanetakis/data/sound/glitch/" + #playlist_folder = "/Users/georgetzanetakis/data/sound/normal/" + #playlist_folder = "/tmp/smule_songs1/" + #playlist_folder = "/Users/georgetzanetakis/data/sound/headphones/" + #playlist_folder = "/Users/georgetzanetakis/data/sound/2017/" + #playlist_folder = "/Users/georgetzanetakis/data/sound/2016/" + + positive_folder = sys.argv[1] + negative_folder = sys.argv[2] + test_folder = sys.argv[3] + + # process positives + output_file("positive_histograms.html") + wav_fnames = get_wavs_from_folder(positive_folder) + (pos_ratios, pos_names) = process_collection(wav_fnames) + pfeatures = np.asarray(pos_ratios) + ptruth = np.ones(len(pos_ratios)) + + # process negatives + output_file("negative_histograms.html") + wav_fnames = get_wavs_from_folder(negative_folder) + (neg_ratios, neg_names) = process_collection(wav_fnames); + nfeatures = np.asarray(neg_ratios) + ntruth = np.zeros(len(neg_ratios)) + + # create feature matrices for training classifiers + X = np.concatenate([pos_ratios, neg_ratios]) + print(X.shape) + y = np.concatenate([ptruth,ntruth]) + print(y.shape) + + # hack to get results in order of performances in spreadsheet + # csv_fname = "glitch_other.csv" + # with open(csv_fname, 'rb') as f: + # reader = csv.reader(f) + # i = 0 + # wav_fnames = [] + # for row in reader: + # wav_fnames.append(test_folder + row[0] + '.wav') + # print(wav_fnames) + + # load a test folder and compute the features + wav_fnames = get_wavs_from_folder(test_folder) + (test_ratios, test_names) = process_collection(wav_fnames) + + # scale test based on training set scale + Xtest = np.concatenate([test_ratios]) + min_max_scaler = preprocessing.MinMaxScaler() + X = min_max_scaler.fit_transform(X) + Xtest = min_max_scaler.transform(Xtest) + + clf = svm.SVC(kernel='linear', C=1) +# clf = svm.SVC(kernel='linear', C=0.025) +# clf = svm.SVC(gamma = 2, C=1) + clf.fit(X,y) + + scores = cross_val_score(clf, X, y, cv=30) + predicted = cross_val_predict(clf, X, y, cv=30) + cm = metrics.confusion_matrix(y, predicted) + cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] + print(cm) + print("SUPPORT VECTOR MACHINE") + print(scores) + print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2)) + + # rclf = RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1) + # rclf.fit(X,y) + # rscores = cross_val_score(rclf, X, y, cv=30) + # print("RANDOM FOREST") + # print(rscores) + # print("Accuracy: %0.2f (+/- %0.2f)" % (rscores.mean(), rscores.std() * 2)) + + + # mclf = MLPClassifier(alpha=1) + # mclf.fit(X,y) + # mscores = cross_val_score(rclf, X, y, cv=30) + # print("Multilayer Perceptron") + # print(mscores) + # print("Accuracy: %0.2f (+/- %0.2f)" % (mscores.mean(), mscores.std() * 2)) + + # dclf = DummyClassifier(strategy='most_frequent',random_state=0) + # dclf.fit(X,y) + # dscores = cross_val_score(dclf, X, y, cv=30) + # print("ZeroR") + # print(dscores) + # print("Accuracy: %0.2f (+/- %0.2f)" % (dscores.mean(), dscores.std() * 2)) + + # Run the trained classifier (SVM) to predict the test test + i = 0 + glitches = 0 + for prediction in clf.predict(Xtest): + print(str(prediction) + test_names[i]) + # print(prediction) + if (prediction == 1): + glitches = glitches + 1 + i = i + 1 + print("Accuracy for test set:" + test_folder) + print(glitches, i) + print("Accuracy: %0.2f" % (glitches * 1.0 / i * 100)) + +if __name__ == "__main__": + main() + diff --git a/code/train/Python/0096573_contextgenerator.py b/code/train/Python/0096573_contextgenerator.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8f20c4ea8a5767a2e0c548b24d1b3c5337906b --- /dev/null +++ b/code/train/Python/0096573_contextgenerator.py @@ -0,0 +1,115 @@ +import unicodehelper + + +INFINITY = float("inf") + + +class ContextGenerator: + """The context generator creates a line-by-line mapping of all files that + are validated. It will then use that to help produce useful bits of code + for errors, warnings, and the like.""" + + def __init__(self, data=None): + self.data = data.split("\n") + + def get_context(self, line=1, column=0): + """Return a tuple containing the context for a line.""" + + line -= 1 # The line is one-based + + # If there is no data in the file, there can be no context. + datalen = len(self.data) + if datalen <= line: + return None + + build = [self.data[line]] + + # Add surrounding lines if they're available. There must always be + # three elements in the context. + if line > 0: + build.insert(0, self.data[line - 1]) + else: + build.insert(0, None) + + if line < datalen - 1: + build.append(self.data[line + 1]) + else: + build.append(None) + + leading_counts = [] + + # Count whitespace to determine how much needs to be stripped. + lstrip_count = INFINITY + for line in build: + # Don't count empty/whitespace-only lines. + if line is None or not line.strip(): + leading_counts.append(lstrip_count) + continue + + # Isolate the leading whitespace. + ws_count = len(line) - len(line.lstrip()) + leading_counts.append(ws_count) + if ws_count < lstrip_count: + lstrip_count = ws_count + + # If all of the lines were skipped over, it means everything was + # whitespace. + if lstrip_count == INFINITY: + return ("", "", "") + + for lnum in range(3): + # Skip edge lines. + if not build[lnum]: + continue + + line = build[lnum].strip() + + # Empty lines stay empty. + if not line: + build[lnum] = "" + continue + + line = self._format_line(line, column=column, rel_line=lnum) + line = "%s%s" % (" " * (leading_counts[lnum] - lstrip_count), line) + + build[lnum] = line + + # Return the final output as a tuple. + return tuple(build) + + def _format_line(self, data, column=0, rel_line=1): + """Formats a line from the data to be the appropriate length.""" + line_length = len(data) + + if line_length > 140: + if rel_line == 0: + # Trim from the beginning + data = "... %s" % data[-140:] + elif rel_line == 1: + # Trim surrounding the error position + if column < 70: + data = "%s ..." % data[:140] + elif column > line_length - 70: + data = "... %s" % data[-140:] + else: + data = "... %s ..." % data[column - 70:column + 70] + + elif rel_line == 2: + # Trim from the end + data = "%s ..." % data[:140] + + return unicodehelper.decode(data) + + def get_line(self, position): + """Returns the line number that the given string position is found on.""" + + datalen = len(self.data) + count = len(self.data[0]) + line = 1 + while count < position: + if line >= datalen: + break + count += len(self.data[line]) + 1 + line += 1 + + return line diff --git a/code/train/Python/0096602_get_emrald.py b/code/train/Python/0096602_get_emrald.py new file mode 100644 index 0000000000000000000000000000000000000000..e36fe7700f0c257448669ee503e4ca899e2bdaa7 --- /dev/null +++ b/code/train/Python/0096602_get_emrald.py @@ -0,0 +1,39 @@ +import re +import random +import pickle + +import progressbar +import requests + +URL = "http://chess.emrald.net/psolution.php?Pos=" + + +def get_pos(i): + h = requests.get(URL + str(i)) + try: + xs = re.findall("text/javascript'>([^<]+)<", h.text) + except Exception as e: + print('Error %s (%d)' % (e, i)) + return + if len(xs) != 3: + print("%d len %d" % (i, len(xs))) + else: + return xs[0] + + +def get_all_pos(start, end): + bar = progressbar.ProgressBar() + nrs = list(range(start, end)) + random.shuffle(nrs) + rets = [] + for i in bar(nrs): + ret = get_pos(i) + if ret: + rets.append((i, ret)) + + try: + with open('emrald.p', 'wb') as outf: + pickle.dump(rets, outf) + except Exception as e: + print(e) + return rets diff --git a/code/train/Python/0096862_signin.py b/code/train/Python/0096862_signin.py new file mode 100644 index 0000000000000000000000000000000000000000..93989990afd51d6ac82743ab0e38314ca7b49a68 --- /dev/null +++ b/code/train/Python/0096862_signin.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, unicode_literals +import xbmcgui + +from . import kodigui +from .. import variables as v + + +class Background(kodigui.BaseWindow): + xmlFile = 'script-plex-signin_background.xml' + path = v.ADDON_PATH + theme = 'Main' + res = '1080i' + width = 1920 + height = 1080 + + +class SignInMessage(kodigui.BaseWindow): + xmlFile = 'script-plex-signin_blank.xml' + path = v.ADDON_PATH + theme = 'Main' + res = '1080i' + width = 1920 + height = 1080 + + SCREEN_BUTTON_ID = 100 + + def __init__(self, *args, **kwargs): + self.message = kwargs.get('message') + kodigui.BaseWindow.__init__(self, *args, **kwargs) + + def onFirstInit(self): + self.setProperty('message', self.message) + + def onClick(self, controlID): + if controlID == self.SCREEN_BUTTON_ID: + self.doClose() + + +class SignInPlexPass(kodigui.BaseWindow): + xmlFile = 'script-plex-plex_pass.xml' + path = v.ADDON_PATH + theme = 'Main' + res = '1080i' + width = 1920 + height = 1080 + + RETRY_BUTTON_ID = 100 + + def __init__(self, *args, **kwargs): + self.retry = False + kodigui.BaseWindow.__init__(self, *args, **kwargs) + + def onAction(self, action): + if action == xbmcgui.ACTION_SELECT_ITEM: + self.retry = True + self.doClose() + kodigui.BaseWindow.onAction(self, action) + + def onClick(self, controlID): + if controlID == self.RETRY_BUTTON_ID: + self.retry = True + self.doClose() + + +class PreSignInWindow(kodigui.BaseWindow): + xmlFile = 'script-plex-pre_signin.xml' + path = v.ADDON_PATH + theme = 'Main' + res = '1080i' + width = 1920 + height = 1080 + + SIGNIN_BUTTON_ID = 100 + + def __init__(self, *args, **kwargs): + self.doSignin = False + kodigui.BaseWindow.__init__(self, *args, **kwargs) + + def onFirstInit(self): + self.signinButton = self.getControl(self.SIGNIN_BUTTON_ID) + + def onAction(self, action): + if action == xbmcgui.ACTION_SELECT_ITEM: + self.doSignin = True + self.doClose() + kodigui.BaseWindow.onAction(self, action) + + def onClick(self, controlID): + if controlID == self.SIGNIN_BUTTON_ID: + self.doSignin = True + self.doClose() + + +class PinLoginWindow(kodigui.BaseWindow): + xmlFile = 'script-plex-pin_login.xml' + path = v.ADDON_PATH + theme = 'Main' + res = '1080i' + width = 1920 + height = 1080 + + def __init__(self, *args, **kwargs): + self.abort = False + kodigui.BaseWindow.__init__(self, *args, **kwargs) + + def setPin(self, pin): + self.setProperty('pin.image.0', 'plugin.video.plexkodiconnect/sign_in/digits/{0}.png'.format(pin[0].upper())) + self.setProperty('pin.image.1', 'plugin.video.plexkodiconnect/sign_in/digits/{0}.png'.format(pin[1].upper())) + self.setProperty('pin.image.2', 'plugin.video.plexkodiconnect/sign_in/digits/{0}.png'.format(pin[2].upper())) + self.setProperty('pin.image.3', 'plugin.video.plexkodiconnect/sign_in/digits/{0}.png'.format(pin[3].upper())) + + def setLinking(self): + self.setProperty('linking', '1') + self.setProperty('pin.image.0', '') + self.setProperty('pin.image.1', '') + self.setProperty('pin.image.2', '') + self.setProperty('pin.image.3', '') + + def onAction(self, action): + if action == xbmcgui.ACTION_NAV_BACK or action == xbmcgui.ACTION_PREVIOUS_MENU: + self.abort = True + kodigui.BaseWindow.onAction(self, action) + + +class ExpiredWindow(kodigui.BaseWindow): + xmlFile = 'script-plex-refresh_code.xml' + path = v.ADDON_PATH + theme = 'Main' + res = '1080i' + width = 1920 + height = 1080 + + REFRESH_BUTTON_ID = 100 + + def __init__(self, *args, **kwargs): + self.refresh = False + kodigui.BaseWindow.__init__(self, *args, **kwargs) + + def onFirstInit(self): + self.refreshButton = self.getControl(self.REFRESH_BUTTON_ID) + + def onClick(self, controlID): + if controlID == self.REFRESH_BUTTON_ID: + self.refresh = True + self.doClose() diff --git a/code/train/Python/0096988_bootstrap_admin_template_tags.py b/code/train/Python/0096988_bootstrap_admin_template_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..15d16b9a01afd6f45f795386bdac219813cf1a15 --- /dev/null +++ b/code/train/Python/0096988_bootstrap_admin_template_tags.py @@ -0,0 +1,190 @@ +from django.contrib.admin import site +from django.apps import apps +from django.utils.text import capfirst +from django.core.urlresolvers import reverse, NoReverseMatch +from django.core.exceptions import ImproperlyConfigured +from django.utils import six +from django.conf import settings +from django import template +from django import VERSION as DJANGO_VERSION + +# Depending on you python version, reduce has been moved to functools +try: + from functools import reduce +except ImportError: + pass + +register = template.Library() + +MAX_LENGTH_BOOTSTRAP_COLUMN = 12 + + +def css_classes_for_field(field, custom_classes): + orig_class = field.field.widget.attrs.get('class', '') + required = 'required' if field.field.required else '' + classes = field.css_classes(' '.join([orig_class, custom_classes, required])) + return classes + + +@register.filter() +def get_label(field, custom_classes=''): + classes = css_classes_for_field(field, custom_classes) + return field.label_tag(attrs={'class': classes}, label_suffix='') + + +@register.filter() +def add_class(field, custom_classes=''): + classes = css_classes_for_field(field, custom_classes) + try: + # For widgets like SelectMultiple, checkboxselectmultiple + field.field.widget.widget.attrs.update({'class': classes}) + except: + field.field.widget.attrs.update({'class': classes}) + return field + + +@register.filter() +def widget_type(field): + if isinstance(field, dict): + return 'adminreadonlyfield' + try: + # For widgets like SelectMultiple, checkboxselectmultiple + widget_type = field.field.widget.widget.__class__.__name__.lower() + except: + widget_type = field.field.widget.__class__.__name__.lower() + return widget_type + + +@register.filter() +def placeholder(field, placeholder=''): + field.field.widget.attrs.update({'placeholder': placeholder}) + return field + + +def sidebar_menu_setting(): + return getattr(settings, 'BOOTSTRAP_ADMIN_SIDEBAR_MENU', False) + + +@register.assignment_tag +def display_sidebar_menu(has_filters=False): + if has_filters: + # Always display the menu in change_list.html + return True + return sidebar_menu_setting() + + +@register.assignment_tag +def jquery_vendor_path(): + if DJANGO_VERSION < (1, 9): + return 'admin/js/jquery.js' + return 'admin/js/vendor/jquery/jquery.js' + + +@register.assignment_tag +def datetime_widget_css_path(): + if DJANGO_VERSION < (1, 9): + return '' + return 'admin/css/datetime_widget.css' + + +@register.inclusion_tag('bootstrap_admin/sidebar_menu.html', + takes_context=True) +def render_menu_app_list(context): + show_global_menu = sidebar_menu_setting() + if not show_global_menu: + return {'app_list': ''} + + if DJANGO_VERSION < (1, 8): + dependencie = 'django.core.context_processors.request' + processors = settings.TEMPLATE_CONTEXT_PROCESSORS + dependency_str = 'settings.TEMPLATE_CONTEXT_PROCESSORS' + else: + dependencie = 'django.template.context_processors.request' + implemented_engines = getattr(settings, 'BOOTSTRAP_ADMIN_ENGINES', + ['django.template.backends.django.DjangoTemplates']) + dependency_str = "the 'context_processors' 'OPTION' of one of the " + \ + "following engines: %s" % implemented_engines + filtered_engines = [engine for engine in settings.TEMPLATES + if engine['BACKEND'] in implemented_engines] + if len(filtered_engines) == 0: + raise ImproperlyConfigured( + "bootstrap_admin: No compatible template engine found" + + "bootstrap_admin requires one of the following engines: %s" + % implemented_engines + ) + processors = reduce(lambda x, y: x.extend(y), [ + engine.get('OPTIONS', {}).get('context_processors', []) + for engine in filtered_engines]) + + if dependencie not in processors: + raise ImproperlyConfigured( + "bootstrap_admin: in order to use the 'sidebar menu' requires" + + " the '%s' to be added to %s" + % (dependencie, dependency_str) + ) + + # Code adapted from django.contrib.admin.AdminSite + app_dict = {} + user = context.get('user') + for model, model_admin in site._registry.items(): + app_label = model._meta.app_label + has_module_perms = user.has_module_perms(app_label) + + if has_module_perms: + perms = model_admin.get_model_perms(context.get('request')) + + # Check whether user has any perm for this module. + # If so, add the module to the model_list. + if True in perms.values(): + info = (app_label, model._meta.model_name) + model_dict = { + 'name': capfirst(model._meta.verbose_name_plural), + 'object_name': model._meta.object_name, + 'perms': perms, + } + if perms.get('change', False): + try: + model_dict['admin_url'] = reverse( + 'admin:%s_%s_changelist' % info, + current_app=site.name + ) + except NoReverseMatch: + pass + if perms.get('add', False): + try: + model_dict['add_url'] = reverse( + 'admin:%s_%s_add' % info, + current_app=site.name + ) + except NoReverseMatch: + pass + if app_label in app_dict: + app_dict[app_label]['models'].append(model_dict) + else: + if app_label != "categories": + app_dict[app_label] = { + 'name': apps.get_app_config(app_label).verbose_name, + 'app_label': app_label, + 'app_url': reverse( + 'admin:app_list', + kwargs={'app_label': app_label}, + current_app=site.name + ), + 'has_module_perms': has_module_perms, + 'models': [model_dict], + } + + # Sort the apps alphabetically. + app_list = list(six.itervalues(app_dict)) + app_list.sort(key=lambda x: x['name'].lower()) + + # Sort the models alphabetically within each sapp. + for app in app_list: + app['models'].sort(key=lambda x: x['name']) + return {'app_list': app_list, 'current_url': context.get('request').path} + + +@register.filter() +def class_for_field_boxes(line): + size_column = MAX_LENGTH_BOOTSTRAP_COLUMN // len(line.fields) + return 'col-sm-{0}'.format(size_column or 1) # if '0' replace with 1 diff --git a/code/train/Python/0097565_routing.py b/code/train/Python/0097565_routing.py new file mode 100644 index 0000000000000000000000000000000000000000..cd901a3ffbc1212f1ec4e872c08d0f0371c5aeb3 --- /dev/null +++ b/code/train/Python/0097565_routing.py @@ -0,0 +1,199 @@ +# -*- coding: utf-8 -*- +# pylint: disable=line-too-long + +"""This module is used for parsing the received lines into a machine readable structure.""" + +from __future__ import annotations + +import re +import typing + +import eml_parser.decode +import eml_parser.regex + + +def noparenthesis(line: str) -> str: + """Remove nested parenthesis, until none are present. + + @FIXME rewrite this function. + + Args: + line (str): Input text to search in for parenthesis. + + Returns: + str: Return a string with all parenthesis removed. + """ + # check empty string + if not line: + return line + + line_ = line + + while True: + lline = line_ + line_ = eml_parser.regex.noparenthesis_regex.sub('', line_) + if lline == line_: + break + + return line_ + + +def cleanline(line: str) -> str: + """Remove space and ; from start/end of line. + + Args: + line (str): Line to clean. + + Returns: + str: Cleaned string. + """ + if line == '': + return line + + return eml_parser.regex.cleanline_regex.sub('', line) + + +def get_domain_ip(line: str) -> typing.List[str]: + """Method returns all domains, IPv4 and IPv6 addresses found in a given string. + + Args: + line (str): String to search in. + + Returns: + list: Unique list of strings with matches + """ + m = eml_parser.regex.dom_regex.findall(' ' + line) + eml_parser.regex.ipv4_regex.findall(line) + eml_parser.regex.ipv6_regex.findall(line) + + return list(set(m)) + + +def parserouting(line: str) -> typing.Dict[str, typing.Any]: + """This method tries to parsed a e-mail header received line\ + and extract machine readable information. + + Note that there are a large number of formats for these lines + and a lot of weird ones which are not commonly used. + We try our best to match a large number of formats. + + Args: + line (str): Received line to be parsed. + + Returns: + dict: Returns a dict with the extracted information. + """ + # if re.findall(reg_date, line): + # return 'date\n' + # Preprocess the line to simplify from/by/with/for border detection. + out = {} # type: typing.Dict[str, typing.Any] # Result + out['src'] = line + line = line.lower() # Convert everything to lowercase + npline = line.replace(')', ' ) ') # normalise space # Re-space () ")by " exists often + npline = npline.replace('(', ' ( ') # normalise space # Re-space () + npline = npline.replace(';', ' ; ') # normalise space # Re-space ; + npline = noparenthesis(npline) # Remove any "()" + npline = ' '.join(npline.split()) # normalise space + npline = npline.strip('\n') # Remove any new-line + raw_find_data = eml_parser.regex.date_regex.findall(npline) # extract date on end line. + + # Detect "sticked lines" + if ' received: ' in npline: + out['warning'] = ['Merged Received headers'] + return out + + if raw_find_data: + npdate = raw_find_data[0] # Remove spaces and starting ; + npdate = npdate.lstrip(';') # Remove Spaces and stating ; from date + npdate = npdate.strip() + else: + npdate = '' + + npline = npline.replace(npdate, '') # Remove date from input line + npline = npline.strip(' ') # Remove any border WhiteSpace + + borders = ['from ', 'by ', 'with ', 'for '] + result: typing.List[typing.Dict[str, typing.Any]] = [] + + # Scan the line to determine the order, and presence of each "from/by/with/for" words + for word in borders: + candidate = list(borders) + candidate.remove(word) + for endword in candidate: + if word in npline: + loc = npline.find(word) + end = npline.find(endword) + if end < loc or end == -1: + end = 0xfffffff # Kindof MAX 31 bits + result.append({'name_in': word, 'pos': loc, 'name_out': endword, 'weight': end + loc}) + # print({'name_in': word, 'pos': loc, 'name_out': endword, 'weight': end+loc}) + + # Create the word list... "from/by/with/for" by sorting the list. + if not result: + out['warning'] = ['Nothing Parsable'] + return out + + tout = [] + for word in borders: + result_max = 0xffffffff + line_max: typing.Dict[str, typing.Any] = {} + for eline in result: + if eline['name_in'] == word and eline['weight'] <= result_max: + result_max = eline['weight'] + line_max = eline + + if line_max: + tout.append([line_max.get('pos'), line_max.get('name_in')]) + + # structure is list[list[int, str]] + # we sort based on the first element of the sub list, i.e. int + tout = sorted(tout, key=lambda x: x[0]) + + # build regex. + reg = '' + for item in tout: + reg += item[1] + '(?P<' + item[1].strip() + '>.*)' # type: ignore + if npdate: + # escape special regex chars + reg += eml_parser.regex.escape_special_regex_chars.sub(r'''\\\1''', npdate) + + reparse = re.compile(reg) + reparseg = reparse.search(line) + + # Fill the data + if reparseg is not None: + for item in borders: # type: ignore + try: + out[item.strip()] = cleanline(reparseg.group(item.strip())) # type: ignore + except (LookupError, ValueError, AttributeError): + pass + + if npdate: + out['date'] = eml_parser.decode.robust_string2date(npdate) + + # Fixup for "From" in "for" field + # ie google, do that... + if out.get('for'): + # include spaces in test, otherwise there will be an exception with domains containing "from" in itself + if ' from ' in out.get('for', ''): + temp = re.split(' from ', out['for']) + out['for'] = temp[0] + out['from'] = '{} {}'.format(out['from'], ' '.join(temp[1:])) + + m = eml_parser.regex.email_regex.findall(out['for']) + if m: + out['for'] = list(set(m)) + else: + del out['for'] + + # Now.. find IP and Host in from + if out.get('from'): + out['from'] = get_domain_ip(out['from']) + if not out.get('from', []): # if array is empty remove + del out['from'] + + # Now.. find IP and Host in from + if out.get('by'): + out['by'] = get_domain_ip(out['by']) + if not out.get('by', []): # If array is empty remove + del out['by'] + + return out diff --git a/code/train/Python/0097932_410._Split_Array_Largest_Sum.py b/code/train/Python/0097932_410._Split_Array_Largest_Sum.py new file mode 100644 index 0000000000000000000000000000000000000000..7f3a66c2329fc2c4eb36b7a84e0c0b930b544dec --- /dev/null +++ b/code/train/Python/0097932_410._Split_Array_Largest_Sum.py @@ -0,0 +1,53 @@ +""" +Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. + +Note: +Given m satisfies the following constraint: 1 ≤ m ≤ length(nums) ≤ 14,000. + +Examples: + +Input: +nums = [7,2,5,10,8] +m = 2 + +Output: +18 + +Explanation: +There are four ways to split nums into two subarrays. +The best way is to split it into [7,2,5] and [10,8], +where the largest sum among the two subarrays is only 18. +""" + +class Solution(object): + def splitArray(self, nums, m): + """ + :type nums: List[int] + :type m: int + :rtype: int + """ + def dividable(nums, limit, total_cut): + accu, cut = 0, 1 + for n in nums: + if accu + n <= limit: + accu += n + else: + cut += 1 + accu = n + if cut > total_cut: + return False + return True + + biggest, sum = float('-inf'), 0 + for n in nums: + sum += n + biggest = max(biggest, n) + l, r = biggest, sum + while l < r: + mid = (l + r) / 2 + if dividable(nums, mid, m): + r = mid + else: + l = mid + 1 + return l + diff --git a/code/train/Python/0097985_8QueensHill.py b/code/train/Python/0097985_8QueensHill.py new file mode 100644 index 0000000000000000000000000000000000000000..21fa64a77d4f6f1aa52d89a36fc359de945b6008 --- /dev/null +++ b/code/train/Python/0097985_8QueensHill.py @@ -0,0 +1,103 @@ +#-*- coding: utf-8 -*- +# Solution for eight queens problem using the hill climbing algorithm + +import random +import time + +possibleStatements = 0 # The number of analyzed possible statements +changeStatements = 0 # The number of statement changes +randomRestarts = 0 # The number of random restarts + +def randomState(): + # Initialize the board + items = [0, 1, 2, 3, 4, 5, 6, 7] + random.shuffle(items) + return items + + +def stateValue(state): + # The number of illegal statements + value = 0 + + for i in range(8): + for j in range(8): + if i != j and (abs(i-j) == abs(state[i]-state[j]) or state[i] == state[j]): + value += 1 + + return value/2 # For duplicate statements + + +def selectNextMove(currentState, iteration): + # Calculate value for every position of queen where same column + tempState = list(currentState) + passIt = tempState[iteration] # For same statement; current and next. + bestValue = 28 # Worst-case + global possibleStatements + + for i in range(8): + + if i != passIt: # Don't control to same statement + + tempState[iteration] = i + currentValue = stateValue(tempState) # The number of illegal statements + print "i:",i, " currentValue:",currentValue," tempState:", tempState + + if currentValue < bestValue: # Choose the best statement + bestValue = currentValue + bestState = list(tempState) + print "change i:",i," bestValue:",bestValue," bestState:",bestState + + possibleStatements += 1 + + return bestState, bestValue + + +def hillClimbing(initState, selectNextMove, stateValue): + + currentState = initState + currentValue = stateValue(currentState) + + global changeStatements + global randomRestarts + iteration = 0 + + while True: + + print "iteration:", iteration," currentValue:",currentValue," currentState:",currentState + + nextState, nextValue = selectNextMove(currentState, iteration) # Find the best next statement + print "iteration:", iteration," nextValue:",nextValue," nextState:",nextState,"\n\n" + + if nextValue < currentValue: # Compare number of illegal statements + currentState = list(nextState) + currentValue = nextValue + print "statement changed currentState:",currentState," currentValue:",currentValue,"\n\n" + + changeStatements += 1 + + if currentValue == 0: # Problem was solved? + return currentState + + elif iteration == 7: # If algorithm doesn't climb and all columns finished, board refresh + print "Problem didn't solve. Restarting..\n\n" + randomRestarts += 1 + return hillClimbing(randomState(), selectNextMove, stateValue) + break; + + iteration = (iteration+1)%8 # When 8 columns finish, iteration restarts + + + +if __name__=='__main__': + + start = time.time() + + initState = randomState() + resultStatement = hillClimbing(initState, selectNextMove, stateValue) + print "Result Statement:",resultStatement + + elapsed = (time.time() - start) + print "\nTotal processing time:",elapsed,"seconds" + print "\nThe number of analyzed possible statements:",possibleStatements + print "\nThe number of statement changes:",changeStatements + print "\nThe number of random restarts:",randomRestarts diff --git a/code/train/Python/0098120_solution.py b/code/train/Python/0098120_solution.py new file mode 100644 index 0000000000000000000000000000000000000000..efd61e889891cddd3839514dd0e8b6970daf899f --- /dev/null +++ b/code/train/Python/0098120_solution.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +''' +***************************************** +Author: zhlinh +Email: zhlinhng@gmail.com +Version: 0.0.1 +Created Time: 2016-05-18 +Last_modify: 2016-05-18 +****************************************** +''' + +''' +You are given coins of different denominations and a total amount of money amount. +Write a function to compute the fewest number of coins that you need to make up +that amount. If that amount of money cannot be made up by any combination of +the coins, return -1. + +Example 1: +coins = [1, 2, 5], amount = 11 +return 3 (11 = 5 + 5 + 1) + +Example 2: +coins = [2], amount = 3 +return -1. + +Note: +You may assume that you have an infinite number of each kind of coin. + +Credits: +Special thanks to @jianchao.li.fighter for adding this problem and +creating all test cases. +''' + +class Solution(object): + def coinChange(self, coins, amount): + """ + :type coins: List[int] + :type amount: int + :rtype: int + """ + if amount < 1: + return 0 + coins.sort(reverse=True) + self.times = 2 ** 31 - 1 + self.helper(coins, 0, 0, amount) + return -1 if self.times == 2 ** 31 - 1 else self.times + + def helper(self, coins, pos, count, amount): + if pos >= len(coins) or count + 1 >= self.times: + return + maxN = amount // coins[pos] + while maxN >= 0: + newCount = count + maxN + rem = amount - maxN * coins[pos] + if rem > 0 and newCount + 1 < self.times: + self.helper(coins, pos + 1, newCount, rem) + else: + if rem == 0 and newCount < self.times: + self.times = newCount + break + maxN -= 1 diff --git a/code/train/Python/0098237_getopt.py b/code/train/Python/0098237_getopt.py new file mode 100644 index 0000000000000000000000000000000000000000..31564bea00b7dc370b1238218db307ed464874eb --- /dev/null +++ b/code/train/Python/0098237_getopt.py @@ -0,0 +1,211 @@ +# -*- coding: iso-8859-1 -*- +"""Parser for command line options. + +This module helps scripts to parse the command line arguments in +sys.argv. It supports the same conventions as the Unix getopt() +function (including the special meanings of arguments of the form `-' +and `--'). Long options similar to those supported by GNU software +may be used as well via an optional third argument. This module +provides two functions and an exception: + +getopt() -- Parse command line options +gnu_getopt() -- Like getopt(), but allow option and non-option arguments +to be intermixed. +GetoptError -- exception (class) raised with 'opt' attribute, which is the +option involved with the exception. +""" + +# Long option support added by Lars Wirzenius . +# +# Gerrit Holl moved the string-based exceptions +# to class-based exceptions. +# +# Peter Åstrand added gnu_getopt(). +# +# TODO for gnu_getopt(): +# +# - GNU getopt_long_only mechanism +# - allow the caller to specify ordering +# - RETURN_IN_ORDER option +# - GNU extension with '-' as first character of option string +# - optional arguments, specified by double colons +# - a option string with a W followed by semicolon should +# treat "-W foo" as "--foo" + +__all__ = ["GetoptError","error","getopt","gnu_getopt"] + +import os + +class GetoptError(Exception): + opt = '' + msg = '' + def __init__(self, msg, opt=''): + self.msg = msg + self.opt = opt + Exception.__init__(self, msg, opt) + + def __str__(self): + return self.msg + +error = GetoptError # backward compatibility + +def getopt(args, shortopts, longopts = []): + """getopt(args, options[, long_options]) -> opts, args + + Parses command line options and parameter list. args is the + argument list to be parsed, without the leading reference to the + running program. Typically, this means "sys.argv[1:]". shortopts + is the string of option letters that the script wants to + recognize, with options that require an argument followed by a + colon (i.e., the same format that Unix getopt() uses). If + specified, longopts is a list of strings with the names of the + long options which should be supported. The leading '--' + characters should not be included in the option name. Options + which require an argument should be followed by an equal sign + ('='). + + The return value consists of two elements: the first is a list of + (option, value) pairs; the second is the list of program arguments + left after the option list was stripped (this is a trailing slice + of the first argument). Each option-and-value pair returned has + the option as its first element, prefixed with a hyphen (e.g., + '-x'), and the option argument as its second element, or an empty + string if the option has no argument. The options occur in the + list in the same order in which they were found, thus allowing + multiple occurrences. Long and short options may be mixed. + + """ + + opts = [] + if type(longopts) == type(""): + longopts = [longopts] + else: + longopts = list(longopts) + while args and args[0].startswith('-') and args[0] != '-': + if args[0] == '--': + args = args[1:] + break + if args[0].startswith('--'): + opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) + else: + opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) + + return opts, args + +def gnu_getopt(args, shortopts, longopts = []): + """getopt(args, options[, long_options]) -> opts, args + + This function works like getopt(), except that GNU style scanning + mode is used by default. This means that option and non-option + arguments may be intermixed. The getopt() function stops + processing options as soon as a non-option argument is + encountered. + + If the first character of the option string is `+', or if the + environment variable POSIXLY_CORRECT is set, then option + processing stops as soon as a non-option argument is encountered. + + """ + + opts = [] + prog_args = [] + if isinstance(longopts, str): + longopts = [longopts] + else: + longopts = list(longopts) + + # Allow options after non-option arguments? + if shortopts.startswith('+'): + shortopts = shortopts[1:] + all_options_first = True + elif os.environ.get("POSIXLY_CORRECT"): + all_options_first = True + else: + all_options_first = False + + while args: + if args[0] == '--': + prog_args += args[1:] + break + + if args[0][:2] == '--': + opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) + elif args[0][:1] == '-': + opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) + else: + if all_options_first: + prog_args += args + break + else: + prog_args.append(args[0]) + args = args[1:] + + return opts, prog_args + +def do_longs(opts, opt, longopts, args): + try: + i = opt.index('=') + except ValueError: + optarg = None + else: + opt, optarg = opt[:i], opt[i+1:] + + has_arg, opt = long_has_args(opt, longopts) + if has_arg: + if optarg is None: + if not args: + raise GetoptError('option --%s requires argument' % opt, opt) + optarg, args = args[0], args[1:] + elif optarg: + raise GetoptError('option --%s must not have an argument' % opt, opt) + opts.append(('--' + opt, optarg or '')) + return opts, args + +# Return: +# has_arg? +# full option name +def long_has_args(opt, longopts): + possibilities = [o for o in longopts if o.startswith(opt)] + if not possibilities: + raise GetoptError('option --%s not recognized' % opt, opt) + # Is there an exact match? + if opt in possibilities: + return False, opt + elif opt + '=' in possibilities: + return True, opt + # No exact match, so better be unique. + if len(possibilities) > 1: + # XXX since possibilities contains all valid continuations, might be + # nice to work them into the error msg + raise GetoptError('option --%s not a unique prefix' % opt, opt) + assert len(possibilities) == 1 + unique_match = possibilities[0] + has_arg = unique_match.endswith('=') + if has_arg: + unique_match = unique_match[:-1] + return has_arg, unique_match + +def do_shorts(opts, optstring, shortopts, args): + while optstring != '': + opt, optstring = optstring[0], optstring[1:] + if short_has_arg(opt, shortopts): + if optstring == '': + if not args: + raise GetoptError('option -%s requires argument' % opt, + opt) + optstring, args = args[0], args[1:] + optarg, optstring = optstring, '' + else: + optarg = '' + opts.append(('-' + opt, optarg)) + return opts, args + +def short_has_arg(opt, shortopts): + for i in range(len(shortopts)): + if opt == shortopts[i] != ':': + return shortopts.startswith(':', i+1) + raise GetoptError('option -%s not recognized' % opt, opt) + +if __name__ == '__main__': + import sys + print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]) diff --git a/code/train/Python/0098559_stringconv.py b/code/train/Python/0098559_stringconv.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad3eb3bb10f889ec33bb8af437cb6a5ca90f91c --- /dev/null +++ b/code/train/Python/0098559_stringconv.py @@ -0,0 +1,30 @@ +""" +This file is part of the TheLMA (THe Laboratory Management Application) project. +See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. + +String conversion utilities. +""" +import string # pylint: disable=W0402 + +__docformat__ = 'reStructuredText en' + + +__all__ = ['reverse_dna_sequence'] + + +def reverse_dna_sequence(sequence): + """ + Convert a DNA strand to its reverse complement. + + Based on http://www.wellho.net/resources/ex.php4?item=y108/seqrev.py + + :param str sequence: a DNA sequence + :returns: reverse complement of sequence + :rtype: str + """ + seq = sequence.upper() + trans_table = string.maketrans('ACGT', 'TGCA') + base_list = list(seq.translate(trans_table, ' \n')) + base_list.reverse() + reverse_seq = ''.join(base_list) + return reverse_seq diff --git a/code/train/Python/0098570_imm-turn-test.py b/code/train/Python/0098570_imm-turn-test.py new file mode 100644 index 0000000000000000000000000000000000000000..eea931c57ec03db140e53768bbb87476b53cb751 --- /dev/null +++ b/code/train/Python/0098570_imm-turn-test.py @@ -0,0 +1,146 @@ +import matplotlib.pyplot as plt +import numpy as np +import copy +from filterpy.kalman import IMMEstimator +from filterpy.kalman import KalmanFilter +from filterpy.common import Q_discrete_white_noise +from math import sin, cos, sqrt, atan2 +from scipy.linalg import block_diag +from tracker import simulateCircle as sc +from tracker import predictIMM as imm + +def sign(x): + return(math.copysign(1,x)) + +def turning_target(N=600, turn_start=400): + """ simulate a moving target blah""" + + #r = 1. + dt = 1. + phi_sim = np.array( + [[1, dt, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, dt], + [0, 0, 0, 1]]) + + gam = np.array([[dt**2/2, 0], + [dt, 0], + [0, dt**2/2], + [0, dt]]) + + x = np.array([[2000, 0, 10000, -15.]]).T + + simxs = [] + + for i in range(N): + x = np.dot(phi_sim, x) + if i >= turn_start: + x += np.dot(gam, np.array([[.075, .075]]).T) + #print(x) + simxs.append(x) + simxs = np.array(simxs) + + return simxs + +def circle_target(N=50): + simxs = [] + # R, MX, MY, MZ, gamma + cs = sc.simulateCircle(90., 100., 100., 0., gamma=60.0) + dn = 180. / float(N) + alpha = 0. + xo,yo,zo = cs.pointAt(0.) + while alpha < 180.: + #for alpha in range(0,360,N): + x,y,z = cs.pointAt(alpha) + vx = (xo - x) / dt + vy = (yo - y) / dt + xs = np.array([x,vx,y,vy]).T + #print(xs) + xo = x + yo = y + simxs.append(xs) + alpha = alpha + dn + + return np.array(simxs) + +def linear_target(N=50): + m = 0.5 + b = 100. + simxs = [] + for x in range(0,10*N,10): + y = m*x+b + xs = np.array([x,10.,y,5.]) + simxs.append(xs) + return np.array(simxs) + +if __name__ == "__main__": + + N = 40 + dt = 0.04 + p = 100. + q = 5. + #track = turning_target(N) + track = circle_target(N) + #track = linear_target(N) + alpha0 = atan2(track[0,2], track[0,0]) + alpha1 = atan2(track[1,2], track[1,0]) + omega = 1.41 * (alpha0 - alpha1) / dt + print(omega) + + # create noisy measurements + zs = np.zeros((N, 2)) + r = 0.5 + for i in range(N): + px = track[i, 0] + np.random.randn()*r + py = track[i, 2] + np.random.randn()*r + #print "px: %4.2f, py: %4.2f" % (px,py) + zs[i, 0] = px + zs[i, 1] = py + + + immfilter = imm.filterIMM(dt,omega,p,r,q) + xstart = np.array([[10., 10., 0, 100., 1., 0]]).T + immfilter.startAt(xstart) + xs, probs = [], [] + for i, z in enumerate(zs): + #z = np.array([z]).T + #print("x: %4.2f, y: %4.2f" % (z[0], z[1])) + #bank.update(z) + x = z[0] + y = z[1] + immfilter.update(x,y) + xs.append(immfilter.bank.x.copy()) + probs.append(immfilter.bank.mu.copy()) + print(immfilter.bank.mu) + + + xs = np.array(xs) + #cvxs = np.array(cvxs) + #caxs = np.array(caxs) + probs = np.array(probs) + plt.subplot(131) + plt.title('imm2.py') + plt.plot(track[:, 0], track[:, 2], '--r') + plt.plot(xs[:, 0], xs[:, 3], 'k') + plt.scatter(zs[:, 0], zs[:, 1], marker='+') + + plt.subplot(132) + plt.plot(probs[:, 0], 'r') + plt.plot(probs[:, 1], 'g') + plt.plot(probs[:, 2], 'b') + + plt.ylim(0., 1.0) + plt.legend(['p(cv)', 'p(ca)', 'p(ct)']) + plt.title('probability ratio') + + plt.subplot(133) + dx = (xs[:,0].T - zs[:,0]) / zs[:,0] + dy = (xs[:,3].T - zs[:,1]) / zs[:,1] + plt.plot(dx.T, 'g') + plt.plot(dy.T, 'b') + plt.title('relative error') + plt.legend(['dx', 'dy']) + plt.axhline(y=0, color='k') + + + plt.show() diff --git a/code/train/Python/0098764_blueblue.py b/code/train/Python/0098764_blueblue.py new file mode 100644 index 0000000000000000000000000000000000000000..7b498920053a4150b188655f9ec8f8a26671619e --- /dev/null +++ b/code/train/Python/0098764_blueblue.py @@ -0,0 +1,242 @@ +#!/usr/bin/python + +import getopt +import sys +import os +import bluetooth + +vernum = "0.1beta" +debug = False +verbose = False +listdevices = False +known_devices=[] + +# Print help information and exit: +def version(): + print "+----------------------------------------------------------------------+" + print "| "+ sys.argv[0] + " Version "+ vernum +" |" + print "| This program is free software; you can redistribute it and/or modify |" + print "| it under the terms of the GNU General Public License as published by |" + print "| the Free Software Foundation; either version 2 of the License, or |" + print "| (at your option) any later version. |" + print "| |" + print "| Author: Veronica Valeros, vero dot valeros at gmail dot com |" + print "+----------------------------------------------------------------------+" + print + + +# Print help information and exit: +def usage(): + """ + This function prints the posible options of this program. + + No parameters are needed. + """ + print "+----------------------------------------------------------------------+" + print "| "+ sys.argv[0] + " Version "+ vernum +" |" + print "| This program is free software; you can redistribute it and/or modify |" + print "| it under the terms of the GNU General Public License as published by |" + print "| the Free Software Foundation; either version 2 of the License, or |" + print "| (at your option) any later version. |" + print "| |" + print "| Author: Veronica Valeros, vero.valeros@gmail.com |" + print "+----------------------------------------------------------------------+" + print + print "\nUsage: %s " % sys.argv[0] + print "Options:" + print " -h, --help Show this help message and exit" + print " -V, --version Output version information and exit" + print " -v, --verbose Be verbose" + print " -D, --debug Debug" + print " -f, --filename Filename to send." + print " -l, --listdevices Just list devices, no send any file." + print + print + + sys.exit(1) + +def search_channel(): + """ + This function searches the channel of a device in the tmp file generated by the previous executed command sdptool. + Without this channel is difficult to invocate the obexftp command to send files. + """ + global debug + global verbose + + try: + + data = open('tmp','r') + line = data.readline() + + while line: + if 'OBEX Object Push' in line: + while line: + if 'Channel' in line: + channel = line.split(': ')[1] + return str(channel) + else: + line = data.readline() + else: + line = data.readline() + return -1 + + except KeyboardInterrupt: + # CTRL-C pretty handling + print 'Keyboard Interruption!. Exiting.' + sys.exit(1) + except Exception as inst: + print '[!] Exception in main() function' + print type(inst) # the exception instance + print inst.args # arguments stored in .args + print inst # __str__ allows args to printed directly + x, y = inst # __getitem__ allows args to be unpacked directly + print 'x =', x + print 'y =', y + sys.exit(1) + +def bluecast(filename): + """ + This function list near devices using blutooth and send them a given file if it is given by the user. + """ + global debug + global verbose + global listdevices + global known_devices + + + try: + listdev = [] + devs = [] + + # Discovering devices + listdev = bluetooth.discover_devices(lookup_names=True) + if debug: + print "[+] Discovering devices..." + print '- devices: {}'.format(listdev) + + # Printing information + print '+------------------------------------------------+' + print '|NAME\t\t BDADDR\t\t\t CHANNEL |' + print '+------------------------------------------------+' + for [device,name] in listdev: + # Retrieving device channel with sdptool + os.system('sdptool browse '+device+'> tmp') + channel = search_channel() + os.system('rm tmp') + + if (channel != -1): + if (len(name) > 7 ): + print "{}\t {}\t {}".format(name,device,channel.strip('\n')) + else: + print "{}\t\t {}\t {}".format(name,device,channel.strip('\n')) + + devs.append([device,name,channel.strip('\n')]) + + if not listdevices and len(devs)>0: + + print 'Sending file....' + for [device,name,channel] in devs: + if [device,name,channel] not in known_devices: + print + print + print '[+] {} ({})'.format(device,name) + print ' File: {}'.format(filename) + print ' Command: obexftp --nopath --noconn --uuid none --bluetooth '+device+' --channel '+channel+' -p '+filename + + status = os.system('obexftp --nopath --noconn --uuid none --bluetooth '+device+' --channel '+channel+' -p '+filename) + retval, sig = ((status >> 8) & 0xFF), (status & 0xFF) + + if debug: + print '\nretval: {}, sig: {}'.format(retval,sig) + if retval == 255: + known_devices.append([device,name,channel]) + print + print 'Succeded!' + else: + print + print 'Failed!' + else: + print 'Ignoring device {} ({})'.format(device,name) + + print + print + + except KeyboardInterrupt: + # CTRL-C pretty handling + print 'Keyboard Interruption!. Exiting.' + return -2 + except Exception as inst: + print '[!] Exception in main() function' + print type(inst) # the exception instance + print inst.args # arguments stored in .args + print inst # __str__ allows args to printed directly + x, y = inst # __getitem__ allows args to be unpacked directly + print 'x =', x + print 'y =', y + return -1 + + +def main(): + + """ + blueblue.py is a tool for bluetooth marketing and sharing. It allows to broadcast files in the bluetooth neighborhood. + + Example: blueblue.py -f image.jpg + """ + + global debug + global verbose + global listdevices + + filename = "" + + try: + opts, args = getopt.getopt(sys.argv[1:], "hVdvf:l", ["help","version","debug","verbose","file","list-devices"]) + + + except getopt.GetoptError: usage() + + for opt, arg in opts: + if opt in ("-h", "--help"): usage() + if opt in ("-V", "--version"): version();sys.exit(1) + if opt in ("-D", "--debug"): debug=True + if opt in ("-v", "--verbose"): verbose=True + if opt in ("-f", "--file"): filename=arg + if opt in ("-l", "--list-devices"): listdevices=True + + try: + version() + + print "blueblue.py is a tool for bluetooth marketing and sharing." + print + + if not filename and not listdevices: + print 'You must specify a file to send or use the --list-devices option instead.' + sys.exit(1) + + while True: + code = bluecast(filename) + if code == -2: + sys.exit(1) + + + + except KeyboardInterrupt: + # CTRL-C pretty handling + print + print 'Bye' + sys.exit(1) + except Exception as inst: + print '[!] Exception in main() function' + print type(inst) # the exception instance + print inst.args # arguments stored in .args + print inst # __str__ allows args to printed directly + x, y = inst # __getitem__ allows args to be unpacked directly + print 'x =', x + print 'y =', y + sys.exit(1) + +if __name__ == '__main__': + main() + + diff --git a/code/train/Python/0098895_binaria.py b/code/train/Python/0098895_binaria.py new file mode 100644 index 0000000000000000000000000000000000000000..f92aa84f61735122c104d127bc66b1b29fe11d8f --- /dev/null +++ b/code/train/Python/0098895_binaria.py @@ -0,0 +1,107 @@ +#! /usr/bin/env python +# +# GUI module generated by PAGE version 4.9 +# In conjunction with Tcl version 8.6 +# Dec 22, 2017 02:19:10 PM +import sys + +from tkinter import messagebox + +try: + from Tkinter import * +except ImportError: + from tkinter import * + +try: + import ttk + py3 = 0 +except ImportError: + import tkinter.ttk as ttk + py3 = 1 + +class BINARIA: + def __init__(self, top): + self.top = Toplevel(top) + self.top.focus() + self.top.transient() + self.top.grab_set() + + '''This class configures and populates the toplevel window. + top is the toplevel containing window.''' + _bgcolor = '#d9d9d9' # X11 color: 'gray85' + _fgcolor = '#000000' # X11 color: 'black' + _compcolor = '#d9d9d9' # X11 color: 'gray85' + _ana1color = '#d9d9d9' # X11 color: 'gray85' + _ana2color = '#d9d9d9' # X11 color: 'gray85' + self.style = ttk.Style() + if sys.platform == "win32": + self.style.theme_use('winnative') + self.style.configure('.', background=_bgcolor) + self.style.configure('.', foreground=_fgcolor) + self.style.configure('.', font="TkDefaultFont") + self.style.map('.', background= + [('selected', _compcolor), ('active', _ana2color)]) + + + self.top.geometry("1080x720+180+10") + self.top.title("Árvore Binária") + self.top.configure(background="#d9d9d9") + + + + self.frPrincipal = Frame(self.top) + self.frPrincipal.place(relx=0.00, rely=0.00, relheight=1 , relwidth=1) + self.frPrincipal.configure(relief=GROOVE,background="#d9d9d9") + + self.lblInserir = Label(self.frPrincipal) + self.lblInserir.place(relx=0.0, rely=0.02 ) + self.lblInserir.configure(text='''Inserir: ''' , background="#d9d9d9") + + self.txtInserir = Entry(self.frPrincipal) + self.txtInserir.place(relx=0.055, rely=0.02, relheight=0.03, relwidth=0.05) + self.txtInserir.bind('', lambda e: self.inserir()) + + self.lblRemover = Label(self.frPrincipal) + self.lblRemover.place(relx=0.00, rely=0.06 ) + self.lblRemover.configure(text='''Remover: ''' , background="#d9d9d9") + + self.txtRemover = Entry(self.frPrincipal) + self.txtRemover.place(relx=0.055, rely=0.06, relheight=0.03, relwidth=0.05) + self.txtRemover.bind('', lambda e: self.remover()) + + self.lblPesquisar = Label(self.frPrincipal) + self.lblPesquisar.place(relx=0.0, rely=0.097 ) + self.lblPesquisar.configure(text='''Pesquisar: ''' , background="#d9d9d9") + + self.txtPesquisar = Entry(self.frPrincipal) + self.txtPesquisar.place(relx=0.055, rely=0.1, relheight=0.03, relwidth=0.05) + self.txtPesquisar.bind('', lambda e: self.pesquisar()) + + def inserir(self): + messagebox.showinfo("Inserir", "Inserindo ...") + + self.lblPesquisar1 = Label(self.frPrincipal) + self.lblPesquisar1.place(relx=0.5, rely=0.0 ) + self.lblPesquisar1.configure(text='''2''' , background="#d9d9d9") + + self.lblPesquisar2 = Label(self.frPrincipal) + self.lblPesquisar2.place(relx=0.48, rely=0.02 ) + self.lblPesquisar2.configure(text='''1''' , background="#d9d9d9") + + self.lblPesquisar3 = Label(self.frPrincipal) + self.lblPesquisar3.place(relx=0.52, rely=0.02 ) + self.lblPesquisar3.configure(text='''3''' , background="#d9d9d9") + + def remover(self): + messagebox.showinfo("Remover", "Removendo ...") + + def pesquisar(self): + messagebox.showinfo("Pesquisar", "Pesquisando ...") + +if __name__ == '__main__': + root = Tk() + top = BINARIA(root) + root.mainloop() + + + diff --git a/code/train/Python/0098937_docstrings.py b/code/train/Python/0098937_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..98a63ff94cb4a8559ed934d34d3633d6e08d2f26 --- /dev/null +++ b/code/train/Python/0098937_docstrings.py @@ -0,0 +1,124 @@ +# -*- coding: utf-8 -*- +''' pyglet specific docstring transformations. +''' + +_debug = False + +def debug(lines): + with open('debug.log', 'a') as f: + for line in lines: + f.write(line+"\n") + +if _debug: + with open('debug.log', 'w') as f: + f.write("Docstring modifications.\n\n") + + +def indentation(line): + if line.strip()=="": return 0 + return len(line) - len(line.lstrip()) + + +def process_block(converter, lines, start): + ''' Apply a transformation to an indented block + ''' + first = indentation(lines[start]) + current = first + blocks = [[]] + block = 0 + + for i, line in enumerate(lines[start+1:]): + level = indentation(line) + if level<=first: + try: # allow one blank line in the block + if line.strip()=="" and \ + (current == indentation(lines[start + i + 2])): + continue + except: pass + break + if level1: + rest.append(":type "+name+": "+part[1].strip().lstrip()) + return rest + + +def ReST_Ivariable(lines): + ''' Converts :Ivariable: blocks to :var: markup + ''' + indent = indentation(lines[0]) + part = lines[0].replace("`","").split(":") + name = part[0].replace(" ", "") + rest = [":var "+name+":"] + for line in lines[1:]: + rest.append(line[indent:]) + if len(part)>1: + rest.append(":vartype "+name+": "+part[1].strip().lstrip()) + return rest + + + + +def modify_docstrings(app, what, name, obj, options, lines, + reference_offset=[0]): + + original = lines[:] + + def convert(converter, start): + affected, result = process_block(converter, lines, start) + for x in range(start, start+affected+1): + del lines[start] + for i, line in enumerate(result): + lines.insert(start+i, line) + + i=0 + while i= 2: + sock_path = sys.argv[1] +else: + sock_path = "/run/lcd/socket" + +print('Use socket : ' + sock_path) + +# Initialize the LCD plate. Should auto-detect correct I2C bus. If not, +# pass '0' for early 256 MB Model B boards or '1' for all later versions +lcd = Adafruit_CharLCDPlate() +atexit.register(lcd.stop) +lcd.backlight(True) + + +lcd.createChar(0, Sprites.horizontalLines) + +# Clear display and show greeting, pause 1 sec +lcd.clear() +lcd.message("Adafruit RGB LCD\nPlate w/Keypad!\x00") +sleep(1) + +# Cycle through backlight colors +col = (lcd.RED , lcd.YELLOW, lcd.GREEN, lcd.TEAL, + lcd.BLUE, lcd.VIOLET, lcd.WHITE, lcd.OFF) +for c in col: + lcd.ledRGB(c) + sleep(.5) + +# Poll buttons, display message & set backlight accordingly +buttonState = 0 +rm = RecvMsg(sock_path) +ledBlink, ledColor, ledGreenPulseModulo = False, lcd.OFF, 0 +menu_manager = MenuMgr() +while True: + lcd.scrollDisplayLeft() + previousButtonState = buttonState + buttonState = lcd.buttons() + if previousButtonState != buttonState: + if (buttonState & (1 << lcd.SELECT)) != 0: + print('SELECT button') + if ledBlink: + ledBlink = False + else: + lcd.backlight(False) + if (buttonState & (1 << lcd.DOWN)) != 0: + print('DOWN button') + lcd.backlight(True) + menu_manager.next_item() + if (buttonState & (1 << lcd.UP)) != 0: + print('UP button') + lcd.backlight(True) + menu_manager.prev_item() + if (buttonState & (1 << lcd.RIGHT)) != 0: + print('RIGHT button') + lcd.backlight(True) + display_message(lcd, menu_manager.execute_item(lcd)) + if menu_manager.menu_need_refresh: + print('Refresh Menu') + lcd.backlight(True) + display_message(lcd, menu_manager.get_text()) + + #look in the socket if there is a message to display! + (user, message) = rm.recvMsg(0.1) + if user is not None and message is not None: + display_message(lcd, message) + ledBlink = True + ledColor = lcd.RED + # Manage led blink (about 10Hz) + if ledBlink: + lcd.ledRGB(ledColor) + ledColor = (~ledColor) & lcd.WHITE + elif ledGreenPulseModulo % 100 == 0: + lcd.ledRGB(lcd.GREEN) + else: + lcd.ledRGB(lcd.OFF) + ledGreenPulseModulo += 1 diff --git a/code/train/Python/0099631_quick_sort.py b/code/train/Python/0099631_quick_sort.py new file mode 100644 index 0000000000000000000000000000000000000000..0b88709e9fe5053e2795834669b75eb9ebae5277 --- /dev/null +++ b/code/train/Python/0099631_quick_sort.py @@ -0,0 +1,98 @@ +from random import randint + +def quick_sort(input): + """ + Time: average - O(nlogn), worst - O(n^2) + :param input: + :return: + """ + if len(input) <=1: + return input + + small, equal, large = [], [], [] + pivot = input[randint(0, len(input) - 1)] + for item in input: + if item < pivot: + small.append(item) + elif item == pivot: + equal.append(item) + elif item > pivot: + large.append(item) + + return quick_sort(small) + equal + quick_sort(large) + + +## in-place quick sort + +def quick_sort_inplace(a, low=0, high=None): + if high is None: + high = len(a) - 1 + + if low < high: + p = partition(a, low, high) + quick_sort_inplace(a, low, p-1) + quick_sort_inplace(a, p+1, high) + +def partition(a, low, high): + i = low-1 + pivot = a[high] + + for j in range(low, high): + if a[j] <= pivot: + i += 1 + # swap + a[i], a[j] = a[j], a[i] + + a[i+1], a[high] = a[high], a[i+1] + + return i+1 + + +def create_array(size=20, max_val=500): + return [randint(0, max_val) for _ in range(size)] + +if __name__ == "__main__": + + a = create_array() + print(a) + + print(quick_sort(a)) + + b = create_array() + print("Unsorted: ", b) + quick_sort_inplace(b) + print("Sorted: ", b) + + + # code for bench mark both functions + from time import time + times = {'new':[], 'inplace':[]} + sizes = [10,100,1000,10000,100000] + samples = 3 + + for s in sizes: + total = 0.0 + for _ in range(samples): + a = create_array() + t0 = time() + a = quick_sort(a) + t1 = time() + total += (t1 - t0) + times['new'].append(float(total/samples)) + + for _ in range(samples): + a = create_array() + t0 = time() + quick_sort_inplace(a) + t1 = time() + total += (t1 - t0) + times['inplace'].append(float(total/samples)) + + print ("\nn\tQuicksort\tQuicsort - inplace") + print ("_"*40) + for i, s in enumerate(sizes): + print("%d\t%0.5f \t%0.5f"%(s,times['new'][i], times['inplace'][i])) + print("\n") + + + diff --git a/code/train/Python/0099636_e4_2013_7_boxline.py b/code/train/Python/0099636_e4_2013_7_boxline.py new file mode 100644 index 0000000000000000000000000000000000000000..71020c5f80367c5259cfde38ece8b53e87a22213 --- /dev/null +++ b/code/train/Python/0099636_e4_2013_7_boxline.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +''' +@author Michele Tomaiuolo - http://www.ce.unipr.it/people/tomamic +@license This software is free - http://www.gnu.org/licenses/gpl.html +''' + +from e3_2013_3_box import Box + +class BoxLine: + def __init__(self): + self._boxes = [] + + def add_box(self, b: Box): + self._boxes.append(b) + + def sum_areas(self) -> int: + area = 0 + for b in self._boxes: + area += b.area() + return area + + def containing_box(self) -> Box: + width, height = 0, 0 + for b in self._boxes: + w, h = b.dimensions() + height += h + if w > width: + width = w + return Box(width, height) + +def main(): + line = BoxLine() + w = int(input('w? ')) + h = int(input('h? ')) + while w > 0 and h > 0: + b = Box(w, h) + line.add_box(b) + w = int(input('w? ')) + h = int(input('h? ')) + box = line.containing_box() + area = line.sum_areas() + print('Sum of areas:', area) + print('Containing box:', box.dimensions()) + print('Wasted space (ratio):', 1 - area / box.area()) + +if __name__ == '__main__': + main() diff --git a/code/train/Python/0099660_test_ryu_db.py b/code/train/Python/0099660_test_ryu_db.py new file mode 100644 index 0000000000000000000000000000000000000000..c93a8b15f9f5bda6eb6b71c67400e1863bca58f7 --- /dev/null +++ b/code/train/Python/0099660_test_ryu_db.py @@ -0,0 +1,60 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 +# +# Copyright 2012 Isaku Yamahata +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from contextlib import nested +import operator + +from quantum.db import api as db +from quantum.openstack.common import cfg +# NOTE: this import is needed for correct plugin code work +from quantum.plugins.ryu.common import config +from quantum.plugins.ryu.db import api_v2 as db_api_v2 +from quantum.plugins.ryu.db import models_v2 as ryu_models_v2 +from quantum.tests.unit import test_db_plugin as test_plugin + + +class RyuDBTest(test_plugin.QuantumDbPluginV2TestCase): + @staticmethod + def _tunnel_key_sort(key_list): + key_list.sort(key=operator.attrgetter('tunnel_key')) + return [(key.network_id, key.tunnel_key) for key in key_list] + + def test_key_allocation(self): + tunnel_key = db_api_v2.TunnelKey() + session = db.get_session() + with nested(self.network('network-0'), + self.network('network-1') + ) as (network_0, + network_1): + network_id0 = network_0['network']['id'] + key0 = tunnel_key.allocate(session, network_id0) + network_id1 = network_1['network']['id'] + key1 = tunnel_key.allocate(session, network_id1) + key_list = tunnel_key.all_list() + self.assertEqual(len(key_list), 2) + + expected_list = [(network_id0, key0), (network_id1, key1)] + self.assertEqual(self._tunnel_key_sort(key_list), + expected_list) + + tunnel_key.delete(session, network_id0) + key_list = tunnel_key.all_list() + self.assertEqual(self._tunnel_key_sort(key_list), + [(network_id1, key1)]) + + tunnel_key.delete(session, network_id1) + self.assertEqual(tunnel_key.all_list(), []) diff --git a/code/train/Python/0099843_ipcserver.py b/code/train/Python/0099843_ipcserver.py new file mode 100644 index 0000000000000000000000000000000000000000..51ba2ccefad62d354648bc2079d08d4df13c5031 --- /dev/null +++ b/code/train/Python/0099843_ipcserver.py @@ -0,0 +1,203 @@ +import socket, threading, select +import greensd.logger +from greensd.constants import IPC_SERVER_PORT, IPC_DELIMITER, LIVE_SESSION_INIT, LIVE_SESSION_ERROR + +#******************************************************* +# IPC Server Class +#******************************************************* +class IPCSrv(threading.Thread): + + #******************************************************* + # init() + # create socket, pollobj,... + #******************************************************* + def __init__(self, controller): + + self.controller = controller + self.connections = {} + self.liveID = -1 + + threading.Thread.__init__(self) + self.setDaemon(True) + + def listen(self): + + try: + self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.s.setblocking(0) + self.s.bind(("localhost", IPC_SERVER_PORT)) + self.s.listen(5) + + self.running = True + self.pollobj = select.poll() + self.pollobj.register(self.s, select.POLLIN) + + except Exception: + greensd.logger.logError("Couldn't open IPC server socket") + self.running = False + + #******************************************************* + # stop() + # send the shutdown command to client and close all sockets + #******************************************************* + def stop(self): + try: + #self.sendMsg("quit"); # give the client the command to terminate the connection + for conn in self.connections.keys(): + self.connections[conn].close() + self.pollobj.unregister(self.s) + self.s.close() + self.running = False + except Exception: + greensd.logger.logError("Couldn't terminate IPC Server") + return + + #******************************************************* + # sendMsg(msg) + # send a msg (live session) + #******************************************************* + def sendMsg(self, msg): + + if not msg: + return + + try: + if self.liveID != -1: + self.connections[self.liveID].send(str(msg) + IPC_DELIMITER) + except Exception: + greensd.logger.logError("Couldn't send IPC message") + return + + #******************************************************* + # Thread run() + #******************************************************* + def run(self): + + # init socket, listen + self.listen() + + while self.running: + + try: + + events = self.pollobj.poll() + + for sock, event in events: + + if event == select.POLLIN or event == select.POLLPRI: + + # new connection? + if sock == self.s.fileno(): + conn, addr = self.s.accept() + self.connections[conn.fileno()] = IPCConn(conn, self.pollobj, self.controller) + + else: + # read and dispatch commands + if self.connections[sock].read(): + # a live session has been requested... + if self.liveID == -1: + # accept live session + self.liveID = sock + self.connections[sock].send(LIVE_SESSION_INIT + IPC_DELIMITER) + else: + # only one live session allowed + self.connections[sock].send(LIVE_SESSION_ERROR + IPC_DELIMITER) + self.connections[sock].close() + del self.connections[sock] + continue + + if self.connections[sock].isEOF: + if sock == self.liveID: + self.liveID = -1 + del self.connections[sock] + + + except Exception: + greensd.logger.logWarning("Closing IPC server due to exception in main loop") + greensd.logger.logError("IPC main loop Exception") + return + + # clear the connections list + self.connections.clear() + + +#******************************************************* +# Connection Class +# contains the data for one connection +#******************************************************* +class IPCConn: + + #******************************************************* + # init this connection, + # register socket at global pollobj + #******************************************************* + def __init__(self, sock, pollobj, controller): + self.socket = sock + self.pollobj = pollobj + self.data = '' + self.controller = controller + self.isEOF = False + self.isLiveSession = False + + self.pollobj.register(self.socket, select.POLLIN) + + #******************************************************* + # return fileno of the connections socket + #******************************************************* + def fileno(self): + return self.socket.fileno() + + #******************************************************* + # read and parse data from the socket + #******************************************************* + def read(self): + + # read data + buf = self.socket.recv(1024) + + # has the connection been closed by the client? + if buf == '': + self.isEOF = True + self.close() + return False + + self.data += buf + + # End of command? + if self.data.endswith(IPC_DELIMITER): + self.data = self.data.split(IPC_DELIMITER)[0] + self.data.strip() + + # is a live session used? + if self.isLiveSession == False and self.data == "live": + self.data = '' + self.isLiveSession = True + return True + + # send this command to the daemon + self.controller.dispatchIPCCommand(self.data) + self.data = '' + + return False + + #******************************************************* + # write data to the socket + #******************************************************* + def send(self, data): + try: + self.socket.send(data) + except: + pass + + #******************************************************* + # close this connection + #******************************************************* + def close(self): + self.pollobj.unregister(self.socket) + self.socket.close() + + + + + diff --git a/code/train/Python/0099894_xpay_client.py b/code/train/Python/0099894_xpay_client.py new file mode 100644 index 0000000000000000000000000000000000000000..c71c09de60b3bf93b1fee185b714890144df4a99 --- /dev/null +++ b/code/train/Python/0099894_xpay_client.py @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- + +from django.conf import settings +import logging +from config_uplus import * +from xpay_context import Context + +logger = logging.getLogger(__name__) + +class XPayClient(object): + def __init__(self, is_test=True): + """Initialize xpay client. + + Args: + home_dir: (string) Path where configuration files are stored + mode: (string) Mode of operation (test/service) + """ + self._is_test = is_test + self._response_code = None + self._response_message = None + self._mid = LGUPLUS_MID + + def init_tx(self): + self._context = Context(self._mid) + + def set(self, key, value): + self._context.set(key, value) + + def TX(self): + # Initialize variables + is_success = False + is_rollback = False + is_reporting = False + rollback_on_error = auto_rollback + report_on_error = report_error + + # (reports) + report_status = None + report_message = None + rollback_reason = None + + context_success = self._context.TX(self.URL) + if not context_success: + is_rollback = True + elif (self._context.status < 200 or + self._context.status >= 300): + self._response_code = 30000 + self._context.status + self._response_message = u"HTTP response code = {response_code}".format(response_code=self._context.status) + + logger.error(u"[%s] TX failed: response code = %s, response message = %d", + self.tx_id, self._response_code, self._response_message) + + report_status = u"HTTP response {response_code}".format(response_code=self._context.status) + report_message = self._context.body + + if report_on_error: + is_rollback = True + rollback_reason = u"HTTP {response_code}".format(response_code=self._context.status) + + is_reporting = True + elif self._context.is_json: + is_success = True + self._response_code = self._context.response_code + self._response_message = self._context.response_message + elif rollback_on_error: + is_rollback = True + rollback_reason = u"JSON decode fail" + + if rollback_on_error and is_rollback: + new_context = Context(self._mid) + new_context.set("LGD_TXNAME", "Rollback") + new_context.set("LGD_RB_TXID", self.tx_id) + new_context.set("LGD_RB_REASON", rollback_reason) + new_context.TX(self.URL) + if report_on_error and is_reporting: + new_context = Context(self._mid) + new_context.set("LGD_TXNAME", "Report") + new_context.set("LGD_STATUS", report_status) + new_context.set("LGD_MSG", report_message) + new_context.TX(aux_url) + + return is_success + + def rollback(self, rollback_reason): + try: + new_context = Context(self._mid) + new_context.set("LGD_TXNAME", "Rollback") + new_context.set("LGD_RB_TXID", self.tx_id) + new_context.set("LGD_RB_REASON", rollback_reason) + is_success = new_context.TX(self.URL) + except: + is_success = False + + if not is_success: + logger.error("[%s] Rollback failed!", self.tx_id) + return is_success + + @property + def tx_id(self): + return self._context.tx_id + + @property + def URL(self): + if self._is_test: + url = test_url + else: + url = dacom_url + return url + + @property + def response_code(self): + return self._response_code + @property + def response_message(self): + return self._response_message + + @property + def response_names(self): + return self._context.response_names + @property + def response_name_count(self): + return self._context.response_name_count + @property + def response_array_count(self): + return self._context.response_array_count + + def response_name(self, idx): + return self._context.response_name(idx) + def response(self, name, idx=0): + return self._context.response(name, idx) + def response_with_default(self, name, default): + try: + response = self.response(name) + except: + response = default + return response + +#if __name__ == '__main__': +# xpay_client = XPayClient(is_test=True) +# xpay_client.init_tx() +# xpay_client.set("LGD_TXNAME", "Ping") +# xpay_client.set("LGD_DUMMY", "=+A\uAC00\uB098\uB2E4") +# xpay_client.set("LGD_RESULTCNT", "3"); +# xpay_client.TX() diff --git a/code/train/Python/0099923_sequence.py b/code/train/Python/0099923_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..5a24a63b0140620b9ffc7ef9621e00b903d986c3 --- /dev/null +++ b/code/train/Python/0099923_sequence.py @@ -0,0 +1,222 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Preprocessing utilities for sequence data. +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import random + +import numpy as np +from six.moves import range # pylint: disable=redefined-builtin + + +def pad_sequences(sequences, + maxlen=None, + dtype='int32', + padding='pre', + truncating='pre', + value=0.): + """Pads each sequence to the same length (length of the longest sequence). + + If maxlen is provided, any sequence longer + than maxlen is truncated to maxlen. + Truncation happens off either the beginning (default) or + the end of the sequence. + + Supports post-padding and pre-padding (default). + + Arguments: + sequences: list of lists where each element is a sequence + maxlen: int, maximum length + dtype: type to cast the resulting sequence. + padding: 'pre' or 'post', pad either before or after each sequence. + truncating: 'pre' or 'post', remove values from sequences larger than + maxlen either in the beginning or in the end of the sequence + value: float, value to pad the sequences to the desired value. + + Returns: + x: numpy array with dimensions (number_of_sequences, maxlen) + + Raises: + ValueError: in case of invalid values for `truncating` or `padding`, + or in case of invalid shape for a `sequences` entry. + """ + if not hasattr(sequences, '__len__'): + raise ValueError('`sequences` must be iterable.') + lengths = [] + for x in sequences: + if not hasattr(x, '__len__'): + raise ValueError('`sequences` must be a list of iterables. ' + 'Found non-iterable: ' + str(x)) + lengths.append(len(x)) + + num_samples = len(sequences) + if maxlen is None: + maxlen = np.max(lengths) + + # take the sample shape from the first non empty sequence + # checking for consistency in the main loop below. + sample_shape = tuple() + for s in sequences: + if len(s) > 0: # pylint: disable=g-explicit-length-test + sample_shape = np.asarray(s).shape[1:] + break + + x = (np.ones((num_samples, maxlen) + sample_shape) * value).astype(dtype) + for idx, s in enumerate(sequences): + if not len(s): # pylint: disable=g-explicit-length-test + continue # empty list/array was found + if truncating == 'pre': + trunc = s[-maxlen:] # pylint: disable=invalid-unary-operand-type + elif truncating == 'post': + trunc = s[:maxlen] + else: + raise ValueError('Truncating type "%s" not understood' % truncating) + + # check `trunc` has expected shape + trunc = np.asarray(trunc, dtype=dtype) + if trunc.shape[1:] != sample_shape: + raise ValueError( + 'Shape of sample %s of sequence at position %s is different from ' + 'expected shape %s' + % (trunc.shape[1:], idx, sample_shape)) + + if padding == 'post': + x[idx, :len(trunc)] = trunc + elif padding == 'pre': + x[idx, -len(trunc):] = trunc + else: + raise ValueError('Padding type "%s" not understood' % padding) + return x + + +def make_sampling_table(size, sampling_factor=1e-5): + """Generates a word rank-based probabilistic sampling table. + + This generates an array where the ith element + is the probability that a word of rank i would be sampled, + according to the sampling distribution used in word2vec. + + The word2vec formula is: + p(word) = min(1, sqrt(word.frequency/sampling_factor) / + (word.frequency/sampling_factor)) + + We assume that the word frequencies follow Zipf's law (s=1) to derive + a numerical approximation of frequency(rank): + frequency(rank) ~ 1/(rank * (log(rank) + gamma) + 1/2 - 1/(12*rank)) + where gamma is the Euler-Mascheroni constant. + + Arguments: + size: int, number of possible words to sample. + sampling_factor: the sampling factor in the word2vec formula. + + Returns: + A 1D Numpy array of length `size` where the ith entry + is the probability that a word of rank i should be sampled. + """ + gamma = 0.577 + rank = np.array(list(range(size))) + rank[0] = 1 + inv_fq = rank * (np.log(rank) + gamma) + 0.5 - 1. / (12. * rank) + f = sampling_factor * inv_fq + + return np.minimum(1., f / np.sqrt(f)) + + +def skipgrams(sequence, + vocabulary_size, + window_size=4, + negative_samples=1., + shuffle=True, + categorical=False, + sampling_table=None): + """Generates skipgram word pairs. + + Takes a sequence (list of indexes of words), + returns couples of [word_index, other_word index] and labels (1s or 0s), + where label = 1 if 'other_word' belongs to the context of 'word', + and label=0 if 'other_word' is randomly sampled + + Arguments: + sequence: a word sequence (sentence), encoded as a list + of word indices (integers). If using a `sampling_table`, + word indices are expected to match the rank + of the words in a reference dataset (e.g. 10 would encode + the 10-th most frequently occuring token). + Note that index 0 is expected to be a non-word and will be skipped. + vocabulary_size: int. maximum possible word index + 1 + window_size: int. actually half-window. + The window of a word wi will be [i-window_size, i+window_size+1] + negative_samples: float >= 0. 0 for no negative (=random) samples. + 1 for same number as positive samples. etc. + shuffle: whether to shuffle the word couples before returning them. + categorical: bool. if False, labels will be + integers (eg. [0, 1, 1 .. ]), + if True labels will be categorical eg. [[1,0],[0,1],[0,1] .. ] + sampling_table: 1D array of size `vocabulary_size` where the entry i + encodes the probabibily to sample a word of rank i. + + Returns: + couples, labels: where `couples` are int pairs and + `labels` are either 0 or 1. + + # Note + By convention, index 0 in the vocabulary is + a non-word and will be skipped. + """ + couples = [] + labels = [] + for i, wi in enumerate(sequence): + if not wi: + continue + if sampling_table is not None: + if sampling_table[wi] < random.random(): + continue + + window_start = max(0, i - window_size) + window_end = min(len(sequence), i + window_size + 1) + for j in range(window_start, window_end): + if j != i: + wj = sequence[j] + if not wj: + continue + couples.append([wi, wj]) + if categorical: + labels.append([0, 1]) + else: + labels.append(1) + + if negative_samples > 0: + num_negative_samples = int(len(labels) * negative_samples) + words = [c[0] for c in couples] + random.shuffle(words) + + couples += [[words[i % len(words)], random.randint(1, vocabulary_size - 1)] + for i in range(num_negative_samples)] + if categorical: + labels += [[1, 0]] * num_negative_samples + else: + labels += [0] * num_negative_samples + + if shuffle: + seed = random.randint(0, 10e6) + random.seed(seed) + random.shuffle(couples) + random.seed(seed) + random.shuffle(labels) + + return couples, labels diff --git a/code/train/Python/0100205_Algorithm-2017-09-11.py b/code/train/Python/0100205_Algorithm-2017-09-11.py new file mode 100644 index 0000000000000000000000000000000000000000..0d91e6b49b39cb08e095e55d7b578f3bcadc4e20 --- /dev/null +++ b/code/train/Python/0100205_Algorithm-2017-09-11.py @@ -0,0 +1,131 @@ +# Algorithm-2017-09-11.py + + +# coding: utf-8 + +# In[ ]: + +import pandas as pd +import numpy as np +from pprint import pprint +import math +from utils import import_net, export_net +from time import time + + +# In[ ]: + +def sort_nodes(t): + v = t[1] + return -v[0], -v[1] + +def BFS(graph, start): + """ André, please clarify: + + this code is adding +1 to the second counter + if the node connected by an outgoing edge + also has an outgoing edge going back to the parent node + + is this what we were looking for? + my understanding is that we wanted to count the number of incoming nodes, + regardless of its origin + """ + + queue = list() + output = dict() + visited = set() + queue.append(start) + while queue: + node = queue.pop(0) + visited.add(node) + if node in output: + output[node][0] = len(graph[node]) + else: + output[node] = [len(graph[node]), 0] + for adjacent in graph[node]: + # check logic of next two lines + if adjacent in output: + output[adjacent][1] += 1; + else: + output[adjacent] = [0, 1]; + if adjacent not in visited: + visited.add(adjacent) + if adjacent in graph: + queue.append(adjacent) + + return sorted(output.items(), key=sort_nodes), visited + + +# In[ ]: + +def sort_forests(f): + return -len(f) + +def alg(network, all_nodes): + """ Run BFS for the entire network """ + + num_nodes = len(all_nodes) + output = {} + visited_nodes = set() + for node in all_nodes: + if node not in visited_nodes: + forest, visited = BFS(network, node) + visited_nodes.update(visited) + + # calcular score + forest_size = len(forest) + for node in forest: + node_id = node[0] + num_incoming_nodes = node[1][0] + num_outgoing_nodes = node[1][1] + score = (num_incoming_nodes+num_outgoing_nodes) * forest_size / num_nodes + if node_id not in output: + output[node_id] = score + else: + output[node_id] += score + forest_size -= 1 + + return sorted(output.items(), key=lambda x:-x[1]) + + +# In[ ]: + +### ALTERNATIVE: RUN THIS TO TEST +network = { 'A': ['B', 'C'], + 'B': ['A', 'C'], + 'C': ['B', 'D', 'E' ,'F'], + 'D': ['E'], + 'E': ['C'], + 'F': ['B', 'D'], + 'G': ['H', 'I','C'], + 'H': ['G'], + 'I': ['G', 'J']} + +all_nodes = ['A', 'B', 'C', 'D', 'E', + 'F', 'G', 'H', 'I', 'J'] + +# results = alg(network, all_nodes) +# pprint(results) + +## ON REAL DATA +first = True +for ftype in ['real','model']: +# for ftype in ['real']: + for i in range(1,5): + t0 = time() + network_name = ftype+str(i) + network, all_nodes = import_net(network_name) + results = alg(network, all_nodes) + + print('Nodes in results: ' + str(len(results))) + print("Run-time (in minutes): " + str(int((time()-t0)/60))) + + if first: + export_net(results, network_name, 'results-full-v4.csv', first=True) + first = False + else: + export_net(results, network_name, 'results-full-v4.csv', first=False) + + + + diff --git a/code/train/Python/0100288_relationships.py b/code/train/Python/0100288_relationships.py new file mode 100644 index 0000000000000000000000000000000000000000..6b7aec456ab6fb8ebe549be047f88d540fb217ea --- /dev/null +++ b/code/train/Python/0100288_relationships.py @@ -0,0 +1,53 @@ +# Make CSV files with nodes and edges to explore relationships between reasons. + +import csv +from pymongo import MongoClient +from credentials import MONGOLAB_URL +import datetime + +harvest_date = datetime.datetime(2016, 1, 1) + + +def get_db(): + dbclient = MongoClient(MONGOLAB_URL) + db = dbclient.get_default_database() + return db + + +def get_reasons(): + db = get_db() + agg = db.aggregates.find_one({'harvest_date': harvest_date, 'agg_type': 'reason_totals'}) + reasons = [reason['reason'] for reason in agg['results']] + return reasons + + +def get_edges(source, targets): + edges = [] + for target in targets: + edges.append([source, target, 'Undirected']) + return edges + + +def make_edges(): + db = get_db() + reasons = get_reasons() + for item in db.items.find({'harvests': harvest_date}): + edges = [] + nodes = [reasons.index(reason) for reason in item['reasons']] + while len(nodes) > 1: + source = nodes[0] + nodes.pop(0) + edges += get_edges(source, nodes) + if edges: + with open('edges.csv', 'ab') as edges_csv: + csv_writer = csv.writer(edges_csv) + for edge in edges: + csv_writer.writerow(edge) + + +def make_nodes(): + reasons = get_reasons() + with open('nodes.csv', 'wb') as nodes_csv: + csv_writer = csv.writer(nodes_csv) + for index, reason in enumerate(reasons): + csv_writer.writerow([index, reason]) diff --git a/code/train/Python/0100649_build-idnadata.py b/code/train/Python/0100649_build-idnadata.py new file mode 100644 index 0000000000000000000000000000000000000000..b85d7f59cd494a22e498fffc7b6e0686af9e8f8c --- /dev/null +++ b/code/train/Python/0100649_build-idnadata.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python + +from __future__ import print_function + +try: + from urllib.request import urlopen +except ImportError: + from urllib2 import urlopen +import xml.etree.ElementTree as etree + +SCRIPTS_URL = "http://www.unicode.org/Public/UNIDATA/Scripts.txt" +JOININGTYPES_URL = "http://www.unicode.org/Public/UNIDATA/ArabicShaping.txt" +IDNATABLES_URL = "http://www.iana.org/assignments/idna-tables-{version}/idna-tables-{version}.xml" +IDNATABLES_NS = "http://www.iana.org/assignments" + + +def print_optimised_list(d): + + codepoint_list = sorted(d) + set_elements = [] + last_write = -1 + for i in range(0, len(codepoint_list)): + if i+1 < len(codepoint_list): + if codepoint_list[i] == codepoint_list[i+1]-1: + continue + codepoint_range = codepoint_list[last_write+1:i+1] + if len(codepoint_range) == 1: + set_elements.append("[{0}]".format(hex(codepoint_range[0]))) + else: + set_elements.append("list(range({0},{1}))".format(hex(codepoint_range[0]), hex(codepoint_range[-1]+1))) + last_write = i + + print("frozenset(") + print(" " + " +\n ".join(set_elements)) + print(" ),") + + +def build_idnadata(version): + + print("# This file is automatically generated by build-idnadata.py\n") + + # + # Script classifications are used by some CONTEXTO rules in RFC 5891 + # + print("scripts = {") + scripts = {} + for line in urlopen(SCRIPTS_URL).readlines(): + line = line.decode('utf-8') + line = line.strip() + if not line or line[0] == '#': + continue + if line.find('#'): + line = line.split('#')[0] + (codepoints, scriptname) = [x.strip() for x in line.split(';')] + if not scriptname in scripts: + scripts[scriptname] = set() + if codepoints.find('..') > 0: + (begin, end) = [int(x, 16) for x in codepoints.split('..')] + for cp in range(begin, end+1): + scripts[scriptname].add(cp) + else: + scripts[scriptname].add(int(codepoints, 16)) + + for script in sorted(scripts): + print(" '{0}':".format(script), end=' ') + print_optimised_list(scripts[script]) + + print("}") + + # + # Joining types are used by CONTEXTJ rule A.1 + # + print("joining_types = {") + scripts = {} + for line in urlopen(JOININGTYPES_URL).readlines(): + line = line.decode('utf-8') + line = line.strip() + if not line or line[0] == '#': + continue + (codepoint, name, joiningtype, group) = [x.strip() for x in line.split(';')] + print(" {0}: '{1}',".format(hex(int(codepoint, 16)), joiningtype)) + print("}") + + # + # These are the classification of codepoints into PVALID, CONTEXTO, CONTEXTJ, etc. + # + print("codepoint_classes = {") + classes = {} + + namespace = "{{{0}}}".format(IDNATABLES_NS) + idntables_data = urlopen(IDNATABLES_URL.format(version=version)).read() + root = etree.fromstring(idntables_data) + + for record in root.findall('{0}registry[@id="idna-tables-properties"]/{0}record'.format(namespace)): + codepoint = record.find("{0}codepoint".format(namespace)).text + prop = record.find("{0}property".format(namespace)).text + if prop == 'UNASSIGNED': + continue + if not prop in classes: + classes[prop] = set() + if codepoint.find('-') > 0: + (begin, end) = [int(x, 16) for x in codepoint.split('-')] + for cp in range(begin, end+1): + classes[prop].add(cp) + else: + classes[prop].add(int(codepoint, 16)) + + for prop in classes: + print(" '{0}':".format(prop), end=' ') + print_optimised_list(classes[prop]) + + print("}") + + +build_idnadata('6.3.0') + diff --git a/code/train/Python/0100881_augmented_hessian.py b/code/train/Python/0100881_augmented_hessian.py new file mode 100644 index 0000000000000000000000000000000000000000..22b26a765ede6662e91ac5aed5d34b7cb645abf5 --- /dev/null +++ b/code/train/Python/0100881_augmented_hessian.py @@ -0,0 +1,175 @@ +# +# @BEGIN LICENSE +# +# Psi4: an open-source quantum chemistry software package +# +# Copyright (c) 2007-2022 The Psi4 Developers. +# +# The copyrights for code used from other parties are included in +# the corresponding files. +# +# This file is part of Psi4. +# +# Psi4 is free software; you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, version 3. +# +# Psi4 is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License along +# with Psi4; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# +# @END LICENSE +# + +import os + +import numpy as np + +from psi4 import core +from psi4.driver import p4util +from psi4.driver.p4util.exceptions import * + + +def ah_iteration(mcscf_obj, tol=1e-3, max_iter=15, lindep=1e-14, print_micro=True): + """ + Solve the generalized eigenvalue problem: + | 0, g.T | | 1/l | = | 1/l | + | g, H/l | | X | = e | X | + + Where g is the gradient, H is the orbital Hessian, X is our orbital update step, + and l is the eigenvalue. + + In some ways this is the subspace reduction of the full MCSCF Hessian where the + CC part has been solved exactly. When this occurs the OC and CO elements collapse + to the above and the CC Hessian becomes diagonally dominant. + + We can solve this through Davidson iterations where we condition the edges. It's the + Pulay equations all over again, just iterative. + + Watch out for lambdas that are zero. Looking for the lambda that is ~1. + + """ + + # Unpack information + orb_grad = mcscf_obj.gradient() + precon = mcscf_obj.H_approx_diag() + approx_step = mcscf_obj.approx_solve() + orb_grad_ssq = orb_grad.sum_of_squares() + + # Gears + min_lambda = 0.3 + converged = False + warning_neg = False + warning_mult = False + + fullG = np.zeros((max_iter + 2, max_iter + 2)) + fullS = np.zeros((max_iter + 2, max_iter + 2)) + fullS[np.diag_indices_from(fullS)] = 1 + + guesses = [] + sigma_list = [] + guesses.append(approx_step) + sigma_list.append(mcscf_obj.compute_Hk(approx_step)) + + if print_micro: + core.print_out("\n Eigenvalue Rel dE dX \n") + + # Run Davidson look for lambda ~ 1 + old_val = 0 + for microi in range(1, max_iter + 1): + + # Gradient + fullG[0, microi] = guesses[-1].vector_dot(orb_grad) + for i in range(microi): + fullG[i + 1, microi] = guesses[-1].vector_dot(sigma_list[i]) + fullS[i + 1, microi] = guesses[-1].vector_dot(guesses[i]) + + fullG[microi] = fullG[:, microi] + fullS[microi] = fullS[:, microi] + + wlast = old_val + + # Slice out relevant S and G + S = fullS[:microi + 1, :microi + 1] + G = fullG[:microi + 1, :microi + 1] + + # Solve Gv = lSv + v, L = np.linalg.eigh(S) + mask = v > (np.min(np.abs(v)) * 1.e-10) + invL = L[:, mask] * (v[mask]**-0.5) + + # Solve in S basis, rotate back + evals, evecs = np.linalg.eigh(np.dot(invL.T, G).dot(invL)) + vectors = np.dot(invL, evecs) + + # Figure out the right root to follow + if np.sum(np.abs(vectors[0]) > min_lambda) == 0: + raise PsiException("Augmented Hessian: Could not find the correct root!\n" + "Try starting AH when the MCSCF wavefunction is more converged.") + + if np.sum(np.abs(vectors[0]) > min_lambda) > 1 and not warning_mult: + core.print_out(r" Warning! Multiple eigenvectors found to follow. Following closest to \lambda = 1.\n") + warning_mult = True + + idx = (np.abs(1 - np.abs(vectors[0]))).argmin() + lam = abs(vectors[0, idx]) + subspace_vec = vectors[1:, idx] + + # Negative roots should go away? + if idx > 0 and evals[idx] < -5.0e-6 and not warning_neg: + core.print_out(' Warning! AH might follow negative eigenvalues!\n') + warning_neg = True + + diff_val = evals[idx] - old_val + old_val = evals[idx] + + new_guess = guesses[0].clone() + new_guess.zero() + for num, c in enumerate(subspace_vec / lam): + new_guess.axpy(c, guesses[num]) + + # Build estimated sigma vector + new_dx = sigma_list[0].clone() + new_dx.zero() + for num, c in enumerate(subspace_vec): + new_dx.axpy(c, sigma_list[num]) + + # Consider restraints + new_dx.axpy(lam, orb_grad) + new_dx.axpy(old_val * lam, new_guess) + + norm_dx = (new_dx.sum_of_squares() / orb_grad_ssq)**0.5 + + if print_micro: + core.print_out(" AH microiter %2d % 18.12e % 6.4e % 6.4e\n" % (microi, evals[idx], + diff_val / evals[idx], norm_dx)) + + if abs(old_val - wlast) < tol and norm_dx < (tol**0.5): + converged = True + break + + # Apply preconditioner + tmp = precon.clone() + val = tmp.clone() + val.set(evals[idx]) + tmp.subtract(val) + new_dx.apply_denominator(tmp) + + guesses.append(new_dx) + sigma_list.append(mcscf_obj.compute_Hk(new_dx)) + + if print_micro and converged: + core.print_out("\n") + # core.print_out(" AH converged! \n\n") + + #if not converged: + # core.print_out(" !Warning. Augmented Hessian did not converge.\n") + + new_guess.scale(-1.0) + + return converged, microi, new_guess diff --git a/code/train/Python/0101185_latticeResample.py b/code/train/Python/0101185_latticeResample.py new file mode 100644 index 0000000000000000000000000000000000000000..be594201e692cba930340739eab7d48425911952 --- /dev/null +++ b/code/train/Python/0101185_latticeResample.py @@ -0,0 +1,195 @@ +#*************************************************************************** +#* * +#* Copyright (c) 2015 - Victor Titov (DeepSOIC) * +#* * +#* * +#* This program is free software; you can redistribute it and/or modify * +#* it under the terms of the GNU Lesser General Public License (LGPL) * +#* as published by the Free Software Foundation; either version 2 of * +#* the License, or (at your option) any later version. * +#* for detail see the LICENCE text file. * +#* * +#* This program is distributed in the hope that it will be useful, * +#* but WITHOUT ANY WARRANTY; without even the implied warranty of * +#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +#* GNU Library General Public License for more details. * +#* * +#* You should have received a copy of the GNU Library General Public * +#* License along with this program; if not, write to the Free Software * +#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +#* USA * +#* * +#*************************************************************************** + +__title__="Lattice Resample object: changes the number of placements in an array, maintaining overall path. Aka interpolation." +__author__ = "DeepSOIC" +__url__ = "" + +import math + +import FreeCAD as App +import Part + +from latticeCommon import * +import latticeBaseFeature +import latticeCompoundExplorer as LCE +import latticeInterpolatorUtil as LIU +import latticeExecuter + +# -------------------------- document object -------------------------------------------------- + +def dotProduct(list1,list2): + sum = 0 + for i in range(0,len(list1)): + sum += list1[i]*list2[i] + return sum + +def makeLatticeResample(name): + '''makeLatticeResample(name): makes a LatticeResample object.''' + return latticeBaseFeature.makeLatticeFeature(name, LatticeResample, ViewProviderLatticeResample) + +class LatticeResample(latticeBaseFeature.LatticeFeature): + "The Lattice Resample object" + + def derivedInit(self,obj): + self.Type = "LatticeResample" + + obj.addProperty("App::PropertyLink","Base","Lattice Resample","Lattice, the array of placements to be interpolated.") + + obj.addProperty("App::PropertyEnumeration","TranslateMode","Lattice Resample","What to do with translation part of placements") + obj.TranslateMode = ['interpolate', 'reset'] + obj.TranslateMode = 'interpolate' + + obj.addProperty("App::PropertyEnumeration","OrientMode","Lattice Resample","what to do with orientation part of placements") + obj.OrientMode = ['interpolate', 'reset'] + obj.OrientMode = 'interpolate' + + obj.addProperty("App::PropertyFloat","NumberSamples","Lattice Resample","Number of placements to generate") + obj.NumberSamples = 51 + + def derivedExecute(self,obj): + # cache stuff + base = obj.Base.Shape + if not latticeBaseFeature.isObjectLattice(obj.Base): + latticeExecuter.warning(obj, "Base is not a lattice, but lattice is expected. Results may be unexpected.\n") + input = [leaf.Placement for leaf in LCE.AllLeaves(base)] + + if len(input) < 2: + raise ValueError("At least 2 placements ar needed to interpolate; there are just "+str(len(input))+" in base array.") + if obj.NumberSamples < 2: + raise ValueError("Can output no less than 2 samples; "+str(obj.NumberSamples)+" was requested.") + + #cache mode comparisons, for speed + posIsInterpolate = obj.TranslateMode == 'interpolate' + posIsReset = obj.TranslateMode == 'reset' + + oriIsInterpolate = obj.OrientMode == 'interpolate' + oriIsReset = obj.OrientMode == 'reset' + + # construct interpolation functions + # prepare lists of input samples + IArray = [float(i) for i in range(0,len(input))] + XArray = [plm.Base.x for plm in input] + YArray = [plm.Base.y for plm in input] + ZArray = [plm.Base.z for plm in input] + QArrays = [[],[],[],[]] + prevQ = [0.0]*4 + for plm in input: + Q = plm.Rotation.Q + #test if quaernion has changed sign compared to previous one. + # Quaternions of opposite sign are equivalent in terms of rotation, + # but sign changes confuse interpolation, so we are detecting sign + # changes and discarding them + if dotProduct(Q,prevQ) < -ParaConfusion: + Q = [-v for v in Q] + for iQ in [0,1,2,3]: + QArrays[iQ].append( Q[iQ] ) + prevQ = Q + + # constuct function objects + if posIsInterpolate: + FX = LIU.InterpolateF(IArray,XArray) + FY = LIU.InterpolateF(IArray,YArray) + FZ = LIU.InterpolateF(IArray,ZArray) + if oriIsInterpolate: + FQs = [] + for iQ in [0,1,2,3]: + FQs.append(LIU.InterpolateF(IArray,QArrays[iQ])) + + # initialize output containers and loop variables + outputPlms = [] #list of placements + + for i_output in range(0,math.trunc(obj.NumberSamples+ParaConfusion)): + i_input = float(i_output) / (obj.NumberSamples-1) * (len(input)-1) + pos = App.Vector() + ori = App.Rotation() + if posIsInterpolate: + pos = App.Vector(FX.value(i_input), FY.value(i_input), FZ.value(i_input)) + + if oriIsInterpolate: + ori = App.Rotation(FQs[0].value(i_input), + FQs[1].value(i_input), + FQs[2].value(i_input), + FQs[3].value(i_input)) + plm = App.Placement(pos, ori) + outputPlms.append(plm) + return outputPlms + + +class ViewProviderLatticeResample(latticeBaseFeature.ViewProviderLatticeFeature): + + def getIcon(self): + return getIconPath('Lattice_Resample.svg') + + def claimChildren(self): + return [self.Object.Base] + + +# -------------------------- /document object -------------------------------------------------- + +# -------------------------- Gui command -------------------------------------------------- + +def CreateLatticeResample(name): + sel = FreeCADGui.Selection.getSelectionEx() + FreeCAD.ActiveDocument.openTransaction("Create LatticeResample") + FreeCADGui.addModule("latticeResample") + FreeCADGui.addModule("latticeExecuter") + FreeCADGui.doCommand("f = latticeResample.makeLatticeResample(name='"+name+"')") + FreeCADGui.doCommand("f.Base = App.ActiveDocument."+sel[0].ObjectName) + FreeCADGui.doCommand("for child in f.ViewObject.Proxy.claimChildren():\n"+ + " child.ViewObject.hide()") + FreeCADGui.doCommand("latticeExecuter.executeFeature(f)") + FreeCADGui.doCommand("f = None") + FreeCAD.ActiveDocument.commitTransaction() + + +class _CommandLatticeResample: + "Command to create LatticeResample feature" + def GetResources(self): + return {'Pixmap' : getIconPath("Lattice_Resample.svg"), + 'MenuText': QtCore.QT_TRANSLATE_NOOP("Lattice_Resample","Resample Array"), + 'Accel': "", + 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Lattice_Resample","Lattice Resample: interpolate placement-path using 3-rd degree b-spline interpolation.")} + + def Activated(self): + if len(FreeCADGui.Selection.getSelection()) == 1 : + CreateLatticeResample(name = "Resample") + else: + mb = QtGui.QMessageBox() + mb.setIcon(mb.Icon.Warning) + mb.setText(translate("Lattice_Resample", "Please select one object, first. The object must be a lattice object (array of placements).", None)) + mb.setWindowTitle(translate("Lattice_Resample","Bad selection", None)) + mb.exec_() + + def IsActive(self): + if FreeCAD.ActiveDocument: + return True + else: + return False + +FreeCADGui.addCommand('Lattice_Resample', _CommandLatticeResample()) + +exportedCommands = ['Lattice_Resample'] + +# -------------------------- /Gui command -------------------------------------------------- + diff --git a/code/train/Python/0101549_stages.py b/code/train/Python/0101549_stages.py new file mode 100644 index 0000000000000000000000000000000000000000..21fc86d9260e5b488371ba1645f1edcb7df694d7 --- /dev/null +++ b/code/train/Python/0101549_stages.py @@ -0,0 +1,151 @@ +# +# MPowerTCX: Share Schwinn A.C. indoor cycle data with Strava, GoldenCheetah and other apps +# Copyright (C) 2017 James Roth +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# + +from . import bikes + + +class Stages(bikes.Bike): + def load(self, peek, reader): + if peek[0] == 'Stages_Data': + self._load(reader) + return True + + # Headerless file + # 0:01,0,18.18,121,0,95 + all_floats = True + + if len(peek) == 6 and ':' in peek[0]: + for f in peek[1:]: + try: + float(f) + except ValueError: + all_floats = False + break + + if all_floats: + self._load(reader) + return True + + return False + + def name(self): + return "Stages" + + def _distance_to_float(self, dist): + # Some strange quirk in Stages firmware? + if dist.startswith(':'): + dist = '10' + dist[1:] + + return float(dist) + + def _load(self, reader): + self.metric = True + distance = 0.0 + header_found = False + last_time = 0 + + for row in reader: + if row == []: + pass + elif row[0] == 'English': + self.metric = False + elif row[0] == 'Ride_Totals': + self._load_header(reader) + header_found = True + elif len(row) >= 6: + time = self._parse_time(row[0]) + + if last_time > 0 and time - last_time > 1: + print("time warp %f %f %r" % (time, last_time, row[0])) + + last_time = time + + if time >= 0: + # ['Time', 'Miles', 'MPH', 'Watts', 'HR', 'RPM'] + # TODO: maybe use this method on all file formats. + # Infer distance from MPH. + distance += self._distance_to_float(row[2]) / (60.0 * 60.0) + + self.ride.add_sample( + power=row[3], + rpm=row[5], + hr=row[4], + distance=self.distance(distance) + ) + else: + self.skip(row) + else: + self.skip(row) + + if not header_found: + print("stages header missing") + self.ride.infer_header(last_time) + + def _load_header(self, reader): + header = {} + + for row in reader: + if len(row): + header[row[0]] = row[1] + else: + break + + parts = header['Time'].split(':') + h = 0 + m = 0 + s = 0 + + if len(parts) == 3: + h = int(parts[0]) + m = int(parts[1]) + s = int(parts[2]) + elif len(parts) == 2: + m = int(parts[0]) + s = int(parts[1]) + elif len(parts) == 2: + s = int(parts[0]) + + time = h * 60 * 60 + m * 60 + s + + self.ride.header.setSummary( + time=time, + distance=self.distance(self._distance_to_float(header["Distance"])), + average_power=header["Watts_Avg"], + max_power=header["Watts_Max"], + average_rpm=header["RPM_Avg"], + max_rpm=header["RPM_Max"], + average_hr=header["HR_Avg"], + max_hr=header["HR_Max"], + calories=header["KCal"] + ) + + def _parse_time(self, time): + # I've seen mm:ss or mm:ss:00 so far + parts = time.split(':') + + if len(parts) == 2 or len(parts) == 3: + try: + minutes = int(parts[0]) + seconds = int(parts[1]) + result = minutes * 60 + seconds + except: + result = -1 + else: + result = -1 + + return result diff --git a/code/train/Python/0101840_snap_reader.py b/code/train/Python/0101840_snap_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..2bb21dd2d076ba793811bd1d447658512705aa22 --- /dev/null +++ b/code/train/Python/0101840_snap_reader.py @@ -0,0 +1,234 @@ +import sys, os +import re +import numpy as np + +sys.path.append('/data/rab200/ChemoDrift/new/') +import DiscEvolution.chemistry as chem +from DiscEvolution.planet_formation import Planets + + +class DiscSnap(object): + + def __init__(self, filename, chem_on=False): + self.read(filename, chem_on) + + def read(self, filename, chem_on=False): + """Read disc data from file""" + # read the header + head = '' + vars = False + count = 0 + with open(filename) as f: + for line in f: + if not vars: + if not (line.startswith('# time') or line.startswith('# InternalEvaporation')): + head += line + elif line.startswith('# InternalEvaporation'): + # Get internal photoevaporation type + self._IPE = line.strip().split(',')[1].split(':')[-1] + print(self._IPE) + elif line.startswith('# time'): + vars = True + # Get the time + self._t = float(line.strip().split(':')[1][:-2]) + + count += 1 + continue + # Get data variables stored + vars = line[2:].split(' ') + assert(len(vars) % 2 == 1) + + # Get the number of dust species + Ndust = len([x for x in vars if x.startswith('epsilon')]) + + # If chemistry was used, get the number of chemical species + if chem_on: + Nchem = (len(vars) - 3 - 2*Ndust) / 2 + + iChem = 2*Ndust + 3 + chem_spec = vars[iChem:iChem + Nchem] + break + + # Parse the actual data: + data = np.genfromtxt(filename, skip_header=count, names=True) + Ndata = data.shape[0] + names = data.dtype.names + self._R = data['R'] + self._Sigma = data['Sigma'] + self._T = data['T'] + + self._eps = np.empty([Ndust, Ndata], dtype='f8') + self._a = np.empty([Ndust, Ndata], dtype='f8') + for i in range(Ndust): + self._eps[i] = data['epsilon{}'.format(i)] + self._a[i] = data['a{}'.format(i)] + + # Only if chemistry used + if chem_on: + if Nchem == 6: + self._chem = chem.MolecularIceAbund(chem.SimpleCOMolAbund(Ndata), + chem.SimpleCOMolAbund(Ndata)) + else: + raise AttributeError('Nchem = {}'.format(Nchem) + + '. Chemistry not recognized') + + for i in range(Nchem): + self._chem.gas.data[i] = data[names[iChem+i]] + self._chem.ice.data[i] = data[names[iChem+Nchem+i]] + + @property + def photo_type(self): + if hasattr(self,"_IPE"): + return self._IPE + else: + return None + @property + def time(self): + return self._t + @property + def R(self): + return self._R + @property + def Sigma(self): + return self._Sigma + @property + def T(self): + return self._T + @property + def dust_frac(self): + return self._eps + @property + def grain_size(self): + return self._a + @property + def chem(self): + return self._chem + +class PlanetSnap(object): + + def __init__(self, filename): + self.read(filename) + + + def read(self, filename): + """Read disc data from file""" + # read the header + head = '' + vars = False + count = 0 + with open(filename) as f: + for line in f: + if not vars: + if not line.startswith('# time'): + head += line + else: + vars = True + # Get the time + self._t = float(line.strip().split(':')[1][:-2]) + count += 1 + continue + # Get data variables stored + vars = line[2:].split(' ') + assert(len(vars) % 2 == 0) + + # Get the number of dust species + Nchem = (len(vars) - 4) / 2 + iChem = 4 + chem_spec = vars[iChem:iChem + Nchem] + break + + # Parse the actual data: + data = np.genfromtxt(filename, skip_header=count, names=True) + planets = Planets(Nchem) + planets.R = data['R'] + planets.M_core = data['M_core'] + planets.M_env = data['M_env'] + planets.t_form = data['t_form'] + planets._N = data.shape[0] + + + if Nchem: + assert(Nchem == 6 or Nchem == 8) + Ndata = data.shape[0] + planets.X_core = np.empty([Nchem, Ndata], dtype='f8') + planets.X_env = np.empty([Nchem, Ndata], dtype='f8') + + names = data.dtype.names + for i in range(Nchem): + planets.X_core[i] = data[names[iChem+i]] + planets.X_env[i] = data[names[iChem+Nchem+i]] + + self._planets = planets + + @property + def time(self): + return self._t + @property + def planets(self): + return self._planets + + +class Reader(object): + + def __init__(self, SnapType, DIR, base='*', chem_on=False): + self._SnapType = SnapType + self._DIR = DIR + self._chem_on = chem_on + + m = re.compile(r'^'+base+r'_\d\d\d\d.dat$') + self._files = [ f for f in os.listdir(DIR) if m.findall(f)] + + snaps = {} + Nmax = 0 + for f in self._files: + n = int(f[-8:-4]) + snaps[n] = os.path.join(self._DIR, f) + Nmax = max(n, Nmax) + self._snaps = snaps + self._Nmax = Nmax + + + def __getitem__(self, n): + return self._SnapType(self._snaps[n], self._chem_on) + + def filename(self, n): + return self._snaps[n] + + @property + def Num_Snaps(self): + return self._Nmax + + +class DiscReader(Reader): + """Read disc snaphshots from file""" + # By default assume no chemistry + def __init__(self, DIR, base='disc', chem_on=False): + super(DiscReader, self).__init__(DiscSnap, DIR, base, chem_on) + +class PlanetReader(Reader): + """Read disc snaphshots from file""" + def __init__(self, DIR, base='planets'): + super(PlanetReader, self).__init__(PlanetSnap, DIR, base) + + def compute_planet_evo(self): + """Compute the time evolution of each planet""" + planets = [] + times = [] + Np = 0 + for n in range(self.Num_Snaps): + try: + pf = self[n] + for i in range(pf.planets.N): + if i == Np: + try: + p = Planets(pf.planets[0].X_core.shape[0]) + except AttributeError: + p = Planets() + p.time = [] + planets.append(p) + Np += 1 + planets[i].append(pf.planets[i]) + planets[i].time = np.append(planets[i].time, pf.time) + except KeyError: + pass + return planets diff --git a/code/train/Python/0101951_status.py b/code/train/Python/0101951_status.py new file mode 100644 index 0000000000000000000000000000000000000000..3e88f6f4fc6a606a4501f324b7e85c82e4b2e449 --- /dev/null +++ b/code/train/Python/0101951_status.py @@ -0,0 +1,117 @@ + +from sedot import SEDOT_BASE +import os +import time +import rfc822 + +class NoStatusError(Exception): + def __init__(self, package, timestamp=None): + self.value = package + self.package = package + self.timestamp = timestamp + + def __str__(self): + print repr(self.value) + +class SyncStatus: + + def __init__(self, package, timestamp): + self.package = package + self.timestamp = timestamp + + self.data = {} + self.success = False + self.done = True + self.code = -1 + self.time = None + self.start = None + self.finish = None + self.status = -1 + + self._load() + + def _load(self): + global SEDOT_BASE + self.dir = os.path.join(SEDOT_BASE, "log", "sync", self.package, self.timestamp) + + if not os.path.isdir(self.dir): + raise NoStatusError(self.package, self.timestamp) + + try: + f = open(os.path.join(self.dir, "status.txt")) + except IOError: + raise NoStatusError(self.package, self.timestamp) + + for line in f.readlines(): + line = line.strip() + pos = line.find(" ") + + key = line[:pos] + val = line[pos+1:] + + self.data[key] = val + + if key == "status": + if val == "200": + self.success = True + elif val == "100": + self.done = False + self.status = int(val) + if key in 'time': + self.time = self._parse_time(val) + if key == 'start': + self.start = self._parse_time(val) + if key == 'finish': + self.finish = self._parse_time(val) + if key == 'code': + self.code = int(val) + + # Backward compatibility + if not self.time and self.finish: + self.time = self.finish + + def _parse_time(self, txt): + return rfc822.parsedate(txt) + +class PackageStatus: + + def __init__(self, package): + self.package = package + + self.success = None + self.last = None + + self._load() + + def _load(self): + global SEDOT_BASE + self.dir = os.path.join(SEDOT_BASE, "log", "sync", self.package) + + if not os.path.isdir(self.dir): + raise NoStatusError(self.package) + + # TODO: check for "current" symlink first. + dirs = os.listdir(self.dir) + dirs.sort(reverse=True) + + for timestamp in dirs: + + # Skip the "current" symbolic link + if os.path.islink(os.path.join(self.dir, timestamp)): + continue + + try: + status = SyncStatus(self.package, timestamp) + except NoStatusError: + continue + + if status.status == 301: # Unable to gain lock + continue + + if self.last == None: + self.last = status + + if status.success: + self.success = status + break + diff --git a/code/train/Python/0102096_main.py b/code/train/Python/0102096_main.py new file mode 100644 index 0000000000000000000000000000000000000000..3a90631371168c68d542d9821d30d8c467b97d49 --- /dev/null +++ b/code/train/Python/0102096_main.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +# encoding: utf-8 +# === This file is part of Calamares - === +# +# Copyright 2014, Aurélien Gâteau +# +# Calamares is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Calamares is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Calamares. If not, see . + +import os +import subprocess + +import libcalamares + + +def list_mounts(root_mount_point): + lst = [] + for line in open("/etc/mtab").readlines(): + device, mount_point, _ = line.split(" ", 2) + if mount_point.startswith(root_mount_point): + lst.append((device, mount_point)) + return lst + + +def run(): + root_mount_point = libcalamares.globalstorage.value("rootMountPoint") + if not root_mount_point: + return ("No mount point for root partition in globalstorage", + "globalstorage does not contain a \"rootMountPoint\" key, " + "doing nothing") + if not os.path.exists(root_mount_point): + return ("Bad mount point for root partition in globalstorage", + "globalstorage[\"rootMountPoint\"] is \"{}\", which does not " + "exist, doing nothing".format(root_mount_point)) + + lst = list_mounts(root_mount_point) + # Sort the list by mount point in decreasing order. This way we can be sure + # we unmount deeper dirs first. + lst.sort(key=lambda x: x[1], reverse=True) + + for device, mount_point in lst: + subprocess.check_call(["umount", mount_point]) + + os.rmdir(root_mount_point) + return None diff --git a/code/train/Python/0102121_insert.py b/code/train/Python/0102121_insert.py new file mode 100644 index 0000000000000000000000000000000000000000..2863a8dc859df78a02bcf8dd3dec98bb01d3997b --- /dev/null +++ b/code/train/Python/0102121_insert.py @@ -0,0 +1,214 @@ +"""insert.py +The insert module handles the Insert phase of the crmprtd +pipeline. This phase simply consists of doing a mass insert of +observations into the database. The phase needs to handle any unique +constraint errors, and track and report on the successes and +failures. This phase needs to manage the database transactions for +speed and reliability. This phase is common to all networks. +""" + +from math import floor, log as mathlog +from sqlalchemy import and_ +import logging +import time +from sqlalchemy.exc import IntegrityError +import random + +from crmprtd.db_exceptions import InsertionError +from pycds import Obs + + +log = logging.getLogger("crmprtd.insert") + + +class DBMetrics(object): + """Keep track of database metrics during the insertion process.""" + + def __init__(self, successes, skips, failures): + self.successes = successes + self.skips = skips + self.failures = failures + + def __add__(self, another): + return DBMetrics( + self.successes + another.successes, + self.skips + another.skips, + self.failures + another.failures, + ) + + +class Timer(object): + def __enter__(self): + self.start = time.time() + return self + + def __exit__(self, *args): + self.end = time.time() + self.run_time = self.end - self.start + + +def pow_two_chunk(num): + return 2 ** floor(mathlog(num, 2)) + + +def get_chunk_sizes(remainder): + chunk_list = [] + while remainder != 0: + chunk_size = pow_two_chunk(remainder) + remainder -= chunk_size + chunk_list.append(chunk_size) + return chunk_list + + +def chunks(obs): + pos = 0 + for chunk_size in get_chunk_sizes(len(obs)): + yield obs[pos : pos + chunk_size] + pos += chunk_size + + +def get_sample_indices(num_obs, sample_size): + if sample_size > num_obs: + sample_size = num_obs + + return random.sample(range(num_obs), sample_size) + + +def obs_exist(sesh, history_id, vars_id, time): + q = sesh.query(Obs).filter( + and_(Obs.history_id == history_id, Obs.vars_id == vars_id, Obs.time == time) + ) + return q.count() > 0 + + +def contains_all_duplicates(sesh, observations, sample_size): + sample_obs = [] + sample_indices = get_sample_indices(len(observations), sample_size) + + for index in sample_indices: + sample_obs.append(observations[index]) + + for sample in sample_obs: + if not obs_exist(sesh, sample.history_id, sample.vars_id, sample.time): + return False + + return True + + +def single_insert_obs(sesh, obs): + dbm = DBMetrics(0, 0, 0) + for o in obs: + if obs_exist(sesh, o.history_id, o.vars_id, o.time): + dbm.skips += 1 + log.debug("Observation already exists in database", extra={"obs_id": o.id}) + continue + + # value does not exist in obs_raw, continue with insertion + try: + sesh.add(o) + sesh.commit() + log.debug("Successfully inserted observation") + dbm.successes += 1 + except Exception as e: + log.warning("Failure, an error occured.", extra={"e": e}) + sesh.rollback() + dbm.failures += 1 + raise InsertionError( + obs_time=o.time, datum=o.datum, vars_id=o.vars_id, hid=o.history_id, e=e + ) + return dbm + + +def split(tuple_): + if len(tuple_) < 1: + return (), () + elif len(tuple_) < 2: + return (tuple_[0], ()) + else: + i = int(floor(len(tuple_) / 2)) + return (tuple_[:i], tuple_[i:]) + + +def bisect_insert_strategy(sesh, obs): + """This function implements a recursive Obs insert strategy to + handle unique constraint errors on members of the set. The + strategy used is to optimistically attempt to insert the entire + set and in the event of a unique constraint error, it will + divide the set into two and try again on each set (which will + presumably have a lower probability of failing). + + In the degenerative case (all observations are duplicates), this + strategy will require up to n *additional* transactions, + but in the optimal case it reduces the transactions to a constant + 1. + """ + log.debug("Begin mass observation insertion", extra={"num_obs": len(obs)}) + + # Base cases + if len(obs) < 1: + return DBMetrics(0, 0, 0) + elif len(obs) == 1: + try: + # Create a nested SAVEPOINT context manager to rollback to in the + # event of unique constraint errors + log.debug("New SAVEPOINT for single observation") + with sesh.begin_nested(): + sesh.add(obs[0]) + except IntegrityError as e: + log.debug( + "Failure, observation already exists", + extra={"obs": obs, "exception": e}, + ) + sesh.rollback() + return DBMetrics(0, 1, 0) + except InsertionError as e: + log.warning( + "Failure occured during insertion", extra={"obs": obs, "exception": e} + ) + sesh.rollback() + return DBMetrics(0, 0, 1) + else: + log.debug("Success for single observation") + sesh.commit() + return DBMetrics(1, 0, 0) + + # The happy case: add everything at once + else: + try: + with sesh.begin_nested(): + log.debug("New SAVEPOINT", extra={"num_obs": len(obs)}) + sesh.add_all(obs) + except IntegrityError: + log.debug("Failed, splitting observations.") + sesh.rollback() + + a, b = split(obs) + dbm_a = bisect_insert_strategy(sesh, a) + dbm_b = bisect_insert_strategy(sesh, b) + return dbm_a + dbm_b + else: + log.info("Successfully inserted observations", extra={"num_obs": len(obs)}) + sesh.commit() + return DBMetrics(len(obs), 0, 0) + + +def insert(sesh, observations, sample_size): + if contains_all_duplicates(sesh, observations, sample_size): + log.info("Using Single Insert Strategy") + with Timer() as tmr: + dbm = single_insert_obs(sesh, observations) + + else: + log.info("Using Chunk + Bisection Strategy") + with Timer() as tmr: + dbm = DBMetrics(0, 0, 0) + for chunk in chunks(observations): + dbm += bisect_insert_strategy(sesh, chunk) + + log.info("Data insertion complete") + return { + "successes": dbm.successes, + "skips": dbm.skips, + "failures": dbm.failures, + "insertions_per_sec": round(dbm.successes / tmr.run_time, 2), + } diff --git a/code/train/Python/0102176_connection.py b/code/train/Python/0102176_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..fb11b036e8987a03b27cd6a523906a1f4f31ca2f --- /dev/null +++ b/code/train/Python/0102176_connection.py @@ -0,0 +1,259 @@ +from pprint import pformat +from urlparse import urlparse +from zmq.eventloop import ioloop, zmqstream +from crypto_util import makePrivCryptor +from crypto_util import hexToPubkey +import logging +import pyelliptic as ec +import socket +import zlib +import obelisk +import zmq +import errno +import json + +ioloop.install() + + +class PeerConnection(object): + def __init__(self, transport, address, nickname=""): + + self.timeout = 10 # [seconds] + self.transport = transport + self.address = address + self.nickname = nickname + self.responses_received = {} + + self.ctx = zmq.Context() + + self.log = logging.getLogger( + '[%s] %s' % (self.transport.market_id, self.__class__.__name__) + ) + + def create_zmq_socket(self): + try: + socket = self.ctx.socket(zmq.REQ) + socket.setsockopt(zmq.LINGER, 0) + return socket + except Exception as e: + self.log.error('Cannot create socket %s' % e) + raise + # self._socket.setsockopt(zmq.SOCKS_PROXY, "127.0.0.1:9051"); + + def cleanup_context(self): + self.ctx.destroy() + + def send(self, data, callback): + self.send_raw(json.dumps(data), callback) + + def send_raw(self, serialized, callback=lambda msg: None): + + compressed_data = zlib.compress(serialized, 9) + + try: + s = self.create_zmq_socket() + try: + s.connect(self.address) + except zmq.ZMQError as e: + if e.errno != errno.EINVAL: + raise + s.ipv6 = True + s.connect(self.address) + + stream = zmqstream.ZMQStream(s, io_loop=ioloop.IOLoop.current()) + stream.send(compressed_data) + + def cb(stream, msg): + response = json.loads(msg[0]) + self.log.debug('[send_raw] %s' % pformat(response)) + + # Update active peer info + + if 'senderNick' in response and\ + response['senderNick'] != self.nickname: + self.nickname = response['senderNick'] + + if callback is not None: + self.log.debug('%s' % msg) + callback(msg) + stream.close() + + stream.on_recv_stream(cb) + except Exception as e: + self.log.error(e) + # Shouldn't we raise the exception here? + # I think not doing this could cause buggy behavior on top. + raise + + +class CryptoPeerConnection(PeerConnection): + + def __init__(self, transport, address, pub=None, guid=None, nickname="", + sin=None): + + # self._priv = transport._myself + self.pub = pub + + # Convert URI over + url = urlparse(address) + self.ip = url.hostname + self.port = url.port + + self.sin = sin + self._peer_alive = False # unused; might remove later if unnecessary + self.guid = guid + self.address = "tcp://%s:%s" % (self.ip, self.port) + + PeerConnection.__init__(self, transport, address, nickname) + + def __eq__(self, other): + if isinstance(other, self.__class__): + return self.guid == other.guid + elif isinstance(other, str): + return self.guid == other + return False + + def start_handshake(self, handshake_cb=None): + + if self.check_port(): + def cb(msg, handshake_cb=None): + if msg: + + self.log.debug('ALIVE PEER %s' % msg[0]) + msg = msg[0] + msg = json.loads(msg) + + # Update Information + self.guid = msg['senderGUID'] + self.sin = self.generate_sin(self.guid) + self.pub = msg['pubkey'] + self.nickname = msg['senderNick'] + + self._peer_alive = True + + # Add this peer to active peers list + for idx, peer in enumerate(self.transport.dht.activePeers): + if peer.guid == self.guid or peer.address == self.address: + self.transport.dht.activePeers[idx] = self + self.transport.dht.add_peer( + self.transport, + self.address, + self.pub, + self.guid, + self.nickname + ) + return + + self.transport.dht.activePeers.append(self) + self.transport.dht.routingTable.addContact(self) + + if handshake_cb is not None: + handshake_cb() + + self.send_raw( + json.dumps({ + 'type': 'hello', + 'pubkey': self.transport.pubkey, + 'uri': self.transport.uri, + 'senderGUID': self.transport.guid, + 'senderNick': self.transport.nickname + }), + cb + ) + else: + self.log.error('CryptoPeerConnection.check_port() failed.') + + def __repr__(self): + return '{ guid: %s, ip: %s, port: %s, pubkey: %s }' % ( + self.guid, self.ip, self.port, self.pub + ) + + @staticmethod + def generate_sin(guid): + return obelisk.EncodeBase58Check('\x0F\x02%s' + guid.decode('hex')) + + def check_port(self): + + try: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.settimeout(10) + s.connect((self.ip, self.port)) + except socket.error: + try: + s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) + s.settimeout(10) + s.connect((self.ip, self.port)) + except socket.error as e: + self.log.error("socket error on %s: %s" % (self.ip, e)) + return False + except TypeError: + self.log.error("tried connecting to invalid address: %s" % self.ip) + return False + + if s: + s.close() + return True + + def sign(self, data): + cryptor = makePrivCryptor(self.transport.settings['secret']) + return cryptor.sign(data) + + def encrypt(self, data): + try: + if self.pub is not None: + hexkey = hexToPubkey(self.pub) + return ec.ECC.encrypt(data, hexkey) + else: + self.log.error('Public Key is missing') + return False + except Exception as e: + self.log.error('Encryption failed. %s' % e) + + def send(self, data, callback=lambda msg: None): + + if hasattr(self, 'guid'): + + if self.check_port(): + + # Include guid + data['guid'] = self.guid + data['senderGUID'] = self.transport.guid + data['uri'] = self.transport.uri + data['pubkey'] = self.transport.pubkey + data['senderNick'] = self.transport.nickname + + self.log.debug( + 'Sending to peer: %s %s' % (self.ip, pformat(data)) + ) + + if self.pub == '': + self.log.info('There is no public key for encryption') + else: + signature = self.sign(json.dumps(data)) + data = self.encrypt(json.dumps(data)) + + try: + if data is not None: + self.send_raw( + json.dumps({ + 'sig': signature.encode('hex'), + 'data': data.encode('hex') + }), + callback + ) + else: + self.log.error('Data was empty') + except Exception as e: + self.log.error( + "Was not able to encode empty data: %s" % e + ) + else: + self.log.error('Peer is not available for sending data') + else: + self.log.error('Cannot send to peer') + + def peer_to_tuple(self): + return self.ip, self.port, self.guid + + def get_guid(self): + return self.guid diff --git a/code/train/Python/0102547_accumulate_langstats.py b/code/train/Python/0102547_accumulate_langstats.py new file mode 100644 index 0000000000000000000000000000000000000000..312d954c0fc84cf58f1eaf70b8ffe5c5097e9650 --- /dev/null +++ b/code/train/Python/0102547_accumulate_langstats.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import sys +from collections import defaultdict +from math import log + +""" Collect language distribution per domain + from language splitting output """ + + +def netloc(url): + # slightly faster than the urlparse version + netloc = url.split('//', 1)[1].split('/', 1)[0] + netloc = netloc.split(':', 1)[0].split('@')[-1] + # netloc = urlparse(uri).netloc + return netloc + + +def parse_line(line): + data = {} + for item in line.rstrip().split()[1:]: + key, value = item.split(':', 1) + if key == "bytes": + value = int(value) + data[key] = value + return data + + +def entropy(lang_dist): + total = float(sum(lang_dist.values())) + h = 0 + for lang, count in lang_dist.iteritems(): + p = count / total + h += p * log(p) + return h + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser() + parser.add_argument('-minbytes', type=int, default=100, + help="ignore chunks smaller than this.") + parser.add_argument('-lang', nargs='*', + help="Ignore all other languages but these.") + args = parser.parse_args(sys.argv[1:]) + + stats = defaultdict(lambda: defaultdict(int)) + + header = None + full_domain = None + valid_languages = [] + if args.lang: + valid_languages = [l.lower() for l in args.lang] + + for linenr, line in enumerate(sys.stdin): + header = parse_line(line) + + lang = header["language"] + if valid_languages and lang.lower() not in valid_languages: + continue + + if header["bytes"] >= args.minbytes: + hostname = netloc(header["uri"]) + stats[hostname][lang] += header["bytes"] + +for domain in stats: + h = entropy(stats[domain]) + if h == 0.0: + continue + sys.stdout.write("%f %s" % (h, domain)) + counts = [(count, language) + for language, count in stats[domain].iteritems()] + counts.sort(reverse=True) + for count, lang in counts: + sys.stdout.write(" %s %d" % (lang, count)) + sys.stdout.write("\n") diff --git a/code/train/Python/0103291_algorithms.py b/code/train/Python/0103291_algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..308a6fbb504e968d3127deb835c931da8c811593 --- /dev/null +++ b/code/train/Python/0103291_algorithms.py @@ -0,0 +1,229 @@ +import collections +import heapq +import time +import random + +from collections import deque +from entities import Board + +from utils import neighbours, surrounding, dist, mul, sub, timing +from constants import DIR_NAMES, DIR_VECTORS, FOOD, EMPTY, SNAKE +from math import floor, ceil + +from copy import copy, deepcopy + +def flood_fill(board, start_pos, allow_start_in_occupied_cell=False): + """ Flood fill is an algorithm that expands from a starting position into adjacent + vacant cells. Returns the set of all vacant cells found. + + If allow_start_in_occupied_cell is True, the flood fill start position may be occupied + and the start position will be included in the resulting set. """ + + visited = set() + + if not allow_start_in_occupied_cell and not board.vacant(start_pos): + return visited + + visited.add(start_pos) + todo = collections.deque([start_pos]) + + while todo: + current = todo.popleft() + for p in neighbours(current): + if p not in visited and board.vacant(p): + visited.add(p) + todo.append(p) + + return visited + + +def astar(vacant_func, start_pos, goal_pos, allow_start_in_occupied_cell=False): + """ A*, a pathfinding algorithm for finding a shortest path from a start location + to a goal. Returns the list of positions comprising the path, or none if no path + could be found. + + If allow_start_in_occupied_cell is True, the search may begin from an occupied cell + (a snake's head, for eg). However, if you do this, you'll probably want to trim off + the first position in the resulting shortest path. """ + + if not allow_start_in_occupied_cell and not vacant_func(start_pos): + return None + + closed_set = set() + min_cost_to = {start_pos: 0} + parent_of = {start_pos: None} + todo = [(dist(start_pos, goal_pos), start_pos)] + + while todo: + priority, current = heapq.heappop(todo) + closed_set.add(current) + + if current == goal_pos: + # Found the goal - walk up the parent chain to build the final path + path = [current] + + while parent_of[current]: + path.append(parent_of[current]) + current = parent_of[current] + + return list(reversed(path)) + + for p in neighbours(current): + if p in closed_set or not vacant_func(p): + continue + + new_cost = min_cost_to[current] + 1 + + if p not in min_cost_to or new_cost < min_cost_to[p]: + min_cost_to[p] = new_cost + parent_of[p] = current + priority = new_cost + dist(p, goal_pos) + # Note that this is a simplification of A* where we don't reprioritize items + # within the heap, we just push the same item again with a lower priority. + # This is wasteful in terms of memory, but for a problem of our scope, it + # doesn't really matter. + heapq.heappush(todo, (priority, p)) + + return None + +def _rate_cell(cell, board, recurse = False): + """ rates a cell based on proximity to other snakes, food, the edge of the board, etc """ + cells = filter(lambda m_cell: board.inside(m_cell), surrounding(cell)) + cells = map(lambda m_cell: (m_cell, board.get_cell(m_cell)), cells) + cell_value = reduce(lambda carry, m_cell: carry + [0.5, -5, 2, 0][m_cell[1]], cells, 0) + + if recurse or cell_value < 2: return cell_value + else: return cell_value + sum([ + _rate_cell(m_cell, board) / 10 + for m_cell in surrounding(cell) if board.inside(m_cell) + ]) + +def find_safest_position(current_position, direction, board): + """ finds a position in a binary-search like fashion, this could probably just + linearly scan the whole board, rating every position, and then returning the highest n + positions """ + + # the whole board + m_bounds = [(0, 0), (board.width, board.height)] + max_depth = 10 + + def _find_safest(bounds = m_bounds, offset = (0, 0), depth = 0, carry = []): + sector_width = (bounds[1][0] - bounds[0][0]) + sector_height = (bounds[1][1] - bounds[0][1]) + + center_point = ( + int(offset[0] + floor(sector_width / 2)), + int(offset[1] + floor(sector_height / 2)) + ) + + if depth == max_depth or (sector_height * sector_width <= 1): + return sorted(carry, lambda cell_1, cell_2: cell_1[1] < cell_2[1])[:3] + else: + # filter cells that we've already rated + carry_cells = [ cell[0] for cell in carry ] + surrounding_ratings = [ + ((cell[0], cell[1]), _rate_cell((cell[0], cell[1]), board, True)) + for cell in surrounding(center_point) + if cell not in carry_cells and board.inside(cell) and board.get_cell(cell) != SNAKE + ] + + # randomize to remove bias towards last in surrounding list + random.shuffle(surrounding_ratings) + position, rating = reduce(lambda m_carry, cell: cell if cell[1] > m_carry[1] else m_carry, surrounding_ratings, (None, -100000000000)) + + new_bounds = bounds + if position is not None: + carry = carry + [(position, rating)] + direction_vector = sub(position, center_point) + + # diagnal + if abs(direction_vector[0]) == abs(direction_vector[1]): + direction_vector = list(direction_vector) # tuples are immutable + direction_vector[int(time.time()) % 2] = 0 # 300% faster than random.randint() + direction_vector = tuple(direction_vector) # back to tuple because DIR_VECTOR contains tuples + + direction = DIR_NAMES[DIR_VECTORS.index(direction_vector)] + + if direction == "up": + new_bounds = [offset, (bounds[1][0], bounds[1][1])] + elif direction == "down": + offset = (offset[0], center_point[1]) + new_bounds = [offset, (bounds[1][0], bounds[1][1])] + elif direction == "left": + new_bounds = [offset, (center_point[0], bounds[1][1])] + else: # right + offset = (center_point[0], offset[1]) + new_bounds = [offset, (bounds[0][0], bounds[1][1])] + + return _find_safest(new_bounds, offset, depth + 1, carry = carry) + + # set up initial bounds + if direction == "up": + bounds = [(0, 0), (board.width, current_position[1])] + elif direction == "down": + bounds = [(0, current_position[1]), (board.width, board.height)] + elif direction == "right": + bounds = [(current_position[0], 0), (board.width, board.height)] + else: # left + bounds = [(0, 0), (current_position[0], board.height)] + + return _find_safest(bounds, bounds[0]) + + +def find_food(current_position, health_remaining, board, board_food): + """ finds and rates food positions """ + rated_food = map(lambda food: (food, _rate_cell(food, board, True)), board_food) + + return sorted(rated_food, lambda food_1, food_2: food_1[1] > food_2[1]) + # rated_food = filter(lambda food: dist(food[0], current_position) < health_remaining, rated_food) + # return reduce(lambda carry, food: food if not carry[0] or food[1] > carry[1] else carry, rated_food, (None, None)) + +def bfs(starting_position, target_position, board, exclude, return_list): + """ BFS implementation to search for path to food + + :param starting_position: starting position + :param target_position: target position + :param board: the board state + + example: + + bfs((0,0), (2,2), board) -> [(0,0), (0,1), (0,2), (1,2), (2,2)] + """ + + def get_path_from_nodes(node): + path = [] + while(node != None): + path.insert(0, (node[0], node[1])) # Reverse + node = node[2] + return return_list.append(path[1:]) + + x = starting_position[0] + y = starting_position[1] + board_copy = deepcopy(board) + board_copy.set_cell((x, y), 0) + for excluded_point in exclude: + board_copy.set_cell(excluded_point, "B") + + print board_copy.format() + queue = deque([(x, y, None)]) + while len(queue) > 0: + node = queue.popleft() + x = node[0] + y = node[1] + + if board_copy.inside((x, y)) == True: + if (x, y) == target_position: # If we reach target_position + return get_path_from_nodes(node) # Rebuild path + + if (board_copy.outside((x, y)) == True or board_copy.get_cell((x, y)) == "B" or board_copy.get_cell((x, y)) == 1) and not (x, y) == starting_position: # Snakes + #print "exclude", (x, y) + continue + + board_copy.set_cell((x, y), "B") # Mark as explored + + for i in neighbours(node): + if board.inside((i[0], i[1])): + #print "append", (x, y) + queue.append((i[0], i[1], node)) + + return None # No path diff --git a/code/train/Python/0103421_book.py b/code/train/Python/0103421_book.py new file mode 100644 index 0000000000000000000000000000000000000000..ae979fde7e79ca938b473e851f1588e10e1e8db8 --- /dev/null +++ b/code/train/Python/0103421_book.py @@ -0,0 +1,91 @@ + + +class Book(object): + + def __init__(self, bc, isbn=0, title="", authors=[], pages=0, publ_year=0, publisher="", location="", description="", call_num="", tags=[]): + self.bc = bc + self.isbn = isbn + self.title = title + self.authors = authors + self.pages = pages + self.publ_year = publ_year + self.publisher = publisher + self.location = location + self.description = description + self.call_num = call_num + self.tags = tags + + def edit(self, bc=None, isbn=None, title=None, authors=None, pages=None, publ_year=None, publisher=None, location=None, description=None, call_num=None, tags=None): + if bc is not None: + self.bc = bc + if isbn is not None: + self.isbn = isbn + if title is not None: + self.title = title + if authors is not None: + self.authors = authors + if pages is not None: + self.pages = pages + if publ_year is not None: + self.publ_year = publ_year + if publisher is not None: + self.publisher = publisher + if location is not None: + self.location = location + if description is not None: + self.description = description + if call_num is not None: + self.call_num = call_num + if tags is not None: + self.tags = tags + + def get_list_representation(self): + """ + Get a list representation of book elements for storing in DB. + + @return: This represented as a list. + """ + + return [self.bc, self.isbn, self.title, self.authors, self.pages, self.publ_year, + self.publisher, self.location, self.description, self.call_num, self.tags] + + def create_from_list(self, myList): + """ + Fill in details of this from a list. + + @param myList: list formatted just right + """ + + if len(myList) != 11: + raise ValueError("Incorrect list length") + else: + self.bc = myList[0] + self.isbn = myList[1] + self.title = myList[2] + self.authors = myList[3] + self.pages = myList[4] + self.publ_year = myList[5] + self.publisher = myList[6] + self.location = myList[7] + self.description = myList[8] + self.call_num = myList[9] + self.tags = myList[10] + + def print_check(self): + """ + Print an easy way to check if everything is acceptable before e.g. storing in the DB. + """ + print("Barcode: " + str(self.bc)) + print("ISBN: " + str(self.isbn)) + print("Title: " + str(self.title)) + print("Authors: " + str(self.authors)) + print("Pages: " + str(self.pages)) + print("Publication Year: " + str(self.publ_year)) + print("Publisher: " + str(self.publisher)) + print("Location: " + str(self.location)) + print("Description: " + str(self.description)) + print("Call Number: " + str(self.call_num)) + print("Tags: " + str(self.tags)) + + def __str__(self): + return self.title + " by: " + self.authors \ No newline at end of file diff --git a/code/train/Python/0103482_PriorityQueueTest.py b/code/train/Python/0103482_PriorityQueueTest.py new file mode 100644 index 0000000000000000000000000000000000000000..011568096020a09aa12108cbe84c2389e2e2b77c --- /dev/null +++ b/code/train/Python/0103482_PriorityQueueTest.py @@ -0,0 +1,178 @@ +import os +import subprocess +import sys +import time + +import sharedstructures + +POOL_NAME_PREFIX = "PriorityQueueTest-py-pool-" +ALLOCATOR_TYPES = ('simple', 'logarithmic') + + +def get_current_process_lsof(): + return subprocess.check_output(['lsof', '-p', str(os.getpid())]) + + +def run_basic_test(allocator_type): + print('-- [%s] basic' % allocator_type) + before_lsof_count = len(get_current_process_lsof().splitlines()) + + q = sharedstructures.PriorityQueue(POOL_NAME_PREFIX + allocator_type, allocator_type) + assert len(q) == 0 + + q.push(b"v1"); + assert 1 == len(q) + q.push(b"v3"); + assert 2 == len(q) + q.push(b"v20"); + assert 3 == len(q) + q.push(b"v2"); + assert 4 == len(q) + + assert b"v1" == q.pop() + assert 3 == len(q) + assert b"v2" == q.pop() + assert 2 == len(q) + assert b"v20" == q.pop() + assert 1 == len(q) + assert b"v3" == q.pop() + assert 0 == len(q) + try: + q.pop() + assert False + except IndexError: + pass + + del q # this should unmap the shared memory pool and close the fd + sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) + + # make sure we didn't leak an fd + assert before_lsof_count == len(get_current_process_lsof().splitlines()) + + +def run_concurrent_producers_test(allocator_type): + print('-- [%s] concurrent producers' % allocator_type) + + child_pids = set() + while (len(child_pids) < 8) and (0 not in child_pids): + child_pids.add(os.fork()) + + if 0 in child_pids: + # child process: generate the numbers [0, 1000) prefixed with our pid + q = sharedstructures.PriorityQueue(POOL_NAME_PREFIX + allocator_type, allocator_type) + + pid = os.getpid() + for x in range(1000): + q.push(b'%d-%04d' % (pid, x)) + + os._exit(0) + + else: + # parent process: write the key, then wait for children to terminate + q = sharedstructures.PriorityQueue(POOL_NAME_PREFIX + allocator_type, allocator_type) + + latest_value_from_process = {pid: -1 for pid in child_pids} + + num_failures = 0 + while child_pids: + try: + data = q.pop() + pid, value = data.split(b'-') + pid = int(pid) + value = int(value) + assert pid in latest_value_from_process + assert latest_value_from_process[pid] < value + latest_value_from_process[pid] = value + + except IndexError: # queue is empty + pid, exit_status = os.wait() + child_pids.remove(pid) + if os.WIFEXITED(exit_status) and (os.WEXITSTATUS(exit_status) == 0): + print('-- [%s] child %d terminated successfully' % ( + allocator_type, pid)) + else: + print('-- [%s] child %d failed (%d)' % ( + allocator_type, pid, exit_status)) + num_failures += 1 + + assert 0 == len(child_pids) + assert 0 == num_failures + + +def run_concurrent_consumers_test(allocator_type): + print('-- [%s] concurrent consumers' % allocator_type) + + # initialize the queue before forking children + q = sharedstructures.PriorityQueue(POOL_NAME_PREFIX + allocator_type, allocator_type) + del q + + child_pids = set() + while (len(child_pids) < 8) and (0 not in child_pids): + child_pids.add(os.fork()) + + if 0 in child_pids: + # child process: read numbers and expect them to be in increasing order + # stop when -1 is received + q = sharedstructures.PriorityQueue(POOL_NAME_PREFIX + allocator_type, allocator_type) + + prev_value = -1 + value = 0 + while True: + try: + item = q.pop() + if item == b'END': + break + value = int(item) + except IndexError: + time.sleep(0.00001) + continue + assert value > prev_value + prev_value = value + + os._exit(0) + + else: + # parent process: push numbers [0, 10000), then wait for children + q = sharedstructures.PriorityQueue(POOL_NAME_PREFIX + allocator_type, allocator_type) + + for v in range(10000): + q.push(b'%04d' % v) + + for _ in child_pids: + q.push(b'END') + + num_failures = 0 + while child_pids: + pid, exit_status = os.wait() + child_pids.remove(pid) + if os.WIFEXITED(exit_status) and (os.WEXITSTATUS(exit_status) == 0): + print('-- [%s] child %d terminated successfully' % ( + allocator_type, pid)) + else: + print('-- [%s] child %d failed (%d)' % ( + allocator_type, pid, exit_status)) + num_failures += 1 + + assert 0 == len(child_pids) + assert 0 == num_failures + + +def main(): + try: + for allocator_type in ALLOCATOR_TYPES: + sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) + run_basic_test(allocator_type) + sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) + run_concurrent_producers_test(allocator_type) + sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) + run_concurrent_consumers_test(allocator_type) + print('all tests passed') + return 0 + + finally: + for allocator_type in ALLOCATOR_TYPES: + sharedstructures.delete_pool(POOL_NAME_PREFIX + allocator_type) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/code/train/Python/0103520_step_project_creation02.py b/code/train/Python/0103520_step_project_creation02.py new file mode 100644 index 0000000000000000000000000000000000000000..67437b83944dafb0b91ad19035263d7795c2d124 --- /dev/null +++ b/code/train/Python/0103520_step_project_creation02.py @@ -0,0 +1,184 @@ +# coding=utf-8 +""" +Cadasta project creation step -**Cadasta Wizard** + +This module provides: Project Creation Step 2 : Attribute Selection + +.. note:: This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + +""" + +import logging + +from cadasta.gui.tools.utilities.edit_text_dialog import EditTextDialog +from cadasta.gui.tools.utilities.questionnaire import QuestionnaireUtility +from cadasta.gui.tools.wizard.wizard_step import WizardStep +from cadasta.gui.tools.wizard.wizard_step import get_wizard_step_ui_class +from cadasta.utilities.i18n import tr + +__copyright__ = "Copyright 2016, Cadasta" +__license__ = "GPL version 3" +__email__ = "info@kartoza.org" +__revision__ = '$Format:%H$' + +FORM_CLASS = get_wizard_step_ui_class(__file__) + +LOGGER = logging.getLogger('CadastaQGISPlugin') + + +class StepProjectCreation2(WizardStep, FORM_CLASS, QuestionnaireUtility): + """Step 2 for project creation.""" + + def __init__(self, parent=None): + """Constructor. + + :param parent: parent - widget to use as parent. + :type parent: QWidget + """ + super(StepProjectCreation2, self).__init__(parent) + self.layer = None + self.layer_attributes = None + self.questionnaire = None + + def cadasta_fields(self): + """Returns layer fields that mapped to cadasta attribute. + + :returns: cadasta fields + :rtype: dict + """ + cadasta_fields = { + 'location_type': self.location_type_box.currentText(), + 'party_name': self.party_name_box.currentText(), + 'party_type': self.party_type_box.currentText(), + 'relationship_type': self.relationship_type_box.currentText(), + } + + return cadasta_fields + + def cadasta_fields_reversed(self): + """Returns cadasta attribute that mapped to layer fields. + + :returns: cadasta fields + :rtype: dict + """ + cadasta_mapped_fields = { + self.location_type_box.currentText(): 'location_type', + self.party_name_box.currentText(): 'party_name', + self.party_type_box.currentText(): 'party_type', + self.relationship_type_box.currentText(): 'relationship_type', + } + + return cadasta_mapped_fields + + def set_widgets(self): + """Set all widgets on the tab.""" + if not self.layer or self.layer != self.parent.layer: + self.layer = self.parent.layer + self.set_attributes_box() + self.advanced_box.setVisible(False) + self.advanced_button.mousePressEvent = self.toogled_advanced_area + self.questionnaire_button.clicked.connect( + self.show_questionnaire + ) + self.check_questionnaire() + self.label.setToolTip( + tr('Location type field is required please select.')) + + # Set tab focus + self.location_type_box.setFocus() + + def toogled_advanced_area(self, event): + """Toogled advanced area + """ + if self.advanced_box.isVisible(): + self.advanced_box.setVisible(False) + else: + self.advanced_box.setVisible(True) + + def set_items_combo_box(self, combo_box, field_names): + """Set items for combo box. + + :param combo_box: combo box that will be filled. + :type combo_box: QComboBox + + :param field_names: fields that will be filled to combo box. + :type field_names: [str] + + """ + field_names.sort() + combo_box.clear() + combo_box.addItems(field_names) + + # set combo box listener for update questionnaire + combo_box.currentIndexChanged.connect( + self.check_questionnaire + ) + + def set_attributes_box(self): + """Set all attribute box widgets.""" + field_names = [field.name() for field in self.layer.pendingFields()] + + self.layer_attributes = [] + + for elem in self.layer.getFeatures(): + self.layer_attributes.append( + (dict(zip(field_names, elem.attributes()))) + ) + + field_names.append('--------- {field} ----------'.format( + field=tr('No field'))) + self.set_items_combo_box(self.location_type_box, field_names) + self.set_items_combo_box(self.party_name_box, field_names) + self.set_items_combo_box(self.relationship_type_box, field_names) + self.set_items_combo_box(self.party_type_box, field_names) + + def validate_step(self): + """Check if the step is valid. + + :returns: Tuple of validation status and error message if any + :rtype: ( bool, str ) + """ + error_message = '' + if not self.location_type_box.currentText() or \ + tr('No field') in self.location_type_box.currentText(): + error_message = tr( + 'Location type field is required, please select.' + ) + + return ( + error_message == '', + error_message + ) + + def get_next_step(self): + """Find the proper step when user clicks the Next button. + + This method must be implemented in derived classes. + + :returns: The step to be switched to + :rtype: WizardStep instance or None + """ + new_step = self.parent.step_project_creation03 + return new_step + + def check_questionnaire(self): + """Method when questionnaire check button is changed. + """ + self.questionnaire = self.generate_new_questionnaire( + self.layer, self.cadasta_fields_reversed(), '', + ) + + def show_questionnaire(self): + """Method to show current questionnaire. + """ + self.input_dialog = EditTextDialog( + self, self.parent.iface, self.questionnaire) + self.input_dialog.edit_text_done.connect(self.edit_text_dialog_done) + + def edit_text_dialog_done(self): + """Method when edit text dialog is done. + """ + self.questionnaire = self.input_dialog.get_text() diff --git a/code/train/Python/0103559_test_sol_75.py b/code/train/Python/0103559_test_sol_75.py new file mode 100644 index 0000000000000000000000000000000000000000..fbbc32a3cbd5184a325310f814661abf7b7153fb --- /dev/null +++ b/code/train/Python/0103559_test_sol_75.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# =============================================================== +# +# Filename: SortColors.py +# +# Author: Oxnz +# Email: yunxinyi@gmail.com +# Created: [2014-12-01 23:36:03 CST] +# Last-update: 2014-12-01 23:36:03 CST +# Description: ANCHOR +# +# Version: 0.0.1 +# Revision: [None] +# Revision history: [None] +# Date Author Remarks: [None] +# +# License: +# Copyright (c) 2013 Oxnz +# +# Distributed under terms of the [LICENSE] license. +# [license] +# +# =============================================================== +# + +class Solution: + # @param A a list of integers + # @return nothing, sort in place + def sortColors(self, A): + if not A: + return + p0, p2 = 0, len(A) - 1 + i = 0 + while i <= p2: + while p2 >= p0 and A[p2] == 2: + p2 -= 1 + while p0 <= p2 and A[p0] == 0: + p0 += 1 + if A[i] == 2 and i < p2: + A[i], A[p2] = A[p2], A[i] + p2 -= 1 + if A[i] == 0 and i > p0: + A[p0], A[i] = A[i], A[p0] + p0 += 1 + i += 1 + +import unittest +import random + +class TestSortColors(unittest.TestCase): + def setUp(self): + self._sort = Solution().sortColors + + def test_sort(self): + l = None + self._sort(l) + self.assertEqual(None, l) + l = [random.randint(0,2) for i in range(10)] + sl = sorted(l) + self._sort(l) + self.assertEqual(sl, l) + random.shuffle(l) + self._sort(l) + sl = sorted(l) + self.assertEqual(sl, l) + l = [0] + self._sort(l) + sl = sorted(l) + self.assertEqual(sl, l) + l = [1] + self._sort(l) + sl = sorted(l) + self.assertEqual(sl, l) + l = [0, 1] + self._sort(l) + sl = sorted(l) + self.assertEqual(sl, l) + l = [1, 2] + self._sort(l) + sl = sorted(l) + self.assertEqual(sl, l) + l = [2, 1] + self._sort(l) + sl = sorted(l) + self.assertEqual(sl, l) + l = [2, 0] + self._sort(l) + sl = sorted(l) + self.assertEqual(sl, l) + +if __name__ == '__main__': + unittest.main() diff --git a/code/train/Python/0103635_commander.py b/code/train/Python/0103635_commander.py new file mode 100644 index 0000000000000000000000000000000000000000..f659bafcc9d8265cccaaddd252ec99c6ba009eb2 --- /dev/null +++ b/code/train/Python/0103635_commander.py @@ -0,0 +1,225 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. + +import os +import math +import rospkg +import rospy + +from qt_gui.plugin import Plugin +from python_qt_binding import loadUi +from python_qt_binding.QtWidgets import QWidget + +from mantis_msgs.msg import State, Parameters +from geometry_msgs.msg import Pose, Vector3, Quaternion + +from std_srvs.srv import SetBool + +import actionlib +from contrail.msg import TrajectoryAction, TrajectoryGoal +from mantis_guidance_joints.msg import JointMovementAction, JointMovementGoal + +class MantisCommander(Plugin): + def __init__(self, context): + super(MantisCommander, self).__init__(context) + # Give QObjects reasonable names + self.setObjectName('MantisCommander') + rp = rospkg.RosPack() + + # Process standalone plugin command-line arguments + #from argparse import ArgumentParser + #parser = ArgumentParser() + # Add argument(s) to the parser. + #parser.add_argument("-q", "--quiet", action="store_true", + # dest="quiet", + # help="Put plugin in silent mode") + #args, unknowns = parser.parse_known_args(context.argv()) + #if not args.quiet: + # print 'arguments: ', args + # print 'unknowns: ', unknowns + + # Create QWidget + self._widget = QWidget() + # Get path to UI file which is a sibling of this file + # in this example the .ui and .py file are in the same folder + ui_file = os.path.join(rp.get_path('rqt_mantis_commander'), 'resource', 'MantisCommander.ui') + # Extend the widget with all attributes and children from UI file + loadUi(ui_file, self._widget) + # Give QObjects reasonable names + self._widget.setObjectName('MantisCommanderUi') + # Show _widget.windowTitle on left-top of each plugin (when + # it's set in _widget). This is useful when you open multiple + # plugins at once. Also if you open multiple instances of your + # plugin at once, these lines add number to make it easy to + # tell from pane to pane.ns + if context.serial_number() > 1: + self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number())) + # Add widget to the user interface + context.add_widget(self._widget) + + self._widget.button_update_namespaces.clicked.connect(self.button_update_namespaces_pressed) + self._widget.button_arm.clicked.connect(self.button_arm_pressed) + self._widget.button_disarm.clicked.connect(self.button_disarm_pressed) + self._widget.button_send_command.clicked.connect(self.button_send_command_pressed) + self._widget.combo_joints.currentIndexChanged.connect(self.combo_joints_pressed) + self._widget.textbox_goto_joint.textChanged.connect(self.goto_joint_changed) + + self.sub_state = None + self.has_state = False + self.current_pose = None + self.current_joints = None + self.joint_sp = [] + self.client_joints = [] + + self.update_namespaces() + + def shutdown_plugin(self): + if self.sub_state is not None: + self.sub_state.unregister() + + def save_settings(self, plugin_settings, instance_settings): + instance_settings.set_value('namespace', self.ns) + instance_settings.set_value('contrail_prefix', self.contrail_prefix) + instance_settings.set_value('joint_prefix', self.joint_prefix) + + def restore_settings(self, plugin_settings, instance_settings): + #self.ns = instance_settings.value('namespace') + #self.contrail_prefix = instance_settings.value('contrail_prefix') + #self.joint_prefix = instance_settings.value('joint_prefix') + pass + + #def trigger_configuration(self): + # Comment in to signal that the plugin has a way to configure + # This will enable a setting button (gear icon) in each dock widget title bar + # Usually used to open a modal configuration dialog + + def quaternion_to_rpy(self,q): + if not isinstance(q, Quaternion): + raise TypeError('Input should be a geometry_msgs/Quaternion') + + q2sqr = q.y * q.y; + t0 = -2.0 * (q2sqr + q.z * q.z) + 1.0 + t1 = 2.0 * (q.x * q.y + q.w * q.z) + t2 = -2.0 * (q.x * q.z - q.w * q.y) + t3 = 2.0 * (q.y * q.z + q.w * q.x) + t4 = -2.0 * (q.x * q.x + q2sqr) + 1.0 + + if(t2 > 1.0): + t2 = 1.0 + elif(t2 < -1.0): + t2 = -1.0 + + e = Vector3() + roll = math.atan2(t3, t4); + pitch = math.asin(t2); + yaw = math.atan2(t1, t0); + + return (roll,pitch,yaw) + + def goto_joint_changed(self): + try: + if(len(self.joint_sp) > 0): + val = float(self._widget.textbox_goto_joint.text()) + idx = self._widget.combo_joints.currentIndex() + self.joint_sp[idx] = val + except: + rospy.logerr("Unexpected error!") + + def combo_joints_pressed(self): + if(len(self.joint_sp) > 0): + idx = self._widget.combo_joints.currentIndex() + self._widget.textbox_goto_joint.setText(str(self.joint_sp[idx])) + + def button_send_command_pressed(self): + rospy.logdebug("Send command pressed!") + + if self.client_base.wait_for_server(rospy.Duration(0.5)): + try: + if self.has_state: + dur = rospy.Duration(float(self._widget.textbox_goto_duration.text())) + + pos_x = float(self._widget.textbox_goto_pos_x.text()) + pos_y = float(self._widget.textbox_goto_pos_y.text()) + pos_z = float(self._widget.textbox_goto_pos_z.text()) + yaw = float(self._widget.textbox_goto_yaw.text()) + roll_c, pitch_c, yaw_c = self.quaternion_to_rpy(self.current_pose.orientation) + + goal_base = TrajectoryGoal() + goal_base.duration = dur + goal_base.positions = [Vector3(self.current_pose.position.x,self.current_pose.position.y,self.current_pose.position.z), + Vector3(pos_x,pos_y,pos_z)] + goal_base.yaws = [yaw_c, yaw] + + goal_joints = [] + for i in range(len(self.joint_sp)): + goal_joints.append(JointMovementGoal()) + goal_joints[i].duration = dur + goal_joints[i].positions = [self.current_joints[i], self.joint_sp[i]] + + timestamp = rospy.Time.now() + rospy.Duration.from_sec(0.5) + + goal_base.start = timestamp + for i in range(len(self.joint_sp)): + goal_joints[i].start = timestamp + + self.client_base.send_goal(goal_base) + for i in range(len(self.joint_sp)): + self.client_joints[i].send_goal(goal_joints[i]) + + rospy.loginfo("Sending command...") + else: + rospy.logerr("No state information received, can't generate command action!") + except: + rospy.logerr("Unexpected error!") + else: + rospy.logerr("Not connected to action server!") + + + def button_update_namespaces_pressed(self): + self.update_namespaces() + rospy.logdebug("Update namespaces button pressed!") + + def callback_state(self, msg_in): + self.has_state = True + self.current_pose = msg_in.pose + self.current_joints = msg_in.r + + def callback_params(self, msg_in): + self.joint_names = [] + self.client_joints = [] + self.joint_sp = [] + + for j in range(len(msg_in.joints)): + if msg_in.joints[j].type != "static": + self._widget.combo_joints.addItem(msg_in.joints[j].name) + self.client_joints.append(actionlib.SimpleActionClient(self.ns + '/' + self.joint_prefix + '/' + msg_in.joints[j].name, JointMovementAction) ) + self.joint_sp.append(0.0) + + def update_namespaces(self): + self.ns = self._widget.textbox_namespace.text() + self.contrail_prefix = self._widget.textbox_contrail.text() + self.joint_prefix = self._widget.textbox_joint_prefix.text() + + self.sub_state = rospy.Subscriber(self.ns + "/state", State, self.callback_state) + self.sub_params = rospy.Subscriber(self.ns + "/params", Parameters, self.callback_params) + + self.client_base = actionlib.SimpleActionClient(self.ns + '/' + self.contrail_prefix, TrajectoryAction) + + def button_arm_pressed(self): + rospy.logdebug("Button arm pressed!") + + try: + arm_jc = rospy.ServiceProxy('/mantis_uav/dynamixel_interface/enable_torque_all', SetBool) + res = arm_jc(True) + except rospy.ServiceException, e: + print "Service call failed: %s"%e + + def button_disarm_pressed(self): + rospy.logdebug("Button disarm pressed!") + + try: + arm_jc = rospy.ServiceProxy('/mantis_uav/dynamixel_interface/enable_torque_all', SetBool) + res = arm_jc(False) + except rospy.ServiceException, e: + print "Service call failed: %s"%e diff --git a/code/train/Python/0103862_barcode_writer.py b/code/train/Python/0103862_barcode_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..094b40d59922737f6e17cf9042e9874254b0c39d --- /dev/null +++ b/code/train/Python/0103862_barcode_writer.py @@ -0,0 +1,110 @@ +# === LICENSE STATEMENT === +# Copyright (c) 2011 Sebastian J. Bronner +# +# Copying and distribution of this file, with or without modification, are +# permitted in any medium without royalty provided the copyright notice and +# this notice are preserved. +# === END LICENSE STATEMENT === + +from typing import Optional + +from barcode.writer import BaseWriter +from PIL import Image, ImageDraw + + +def mm2px(mm, dpi=25.4): + return (mm * dpi) / 25.4 + + +class BarcodeImageWriter(BaseWriter): + _draw: Optional[ImageDraw.ImageDraw] + + def __init__(self): + super().__init__(self._init, self._paint_module, None, self._finish) + self.format = "PNG" + self.dpi = 25.4 + self._image = None + self._draw = None + self.vertical_margin = 0 + + def calculate_size(self, modules_per_line, number_of_lines, dpi=25.4): + width = 2 * self.quiet_zone + modules_per_line * self.module_width + height = self.vertical_margin * 2 + self.module_height * number_of_lines + return int(mm2px(width, dpi)), int(mm2px(height, dpi)) + + def render(self, code): + """Renders the barcode to whatever the inheriting writer provides, + using the registered callbacks. + + :parameters: + code : List + List of strings matching the writer spec + (only contain 0 or 1). + """ + if self._callbacks["initialize"] is not None: + self._callbacks["initialize"](code) + ypos = self.vertical_margin + for cc, line in enumerate(code): + """ + Pack line to list give better gfx result, otherwise in can + result in aliasing gaps + '11010111' -> [2, -1, 1, -1, 3] + """ + line += " " + c = 1 + mlist = [] + for i in range(0, len(line) - 1): + if line[i] == line[i + 1]: + c += 1 + else: + if line[i] == "1": + mlist.append(c) + else: + mlist.append(-c) + c = 1 + # Left quiet zone is x startposition + xpos = self.quiet_zone + bxs = xpos # x start of barcode + for mod in mlist: + if mod < 1: + color = self.background + else: + color = self.foreground + # remove painting for background colored tiles? + self._callbacks["paint_module"]( + xpos, ypos, self.module_width * abs(mod), color + ) + xpos += self.module_width * abs(mod) + bxe = xpos + # Add right quiet zone to every line, except last line, + # quiet zone already provided with background, + # should it be removed complety? + if (cc + 1) != len(code): + self._callbacks["paint_module"]( + xpos, ypos, self.quiet_zone, self.background + ) + ypos += self.module_height + return self._callbacks["finish"]() + + def _init(self, code): + size = self.calculate_size(len(code[0]), len(code), self.dpi) + self._image = Image.new("1", size, self.background) + self._draw = ImageDraw.Draw(self._image) + + def _paint_module(self, xpos, ypos, width, color): + size = [ + (mm2px(xpos, self.dpi), mm2px(ypos, self.dpi)), + ( + mm2px(xpos + width, self.dpi), + mm2px(ypos + self.module_height, self.dpi), + ), + ] + self._draw.rectangle(size, outline=color, fill=color) + + def _finish(self): + return self._image + + def save(self, filename, output): + filename = "{0}.{1}".format(filename, self.format.lower()) + output.save(filename, self.format.upper()) + return filename diff --git a/code/train/Python/0104099_Entropy.py b/code/train/Python/0104099_Entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..5a8ba53b0016f573c6de3c6fbe83494526a96245 --- /dev/null +++ b/code/train/Python/0104099_Entropy.py @@ -0,0 +1,110 @@ +""" +C. H. Cheng, R. J. Chang, and C. A. Yeh, “Entropy-based and trapezoidal fuzzification-based fuzzy time series approach for forecasting IT project cost,” +Technol. Forecast. Social Change, vol. 73, no. 5, pp. 524–542, Jun. 2006. +""" + +import numpy as np +import math +import random as rnd +import functools, operator +from pyFTS.common import FuzzySet, Membership +from pyFTS.partitioners import partitioner + + +def splitBelow(data,threshold): + return [k for k in data if k <= threshold] + + +def splitAbove(data,threshold): + return [k for k in data if k > threshold] + + +def PMF(data, threshold): + a = sum([1.0 for k in splitBelow(data,threshold)]) + b = sum([1.0 for k in splitAbove(data, threshold)]) + l = len(data) + return [a / l, b / l] + + +def entropy(data, threshold): + pmf = PMF(data, threshold) + if pmf[0] == 0 or pmf[1] == 0: + return 1 + else: + return - sum([pmf[0] * math.log(pmf[0]), pmf[1] * math.log(pmf[1])]) + + +def informationGain(data, thres1, thres2): + return entropy(data, thres1) - entropy(data, thres2) + + +def bestSplit(data, npart): + if len(data) < 2: + return [] + count = 1 + ndata = list(set(np.array(data).flatten())) + ndata.sort() + l = len(ndata) + threshold = 0 + try: + while count < l and informationGain(data, ndata[count - 1], ndata[count]) <= 0: + threshold = ndata[count] + count += 1 + except IndexError: + print(threshold) + print (ndata) + print (count) + + rem = npart % 2 + + if (npart - rem)/2 > 1: + p1 = splitBelow(data,threshold) + p2 = splitAbove(data,threshold) + + if len(p1) > len(p2): + np1 = (npart - rem)/2 + rem + np2 = (npart - rem)/2 + else: + np1 = (npart - rem) / 2 + np2 = (npart - rem) / 2 + rem + + tmp = [threshold] + + for k in bestSplit(p1, np1 ): tmp.append(k) + for k in bestSplit(p2, np2 ): tmp.append(k) + + return tmp + + else: + return [threshold] + + +class EntropyPartitioner(partitioner.Partitioner): + """Huarng Entropy Partitioner""" + def __init__(self, **kwargs): + super(EntropyPartitioner, self).__init__(name="Entropy", **kwargs) + + def build(self, data): + sets = {} + + kwargs = {'type': self.type, 'variable': self.variable} + + partitions = bestSplit(data, self.partitions) + partitions.append(self.min) + partitions.append(self.max) + partitions = list(set(partitions)) + partitions.sort() + for c in np.arange(1, len(partitions)-1): + _name = self.get_name(c-1) + if self.membership_function == Membership.trimf: + sets[_name] = FuzzySet.FuzzySet(_name, Membership.trimf, + [partitions[c - 1], partitions[c], partitions[c + 1]],partitions[c], **kwargs) + elif self.membership_function == Membership.trapmf: + b1 = (partitions[c] - partitions[c - 1])/2 + b2 = (partitions[c + 1] - partitions[c]) / 2 + sets[_name] = FuzzySet.FuzzySet(_name, Membership.trapmf, + [partitions[c - 1], partitions[c] - b1, + partitions[c] + b2, partitions[c + 1]], + partitions[c], **kwargs) + + return sets diff --git a/code/train/Python/0104269_trpo.py b/code/train/Python/0104269_trpo.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd0ae60c0e0f96fdb36f665f7f312c40dbec648 --- /dev/null +++ b/code/train/Python/0104269_trpo.py @@ -0,0 +1,191 @@ +import tensorflow as tf +import numpy as np +import math + +from agents import spaces + +tensorType = tf.float32 + +# +# Utility class for converting from weight+bias matrices to/from flat vectors +# of all the parameters. +# +class FlatConverter: + def __init__(self, session, var_list): + self.session = session # So we can run ops + self.var_list = var_list # references to the actual variables + shapes = [v.get_shape().as_list() for v in var_list] # Shapes for each variable + sizes = [np.prod(shape) for shape in shapes] # Total size in elements for each variable + self.total_size = sum(sizes) + + self.flat = tf.placeholder(tensorType, [self.total_size]) + var_start = 0 # Current position in vector + assignments = [] # list of assignment-group ops + retrievals = [] # list of retrieval-group ops + + for (var, shape, size) in zip(var_list, shapes, sizes): + # Define assignment operation (flat vector -> variables): + assignments.append(tf.assign( + var, + tf.reshape(self.flat[var_start : var_start + size], shape) + )) + var_start += size + + # Define retrieval operation (variables -> flat vector): + retrievals.append(tf.reshape(var, [-1])) + + self.set_op = tf.group(*assignments) + self.get_op = tf.concat_v2(retrievals, 0) + + def set(self, flat): + self.session.run(self.set_op, feed_dict={ self.flat: flat }) + + def get(self): + return self.session.run(self.get_op) + +def tensor_list_flatten(in_list): + return tf.concat_v2( [tf.reshape(elem, [-1]) for elem in in_list], 0 ) + +# +# Wraps arbitrary neural networks as TRPO agents. +# +class TRPO: + def __init__(self, session, graph, net_in, netGen, \ + prefix="", divergence_constraint=0.01, cg_damping=0.1): + with graph.as_default(): + self.session = session + self.graph = graph + self.input = net_in + + self.net = netGen(net_in) + self.parameters = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=prefix) + + self.flat_conv = FlatConverter(self.session, self.parameters) + + # various non-trainable and non-network parameters: + self.divergence_constraint = divergence_constraint + self.cg_damping = cg_damping + + self.fim_ops() + self.loss_ops() + + def loss_ops(self): + # Trajectory placeholders. + # traj_state and traj_action form the usual (s, a) pairs. + self.traj_action = tf.placeholder(tf.int32, [None], name="traj_action") # traj. actions + self.traj_dist = tf.placeholder(tensorType, self.net.get_shape().as_list(), name="traj_dist") # traj. NNet outputs + self.traj_adv = tf.placeholder(tensorType, [None], name="traj_adv") # traj. rewards / advantages + self.traj_len = tf.shape(self.traj_action)[0] # length of trajectory + + # Ops to calculate L(theta) (and its gradient) + self.N = tf.range(0, self.traj_len) + self.p_old = tf.gather_nd(self.traj_dist, tf.pack([self.N, self.traj_action], 1)) + self.p_new = tf.gather_nd(self.net, tf.pack([self.N, self.traj_action], 1)) + + self.loss = -tf.reduce_sum( (self.p_new / self.p_old) * self.traj_adv ) # operation for loss function + self.loss_gradient = tensor_list_flatten(tf.gradients(self.loss, self.parameters)) # gradient of loss function (stochastic policy gradient) + + # Calculate the FVP via reverse-mode AD of the KL-divergence + def fim_ops(self): + batch_sz_float = tf.cast(tf.shape(self.input)[0], tensorType) + kl_divergence = tf.reduce_sum( tf.stop_gradient(self.net + 1e-8) * tf.log(tf.stop_gradient(self.net + 1e-8) / (self.net + 1e-8)) ) / batch_sz_float #tf.log(self.net) + first_gradient = tf.gradients(kl_divergence, self.parameters) + + self.flat_tangents = tf.placeholder(tensorType, [None]) + tangents = [] + idx = 0 + for var in self.parameters: + size = np.prod(var.get_shape().as_list()) + param = tf.reshape(self.flat_tangents[idx:idx+size], var.get_shape().as_list()) + tangents.append(param) + idx += size + + self.fim = tensor_list_flatten(tf.gradients( + [tf.reduce_sum(grad * tan) for (grad, tan) in zip(first_gradient, tangents)], self.parameters + )) + + # Compute step direction using conjugate gradient method + def step_dir(self, feed_val): + g = -self.session.run(self.loss_gradient, feed_dict=feed_val) + + x = np.zeros_like( g ) + r = g.copy() + p = g.copy() + + rsq_old = r.dot(r) + for k in range(0,10): + aP = self.fisher_vector_product(p, feed_val) + self.cg_damping * p + pdot = p.dot(aP) + + if np.isnan(rsq_old): + print("rsq_old is NaN?") + break + + if np.isnan(pdot): + print("pdot is NaN?") + break + + alpha = rsq_old / (p.dot(aP) + 1e-8) + + x += (alpha * p) + r -= (alpha * aP) + + rsq_new = r.dot(r) + + beta = (rsq_new / (rsq_old + 1e-8)) + p = r + (beta * p) + + rsq_old = rsq_new + + if rsq_new < 1e-8: # keep pdot from going to NaN + break + + if np.isnan(rsq_new): + print("rsq_new is NaN?") + break + + return x + + # Optimize the current policy using line search. + def optimize_policy(self, states, actions, dists, adv): + feed = { + self.input: states, + self.traj_action: actions, + self.traj_dist: dists, + self.traj_adv: adv + } + + s = self.step_dir(feed) + step_As = s.dot(self.fisher_vector_product(s, feed)) + betasq = 2*self.divergence_constraint / (step_As + 1e-8) + if betasq < 0: + print("negative beta-squared ({})?".format(betasq)) + return + beta = np.sqrt( betasq ) + + current_theta = self.flat_conv.get() + current_loss = self.session.run(self.loss, feed_dict=feed) + + best_theta = current_theta + + for k in range(0, 10): + new_theta = current_theta + ((beta * (.5 ** k))*s) + + # compute new loss: + self.flat_conv.set(new_theta) + new_loss = self.session.run(self.loss, feed_dict=feed) + + if new_loss < current_loss: + best_theta = new_theta + current_loss = new_loss + break + + self.flat_conv.set(best_theta) + + # Calculates a fisher-vector product. + def fisher_vector_product(self, vec, feed_val): + feed_val[self.flat_tangents] = vec + return self.session.run(self.fim, feed_dict=feed_val) + + def act(self, state): + return self.session.run(self.net, {self.input:state}) diff --git a/code/train/Python/0104366_optimal.py b/code/train/Python/0104366_optimal.py new file mode 100644 index 0000000000000000000000000000000000000000..04276182a2094fe71d5709f427c4624f87365f1e --- /dev/null +++ b/code/train/Python/0104366_optimal.py @@ -0,0 +1,190 @@ +#Iz modula Pyclustering smo si sposodili nekaj algoritmov. Avtor le-teh je Andrei Novikov. + +def manhattan_distance(a, b): + """! + @brief Calculate Manhattan distance between vector a and b. + + @param[in] a (list): The first cluster. + @param[in] b (list): The second cluster. + + @return (double) Manhattan distance between two vectors. + + """ + + if (((type(a) == float) and (type(b) == float)) or ((type(a) == int) and (type(b) == int))): + return abs(a - b) + + distance = 0.0 + dimension = len(a) + + for i in range(0, dimension): + distance += abs(a[i] - b[i]) + + return distance +#lahko bi vzela tudi svojo funkcijo razdalja .... + +def median(points, indexes=None): + """! + @brief Calculate geometric median of input set of points using Manhattan distance. + + @param[in] points (list): Set of points for median calculation. + @param[in] indexes (list): Indexes of objects in input set of points that will be taken into account during median calculation. + + @return (uint) index of point in input set that corresponds to median. + + """ + # Mi bomo uporabili manhattansko razdaljo za izracun mediane... + + index_median = None + distance = float('Inf') + + #range_points = None; tega sploh ne rabimo! + if (indexes is None): + range_points = range(len(points)) #ce nimamo indexov za mediane, potem vzamemo kar vse + else: + range_points = indexes + + for index_candidate in range_points: + distance_candidate = 0.0 #nastavimo razdaljo od kandidata do ostalih tock na 0 + for index in range_points: #gledamo po vseh indeksih, ki pridejo v upostev za mediane + distance_candidate += manhattan_distance(points[index_candidate], points[index]) #izracunamo, kaksna je njegova razdalja do ostalih tock + + if (distance_candidate < distance): + distance = distance_candidate + index_median = index_candidate + + return index_median #dobimo indeks tocke, ki je najblizja vsem ostalim tockam v danem seznamu + + + + +class kmedoids: + """! + @brief Class represents clustering algorithm K-Medoids (another one title is PAM - Parti). + @details The algorithm is less sensitive to outliers tham K-Means. The principle difference between K-Medoids and K-Medians is that + K-Medoids uses existed points from input data space as medoids, but median in K-Medians can be unreal object (not from + input data space). + + Example: + @code + # load list of points for cluster analysis + sample = read_sample(path); + + # create instance of K-Medoids algorithm + kmedians_instance = kmedians(sample, [1, 10]); + + # run cluster analysis and obtain results + kmedians_instance.process(); + kmedians_instance.get_clusters(); + @endcode + + """ + + def __init__(self, data, initial_index_medoids, tolerance=0.25): + """! + @brief Constructor of clustering algorithm K-Medoids. + + @param[in] data (list): Input data that is presented as list of points (objects), each point should be represented by list or tuple. + @param[in] initial_index_medoids (list): Indexes of intial medoids (indexes of points in input data). + @param[in] tolerance (double): Stop condition: if maximum value of distance change of medoids of clusters is less than tolerance than algorithm will stop processing. + + """ + self.__pointer_data = data + self.__clusters = [] + self.__medoids = initial_index_medoids + self.__tolerance = tolerance + + def process(self): + """! + @brief Performs cluster analysis in line with rules of K-Medoids algorithm. + + @remark Results of clustering can be obtained using corresponding get methods. + + @see get_clusters() + @see get_medoids() + + """ + + self.__medoids = [self.__pointer_data[medoid_index] for medoid_index in self.__medoids] + + changes = float('inf') + + stop_condition = self.__tolerance * self.__tolerance # Fast solution + # stop_condition = self.__tolerance; # Slow solution + + while (changes > stop_condition): + self.__clusters = self.__update_clusters() + updated_medoids = self.__update_medoids() # changes should be calculated before asignment + + changes = max([manhattan_distance(self.__medoids[index], updated_medoids[index]) for index in + range(len(updated_medoids))]) # Fast solution + + self.__medoids = updated_medoids + + def __update_clusters(self): + """! + @brief Calculate distance to each point from the each cluster. + @details Nearest points are captured by according clusters and as a result clusters are updated. + + @return (list) updated clusters as list of clusters where each cluster contains indexes of objects from data. + + """ + + clusters = [[] for i in range(len(self.__medoids))] + for index_point in range(len(self.__pointer_data)): + index_optim = -1 + dist_optim = 0.0 + + for index in range(len(self.__medoids)): + # dist = euclidean_distance_sqrt(self.__pointer_data[index_point], self.__medoids[index]); + dist = manhattan_distance(self.__pointer_data[index_point], self.__medoids[index]) + + if ((dist < dist_optim) or (index is 0)): + index_optim = index + dist_optim = dist + + clusters[index_optim].append(index_point) + #clusters[index_optim] += [index_point] + + # If cluster is not able to capture object it should be removed + clusters = [cluster for cluster in clusters if len(cluster) > 0] + + return clusters + + def __update_medoids(self): + """! + @brief Find medoids of clusters in line with contained objects. + + @return (list) list of medoids for current number of clusters. + + """ + + medoids = [[] for i in range(len(self.__clusters))] + + for index in range(len(self.__clusters)): + medoid_index = median(self.__pointer_data, self.__clusters[index]) + medoids[index] = self.__pointer_data[medoid_index] + + return medoids + + def get_clusters(self): + """! + @brief Returns list of allocated clusters, each cluster contains indexes of objects in list of data. + + @see process() + @see get_medoids() + + """ + + return self.__clusters + + def get_medoids(self): + """! + @brief Returns list of medoids of allocated clusters. + + @see process() + @see get_clusters() + + """ + + return self.__medoids \ No newline at end of file diff --git a/code/train/Python/0104452_myrandom.py b/code/train/Python/0104452_myrandom.py new file mode 100644 index 0000000000000000000000000000000000000000..64e93dd185ea13f81ad573c906b8067ae7330bc2 --- /dev/null +++ b/code/train/Python/0104452_myrandom.py @@ -0,0 +1,47 @@ +from _gfrd import RandomNumberGenerator, create_gsl_rng, create_static_gsl_rng +import numpy +import os + +__all__ = ( + 'shuffle', + 'uniform', + 'normal', + 'seed', + 'get_raw' + ) + +rng_number_file = os.environ.get('ECELL_STATIC_RNG', None) +if rng_number_file is not None: + rng = create_static_gsl_rng([int(l.strip()) for l in file(rng_number_file)]) +else: + rng = create_gsl_rng() + +def uniform(min=0.0, max=1.0, size=None): + global rng + return rng.uniform(min, max) + +get_raw = rng.get_raw +random = rng +normal = rng.normal +seed = rng.seed + +# By default seed is 0. +myseed = 0 + +# Choose seed at random. +#import random +#myseed = int(1e3 * random.random()) + +# Set seed. +seed(myseed) + +def shuffle(seq): + for i in reversed(range(0, len(seq))): + j = rng.uniform_int(0, i) + seq[i], seq[j] = seq[j], seq[i] + +def choice(a, b): + '''Return a or b with 50% probability each. + + ''' + return uniform() > 0.5 and a or b diff --git a/code/train/Python/0104840_streams.py b/code/train/Python/0104840_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..ec425cade84912db7008256bb76901244954c190 --- /dev/null +++ b/code/train/Python/0104840_streams.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 + +import argparse +import json +import os +import sys +from datetime import datetime + +import requests +from jinja2 import Template + +from qllr.db import db_connect +from qllr.settings import TWITCH_CLIENT_ID + +DIR = os.path.dirname(os.path.realpath(__file__)) +OUTPUT_PATH = DIR + "/../static/vods" + +pairs = ( + # ('sergeynixon', 76561198146349598), + # ('h8m3', 76561197976338965), + # ('omen812', 76561198256352933), + # ('p5ych0tr0n', 76561197995121689), + # ('alostraz', 76561198002370961), + # ('ch33rra', 76561198292668372), + # ('Klybi4', 76561198199452077), + # ('troolzrock', 76561198061282570), + # ('clawz', 76561198052511951), + ("madgabz", 76561197972763865), + ("caretocry", 76561197985202252), + ("bombaziin", 76561198256292896), +) + +db = db_connect() +cu = db.cursor() + + +def seconds_to_hms(seconds): + result = "" + m, s = divmod(seconds, 60) + h, m = divmod(m, 60) + if h > 0: + result += str(h) + "h" + return result + "{0}m{1}s".format(m, s) + + +def seconds_to_hms2(seconds): + m, s = divmod(seconds, 60) + h, m = divmod(m, 60) + return "{0}:{1}:{2}".format(str(h).zfill(2), str(m).zfill(2), str(s).zfill(2)) + + +def get_twitch_videos(account): + + r = requests.get( + "https://api.twitch.tv/kraken/users?login={0}".format(account), + headers={ + "Client-ID": TWITCH_CLIENT_ID, + "Accept": "application/vnd.twitchtv.v5+json", + }, + ) + + data = r.json() + + # fallback if user not found + if not data["_total"]: + return {"_total": 0, "videos": []} + + user_id = data["users"][0]["_id"] + + r = requests.get( + "https://api.twitch.tv/kraken/channels/{0}/videos?limit=100&broadcast_type=archive".format( + user_id + ), + headers={ + "Client-ID": TWITCH_CLIENT_ID, + "Accept": "application/vnd.twitchtv.v5+json", + }, + ) + + return r.json() + + +def grab_matches(videos, steam_id): + for v in videos: + video_start_timestamp = int( + datetime.strptime( + v["recorded_at"] + "+0000", "%Y-%m-%dT%H:%M:%SZ%z" + ).timestamp() + ) + video_end_timestamp = video_start_timestamp + v["length"] + v["recorded_at_timestamp"] = video_start_timestamp + cu.execute( + """ +SELECT s.match_id, m.timestamp-m.duration, m.duration, mm.map_name +FROM ( + SELECT match_id, steam_id + FROM scoreboards + WHERE steam_id = %(steam_id)s +) s +LEFT JOIN matches m ON s.match_id = m.match_id +LEFT JOIN maps mm ON m.map_id = mm.map_id +WHERE + m.timestamp-m.duration < %(video_end)s AND + m.timestamp-m.duration > %(video_start)s +ORDER BY m.timestamp ASC + """, + { + "steam_id": steam_id, + "video_end": video_end_timestamp, + "video_start": video_start_timestamp, + }, + ) + v["matches"] = [] + + for row in cu.fetchall(): + v["matches"].append( + { + "start_time": row[1] - video_start_timestamp, + "map": row[3], + "duration": row[2], + "match_id": row[0], + } + ) + v["matches"].sort(key=lambda v: -v["start_time"]) + videos.sort(key=lambda v: -v["recorded_at_timestamp"]) + return videos + + +video_entry_template = Template( + """ +

{{ title|e }}

+{% for match in matches %} + {{ match.link }} {{ match.mapname }} +
{{ match.command }}
+
+{% endfor %} +""" +) + +for account, steam_id in pairs: + result = get_twitch_videos(account) + + if "videos" not in result: + continue + + with open("{}.html".format(OUTPUT_PATH + "/" + account), "w") as f: + videos = grab_matches(result["videos"], steam_id) + for v in videos: + # from pprint import pprint + # pprint(v) + + if len(v["matches"]) == 0: + continue + + entry = video_entry_template.render( + title=v["title"], + matches=map( + lambda match: { + "link": v["url"] + "?t=" + seconds_to_hms(match["start_time"]), + "mapname": match["map"], + # Thanks to JaySandhu for this: + # https://github.com/ytdl-org/youtube-dl/issues/622#issuecomment-162337869 + "command": "ffmpeg -ss {0} -i `youtube-dl -g {4}` -t {1} -c copy {2}_{3}.mp4".format( + seconds_to_hms2(match["start_time"] - 5), + seconds_to_hms2(match["duration"] + 60), + account, + "{}_{}_{}".format( + v["_id"], match["map"], match["start_time"] + ), + v["url"], + ), + }, + v["matches"], + ), + ) + + print(entry, file=f) diff --git a/code/train/Python/0104939_function.py b/code/train/Python/0104939_function.py new file mode 100644 index 0000000000000000000000000000000000000000..67769f497660b9c4dc7f1bbca0f5f0ec28de7782 --- /dev/null +++ b/code/train/Python/0104939_function.py @@ -0,0 +1,134 @@ +###################################################################### +## +## Copyright (C) 2006, Simon Kagstrom +## +## Filename: function.py +## Author: Simon Kagstrom +## Description: Function defs (inherits codeblock) +## +## $Id: function.py 13391 2007-02-02 12:26:28Z ska $ +## +###################################################################### +from Cibyl.BinaryTranslation.codeblock import CodeBlock +from Cibyl.BinaryTranslation.basicblock import BasicBlock +from Cibyl import config +import Mips.instruction as instruction +import Mips.mips as mips + +class Function(CodeBlock): + """Container class for functions""" + def __init__(self, controller, name, instructions, labels, trace=False): + CodeBlock.__init__(self, controller, instructions, labels, trace, setupRegisters = True) + self.name = name + sym = self.controller.elf.getSymbolByAddress(self.address) + if self.address == self.controller.elf.getEntryPoint(): + self.name = "start" + elif sym.localLinkage(): + self.name = self.name + "_%x" % (self.address) + self.basicBlocks = [] + + # Assume this is a leaf function, but non-recursive + self.isLeafFunction = True + self.isRecursive = False + + # Create basic blocks and check leafness + first = 0 + last = 0 + for insn in self.instructions: + last = last + 1 + if insn.isBranch or insn.isBranchDestination and not insn.address == self.address: + # Remove the last instruction if this is a branch - + # but not for the function entry point. The reason is + # that some functions might start with a branch + if insn.isBranchDestination and not insn.address == self.address: + last = last - 1 + if last != first: + # Do not append empty basic blocks + bb = BasicBlock(self.controller, self.instructions[first:last], self.labels, trace) + self.basicBlocks.append(bb) + first = last + if insn.isBranchDestination and not insn.address == self.address: + last = last + 1 + + if insn.isFunctionCall: + self.isLeafFunction = False + + # Is this a recursive function call (only Jal is important) + if isinstance(insn, instruction.Jal) and insn.dstAddress == self.address: + self.isRecursive = True + insn.setFunction(self) + else: + # Last one + if last != first: + self.basicBlocks.append(BasicBlock(self.controller, self.instructions[first:last], self.labels, trace)) + + def isLeaf(self): + return self.isLeafFunction + + def getReturnBasicBlocks(self): + out = [] + for bb in self.basicBlocks: + if bb.isReturnBlock: + out.append(bb) + return out + + def setIndex(self, index): + "Set the index of this function (within a multi-function Java method)" + self.index = index + + def getIndex(self): + return self.index + + def setJavaMethod(self, method): + "Define which java method this instruction is in" + self.javaMethod = method + + def getJavaMethod(self): + "Return which java method this instruction is in" + return self.javaMethod + + def doSkipStackStoreOptimization(self): + """Optimization to skip the stack saving and restoring since + these are not actually needed with Cibyl (registers in local + java variables)""" + + def instructionIsStackStore(insn): + return isinstance(insn, instruction.Sw) and insn.rt in mips.callerSavedRegisters and insn.rs == mips.R_SP + + def instructionIsStackLoad(insn): + return isinstance(insn, instruction.Lw) and insn.rt in mips.callerSavedRegisters and insn.rs == mips.R_SP + + for insn in self.basicBlocks[0].instructions: + if instructionIsStackStore(insn): + if config.verbose: print "Removing", insn + insn.nullify() + + returnBasicBlocks = self.getReturnBasicBlocks() + for bb in returnBasicBlocks: + for insn in bb.instructions: + # Validate that there is no use of the saved registers + for dst in self.destinationRegisters: + if dst in mips.callerSavedRegisters and not instructionIsStackLoad(insn): + continue + + for insn in bb.instructions: + if instructionIsStackLoad(insn): + if config.verbose: print "Removing", insn + insn.nullify() + + def fixup(self): + # Perform skip stack store optimization. This optimization + # should not be done if this is a recursive function and it is + # contained in a multiple-functions method since the MIPS + # registers are not automatically saved then + if not config.debug and not (self.javaMethod.hasMultipleFunctions() and self.isRecursive): + self.doSkipStackStoreOptimization() + + def compile(self): + "Compile this basic block to Java assembly" + for bb in self.basicBlocks: + bb.compile() + + def __str__(self): + out = "%s:\n" % (self.name) + return out + CodeBlock.__str__(self) diff --git a/code/train/Python/0105671_ImageAnalysis.py b/code/train/Python/0105671_ImageAnalysis.py new file mode 100644 index 0000000000000000000000000000000000000000..4979c50a0238b56b428fba51a21feb229512ee1a --- /dev/null +++ b/code/train/Python/0105671_ImageAnalysis.py @@ -0,0 +1,233 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from acq4.util import Qt +from acq4.analysis.AnalysisModule import AnalysisModule +from collections import OrderedDict +import acq4.pyqtgraph as pg +from acq4.util.metaarray import MetaArray +import numpy as np + +class ImageAnalysis(AnalysisModule): + def __init__(self, host): + AnalysisModule.__init__(self, host) + + self.background = None + + #self.view = pg.GraphicsView() + self.ctrl = Qt.QWidget() + l = Qt.QGridLayout() + self.ctrl.setLayout(l) + self.ctrl.layout = l + #self.loadBgBtn = Qt.QPushButton('load reference') + #l.addWidget(self.loadBgBtn, 0, 0) + self.addRoiBtn = Qt.QPushButton('add ROI') + l.addWidget(self.addRoiBtn, 0, 0) + s = Qt.QSpinBox() + s.setMaximum(10) + s.setMinimum(1) + self.nsegSpin = s + l.addWidget(s, 1, 0) + self.rois = [] + self.data = [] + + + ## Setup basic GUI + self._elements_ = OrderedDict([ + ('File Loader', {'type': 'fileInput', 'size': (200, 300), 'host': self, 'showFileTree': False}), + ('Image', {'type': 'imageView', 'pos': ('right', 'File Loader'), 'size': (800, 300)}), + ('Time Plot', {'type': 'plot', 'pos': ('bottom',), 'size': (800, 300)}), + ('Trial Plot', {'type': 'plot', 'pos': ('bottom', 'Time Plot'), 'size': (800, 300)}), + ('Line Scan', {'type': 'imageView', 'pos': ('right', 'Time Plot'), 'size': (800, 300)}), + #('Data Table', {'type': 'table', 'pos': ('below', 'Time Plot')}), + ('Ctrl', {'type': 'ctrl', 'pos': ('bottom', 'File Loader'), 'size': (200,30), 'object': self.ctrl}), + ]) + self.initializeElements() + + #self.traces = None + self.plot = self.getElement('Time Plot', create=True) + self.plot2 = self.getElement('Trial Plot', create=True) + self.lr = pg.LinearRegionItem([0, 1]) + self.plot.addItem(self.lr) + + self.view = self.getElement('Image', create=True) + + ## Add a color scale + ## removed for now--seems to be causing crashes :( + #self.colorScale = pg.GradientLegend(self.plot1, (20, 150), (-10, -10)) + #self.plot1.scene().addItem(self.colorScale) + + ## Plots are updated when the selected region changes + self.lr.sigRegionChanged.connect(self.updateAnalysis) + self.addRoiBtn.clicked.connect(self.addRoi) + self.view.sigProcessingChanged.connect(self.processData) + #self.loadBgBtn.clicked.connect(self.loadBg) + + def addRoi(self): + if self.nsegSpin.value() == 1: + roi = pg.widgets.LineROI((0,0), (20, 20), 5) + else: + pts = [(i*10,i*10) for i in range(self.nsegSpin.value()+1)] + roi = pg.widgets.MultiLineROI(pts, 5) + self.rois.append(roi) + self.view.addItem(roi) + roi.sigRegionChanged.connect(self.roiChanged) + + def roiChanged(self, roi): + if isinstance(roi, int): + roi = self.currentRoi + self.plot.clearPlots() + c = 0 + lineScans = [] + for imgSet in self.data: + data = roi.getArrayRegion(imgSet['procMean'], self.view.imageItem, axes=(1,2)) + m = data.mean(axis=1).mean(axis=1) + lineScans.append(data.mean(axis=2)) + spacer = np.empty((lineScans[-1].shape[0], 1), dtype = lineScans[-1].dtype) + spacer[:] = lineScans[-1].min() + lineScans.append(spacer) + + data = roi.getArrayRegion(imgSet['procStd'], self.view.imageItem, axes=(1,2)) + s = data.mean(axis=1).mean(axis=1) + + self.plot.plot(m, pen=pg.hsvColor(c*0.2, 1.0, 1.0)) + self.plot.plot(m-s, pen=pg.hsvColor(c*0.2, 1.0, 0.4)) + self.plot.plot(m+s, pen=pg.hsvColor(c*0.2, 1.0, 0.4)) + + c += 1 + + lineScan = np.hstack(lineScans) + self.getElement('Line Scan').setImage(lineScan) + self.currentRoi = roi + + def processData(self): + self.normData = [] + self.data = [] + for img in self.rawData: + n = np.empty(img.shape, dtype=img.dtype) + for i in range(img.shape[0]): + n[i] = self.view.normalize(img[i]) + self.normData.append(n) + + imgSet = {'procMean': n.mean(axis=0), 'procStd': n.std(axis=0)} + self.data.append(imgSet) + + def updateAnalysis(self): + roi = self.currentRoi + plot = self.getElement('Trial Plot') + plot.clearPlots() + c = 0 + for img in self.normData: + #img = img.mean(axis=1) + rgn = self.lr.getRegion() + img = img[:, rgn[0]:rgn[1]].mean(axis=1) + data = roi.getArrayRegion(img, self.view.imageItem, axes=(1,2)) + m = data.mean(axis=1).mean(axis=1) + #data = roi.getArrayRegion(img, self.view.imageItem, axes=(1,2)) + #s = data.mean(axis=1).mean(axis=1) + plot.plot(m, pen=pg.hsvColor(c*0.2, 1.0, 1.0)) + #self.plot.plot(m-s, pen=pg.hsvColor(c*0.2, 1.0, 0.4)) + #self.plot.plot(m+s, pen=pg.hsvColor(c*0.2, 1.0, 0.4)) + c += 1 + + #if c == 1: + #self.getElement('Line Scan').setImage(data.mean(axis=2)) + #if self.traces is None: + #return + #rgn = self.lr.getRegion() + #data = self.traces['Time': rgn[0]:rgn[1]] + #self.plot2.plot(data.mean(axis=1), clear=True) + #self.plot2.plot(data.max(axis=1)) + #self.plot2.plot(data.min(axis=1)) + + + def loadFileRequested(self, dh): + """Called by file loader when a file load is requested.""" + if len(dh) != 1: + raise Exception("Can only load one file at a time.") + dh = dh[0] + + if dh.isFile(): + self.background = dh.read()[np.newaxis,...].astype(float) + self.background /= self.background.max() + return + + + self.plot.clearPlots() + dirs = dh.subDirs() + + images = [[],[],[],[]] + + ## Iterate over sequence + minFrames = None + + for d in dirs: + d = dh[d] + try: + ind = d.info()[('Clamp1', 'amp')] + except: + print(d) + print(d.info()) + raise + img = d['Camera/frames.ma'].read() + images[ind].append(img) + + if minFrames is None or img.shape[0] < minFrames: + minFrames = img.shape[0] + + + self.rawData = [] + self.data = [] + #print "len images: %d " % (len(images)) + while len(images) > 0: + imgs = images.pop(0) + img = np.concatenate([i[np.newaxis,:minFrames,...] for i in imgs], axis=0) + self.rawData.append(img.astype(np.float32)) + #img /= self.background + + ## remove bleaching curve from first two axes + ctrlMean = self.rawData[0].mean(axis=2).mean(axis=2) + trialCurve = ctrlMean.mean(axis=1)[:,np.newaxis,np.newaxis,np.newaxis] + timeCurve = ctrlMean.mean(axis=0)[np.newaxis,:,np.newaxis,np.newaxis] + del ctrlMean + for img in self.rawData: + img /= trialCurve + img /= timeCurve + + + + #for img in self.rawData: + + #m = img.mean(axis=0) + #s = img.std(axis=0) + #if self.background is not None: + #m = m.astype(np.float32) + #m /= self.background + #s = s.astype(np.float32) + #s /= self.background + #imgSet = {'mean': m, 'std': s} + #self.data.append(imgSet) + #self.imgMeans.append(m) + #self.imgStds.append(s) + + self.view.setImage(self.rawData[1].mean(axis=0)) + + self.processData() + + ## set up the selection region correctly and prepare IV curves + #if len(dirs) > 0: + #end = cmd.xvals('Time')[-1] + #self.lr.setRegion([end *0.5, end * 0.6]) + #self.updateAnalysis() + #info = [ + #{'name': 'Command', 'units': cmd.axisUnits(-1), 'values': np.array(values)}, + #data.infoCopy('Time'), + #data.infoCopy(-1)] + #self.traces = MetaArray(np.vstack(traces), info=info) + + return True + + + + + + \ No newline at end of file diff --git a/code/train/Python/0105756_simulation.py b/code/train/Python/0105756_simulation.py new file mode 100644 index 0000000000000000000000000000000000000000..df02405db1ec6cd55f5ee4072ce3712384bce750 --- /dev/null +++ b/code/train/Python/0105756_simulation.py @@ -0,0 +1,161 @@ +''' +Created on 16.3.2012 + +@author: Antti Vainio +''' + +from leader import leader +from follower import follower +from vector import vector +from thinker import unitType + +class simulation(): + ''' + This class handles the calculation of simulation. + + A single frame can be calculated and executed just by calling calculateFrame() once. + When a single frame is calculated, + first the new positions for all the thinkers are calculated + and only after that they are moved to their new positions. + This is because if they were moved instantly + the thinkers that were calculated after the first ones would use their new positions instead of their old ones. + + New thinkers can also be created and old ones removed with simple function calls to this class. + Also when the window is resized this class should be informed for that + as the random placement of thinkers use that information. + + This class also handles "moving the camera". + This is done so that first the new "position" for the camera is determined + and then all the thinkers are displaced so that they are in the middle of the window. + This way the simulation area is practically infinite. + ''' + + def __init__(self, x, y, amount, force_leader = False): + ''' + x and y are the current dimensions of the window. + amount is the amount of followers to be created. + If any followers are to be created a leader will also be created, + otherwise no leader will be created. + if force_leader is set a leader will be created even if no followers are created. + ''' + self.framecount = 0 #1 is added to this every time calculateFrame() is called + self.window_middle = vector(x, y) / 2.0 + self.mean_position = vector(0, 0) + self.thinkers = [] + self.leader = None + self.thinker_near_mouse = None + self.active_thinker = None + if amount or force_leader: + self.thinkers.append(leader(False, x, y)) + self.leader = self.thinkers[0] + for i in range(amount): self.thinkers.append(follower(self.leader, x, y)) + self.cam_movement = [] + self.cam_offset = vector(0, 0) + self.camera_follow = True + self.user_controlled_leader = False + + + def setWindowSize(self, x, y): + ''' + This should be called every time the window is resized. + ''' + self.window_middle = vector(x, y) / 2.0 + del self.cam_movement[:] + + + def move_camera(self, x, y): + ''' + Is used for user forced camera movement. + ''' + offset_vector = vector(x, y) + for i in self.thinkers: i.displace(offset_vector) + ''' + -1 is added there to "fix" an error + This used to throw an out of range error probably because: + len(self.cam_movement) is 35 at first which is also the maximum + then in calculateFrame() cam_movement gets popped + then the following 'for' reaches the end where there is no object anymore + and throws an error + this can happen because these two functions can be called simultaneously because of threading + This "fix" only makes the last one of the camera trail dots (that is also soon to be deleted) + not to move in the debug-drawing mode when user is moving the camera + ''' + for i in range(len(self.cam_movement) - 1): self.cam_movement[i]+= offset_vector + self.cam_offset+= offset_vector + + + def setMousePosition(self, x = -1000, y = -1000): + ''' + This is used to inform this class about the position of the mouse. + ''' + best_thinker = None + best_value = 300 + for i in self.thinkers: + value = (i.pos.x - x) ** 2 + (i.pos.y - y) ** 2 + if value < best_value: + best_thinker = i + best_value = value + self.thinker_near_mouse = best_thinker + + + def chooseThinker(self): + ''' + Sets the active thinker. + ''' + self.active_thinker = self.thinker_near_mouse + if not self.active_thinker: return unitType.none + elif self.active_thinker.is_leader: return unitType.leader + return unitType.follower + + + def removeThinker(self, thinker): + if thinker.is_leader: + for i in self.thinkers: i.leader = None + self.leader = None + self.thinkers.remove(thinker) + + + def createLeader(self, max_speed, max_force, size, random_position = True, x = 0, y = 0): + old_leader = self.leader + if random_position: self.thinkers.append(leader(self.user_controlled_leader, self.window_middle.x * 2.0, self.window_middle.y * 2.0, max_speed, max_force, size)) + else: self.thinkers.append(leader(self.user_controlled_leader, x, y, max_speed, max_force, size, False)) + self.leader = self.thinkers[-1] + for i in range(len(self.thinkers) - 1): self.thinkers[i].leader = self.leader + if old_leader: self.thinkers.remove(old_leader) + + + def createFollower(self, max_speed, max_force, size, random_position = True, x = 0, y = 0): + if random_position: self.thinkers.append(follower(self.leader, self.window_middle.x * 2.0, self.window_middle.y * 2.0, max_speed, max_force, size)) + else: self.thinkers.append(follower(self.leader, x, y, max_speed, max_force, size, False)) + + + def calculateFrame(self): + ''' + First lets every thinker determine their new position. + Then lets them move to their new positions + and also displaces them so that they are in the middle of the window. + Then calculates the new displacement values for the next frame. + Finally handles camera trail and its displacement. + ''' + if not len(self.thinkers): return + self.framecount+= 1 + if self.camera_follow: offset_vector = self.mean_position + else: offset_vector = vector(0, 0) + self.mean_position = vector(0, 0) + for i in self.thinkers: + i.think(self.thinkers) + for i in self.thinkers: + i.move() + i.displace(offset_vector) + self.mean_position+= i.pos + self.mean_position/= len(self.thinkers) + self.mean_position = self.window_middle - self.mean_position + #camera movement trail and offset + if self.framecount % 20 == 0: + if len(self.cam_movement) == 35: self.cam_movement.pop() + for i in range(len(self.cam_movement)): self.cam_movement[i]+= offset_vector + #for i in self.cam_movement: i+= offset_vector + if self.framecount % 20 == 0: self.cam_movement.insert(0, self.window_middle + self.window_middle / 3.0) + self.cam_offset+= offset_vector + + \ No newline at end of file diff --git a/code/train/Python/0105940_router.py b/code/train/Python/0105940_router.py new file mode 100644 index 0000000000000000000000000000000000000000..a38992320eb7a2be42d55535c710274d5048fb59 --- /dev/null +++ b/code/train/Python/0105940_router.py @@ -0,0 +1,214 @@ +"""Represent the Freebox router and its devices and sensors.""" +from datetime import datetime, timedelta +import logging +import os +from pathlib import Path +from typing import Any, Dict, List, Optional + +from freebox_api import Freepybox +from freebox_api.api.wifi import Wifi +from freebox_api.exceptions import HttpRequestError + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import CONF_HOST, CONF_PORT +from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC +from homeassistant.helpers.dispatcher import async_dispatcher_send +from homeassistant.helpers.event import async_track_time_interval +from homeassistant.helpers.typing import HomeAssistantType +from homeassistant.util import slugify + +from .const import ( + API_VERSION, + APP_DESC, + CONNECTION_SENSORS, + DOMAIN, + STORAGE_KEY, + STORAGE_VERSION, +) + +_LOGGER = logging.getLogger(__name__) + +SCAN_INTERVAL = timedelta(seconds=30) + + +async def get_api(hass: HomeAssistantType, host: str) -> Freepybox: + """Get the Freebox API.""" + freebox_path = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY).path + + if not os.path.exists(freebox_path): + await hass.async_add_executor_job(os.makedirs, freebox_path) + + token_file = Path(f"{freebox_path}/{slugify(host)}.conf") + + return Freepybox(APP_DESC, token_file, API_VERSION) + + +class FreeboxRouter: + """Representation of a Freebox router.""" + + def __init__(self, hass: HomeAssistantType, entry: ConfigEntry) -> None: + """Initialize a Freebox router.""" + self.hass = hass + self._entry = entry + self._host = entry.data[CONF_HOST] + self._port = entry.data[CONF_PORT] + + self._api: Freepybox = None + self.name = None + self.mac = None + self._sw_v = None + self._attrs = {} + + self.devices: Dict[str, Dict[str, Any]] = {} + self.disks: Dict[int, Dict[str, Any]] = {} + self.sensors_temperature: Dict[str, int] = {} + self.sensors_connection: Dict[str, float] = {} + self.call_list: List[Dict[str, Any]] = [] + + self._unsub_dispatcher = None + self.listeners = [] + + async def setup(self) -> None: + """Set up a Freebox router.""" + self._api = await get_api(self.hass, self._host) + + try: + await self._api.open(self._host, self._port) + except HttpRequestError: + _LOGGER.exception("Failed to connect to Freebox") + return ConfigEntryNotReady + + # System + fbx_config = await self._api.system.get_config() + self.mac = fbx_config["mac"] + self.name = fbx_config["model_info"]["pretty_name"] + self._sw_v = fbx_config["firmware_version"] + + # Devices & sensors + await self.update_all() + self._unsub_dispatcher = async_track_time_interval( + self.hass, self.update_all, SCAN_INTERVAL + ) + + async def update_all(self, now: Optional[datetime] = None) -> None: + """Update all Freebox platforms.""" + await self.update_device_trackers() + await self.update_sensors() + + async def update_device_trackers(self) -> None: + """Update Freebox devices.""" + new_device = False + fbx_devices: [Dict[str, Any]] = await self._api.lan.get_hosts_list() + + # Adds the Freebox itself + fbx_devices.append( + { + "primary_name": self.name, + "l2ident": {"id": self.mac}, + "vendor_name": "Freebox SAS", + "host_type": "router", + "active": True, + "attrs": self._attrs, + } + ) + + for fbx_device in fbx_devices: + device_mac = fbx_device["l2ident"]["id"] + + if self.devices.get(device_mac) is None: + new_device = True + + self.devices[device_mac] = fbx_device + + async_dispatcher_send(self.hass, self.signal_device_update) + + if new_device: + async_dispatcher_send(self.hass, self.signal_device_new) + + async def update_sensors(self) -> None: + """Update Freebox sensors.""" + # System sensors + syst_datas: Dict[str, Any] = await self._api.system.get_config() + + # According to the doc `syst_datas["sensors"]` is temperature sensors in celsius degree. + # Name and id of sensors may vary under Freebox devices. + for sensor in syst_datas["sensors"]: + self.sensors_temperature[sensor["name"]] = sensor["value"] + + # Connection sensors + connection_datas: Dict[str, Any] = await self._api.connection.get_status() + for sensor_key in CONNECTION_SENSORS: + self.sensors_connection[sensor_key] = connection_datas[sensor_key] + + self._attrs = { + "IPv4": connection_datas.get("ipv4"), + "IPv6": connection_datas.get("ipv6"), + "connection_type": connection_datas["media"], + "uptime": datetime.fromtimestamp( + round(datetime.now().timestamp()) - syst_datas["uptime_val"] + ), + "firmware_version": self._sw_v, + "serial": syst_datas["serial"], + } + + self.call_list = await self._api.call.get_calls_log() + + await self._update_disks_sensors() + + async_dispatcher_send(self.hass, self.signal_sensor_update) + + async def _update_disks_sensors(self) -> None: + """Update Freebox disks.""" + # None at first request + fbx_disks: [Dict[str, Any]] = await self._api.storage.get_disks() or [] + + for fbx_disk in fbx_disks: + self.disks[fbx_disk["id"]] = fbx_disk + + async def reboot(self) -> None: + """Reboot the Freebox.""" + await self._api.system.reboot() + + async def close(self) -> None: + """Close the connection.""" + if self._api is not None: + await self._api.close() + self._unsub_dispatcher() + self._api = None + + @property + def device_info(self) -> Dict[str, Any]: + """Return the device information.""" + return { + "connections": {(CONNECTION_NETWORK_MAC, self.mac)}, + "identifiers": {(DOMAIN, self.mac)}, + "name": self.name, + "manufacturer": "Freebox SAS", + "sw_version": self._sw_v, + } + + @property + def signal_device_new(self) -> str: + """Event specific per Freebox entry to signal new device.""" + return f"{DOMAIN}-{self._host}-device-new" + + @property + def signal_device_update(self) -> str: + """Event specific per Freebox entry to signal updates in devices.""" + return f"{DOMAIN}-{self._host}-device-update" + + @property + def signal_sensor_update(self) -> str: + """Event specific per Freebox entry to signal updates in sensors.""" + return f"{DOMAIN}-{self._host}-sensor-update" + + @property + def sensors(self) -> Dict[str, Any]: + """Return sensors.""" + return {**self.sensors_temperature, **self.sensors_connection} + + @property + def wifi(self) -> Wifi: + """Return the wifi.""" + return self._api.wifi diff --git a/code/train/Python/0105999_gnrprinthandler.py b/code/train/Python/0105999_gnrprinthandler.py new file mode 100644 index 0000000000000000000000000000000000000000..108e24f0e832f58603a89d4fe6f66a128c07025f --- /dev/null +++ b/code/train/Python/0105999_gnrprinthandler.py @@ -0,0 +1,235 @@ +try: + import cups + + HAS_CUPS = True +except ImportError: + HAS_CUPS = False + +import os.path +from subprocess import call + +try: + import warnings + + warnings.filterwarnings(category=DeprecationWarning, module='pyPdf', action='ignore') + from pyPdf import PdfFileWriter, PdfFileReader + from cStringIO import StringIO + + HAS_PYPDF = True +except ImportError: + HAS_PYPDF = False + +from gnr.core.gnrbag import Bag, DirectoryResolver +from gnr.core.gnrbaseservice import GnrBaseService +import sys + +class PrinterConnection(GnrBaseService): + """add??? + """ + service_name='print' + + def __init__(self, parent, printer_name=None, printerParams=None, **kwargs): + self.parent = parent + self.orientation = printerParams.pop('orientation',None) + if printer_name == 'PDF': + self.initPdf(printerParams=printerParams, **kwargs) + else: + self.initPrinter(printer_name, printerParams, **kwargs) + + def initPdf(self, printerParams=None, **kwargs): + """add??? + + :param printerParams: add???. Default value is ``None`` + """ + self.zipped = printerParams.pop('zipped') + self.printAgent = self.printPdf + + def printPdf(self, pdf_list, jobname, outputFilePath=None): + """add??? + + :param pdf_list: add??? + :param jobname: add??? + :param outputFilePath: add???. Default value is ``None`` + """ + if self.zipped: + outputFilePath += '.zip' + self.parent.zipPdf(pdf_list, outputFilePath) + else: + outputFilePath += '.pdf' + self.parent.joinPdf(pdf_list, outputFilePath) + return os.path.basename(outputFilePath) + + def printCups(self, pdf_list, jobname, **kwargs): + """add??? + + :param pdf_list: add??? + :param jobname: add??? + """ + self.cups_connection.printFiles(self.printer_name, pdf_list, jobname, self.printer_options) + + def initPrinter(self, printer_name=None, printerParams=None, **kwargs): + """add??? + + :param printer_name: add???. Default value is ``None`` + :param printerParams: add???. Default value is ``None`` + """ + printerParams = printerParams or Bag() + self.cups_connection = cups.Connection() + self.printer_name = printer_name + printer_media = [] + for media_option in ('paper', 'tray', 'source'): + media_value = printerParams['printer_options'] and printerParams['printer_options'].pop(media_option) + if media_value: + printer_media.append(media_value) + self.printer_options = printerParams['printer_options'] or {} + if printer_media: + self.printer_options['media'] = str(','.join(printer_media)) + self.printAgent = self.printCups + + def printFiles(self, file_list, jobname='GenroPrint', storeFolder=None, outputFilePath=None): + pdf_list = self.parent.autoConvertFiles(file_list, storeFolder, orientation=self.orientation) + return self.printAgent(pdf_list, jobname, outputFilePath=outputFilePath) + +class PrintHandler(object): + """add??? + """ + paper_size = { + 'A4': '!!A4', + 'Legal': '!!Legal', + 'A4Small': '!!A4 with margins', + 'COM10': '!!COM10', + 'DL': '!!DL', + 'Letter': '!!Letter', + 'ISOB5': 'ISOB5', + 'JISB5': 'JISB5', + 'LetterSmall': 'LetterSmall', + 'LegalSmall': 'LegalSmall' + } + paper_tray = { + 'MultiPurpose': '!!MultiPurpose', + 'Transparency': '!!Transparency', + 'Upper': '!!Upper', + 'Lower': '!!Lower', + 'LargeCapacity': '!!LargeCapacity' + } + + def __init__(self, parent=None): + global HAS_CUPS, HAS_PYPDF + self.hasCups = HAS_CUPS + self.hasPyPdf = HAS_PYPDF + self.parent = parent + + def htmlToPdf(self, srcPath, destPath, orientation=None): #srcPathList per ridurre i processi? + """add??? + + :param src_path: add??? + :param destPath: add??? + :param orientation: add???. Default value is ``None`` + :returns: add??? + """ + orientation = orientation or 'Portrait' + if os.path.isdir(destPath): + baseName = os.path.splitext(os.path.basename(srcPath))[0] + destPath = os.path.join(destPath, '%s.pdf' % baseName) + if sys.platform.startswith('linux'): + result = call(['wkhtmltopdf', '-q', '-O', orientation, srcPath, destPath]) + else: + result = call(['wkhtmltopdf', '-q', '-O', orientation, srcPath, destPath]) + if result < 0: + raise PrintHandlerError('wkhtmltopdf error') + return destPath + + def autoConvertFiles(self, files, storeFolder): + """add??? + + :param files: add??? + :param storeFolder: add??? + """ + resultList = [] + for filename in files: + baseName, ext = os.path.splitext(os.path.basename(filename)) + if ext.lower() == '.html': + resultList.append(self.htmlToPdf(filename, storeFolder)) + + #destPath=os.path.join(storeFolder, '%s.pdf' % baseName) + + #if sys.platform.startswith('linux'): + # result = call(['wkhtmltopdf','-q',filename,destPath]) + #else: + # result = call(['wkhtmltopdf','-q',filename,destPath]) + #if result < 0: + # raise PrintHandlerError('wkhtmltopdf error') + #resultList.append(destPath) + elif ext.lower() == '.pdf': + resultList.append(filename) + else: + raise + return resultList + + def getPrinters(self): + """add??? + """ + printersBag = Bag() + if self.hasCups: + cups_connection = cups.Connection() + for printer_name, printer in cups_connection.getPrinters().items(): + printer.update(dict(name=printer_name)) + printersBag.setItem('%s.%s' % (printer['printer-location'], printer_name), None, printer) + else: + print 'pyCups is not installed' + return printersBag + + def getPrinterAttributes(self, printer_name): + """add??? + + :param printer_name: add??? + """ + cups_connection = cups.Connection() + printer_attributes = cups_connection.getPrinterAttributes(printer_name) + attributesBag = Bag() + for i, (media, description) in enumerate(self.paper_size.items()): + if media in printer_attributes['media-supported']: + attributesBag.setItem('paper_supported.%i' % i, None, id=media, caption=description) + for i, (tray, description) in enumerate(self.paper_tray.items()): + if tray in printer_attributes['media-supported']: + attributesBag.setItem('tray_supported.%i' % i, None, id=tray, caption=description) + return attributesBag + + def getPrinterConnection(self, printer_name=None, printerParams=None, **kwargs): + """add??? + + :param printer_name: add???. Default value is ``None`` + :param printerParams: add???. Default value is ``None`` + """ + return PrinterConnection(self, printer_name=printer_name, printerParams=printerParams, **kwargs) + + def joinPdf(self, pdf_list, output_filepath): + """add??? + + :param pdf_list: add??? + :param output_filepath: add??? + """ + output_pdf = PdfFileWriter() + open_files = [] + for input_path in pdf_list: + input_file = open(input_path, 'rb') + memory_file = StringIO(input_file.read()) + open_files.append(memory_file) + input_file.close() + input_pdf = PdfFileReader(memory_file) + for page in input_pdf.pages: + output_pdf.addPage(page) + output_file = open(output_filepath, 'wb') + output_pdf.write(output_file) + output_file.close() + for input_file in open_files: + input_file.close() + + def zipPdf(self, file_list=None, zipPath=None): + """add??? + + :param file_list: add???. Default value is ``None`` + :param zipPath: add???. Default value is ``None`` + """ + self.parent.zipFiles(file_list=file_list, zipPath=zipPath) + \ No newline at end of file diff --git a/code/train/Python/0106156_promote.py b/code/train/Python/0106156_promote.py new file mode 100644 index 0000000000000000000000000000000000000000..b5e6f0f1b9351048614073ec0cdb716eaa594a8e --- /dev/null +++ b/code/train/Python/0106156_promote.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python + +import sys +from qt import * +from promoter import main_form +from environment_form import env_form +from pyrpm.rpm import RPM +from pyrpm import rpmdefs +import re +import os +import shutil + + +DEBUG = 0 +PROD_HOSTS = ['s1-noc-01', 's2-noc-01'] + +#======================================================== + + +INT_TO_PPLT = 0 +PP_TO_PROD = 0 +DIR = '' +TO_PATH = [] +RPM_REGEX = re.compile(r""".+\.rpm$""") + +PACKAGES_DICT = {} + +ENVIRONMENT = "" + +class Promo(main_form): + def __init__(self, parent=None, name=None, fl=0): + main_form.__init__(self,parent,name,fl) + + self.connect(self.name_list, SIGNAL("selectionChanged()"), self.name_list_selectionChanged) + self.connect(self.version_list, SIGNAL("selectionChanged()"), self.version_list_selectionChanged) + self.connect(self.add_button, SIGNAL("clicked()"), self.add_button_clicked) + self.connect(self.remove_button, SIGNAL("clicked()"), self.remove_button_clicked) + self.connect(self.quit_button, SIGNAL("clicked()"), self.quit_button_clicked) + self.connect(self.promote_button, SIGNAL("clicked()"), self.promote_button_clicked) + + #Get packages and populate name_list + FILELIST = os.listdir(DIR) + self.Get_Rpm_Package_info(FILELIST) + + + #SORT THE PACKAGES, LETS TRY AND MAKE IT NEAT + LIST_OF_PACKAGES_TO_SORT = [] + + for PACKAGE in PACKAGES_DICT: + + LIST_OF_PACKAGES_TO_SORT.append(PACKAGE) + + LIST_OF_PACKAGES_TO_SORT.sort() + + for PACKAGE in LIST_OF_PACKAGES_TO_SORT: + + self.name_list.insertItem(PACKAGE, -1) + + + def Get_Rpm_Package_info(self, FILELIST): + + global PACKAGES_DICT + + for FILE in FILELIST: + + try: + + if RPM_REGEX.match(FILE): + + FULL_FILENAME = DIR + '/' + FILE + rpm = RPM(file(FULL_FILENAME)) + + if DEBUG > 0: + print "==============" + print "RPM Name: " + rpm.name() + print "Package: " + rpm.package() + print "Version: " + rpm[rpmdefs.RPMTAG_VERSION] + print "Release: " + rpm[rpmdefs.RPMTAG_RELEASE] + print "==============" + + + if PACKAGES_DICT.has_key(rpm.name()): + + if PACKAGES_DICT[rpm.name()].has_key(rpm[rpmdefs.RPMTAG_VERSION]): + + PACKAGES_DICT[rpm.name()][rpm[rpmdefs.RPMTAG_VERSION]][rpm[rpmdefs.RPMTAG_RELEASE]] = FULL_FILENAME + + else: + + PACKAGES_DICT[rpm.name()][rpm[rpmdefs.RPMTAG_VERSION]] = {} + PACKAGES_DICT[rpm.name()][rpm[rpmdefs.RPMTAG_VERSION]][rpm[rpmdefs.RPMTAG_RELEASE]] = FULL_FILENAME + + else: + + PACKAGES_DICT[rpm.name()] = {} + PACKAGES_DICT[rpm.name()][rpm[rpmdefs.RPMTAG_VERSION]] = {} + PACKAGES_DICT[rpm.name()][rpm[rpmdefs.RPMTAG_VERSION]][rpm[rpmdefs.RPMTAG_RELEASE]] = FULL_FILENAME + + + except: + pass + + return() + + + def name_list_selectionChanged(self): + #Get version list and populate version_list + + self.version_list.clear() + self.release_list.clear() + + self.SELECTED_PACKAGE = str(self.name_list.currentText()) + + VERSION_LIST_TO_SORT = [] + + for VERSION in PACKAGES_DICT[self.SELECTED_PACKAGE]: + + VERSION_LIST_TO_SORT.append(VERSION) + + VERSION_LIST_TO_SORT.sort() + + for VERSION in VERSION_LIST_TO_SORT: + + self.version_list.insertItem(VERSION, -1) + + + def version_list_selectionChanged(self): + #Get releases and populate release_list + + self.release_list.clear() + + self.SELECTED_VERSION = str(self.version_list.currentText()) + + RELEASE_LIST_TO_SORT = [] + + for RELEASE in PACKAGES_DICT[self.SELECTED_PACKAGE][self.SELECTED_VERSION]: + + RELEASE_LIST_TO_SORT.append(RELEASE) + + RELEASE_LIST_TO_SORT.sort() + + for RELEASE in RELEASE_LIST_TO_SORT: + + self.release_list.insertItem(RELEASE, -1) + + + def add_button_clicked(self): + #add selected release to promote_list + + self.SELECTED_RELEASE = str(self.release_list.currentText()) + + if self.SELECTED_RELEASE: + + self.SELECTED_FULL_FILE_NAME = PACKAGES_DICT[self.SELECTED_PACKAGE][self.SELECTED_VERSION][self.SELECTED_RELEASE] + self.SELECTED_FILE_NAME = os.path.basename(self.SELECTED_FULL_FILE_NAME) + + ALREADY_EXISTS = self.promote_list.findItem(self.SELECTED_FILE_NAME) + + if not ALREADY_EXISTS: + + self.promote_list.insertItem(self.SELECTED_FILE_NAME, -1) + + def remove_button_clicked(self): + #remove selected item from promote list + + SOMETHING_SELECTED = str(self.promote_list.currentText()) + + if SOMETHING_SELECTED: + self.promote_list.removeItem(self.promote_list.currentItem()) + + def quit_button_clicked(self): + #exit the application + sys.exit() + + def promote_button_clicked(self): + #promote the packages + + HOW_MANY_PACKAGES = int(self.promote_list.count()) + + #COPY FILE TO RELEVANT REPO + for i in range(HOW_MANY_PACKAGES): + + FILE = str(self.promote_list.text(i)) + + for PATH in TO_PATH: + + if INT_TO_PPLT: + + shutil.copy("/var/www/html/intrepo/" + FILE, PATH) + + elif PP_TO_PROD: + + for HOST in PROD_HOSTS: + + CMD = "/usr/bin/scp " + "/var/www/html/pprepo/" + FILE + " repouser@" + HOST + ":" + PATH + + RET_CODE = os.system(CMD) + if RET_CODE > 0: + print "Failed to copy files to production !!!" + sys.exit(1) + + #CALL REPO MAINTENANCE ON THAT REPO + if INT_TO_PPLT: + + CMD = "/opt/scripts/pp_repo_maint.py" + RET_CODE = os.system(CMD) + + if RET_CODE > 0: + print "Create repo for PREPROD failed !!" + sys.exit(1) + + CMD = "/opt/scripts/lt_repo_maint.py" + RET_CODE = os.system(CMD) + + if RET_CODE > 0: + print "Create repo LOAD TEST failed !!" + sys.exit(1) + + elif PP_TO_PROD: + + for HOST in PROD_HOSTS: + + CMD = "ssh repouser@" + HOST + " /opt/scripts/prod_repo_maint.py" + RET_CODE = os.system(CMD) + + if RET_CODE > 0: + print "create repo on " + HOST + " failed !!" + sys.exit(1) + + QMessageBox.information(self, "Packages Promoted", "All the selected packages have been promoted", QMessageBox.Ok) + sys.exit(0) + + +class Env(env_form): + def __init__(self, parent=None, name=None, fl=0): + env_form.__init__(self,parent,name,fl) + self.connect(self.ok_button, SIGNAL("clicked()"), self.ok_button_clicked) + + self.connect(self.quit_button, SIGNAL("clicked()"), self.quit_button_clicked) + + def ok_button_clicked(self): + global DIR, TO_PATH, INT_TO_PPLT, PP_TO_PROD + + if self.int_to_pplt_radio.isChecked(): + + DIR = '/var/www/html/intrepo' + TO_PATH = ['/var/www/html/pprepo', '/var/www/html/ltrepo'] + INT_TO_PPLT = 1 + + elif self.pp_to_prod_radio.isChecked(): + + DIR = '/var/www/html/pprepo' + TO_PATH = ['/var/www/html/prodrepo'] + PP_TO_PROD = 1 + + QDialog.done(self, True) + + def quit_button_clicked(self): + sys.exit() + + +if __name__ == "__main__": + app = QApplication(sys.argv) + QObject.connect(app,SIGNAL("lastWindowClosed()"),app,SLOT("quit()")) + + #get the environment + e = Env() + e.exec_loop() + + w = Promo() + app.setMainWidget(w) + w.show() + app.exec_loop() + \ No newline at end of file diff --git a/code/train/Python/0106360_vtgate_utils_test.py b/code/train/Python/0106360_vtgate_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2b952c780047c526a7bdadc96a0f5bea67b5f11d --- /dev/null +++ b/code/train/Python/0106360_vtgate_utils_test.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +# coding: utf-8 + +"""Tests for vtgate_utils.""" + +import exceptions +import time +import unittest +import utils + +from net import gorpc +from vtdb import vtgate_utils +from vtproto import vtrpc_pb2 + + +def setUpModule(): + pass + + +def tearDownModule(): + pass + + +class SomeException(exceptions.Exception): + pass + + +class AnotherException(exceptions.Exception): + pass + + +class FakeVtGateConnection(object): + + def __init__(self): + self.invoked_intervals = [] + # session is used by exponential_backoff_retry + self.session = None + + @vtgate_utils.exponential_backoff_retry( + retry_exceptions=(SomeException, AnotherException)) + def method(self, exc_to_raise): + self.invoked_intervals.append(int(time.time() * 1000)) + if exc_to_raise: + + raise exc_to_raise + + +class TestVtgateUtils(unittest.TestCase): + + def test_retry_exception(self): + fake_conn = FakeVtGateConnection() + with self.assertRaises(SomeException): + fake_conn.method(SomeException('an exception')) + self.assertEquals( + len(fake_conn.invoked_intervals), vtgate_utils.NUM_RETRIES + 1) + previous = fake_conn.invoked_intervals[0] + delay = vtgate_utils.INITIAL_DELAY_MS + for interval in fake_conn.invoked_intervals[1:]: + self.assertTrue(interval - previous >= delay) + previous = interval + delay *= vtgate_utils.BACKOFF_MULTIPLIER + + def test_retry_another_exception(self): + fake_conn = FakeVtGateConnection() + with self.assertRaises(AnotherException): + fake_conn.method(AnotherException('an exception')) + self.assertEquals( + len(fake_conn.invoked_intervals), vtgate_utils.NUM_RETRIES + 1) + + def test_no_retries_inside_txn(self): + fake_conn = FakeVtGateConnection() + fake_conn.session = object() + with self.assertRaises(SomeException): + fake_conn.method(SomeException('an exception')) + self.assertEquals(len(fake_conn.invoked_intervals), 1) + + def test_no_retries_for_non_retryable_exception(self): + fake_conn = FakeVtGateConnection() + with self.assertRaises(exceptions.Exception): + fake_conn.method(exceptions.Exception('an exception')) + self.assertEquals(len(fake_conn.invoked_intervals), 1) + + def test_no_retries_for_no_exception(self): + fake_conn = FakeVtGateConnection() + fake_conn.method(None) + self.assertEquals(len(fake_conn.invoked_intervals), 1) + + +class TestExtractRPCError(unittest.TestCase): + """Tests extract_rpc_error is tolerant to various responses.""" + + def test_reply_is_none(self): + vtgate_utils.extract_rpc_error('method', gorpc.GoRpcResponse()) + + def test_reply_is_empty_string(self): + response = gorpc.GoRpcResponse() + vtgate_utils.extract_rpc_error('method', response) + + def test_reply_is_string(self): + response = gorpc.GoRpcResponse() + response.reply = 'foo' + vtgate_utils.extract_rpc_error('method', response) + + def test_reply_is_dict(self): + response = gorpc.GoRpcResponse() + response.reply = {'foo': 'bar'} + vtgate_utils.extract_rpc_error('method', response) + + def test_reply_has_non_dict_err(self): + response = gorpc.GoRpcResponse() + response.reply = {'Err': 1} + with self.assertRaisesRegexp(vtgate_utils.VitessError, 'UNKNOWN_ERROR'): + vtgate_utils.extract_rpc_error('method', response) + + def test_reply_has_missing_err_message(self): + response = gorpc.GoRpcResponse() + response.reply = {'Err': {'foo': 'bar'}} + with self.assertRaisesRegexp(vtgate_utils.VitessError, + 'Missing error message'): + vtgate_utils.extract_rpc_error('method', response) + + def test_reply_has_err_message(self): + response = gorpc.GoRpcResponse() + response.reply = {'Err': {'Message': 'bar'}} + with self.assertRaisesRegexp(vtgate_utils.VitessError, + 'UNKNOWN_ERROR.+bar'): + vtgate_utils.extract_rpc_error('method', response) + + def test_reply_has_err_code(self): + response = gorpc.GoRpcResponse() + response.reply = {'Err': {'Code': vtrpc_pb2.TRANSIENT_ERROR}} + with self.assertRaisesRegexp(vtgate_utils.VitessError, + 'TRANSIENT_ERROR'): + vtgate_utils.extract_rpc_error('method', response) + +if __name__ == '__main__': + utils.main() diff --git a/code/train/Python/0107071_GitHubPrinter.py b/code/train/Python/0107071_GitHubPrinter.py new file mode 100644 index 0000000000000000000000000000000000000000..4527b6a6d1a2563c9a956b8b1295bea78ab8b14f --- /dev/null +++ b/code/train/Python/0107071_GitHubPrinter.py @@ -0,0 +1,94 @@ +from time import sleep +import requests +import json +import argparse +import configparser + +# GitHub +headers = {'Authorization': ''} +baseUrl = '' +owner = '' + +# Arduino +url = 'http://172.19.106.227' + +# Team Devs +teamDevs = {} + +latestPR = {} + + +def post_to_printer(pr, repo): + title = pr['title'] + user = teamXdevs[pr['head']['user']['login']] + message = "**{0} opened PR in {2}:** {1}".format(user, title, repo) + #print json.dumps(pr, indent=4, sort_keys=True) + r = requests.get(url + '?p=' + message) + print(r.status_code) + sleep(1) + +def post_new_line(): + r = requests.get(url + '?p= ') + print(r.status_code) + + +def parse_and_print(PRs, latest): + temp_num = 0 + for PR in PRs: + user = PR['head']['user']['login'] + number = PR['number'] + repo = PR['head']['repo']['name'] + if user in teamDevs and number > latest: + post_to_printer(PR, repo) + temp_num = max(number, temp_num) + if temp_num: + latest = temp_num + return latest + + +def poll(repos): + changed = False + global latestPR + + for repo in repos: + if repo not in latestPR: + latestPR[repo] = 0 + + PRs = requests.get(baseUrl + 'repos/' + owner + '/' + repo +'/pulls', headers=headers, verify=False) + + if PRs.ok: + PRsText = json.loads(PRs.text or PRs.content) + tempNum = parse_and_print(PRsText, latestPR[repo]) + if tempNum > latestPR[repo]: + changed = True + latestPR[repo] = tempNum + + if changed: + post_new_line() + + +if __name__ == "__main__": + # Read values from config file + Config = configparser.ConfigParser(); + Config.read("config.ini") + section = 'GitHub' + try: + baseUrl = Config.get(section, 'baseUrl') + owner = Config.get(section, 'owner') + token = Config.get(section, 'token') + headers['Authorization'] = 'token ' + token + except KeyError: + print("Unable to find config option") + + parser = argparse.ArgumentParser() + parser.add_argument("-period", type=int, + help="period at which to poll") + parser.add_argument('repositories', metavar='R', nargs='+', + help='a list of repositories to poll') + + args = parser.parse_args() + reposToPoll = args.repositories + + while True: + poll(reposToPoll) + sleep(args.period) diff --git a/code/train/Python/0112801_collect_licenses.py b/code/train/Python/0112801_collect_licenses.py new file mode 100644 index 0000000000000000000000000000000000000000..f67e585246677477f1e4f964eeb268a1d33e5b55 --- /dev/null +++ b/code/train/Python/0112801_collect_licenses.py @@ -0,0 +1,98 @@ +#!/usr/bin/python +# Copyright 2011 Google, Inc. All Rights Reserved. + +# simple script to walk source tree looking for third-party licenses +# dumps resulting html page to stdout + + +import os, re, mimetypes, sys + + +# read source directories to scan from command line +SOURCE = sys.argv[1:] + +# regex to find /* */ style comment blocks +COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL) +# regex used to detect if comment block is a license +COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE) +COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE) + +EXCLUDE_TYPES = [ + "application/xml", + "image/png", +] + + +# list of known licenses; keys are derived by stripping all whitespace and +# forcing to lowercase to help combine multiple files that have same license. +KNOWN_LICENSES = {} + + +class License: + def __init__(self, license_text): + self.license_text = license_text + self.filenames = [] + + # add filename to the list of files that have the same license text + def add_file(self, filename): + if filename not in self.filenames: + self.filenames.append(filename) + + +LICENSE_KEY = re.compile(r"[^\w]") + +def find_license(license_text): + # TODO(alice): a lot these licenses are almost identical Apache licenses. + # Most of them differ in origin/modifications. Consider combining similar + # licenses. + license_key = LICENSE_KEY.sub("", license_text).lower() + if license_key not in KNOWN_LICENSES: + KNOWN_LICENSES[license_key] = License(license_text) + return KNOWN_LICENSES[license_key] + + + +def discover_license(exact_path, filename): + # when filename ends with LICENSE, assume applies to filename prefixed + if filename.endswith("LICENSE"): + with open(exact_path) as file: + license_text = file.read() + target_filename = filename[:-len("LICENSE")] + if target_filename.endswith("."): target_filename = target_filename[:-1] + find_license(license_text).add_file(target_filename) + return None + + # try searching for license blocks in raw file + mimetype = mimetypes.guess_type(filename) + if mimetype in EXCLUDE_TYPES: return None + + with open(exact_path) as file: + raw_file = file.read() + + # include comments that have both "license" and "copyright" in the text + for comment in COMMENT_BLOCK.finditer(raw_file): + comment = comment.group(1) + if COMMENT_LICENSE.search(comment) is None: continue + if COMMENT_COPYRIGHT.search(comment) is None: continue + find_license(comment).add_file(filename) + + +for source in SOURCE: + for root, dirs, files in os.walk(source): + for name in files: + discover_license(os.path.join(root, name), name) + + +print "" + +for license in KNOWN_LICENSES.values(): + + print "

Notices for files:

    " + filenames = license.filenames + filenames.sort() + for filename in filenames: + print "
  • %s
  • " % (filename) + print "
" + print "
%s
" % license.license_text + +print "" diff --git a/code/train/Python/0113082_test_example.py b/code/train/Python/0113082_test_example.py new file mode 100644 index 0000000000000000000000000000000000000000..9502559f01266eb37f89ee040a57420e1698eb5a --- /dev/null +++ b/code/train/Python/0113082_test_example.py @@ -0,0 +1,37 @@ +#!/usr/bin/python +# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- +### BEGIN LICENSE +# Copyright (C) 2013 Aboobacker MK +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 3, as published +# by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranties of +# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +### END LICENSE + +import sys +import os.path +import unittest +sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))) + +from apertium_ui import AboutApertiumUiDialog + +class TestExample(unittest.TestCase): + def setUp(self): + self.AboutApertiumUiDialog_members = [ + 'AboutDialog', 'AboutApertiumUiDialog', 'gettext', 'logger', 'logging'] + + def test_AboutApertiumUiDialog_members(self): + all_members = dir(AboutApertiumUiDialog) + public_members = [x for x in all_members if not x.startswith('_')] + public_members.sort() + self.assertEqual(self.AboutApertiumUiDialog_members, public_members) + +if __name__ == '__main__': + unittest.main() diff --git a/code/train/Python/0113206_microconsensusmanager.py b/code/train/Python/0113206_microconsensusmanager.py new file mode 100644 index 0000000000000000000000000000000000000000..798da3e310b407197abeba2fce09f2174d85177e --- /dev/null +++ b/code/train/Python/0113206_microconsensusmanager.py @@ -0,0 +1,162 @@ +# Copyright 2014, 2015, Nik Kinkel +# See LICENSE for licensing information + +import logging +import random +import time +import zlib + +from twisted.internet import defer +from twisted.web.client import getPage + +from stem import Flag +from stem.descriptor.networkstatus import NetworkStatusDocumentV3 +from stem.descriptor.remote import get_authorities + +from oppy import data_dir + + +MICRO_CONSENSUS_PATH = '/tor/status-vote/current/consensus-microdesc.z' +MICRO_CONSENSUS_CACHE_FILE = data_dir + 'cached-microdesc-consensus' +SLEEP = 30 + + +# Major TODO's: +# - check consensus signatures are valid before accepting +# - better logging +# - docs +# - add download timeout +# - check if cached consensus is still valid and don't download if it is + +class ConsensusDownloadFailed(Exception): + pass + + +class MicroconsensusManager(object): + + def __init__(self, autostart=True): + logging.debug("MicroconsensusManager created.") + self._consensus = None + self._pending_consensus_requests = [] + self._consensus_download_callbacks = set() + + if autostart is True: + self.start() + + def start(self, initial=True): + self._scheduledConsensusUpdate(initial) + + # TODO: add to callback list or something to be nicer + def getMicroconsensus(self): + d = defer.Deferred() + if self._consensus: + d.callback(self._consensus) + else: + self._pending_consensus_requests.append(d) + + return d + + def addMicroconsensusDownloadCallback(self, callback): + self._consensus_download_callbacks.add(callback) + + def removeMicroconsensusDownloadCallback(self, callback): + try: + self._consensus_download_callbacks.remove(callback) + except KeyError: + msg = ("MicroconsensusManager got request to remove callback " + "{} but has no reference to this function." + .format(callback)) + logging.debug(msg) + + def _servePendingRequests(self): + for request in self._pending_consensus_requests: + request.callback(self._consensus) + self._pending_consensus_requests = [] + + def _serveConsensusDownloadCallbacks(self): + for callback in self._consensus_download_callbacks: + callback() + + @defer.inlineCallbacks + def _scheduledConsensusUpdate(self, initial=False): + logging.debug("MicroconsensusManager running scheduled consensus " + "update.") + if initial is True or self._consensus is None: + v2dirs = _readV2DirsFromCacheFile() or get_authorities().values() + else: + v2dirs = getV2DirsFromConsensus(self._consensus) + + try: + self._consensus = yield self._downloadMicroconsensus(v2dirs) + except ConsensusDownloadFailed as e: + logging.debug(e) + from twisted.internet import reactor + reactor.callLater(SLEEP, self._scheduledConsensusUpdate, initial) + return + + self._scheduleNextConsensusDownload() + self._servePendingRequests() + self._serveConsensusDownloadCallbacks() + + @defer.inlineCallbacks + def _downloadMicroconsensus(self, v2dirs): + random.shuffle(v2dirs) + for dc in v2dirs: + try: + host = "http://" + str(dc.address) + ":" + str(dc.dir_port) + raw = yield getPage(str(host+MICRO_CONSENSUS_PATH)) + # TODO: validate signatures + consensus = _processRawMicroconsensus(raw) + defer.returnValue(consensus) + except Exception as e: + msg = "Error downloading consensus: {}. Retrying.".format(e) + logging.debug(msg) + + raise ConsensusDownloadFailed("Failed to download fresh consensus.") + + def _scheduleNextConsensusDownload(self): + from twisted.internet import reactor + + va = time.mktime(self._consensus.valid_after.utctimetuple()) + fu = time.mktime(self._consensus.fresh_until.utctimetuple()) + vu = time.mktime(self._consensus.valid_until.utctimetuple()) + i1 = (fu - va) * (3.0/4.0) + i2 = (vu - (fu +i1)) * (7.0/8.0) + + seconds = random.randrange(int(i1), int(i2)) + + reactor.callLater(seconds, self._scheduledConsensusUpdate) + + +def getV2DirsFromConsensus(consensus): + return [r for r in consensus.routers.values() if Flag.V2DIR in r.flags] + + +def _readV2DirsFromCacheFile(): + try: + with open(MICRO_CONSENSUS_CACHE_FILE, 'rb') as f: + data = f.read() + consensus = NetworkStatusDocumentV3(data) + return getV2DirsFromConsensus(consensus) + except Exception as e: + msg = ("Failed to read cached-consensus-microdesc. Reason: {}." + .format(e)) + logging.debug(msg) + return None + + +def _writeConsensusCacheFile(consensus): + try: + with open(MICRO_CONSENSUS_CACHE_FILE, 'wb') as f: + f.write(str(consensus)) + except Exception as e: + msg = ("Failed to write cached-consensus-microdesc. Reason: {}." + .format(e)) + logging.debug(msg) + + +def _processRawMicroconsensus(raw): + raw = zlib.decompress(raw) + consensus = NetworkStatusDocumentV3(raw) + _writeConsensusCacheFile(consensus) + return consensus diff --git a/code/train/Python/0113252_DL_conv_mlp.py b/code/train/Python/0113252_DL_conv_mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..0aff3b741ba57d28fa238eed79a28e2af50fa92a --- /dev/null +++ b/code/train/Python/0113252_DL_conv_mlp.py @@ -0,0 +1,261 @@ +"""This tutorial introduces the LeNet5 neural network architecture +using Theano. LeNet5 is a convolutional neural network, good for +classifying images. This tutorial shows how to build the architecture, +and comes with all the hyper-parameters you need to reproduce the +paper's MNIST results. + + +This implementation simplifies the model in the following ways: + + - LeNetConvPool doesn't implement location-specific gain and bias parameters + - LeNetConvPool doesn't implement pooling by average, it implements pooling + by max. + - Digit classification is implemented with a logistic regression rather than + an RBF network + - LeNet5 was not fully-connected convolutions at second layer + +References: + - Y. LeCun, L. Bottou, Y. Bengio and P. Haffner: + Gradient-Based Learning Applied to Document + Recognition, Proceedings of the IEEE, 86(11):2278-2324, November 1998. + http://yann.lecun.com/exdb/publis/pdf/lecun-98.pdf + + + +IL PROGRAMMA E' RIADATTATO E COMMENTATO PER LA ELABORAZIONE +DELLE STRINGHE RAPPRESENTATIVE DELLE SEQUENZE + + +""" +#import cPickle +#import gzip +import os +import sys +import time + +import numpy + +import theano +import theano.tensor as T +#from theano.tensor.signal import downsample +#from theano.tensor.nnet import conv + + +import caricaDati as ld + +#from mlp import HiddenLayer + +#import LeNetConvPoolLayer as LNCPL + +import DL_LeNetNetwork as LN + +def evaluate_lenet5(learning_rate=0.05, + n_epochs=200, + dataset="", + nkerns=[10, 20], + batch_size=10, + + ishape=(1,256), + dimKernel0=(1,5), + poolSize0 = (1,2), + + dimKernel1=(1,5), + poolSize1=(1,2), + + out2Shape=500, + + out3Shape=41, + + nomeModello="nomeModello.pkl" + ): + """ Demonstrates lenet on MNIST dataset + + :type learning_rate: float + :param learning_rate: learning rate used (factor for the stochastic + gradient) + + :type n_epochs: int + :param n_epochs: maximal number of epochs to run the optimizer + + :type K: int + :param K : dimensione della rappresentazione + + :type dataset: string + :param dataset: path to the dataset used for training /testing (MNIST here) + + :type nkerns: list of ints + :param nkerns: number of kernels on each layer + """ + + rng = numpy.random.RandomState(23455) + + #datasets = load_data(dataset) # <<<<<<<<<< CARICAMENTO DEL DATASET + datasets=ld.load_data("TRAIN_seq_16S.txt", "TEST_seq_16S.txt", "VALID_seq_16S.txt") + + TEMP_train_set_x, TEMP_train_set_y = datasets[0] + TEMP_test_set_x, TEMP_test_set_y = datasets[1] + TEMP_valid_set_x, TEMP_valid_set_y = datasets[2] + + print TEMP_train_set_y.shape + + train_set_x, train_set_y = ld.shared_dataset(TEMP_train_set_x, TEMP_train_set_y ) + valid_set_x, valid_set_y = ld.shared_dataset(TEMP_valid_set_x, TEMP_valid_set_y ) + test_set_x, test_set_y = ld.shared_dataset(TEMP_test_set_x, TEMP_test_set_y ) + + + # compute number of minibatches for training, validation and testing + n_train_batches = train_set_x.get_value(borrow=True).shape[0] + n_valid_batches = valid_set_x.get_value(borrow=True).shape[0] + n_test_batches = test_set_x.get_value(borrow=True).shape[0] + n_train_batches /= batch_size + n_valid_batches /= batch_size + n_test_batches /= batch_size + + # allocate symbolic variables for the data + index = T.lscalar() # index to a [mini]batch + x = T.matrix('x') # the data is presented as rasterized images + y = T.ivector('y') # the labels are presented as 1D vector of + # [int] labels + + # DIMENSIONA IL MODELLO + LeNet=LN.LeNetNetwork(x, y, rng) + + + + # create a function to compute the mistakes that are made by the model + test_model = theano.function([index], LeNet.errors(y), + givens={ + x: test_set_x[index * batch_size: (index + 1) * batch_size], + y: test_set_y[index * batch_size: (index + 1) * batch_size]}) + + validate_model = theano.function([index], LeNet.errors(y), + givens={ + x: valid_set_x[index * batch_size: (index + 1) * batch_size], + y: valid_set_y[index * batch_size: (index + 1) * batch_size]}) + + params=LeNet.getParams() + + # create a list of gradients for all model parameters + #grads = T.grad(LeNet.f_cost(y), params) + + # train_model is a function that updates the model parameters by + # SGD Since this model has many parameters, it would be tedious to + # manually create an update rule for each model parameter. We thus + # create the updates list by automatically looping over all + # (params[i],grads[i]) pairs. + updates = LeNet.buildUpdates(learning_rate, y) + + train_model = theano.function([index], LeNet.f_cost(y), updates=updates, + givens={ + x: train_set_x[index * batch_size: (index + 1) * batch_size], + y: train_set_y[index * batch_size: (index + 1) * batch_size]}) + + + getOut=theano.function([index], LeNet.getOut(), + givens={ + x: train_set_x[index * batch_size: (index + 1) * batch_size]}) + + ############### + # TRAIN MODEL #----------------------------------------------------- + ############### + print '... training' + # early-stopping parameters + patience = 10000 # look as this many examples regardless + patience_increase = 2 # wait this much longer when a new best is + # found + improvement_threshold = 0.995 # a relative improvement of this much is + # considered significant + validation_frequency = min(n_train_batches, patience / 2) + # go through this many + # minibatche before checking the network + # on the validation set; in this case we + # check every epoch + + best_params = None + best_validation_loss = numpy.inf + best_iter = 0 + test_score = 0. + start_time = time.clock() + + epoch = 0 + done_looping = False + + while (epoch < n_epochs) and (not done_looping): + epoch = epoch + 1 + for minibatch_index in xrange(n_train_batches): + + iter = (epoch - 1) * n_train_batches + minibatch_index + + if iter % 100 == 0: + print 'training @ iter = ', iter + cost_ij = train_model(minibatch_index) + + if (iter + 1) % validation_frequency == 0: + + # compute zero-one loss on validation set + validation_losses = [validate_model(i) for i + in xrange(n_valid_batches)] + this_validation_loss = numpy.mean(validation_losses) + print('epoch %i, minibatch %i/%i, validation error %f %%' % \ + (epoch, minibatch_index + 1, n_train_batches, \ + this_validation_loss * 100.)) + + # if we got the best validation score until now + if this_validation_loss < best_validation_loss: + + #improve patience if loss improvement is good enough + if this_validation_loss < best_validation_loss * \ + improvement_threshold: + patience = max(patience, iter * patience_increase) + + # save best validation score and iteration number + best_validation_loss = this_validation_loss + best_iter = iter + + # test it on the test set + test_losses = [test_model(i) for i in xrange(n_test_batches)] + test_score = numpy.mean(test_losses) + print((' epoch %i, minibatch %i/%i, test error of best ' + 'model %f %%') % + (epoch, minibatch_index + 1, n_train_batches, + test_score * 100.)) + + if patience <= iter: + done_looping = True + break + + end_time = time.clock() + print('Optimization complete.') + print('Best validation score of %f %% obtained at iteration %i,'\ + 'with test performance %f %%' % + (best_validation_loss * 100., best_iter + 1, test_score * 100.)) + print >> sys.stderr, ('The code for file ' + + os.path.split(__file__)[1] + + ' ran for %.2fm' % ((end_time - start_time) / 60.)) + + + + print "...salva la rete" + LeNet.saveModel(nomeModello) + + # stampa l'output della rete + for i in xrange(n_train_batches): + out=getOut(i) + print "stimato", out, "\n", "reale ", train_set_y[i * batch_size: (i + 1) * batch_size].eval() + + + + # restituisce il modello addestrato + return LeNet + + + + + +if __name__ == '__main__': + ln=evaluate_lenet5() + + + + + diff --git a/code/train/Python/0113663_jumpmap.py b/code/train/Python/0113663_jumpmap.py new file mode 100644 index 0000000000000000000000000000000000000000..2a0d71b8103ee3d132ab8c4de59a58c1d96bead5 --- /dev/null +++ b/code/train/Python/0113663_jumpmap.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 + +'''Universe mapping tool for Naev. + +Run this script from the root directory of your Naev source tree. It +reads the XML files in dat/ssys/ and outputs an SVG map to standard +output. Example usage: + user@home:~/naev/$ jumpmap > map.svg + +''' + +# Copyright © 2012 Tim Pederick. +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# Standard library imports. +from datetime import date +import sys + +# Local imports. +from naevdata import SSystem +from dataloader import datafiles + +def mapdata(ssystems): + '''Extract mappable data from a list of star systems. + + Keyword arguments: + ssystems -- A sequence object containing the star systems to be + mapped (instances of naevdata.SSystem). + Returns: + A 4-tuple containing: + * the map boundaries (a 4-tuple of x-minimum, x-maximum, + y-minimum and y-maximum) + * the system locations (a mapping object of system names to + coordinates, given as 2-tuple x-y pairs) + * the two-way jumps between systems (a sequence object of + 2-tuples holding the coordinates of the two ends, themselves + given as 2-tuple x-y pairs) + * the one-way jumps between systems (as above, but note that + the two ends are ordered as origin then destination) + + ''' + syslocs = {} + jumps_by_name = {} + jumps = [] + jumps_oneway = [] + xmin = xmax = ymin = ymax = 0 + + # Extract the data. + for ssys in ssystems: + # Note down the system name and location. + syslocs[ssys.name] = ssys.pos + # Note down any jumps it has. Ignore any that can't be entered from + # here; they'll be recorded in the system at the other end. + jumps_by_name[ssys.name] = list(dest for dest in ssys.jumps + if not ssys.jumps[dest].exit_only) + # Track the outermost systems. + xmin = min(xmin, ssys.pos.x) + xmax = max(xmax, ssys.pos.x) + ymin = min(ymin, ssys.pos.y) + ymax = max(ymax, ssys.pos.y) + + # Convert the jump data to a series of coordinates. + for origin in jumps_by_name: + for dest in jumps_by_name[origin]: + if dest in jumps_by_name and origin in jumps_by_name[dest]: + # Two-way jump. + jumps.append((syslocs[origin], syslocs[dest])) + # Don't duplicate jumps. + jumps_by_name[dest].remove(origin) + else: + # One-way jump. + jumps_oneway.append((syslocs[origin], syslocs[dest])) + + return ((xmin, xmax, ymin, ymax), syslocs, jumps, jumps_oneway) + +def makemap(ssystems, margin=10, sys_size=5, ssystem_colour="orange", + jump_colour="grey", label_colour="black", label_font="serif", + file=sys.stdout): + '''Create an SVG map from a list of star systems. + + Keyword arguments: + ssystems -- A sequence object containing the star systems to be + mapped (instances of naevdata.SSystem). + margin -- The margin width (in pixels) to put around the edges + of the map. The default value is 10. + sys_size -- The radius of the dot representing each star system. + The default is 5. + ssystem_colour, jump_colour, label_colour, label_font -- Control + the appearance of the SVG output. The default appearance has + orange star systems, grey jumps, and labels in black serif. + file -- A file-like object to output the SVG to. Defaults to + standard output. + + ''' + (xmin, xmax, ymin, ymax), systems, jumps, jumps_oneway = mapdata(ssystems) + # Pad the bounds of the map and convert to SVG viewBox specs. + LABEL_SPACE = 200 + svg_bounds = (xmin - margin, -ymax - margin, + xmax - xmin + 2 * margin + LABEL_SPACE, + ymax - ymin + 2 * margin) + + # Output the SVG file. + print('') + print(''.format(*svg_bounds), file=file) + print('Naev universe map {}'.format(date.today()), + file=file) +## print(''.format((xmin, xmax, ymin, ymax))) + + # Style the map. + print('', file=file) + print('', file=file) + print(' '.format(jump_colour), file=file) + print('', file=file) + print('', file=file) + print('', file=file) + print(file=file) + + # Output the jumps first, so they're underneath the system markers. + print('', file=file) + for jump in jumps: + print(' '.format(jump[0].x, -jump[0].y, + jump[1].x, -jump[1].y), + file=file) + for jump in jumps_oneway: + print(' '.format(jump[0].x, + -jump[0].y, + (jump[1].x - jump[0].x) // 2, + -(jump[1].y - jump[0].y) // 2), + file=file) + print('', file=file) + print(file=file) + + # Output the system markers. + print('', file=file) + for name in systems: + x, y = systems[name].coords + print(' '.format(x, -y, sys_size), + file=file) + print(' {}'.format(name), file=file) + print('', file=file) + print(file=file) + + # And we're done! + print('', file=file) + +def main(): + '''Generate an SVG map and print it to standard output. + + The data files are assumed to be in ./dat/ssys/, relative to the + current path, so this should be run from the root of the Naev + source directory. + + ''' + ssystems = [] + for ssysfile in datafiles('SSystems'): + # Parse each XML file into a SSystem object. + ssystems.append(SSystem(ssysfile)) + makemap(ssystems) + +if __name__ == '__main__': + main() diff --git a/code/train/Python/0113878_standartsapma.py b/code/train/Python/0113878_standartsapma.py new file mode 100644 index 0000000000000000000000000000000000000000..5ac02f97fcd03b323c0a22fd427616d1519de39a --- /dev/null +++ b/code/train/Python/0113878_standartsapma.py @@ -0,0 +1,48 @@ +import math +x = [2,3,5,9,82,-5,13,3] + +def enKucuk(dizi): + """Karmaşıklığı O(n)""" + """En kücük elemanı döndüren fonksiyon""" + kucuk = dizi[0] # Baslangic değeri + for i in dizi: + if i < kucuk: + kucuk = i + return kucuk + +def enBuyuk(dizi): + """Karmaşıklığı O(n)""" + """En büyük elemanı döndüren fonksiyon""" + buyuk = dizi[0] # Baslangic değeri + for i in dizi: + if i > buyuk: + buyuk = i + return buyuk + +def ortalamaHesapla(dizi): + """Karmaşıklığı O(n)""" + """Dizinin ortalamasını döndüren fonksiyon""" + return float(sum(dizi)) / max(len(dizi), 1) + +print(ortalamaHesapla(x)) +print(enKucuk(x)) +print(enBuyuk(x)) +ortalama = ortalamaHesapla(x) + +def varyansHesapla(dizi,ortalama): + """Karmaşıklığı O(n)""" + varyansdegeri = 0 + for i in range(len(dizi)): + varyansdegeri += (ortalama - dizi[i]) ** 2 + return varyansdegeri / len(dizi) + +print(varyansHesapla(x,ortalama)) + +varyans = varyansHesapla(x,ortalama) + +def standartSapmaHesapla(varyans): + """ Math sqrt fonksiyonun karmaşıklığı O(logn) olduğu için + karmaşıklık O(logn)'dir """ + return math.sqrt(float(varyans)) + +print(standartSapmaHesapla(varyans)) diff --git a/code/train/Python/0114148_game.py b/code/train/Python/0114148_game.py new file mode 100644 index 0000000000000000000000000000000000000000..9324c515e7044c4a24d1d6be8a772a32e7c18169 --- /dev/null +++ b/code/train/Python/0114148_game.py @@ -0,0 +1,227 @@ +import sys +import pygame +import threading +from fractions import gcd +from grid import Grid + +def getKeycodes(): + """A method to get all the keycodes + used in pygame in to a dictionary""" + + keycodes = {item[2:].lower() : eval("pygame." + item) + for item in dir(pygame) if "K_" in item} + + return keycodes + +KEYCODES = getKeycodes() + +def key(key): + return KEYCODES[key] + +def calcAspectRatio(width, height): + hcf = gcd(width, height) + return (width / hcf, height / hcf) + +class Renderer(threading.Thread): + def __init__(self, RENDERRATE, *renderFuncs): + self.clock = pygame.time.Clock() + + self.renderFuncs = list(renderFuncs) + self.RENDERRATE = RENDERRATE + self.deltaTime = self.clock.tick(self.RENDERRATE) + + threading.Thread.__init__(self) + + def addRenderFunc(self, func): + self.renderFuncs.append(func) + + def run(self): + while True: + self.deltaTime = self.clock.tick(self.RENDERRATE) + + for func in self.renderFuncs: + func() + +class Game(): + def __init__(self, WIDTH, HEIGHT, gameName = "", gridsize = None, + FRAMERATE = 0, RENDERRATE = None, fillcolour = (0, 0, 0), + screenModifiers = (), timeScale = 1, dt_threshold = 0.2): + + self.screen = pygame.display.set_mode((WIDTH, HEIGHT), + *screenModifiers) + + self.gameName = gameName + pygame.display.set_caption(self.gameName) + + self.SCREENSIZE = pygame.math.Vector2(self.screen.get_size()) + self.SCREENRECT = pygame.Rect((0, 0), self.SCREENSIZE) + self.screenModifiers = screenModifiers + self.WIDTH, self.HEIGHT = self.SCREENSIZE + + self.aspectRatio = calcAspectRatio(self.WIDTH, self.HEIGHT) + + self.fillcolour = fillcolour + + self.returnValue = None + self.paused = False + self.dirtyRects = [] + self.oldDirtyRects = [] + + self.clock = pygame.time.Clock() + self.FRAMERATE = FRAMERATE + self.timeScale = timeScale + self.deltaTime = self.clock.tick(self.FRAMERATE) / 1000 * self.timeScale + self.dt_threshold = dt_threshold + + self.particleManager = None + self.threadedPhysics = False + + self.physicsManager = None + + if RENDERRATE is None: + self.renderer = None + else: + self.renderer = Renderer(RENDERRATE, self.render, + self.updateDisplay) + + if gridsize: + self.grid = Grid(self.screen, gridsize) + + self.ended = False + + def updateDisplay(self): + #self.screen.unlock() + + if self.dirtyRects: + pygame.display.update(self.dirtyRects + self.oldDirtyRects) + else: + pygame.display.update() + + #self.screen.lock() + + self.screen.fill(self.fillcolour) + + def setup(self): + """Hook for setup""" + pass + + def title(self): + """Hook for title screen""" + pass + + def update(self): + """Hook for game update""" + pass + + def render(self): + """Hook for game render""" + pass + + def drawBackground(self): + """Hook for background drawing""" + pass + + def handleEvent(self, event): + """Hook for event handling""" + pass + + def physicsUpdate(self): + """Hook for post-physics update""" + pass + + def handleInputs(self): + """Input handling""" + + for event in pygame.event.get(): + if event.type == pygame.QUIT: + self.quit() + + self.handleEvent(event) + + def initParticles(self): + try: + import particles + + except ImportError: + raise ImportError("Particle library not found") + + self.particles = particles + self.particleManager = self.particles.ParticleManager() + + if self.renderer: + self.renderer.addRenderFunc(self.particleManager.render) + + def initPhysics(self, threaded = False, *args, **kwargs): + try: + import physics + + except ImportError: + raise ImportError("Physics library not found") + + self.physicsManager = physics.PhysicsManager(*args, **kwargs) + + self.physicsManager.updateFunc = self.physicsUpdate + self.threadedPhysics = threaded + + if threaded: + self.physicsManager.start() + + def run(self): + if self.renderer: + self.renderer.start() + + self.title() + self.setup() + + while not self.ended: + + self.deltaTime = self.clock.tick(self.FRAMERATE) / 1000 * self.timeScale + + if self.dt_threshold and self.deltaTime > self.dt_threshold: + + # A large deltaTime value indicates that the window was + # being resized or dragged between now and the last + # frame. This large dt value would, if left alone, + # cause all sorts of problems for our game, such as + # objects clipping through each other as their movement + # is scaled by deltaTime. We thus skip this frame. + + continue + + self.oldDirtyRects = self.dirtyRects + self.dirtyRects = [] + + self.update() + self.handleInputs() + + if self.particleManager: + if self.renderer is None or True: + self.particleManager.update(self.deltaTime) + + else: + self.particleManager.update(self.renderer.deltaTime) + + if self.physicsManager and not self.threadedPhysics: + self.physicsManager.update(self.deltaTime) + self.physicsUpdate() + + if not self.renderer: + self.drawBackground() + + if self.particleManager: + self.particleManager.render() + + self.render() + + self.updateDisplay() + + if self.returnValue is not None: + return self.returnValue + + def end(self): + self.ended = True + + def quit(self): + self.end() + pygame.quit() + sys.exit(0) diff --git a/code/train/Python/0114430_createPointerFile.py b/code/train/Python/0114430_createPointerFile.py new file mode 100644 index 0000000000000000000000000000000000000000..950c133e8027026fdd25dd9be446dbb106207ca7 --- /dev/null +++ b/code/train/Python/0114430_createPointerFile.py @@ -0,0 +1,238 @@ +#!/usr/bin/python2 -OO + +import argparse +from lxml import etree +from lxml.builder import ElementMaker +import os.path +import sys +import uuid + +import archivematicaXMLNamesSpace as namespaces +import archivematicaCreateMETS2 + +# dashboard +from django.utils import timezone +from main.models import DublinCore + +# archivematicaCommon +from custom_handlers import get_script_logger +import fileOperations +from externals import checksummingTools + + +# TODO ask about what is duplicated for more files +# amdSec, techMD, file, fptr +def main(aip_uuid, aip_name, compression, sip_dir, aip_filename): + + # Prep work + mets_schema_location = 'http://www.loc.gov/METS/ http://www.loc.gov/standards/mets/version18/mets.xsd' + premis_schema_location = 'info:lc/xmlns/premis-v2 http://www.loc.gov/standards/premis/v2/premis-v2-2.xsd' + # Datetime format string from http://docs.python.org/2/library/datetime.html + # %Y = 4 digit year, %m = 2 digit month, %d = 2 digit day + # %H = 24-hour hour, %M = 2-digit minute, %S = 2 digit second + now = timezone.now().strftime("%Y-%m-%dT%H:%M:%S") + aip_identifier = aip_name+'-'+aip_uuid + aip_path = os.path.join(sip_dir, aip_filename) + # Get archive tool and version + program, algorithm = compression.split('-') + + # Pointer files are not written for uncompressed AIPs; + # the purpose of the pointer file is primarily to provide information + # on how to read a compressed AIP file, so there isn't anything for + # it to do when pointing at an uncompressed AIP. + if program == 'None': + return 0 + + if program == '7z': + archive_tool = '7-Zip' + archive_tool_version = '9.20' # TODO get this dynamically + elif program == 'pbzip2': + archive_tool = program + archive_tool_version = '1.1.6' # TODO get this dynamically + # Format / file extension + _, extension = os.path.splitext(aip_filename) + # PRONOM ID and PRONOM name for each file extension + pronom_conversion = { + '.7z': {'puid': 'fmt/484', 'name': '7Zip format'}, + '.bz2': {'puid': 'x-fmt/268', 'name': 'BZIP2 Compressed Archive'}, + } + num_files = 1 + # Get size + try: + aip_size = os.path.getsize(aip_path) + except os.error: + print >> sys.stderr, "File {} does not exist or is inaccessible. Aborting.".format(aip_path) + return -1 + # Calculate checksum + checksum_algorithm = 'sha256' + checksum = checksummingTools.sha_for_file(aip_path) + # Get package type (AIP, AIC) + sip_metadata_uuid = '3e48343d-e2d2-4956-aaa3-b54d26eb9761' + + try: + dc = DublinCore.objects.get(metadataappliestotype_id=sip_metadata_uuid, + metadataappliestoidentifier=aip_uuid) + except DublinCore.DoesNotExist: + package_type = "Archival Information Package" + else: + package_type = dc.type + + # Namespaces + nsmap = { + # Default, unprefixed namespace + None: namespaces.metsNS, + 'xsi': namespaces.xsiNS, + 'xlink': namespaces.xlinkNS, + } + # Set up structure + E = ElementMaker(namespace=namespaces.metsNS, nsmap=nsmap) + E_P = ElementMaker(namespace=namespaces.premisNS, nsmap={None: namespaces.premisNS}) + + root = ( + E.mets( + E.metsHdr(CREATEDATE=now), + # amdSec goes here + E.fileSec( + E.fileGrp(USE='Archival Information Package'), + ), + E.structMap( + TYPE='physical' + ), + ) + ) + # Namespaced attributes have to be added separately - don't know how to do + # inline with E + root.attrib[namespaces.xsiBNS+'schemaLocation'] = mets_schema_location + + add_amdsec_after = root.find('mets:metsHdr', namespaces=namespaces.NSMAP) + filegrp = root.find('.//mets:fileGrp', namespaces=namespaces.NSMAP) + structmap = root.find('.//mets:structMap', namespaces=namespaces.NSMAP) + # For each file, add amdSec, file, fptr + for admin_id in range(1, num_files+1): + + # amdSec + amdsec_id = 'amdSec_{}'.format(admin_id) + amdsec = E.amdSec( + E.techMD( + E.mdWrap( + E.xmlData( + ), + MDTYPE='PREMIS:OBJECT', # mdWrap + ), + ID='techMD_1', # techMD + ), + ID=amdsec_id, # amdSec + ) + # Add PREMIS:OBJECT + obj = E_P.object( + E_P.objectIdentifier( + E_P.objectIdentifierType('UUID'), + E_P.objectIdentifierValue(aip_uuid), + ), + E_P.objectCharacteristics( + E_P.compositionLevel('1'), + E_P.fixity( + E_P.messageDigestAlgorithm(checksum_algorithm), + E_P.messageDigest(checksum), + ), + E_P.size(str(aip_size)), + E_P.format( + E_P.formatDesignation( + E_P.formatName( + pronom_conversion[extension]['name']), + E_P.formatVersion(), + ), + E_P.formatRegistry( + E_P.formatRegistryName('PRONOM'), + E_P.formatRegistryKey( + pronom_conversion[extension]['puid']) + ), + ), + E_P.creatingApplication( + E_P.creatingApplicationName(archive_tool), + E_P.creatingApplicationVersion(archive_tool_version), + E_P.dateCreatedByApplication(now), + ), + ), + version='2.2', + ) + obj.attrib[namespaces.xsiBNS+'type'] = 'file' + obj.attrib[namespaces.xsiBNS+'schemaLocation'] = premis_schema_location + + # Add as child of xmldata + amdsec.find('.//mets:mdWrap[@MDTYPE="PREMIS:OBJECT"]/mets:xmlData', namespaces=namespaces.NSMAP).append(obj) + + # Add PREMIS:EVENT for compression, use archivematicaCreateMETS2 code + elements = archivematicaCreateMETS2.createDigiprovMD(aip_uuid) + for element in elements: + amdsec.append(element) + # Add PREMIS:AGENT for Archivematica + elements = archivematicaCreateMETS2.createDigiprovMDAgents() + for element in elements: + amdsec.append(element) + + # add amdSec after previous amdSec (or metsHdr if first one) + add_amdsec_after.addnext(amdsec) + add_amdsec_after = amdsec + + # fileGrp + file_ = E.file( + E.FLocat( + LOCTYPE="OTHER", + OTHERLOCTYPE="SYSTEM", + ), + ID=aip_identifier + ) + filegrp.append(file_) + flocat = file_.find('mets:FLocat', namespaces=namespaces.NSMAP) + flocat.attrib['{{{ns}}}href'.format(ns=namespaces.xlinkNS)] = aip_path + + # compression - 7z or tar.bz2 + if extension == '.7z': + etree.SubElement(file_, "transformFile", + TRANSFORMORDER='1', + TRANSFORMTYPE='decompression', + TRANSFORMALGORITHM=algorithm) + elif extension == '.bz2': + etree.SubElement(file_, "transformFile", + TRANSFORMORDER='1', + TRANSFORMTYPE='decompression', + TRANSFORMALGORITHM='bzip2') + etree.SubElement(file_, "transformFile", + TRANSFORMORDER='2', + TRANSFORMTYPE='decompression', + TRANSFORMALGORITHM='tar') + + # structMap + div = etree.SubElement(structmap, namespaces.metsBNS+'div', ADMID=amdsec_id, TYPE=package_type) + etree.SubElement(div, namespaces.metsBNS+'fptr', FILEID=aip_identifier) + + print etree.tostring(root, pretty_print=True) + + # Write out pointer.xml + xml_filename = 'pointer.xml' + filename = os.path.join(os.path.dirname(aip_path), xml_filename) + with open(filename, 'w') as f: + f.write(etree.tostring(root, pretty_print=True)) + fileOperations.addFileToSIP( + filePathRelativeToSIP='%SIPDirectory%'+xml_filename, + fileUUID=str(uuid.uuid4()), + sipUUID=aip_uuid, + taskUUID=str(uuid.uuid4()), # Unsure what should go here + date=now, + sourceType="aip creation", + ) + return 0 + +if __name__ == '__main__': + logger = get_script_logger("archivematica.mcp.client.createPointerFile") + + parser = argparse.ArgumentParser(description='Create AIP pointer file.') + parser.add_argument('aip_uuid', type=str, help='%SIPUUID%') + parser.add_argument('aip_name', type=str, help='%SIPName%') + parser.add_argument('compression', type=str, help='%AIPCompressionAlgorithm%') + parser.add_argument('sip_dir', type=str, help='%SIPDirectory%') + parser.add_argument('aip_filename', type=str, help='%AIPFilename%') + args = parser.parse_args() + rc = main(args.aip_uuid, args.aip_name, args.compression, args.sip_dir, args.aip_filename) + sys.exit(rc) diff --git a/code/train/Python/0114830_tabular_q_er_agent.py b/code/train/Python/0114830_tabular_q_er_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..cd84682dfe6b501f9ed35612d21980de194dbb05 --- /dev/null +++ b/code/train/Python/0114830_tabular_q_er_agent.py @@ -0,0 +1,93 @@ +import numpy as np +import tensorflow as tf + +from agents import TabularQAgent, capacities + +class TabularQERAgent(TabularQAgent): + """ + Agent implementing tabular Q-learning with experience replay. + """ + def set_agent_props(self): + super(TabularQERAgent, self).set_agent_props() + + self.er_batch_size = self.config['er_batch_size'] + self.er_rm_size = self.config['er_rm_size'] + + self.replayMemoryDt = np.dtype([('states', 'int32'), ('actions', 'int32'), ('rewards', 'float32'), ('next_states', 'int32')]) + self.replayMemory = np.array([], dtype=self.replayMemoryDt) + + def get_best_config(self, env_name=""): + return { + 'lr': 0.03 + , 'lr_decay_steps': 40000 + , 'discount': 0.999 + , 'N0': 75 + , 'min_eps': 0.005 + , 'initial_q_value': 0 + , 'er_batch_size': 783 + , 'er_rm_size': 36916 + } + + @staticmethod + def get_random_config(fixed_params={}): + get_lr = lambda: 1e-3 + (1 - 1e-3) * np.random.random(1)[0] + get_lr_decay_steps = lambda: np.random.randint(1e3, 1e5) + get_discount = lambda: 0.5 + (1 - 0.5) * np.random.random(1)[0] + get_N0 = lambda: np.random.randint(1, 5e3) + get_min_eps = lambda: 1e-4 + (1e-1 - 1e-4) * np.random.random(1)[0] + get_initial_q_value = lambda: 0 # int(np.random.random(1)[0] * 200) + get_er_batch_size = lambda: np.random.randint(16, 1024) + get_er_rm_size = lambda: np.random.randint(1000, 50000) + + random_config = { + 'lr': get_lr() + , 'lr_decay_steps': get_lr_decay_steps() + , 'discount': get_discount() + , 'N0': get_N0() + , 'min_eps': get_min_eps() + , 'initial_q_value': get_initial_q_value() + , 'er_batch_size': get_er_batch_size() + , 'er_rm_size': get_er_rm_size() + } + random_config.update(fixed_params) + + return random_config + + def learn_from_episode(self, env, render=False): + score = 0 + av_loss = [] + done = False + + obs = env.reset() + while not done: + if render: + env.render() + + act, state_id = self.act(obs) + next_obs, reward, done, info = env.step(act) + next_state_id = self.phi(next_obs, done) + + memory = np.array([(state_id, act, reward, next_state_id)], dtype=self.replayMemoryDt) + if self.replayMemory.shape[0] >= self.er_rm_size: + self.replayMemory = np.delete(self.replayMemory, 0) + self.replayMemory = np.append(self.replayMemory, memory) + + memories = np.random.choice(self.replayMemory, self.er_batch_size) + loss, _ = self.sess.run([self.loss, self.train_op], feed_dict={ + self.inputs_plh: memories['states'], + self.actions_t: memories['actions'], + self.rewards_plh: memories['rewards'], + self.next_states_plh: memories['next_states'], + }) + + av_loss.append(loss) + score += reward + obs = next_obs + + summary, _, episode_id = self.sess.run([self.all_summary_t, self.inc_ep_id_op, self.episode_id], feed_dict={ + self.score_plh: score, + self.loss_plh: np.mean(av_loss) + }) + self.sw.add_summary(summary, episode_id) + + return \ No newline at end of file diff --git a/code/train/Python/0114850_CPPCoderRoadMap.py b/code/train/Python/0114850_CPPCoderRoadMap.py new file mode 100644 index 0000000000000000000000000000000000000000..059a923fc8181886642bc875cb1500dcf564aa8d --- /dev/null +++ b/code/train/Python/0114850_CPPCoderRoadMap.py @@ -0,0 +1,149 @@ +from . import CPPDataCoder +from . import CPPDataType +from . import CPPMapCoder + +class CPPCoderRoadMap: + model_name = "" + ops = [] + data_holder = None + map_coder = None + + def __init__(self, model_name): + self.model_name = model_name + self.ops = [] + self.data_holder = CPPDataCoder.CPPDataCoder(model_name) + self.map_coder = None + + def set_map(self, mapfile): + self.map_coder = CPPMapCoder.CPPMapCoder(self.model_name) + if mapfile is not None: self.map_coder.parse_from_csv(mapfile) + + def append_op(self, new_op): + if len(self.ops) > 0: + last_op = self.ops[len(self.ops)-1] + match = (last_op.output_shape == new_op.input_shape) + assert match, "last op's output dimensions != new op's input dimensions. ("+str(last_op.output_shape)+" != "+str(new_op.input_shape)+")" + self.ops.append(new_op) + + def dump_codes(self, path, cpp_type): + filename = path + "/" + self.model_name + header_filename = filename + ".hpp" + cpp_filename = filename + ".cpp" + data_filename = filename + "_data.hpp" + map_filename = filename + "_map.hpp" + + input_dimensions = str(len(self.ops[0].input_shape)) + output_dimensions = str(len(self.ops[len(self.ops)-1].output_shape)) + + # write header file + file = open(header_filename, 'w') + template_code = open('templates/predict_header.tmp').read() + template_code = template_code.replace("%FILE_NAME%", self.model_name+".hpp") + template_code = template_code.replace("%CAPTAL_MODEL_NAME%", self.model_name.upper()) + template_code = template_code.replace("%MODEL_NAME%", self.model_name) + template_code = template_code.replace("%CPP_TYPE%", CPPDataType.type_string(cpp_type)) + template_code = template_code.replace("%INPUT_DISMENSIONS%", input_dimensions) + template_code = template_code.replace("%OUTPUT_DISMENSIONS%", output_dimensions) + file.write(template_code) + file.close() + + # write cpp file + file = open(cpp_filename, 'w') + file.write("//\n// "+self.model_name+"cpp"+"\n") + file.write("//\n// generated time: "+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+"\n//\n\n") + file.write("#include \""+self.model_name+".hpp\"\n\n") + file.write("#include \""+self.model_name+"_data.hpp\"\n\n") + file.write("#include \""+self.model_name+"_map.hpp\"\n\n") + file.write("namespace "+self.model_name+" {\n\n") + + # write unit test function + template_code = "" + if self.ops[0].dim_ordering == CPPDataType.ORDER_NHWC: + template_code = open('templates/unit_test_NHWC.tmp').read() + elif self.ops[0].dim_ordering == CPPDataType.ORDER_NCHW: + template_code = open('templates/unit_test_NCHW.tmp').read() + template_code = template_code.replace("%CPP_TYPE%", CPPDataType.type_string(cpp_type)) + file.write(template_code) + + # write predict function + self.data_holder.clear() + for op in self.ops: + op.dump_to_file(file, self.data_holder, cpp_type) + + # function declare + predict_function_declare = "void predict(const Eigen::Tensor<"+CPPDataType.type_string(cpp_type)+", "+input_dimensions+", Eigen::RowMajor>& input,\n" + predict_function_declare = predict_function_declare + " Eigen::Tensor<"+CPPDataType.type_string(cpp_type)+", "+output_dimensions+", Eigen::RowMajor>& output" + + file.write(predict_function_declare+")\n") + file.write("") + file.write("{\n") + file.write("#ifdef DEBUG\n") + file.write(" predict(input, output, false);\n") + file.write("}\n\n") + file.write(predict_function_declare+",\n") + file.write(" bool unit_test)\n") + file.write("{\n") + file.write(" if( unit_test )\n") + file.write(" {\n") + file.write(" start_unit_test_function(\"input\", input.data(), "+str(len(self.ops[0].input_shape))) + for index in range(len(self.ops[0].input_shape)): + file.write(", "+str(self.ops[0].input_shape[index])) + file.write(");\n") + file.write(" }\n") + file.write("#endif // DEBUG\n") + + # function body + last_op_output_name = "input" + last_op_output_shape = None + last_op_output_shape_len = 0 + for op in self.ops: + op_output_dimensions = str(len(op.output_shape)) + op_output_name = "output_"+op.name + op_output_shape = "" + for shape in op.output_shape: + op_output_shape = op_output_shape + str(shape) + ", " + op_output_shape = op_output_shape[:-2] + "" + file.write(" Eigen::Tensor<"+CPPDataType.type_string(cpp_type)+", "+op_output_dimensions+", Eigen::RowMajor> "+op_output_name+"("+op_output_shape+");\n") + file.write(" "+op.name+"("+last_op_output_name+", "+op_output_name+");\n\n") + + file.write("#ifdef DEBUG\n") + file.write(" if( unit_test )\n") + file.write(" {\n") + file.write(" unit_test_function(\""+op.name+"\", "+op_output_name+".data(), "+str(len(op.output_shape))+", "+op_output_shape+");\n") + file.write(" }\n") + file.write("#endif // DEBUG\n\n") + + last_op_output_name = op_output_name + last_op_output_shape = op_output_shape + last_op_output_shape_len = len(op.output_shape) + file.write(" output = "+last_op_output_name+";\n") + + file.write("\n#ifdef DEBUG\n") + file.write(" if( unit_test )\n") + file.write(" {\n") + file.write(" end_unit_test_function(\"output\", output.data(), "+str(last_op_output_shape_len)+", "+last_op_output_shape+");\n") + file.write(" }\n") + file.write("#endif // DEBUG\n\n") + + file.write("}\n") + + # write mapping table + file.write("std::string getMappingTableValue(Eigen::Index index)\n") + file.write("{\n") + file.write(" if( index >= sizeof(value_map)/sizeof(const char*) ) return \"\";\n") + file.write(" else return value_map[index];\n") + file.write("}\n") + + file.write("\n\n};\n\n") + file.close() + + # write data file + self.data_holder.dump_to_file(data_filename) + + # write map file + self.map_coder.dump_to_file(map_filename) + + + + + diff --git a/code/train/Python/0115796_8-tictactoe-minimax.py b/code/train/Python/0115796_8-tictactoe-minimax.py new file mode 100644 index 0000000000000000000000000000000000000000..c4e98ecb37d7e1f37200f71d5220a77ce0f7dae2 --- /dev/null +++ b/code/train/Python/0115796_8-tictactoe-minimax.py @@ -0,0 +1,84 @@ +""" +Mini-max Tic-Tac-Toe Player + +Author: Weikang Sun +Date: 10/29/15 + +CodeSkultpor source: +http://www.codeskulptor.org/#user40_nOKLY8YOrB_15.py +""" + +import poc_ttt_gui +import poc_ttt_provided as provided + +# Set timeout, as mini-max can take a long time +import codeskulptor +codeskulptor.set_timeout(60) + +# SCORING VALUES - DO NOT MODIFY +SCORES = {provided.PLAYERX: 1, + provided.DRAW: 0, + provided.PLAYERO: -1} + +def mm_move(board, player): + """ + Make a move on the board. + + Returns a tuple with two elements. The first element is the score + of the given board and the second element is the desired move as a + tuple, (row, col). + """ + + # check status of game + status = board.check_win() + + # recursive case, when game is not yet finished + if status is None: + avail_moves = board.get_empty_squares() + + # set a score impossibly low with invalid move + max_score = -2 + best_move = (-1, -1) + + for move in avail_moves: + # remember to iterate on a clone of the board + game = board.clone() + game.move(move[0], move[1], player) + # get the best score from the new board based on player + mm_result, dummy_var = mm_move(game, provided.switch_player(player)) + mm_result *= SCORES[player] + + # short circuit in event of winning move + if mm_result == 1: + return SCORES[player], move + + elif mm_result > max_score: + max_score = mm_result + best_move = move + # return the best move available + return SCORES[player]*max_score, best_move + + # base cases, when game is already finished + else: + return SCORES[status], (-1, -1) + + +def move_wrapper(board, player, trials): + """ + Wrapper to allow the use of the same infrastructure that was used + for Monte Carlo Tic-Tac-Toe. + """ + move = mm_move(board, player) + assert move[1] != (-1, -1), "returned illegal move (-1, -1)" + return move[1] + +# Test game with the console or the GUI. +# Uncomment whichever you prefer. +# Both should be commented out when you submit for +# testing to save time. + +# provided.play_game(move_wrapper, 1, False) +# poc_ttt_gui.run_gui(3, provided.PLAYERO, move_wrapper, 1, False) + + + diff --git a/code/train/Python/0116001_random_guessing.py b/code/train/Python/0116001_random_guessing.py new file mode 100644 index 0000000000000000000000000000000000000000..e6d5976be57fd38d964881a256b81b6d654bf538 --- /dev/null +++ b/code/train/Python/0116001_random_guessing.py @@ -0,0 +1,61 @@ +# https://github.com/kvfrans/openai-cartpole/blob/master/cartpole-random.py + +import gym +import numpy as np +import matplotlib.pyplot as plt + + +def run_episode(env, parameters): + observation = env.reset() + totalreward = 0 + for _ in xrange(200): + action = 0 if np.matmul(parameters, observation) < 0 else 1 + observation, reward, done, info = env.step(action) + totalreward += reward + if done: + break + return totalreward + + +def train(submit): + env = gym.make('CartPole-v0') + if submit: + env.monitor.start('cartpole-experiments/', force=True) + + counter = 0 + bestparams = None + bestreward = 0 + for _ in xrange(200): + counter += 1 + parameters = np.random.rand(4) * 2 - 1 + reward = run_episode(env, parameters) + if reward > bestreward: + bestreward = reward + bestparams = parameters + if reward == 200: + break + + if submit: + for _ in xrange(100): + run_episode(env, bestparams) + env.monitor.close() + + return counter + + +# train an agent to submit to openai gym +# train(submit=True) + +# create graphs +results = [] +for _ in xrange(1000): + results.append(train(submit=False)) +weights = np.ones_like(results)/float(len(results)) +plt.hist(results, 10, weights=weights) +# plt.hist(results, 50, normed=1, facecolor='g', alpha=0.75) +plt.xlabel('Episodes required to reach 200') +plt.ylabel('Frequency') +plt.title('Histogram of Random Search') +plt.show() + +print np.sum(results) / 1000.0 diff --git a/code/train/Python/0116625_FileClass.py b/code/train/Python/0116625_FileClass.py new file mode 100644 index 0000000000000000000000000000000000000000..f39d77add7649e27a076aa0d22d65a534e4ddb55 --- /dev/null +++ b/code/train/Python/0116625_FileClass.py @@ -0,0 +1,70 @@ +PAYLOAD_SIZE = 31 + + +class FileClass(object): + # This should be an abstract Object + + def __init__(self, reader, path): + + self.bytes = [] + self.packets = [] + self.path = path + self.send_ack = 0 + + # If file is to send, counter is used to check if we have to send the next packet + # If file is to receive, counter is used to check if we should write the next chunk + self.counter = 0 + + self.finished = False + + if reader: + print("Reading from file: {}".format(path)) + with open(path, 'rb') as f: + byte = f.read(1) + while byte != '': + self.bytes.append(byte) + byte = f.read(1) + + rest = len(self.bytes) + + aux = [] + for i in range(len(self.bytes)): + aux.append(ord(self.bytes[i])) + if len(aux) == PAYLOAD_SIZE or len(aux) == rest: + rest -= len(aux) + self.packets.append(aux) + aux = [] + else: + pass + with open(path, 'wb') as f: + print("Created file in path: {}".format(path)) + + # Sender methods + def getNextPayload(self): + if self.counter == len(self.packets): + self.finished = True + print("Sending last packet!") + return [99], 0b11111 + packet_str = [chr(item) for item in self.packets[self.counter]] + print("Getting packet in position {}: [{}]".format(self.counter, "".join(packet_str))) + return self.packets[self.counter], self.counter + + def receivedACK(self): + self.counter += 1 + print("Now counter is equal to: {}".format(self.counter)) + + # Receiver methods + def writePayload(self, buf, packet_counter): + if packet_counter == 0b11111: + print("No more packets to receive!") + self.finished = True + return + print("Writting to file: self counter: {}, received counter: {}".format(self.counter, packet_counter)) + # If buf contains a list of ints (0-255), do char() and save to file one by one + if packet_counter == self.counter: + with open(self.path, 'ab') as f: + for b in buf: + f.write(chr(b)) + self.counter += 1 + print("Now writing counter is equal to: {}".format(self.counter)) + self.send_ack = 1 diff --git a/code/train/Python/0116678_maxblocksinflight.py b/code/train/Python/0116678_maxblocksinflight.py new file mode 100644 index 0000000000000000000000000000000000000000..53faa13e7e20a954365d37435bd75b4460f8d864 --- /dev/null +++ b/code/train/Python/0116678_maxblocksinflight.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +# Copyright (c) 2015-2016 The Flurbo Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. + +from test_framework.mininode import * +from test_framework.test_framework import FlurboTestFramework +from test_framework.util import * +import logging + +''' +In this test we connect to one node over p2p, send it numerous inv's, and +compare the resulting number of getdata requests to a max allowed value. We +test for exceeding 128 blocks in flight, which was the limit an 0.9 client will +reach. [0.10 clients shouldn't request more than 16 from a single peer.] +''' +MAX_REQUESTS = 128 + +class TestManager(NodeConnCB): + # set up NodeConnCB callbacks, overriding base class + def on_getdata(self, conn, message): + self.log.debug("got getdata %s" % repr(message)) + # Log the requests + for inv in message.inv: + if inv.hash not in self.blockReqCounts: + self.blockReqCounts[inv.hash] = 0 + self.blockReqCounts[inv.hash] += 1 + + def on_close(self, conn): + if not self.disconnectOkay: + raise EarlyDisconnectError(0) + + def __init__(self): + NodeConnCB.__init__(self) + self.log = logging.getLogger("BlockRelayTest") + + def add_new_connection(self, connection): + self.connection = connection + self.blockReqCounts = {} + self.disconnectOkay = False + + def run(self): + self.connection.rpc.generate(1) # Leave IBD + + numBlocksToGenerate = [8, 16, 128, 1024] + for count in range(len(numBlocksToGenerate)): + current_invs = [] + for i in range(numBlocksToGenerate[count]): + current_invs.append(CInv(2, random.randrange(0, 1 << 256))) + if len(current_invs) >= 50000: + self.connection.send_message(msg_inv(current_invs)) + current_invs = [] + if len(current_invs) > 0: + self.connection.send_message(msg_inv(current_invs)) + + # Wait and see how many blocks were requested + time.sleep(2) + + total_requests = 0 + with mininode_lock: + for key in self.blockReqCounts: + total_requests += self.blockReqCounts[key] + if self.blockReqCounts[key] > 1: + raise AssertionError("Error, test failed: block %064x requested more than once" % key) + if total_requests > MAX_REQUESTS: + raise AssertionError("Error, too many blocks (%d) requested" % total_requests) + print("Round %d: success (total requests: %d)" % (count, total_requests)) + + self.disconnectOkay = True + self.connection.disconnect_node() + + +class MaxBlocksInFlightTest(FlurboTestFramework): + def add_options(self, parser): + parser.add_option("--testbinary", dest="testbinary", + default=os.getenv("FLURBOD", "flurbod"), + help="Binary to test max block requests behavior") + + def setup_chain(self): + print("Initializing test directory "+self.options.tmpdir) + initialize_chain_clean(self.options.tmpdir, 1) + + def setup_network(self): + self.nodes = start_nodes(1, self.options.tmpdir, + extra_args=[['-debug', '-whitelist=127.0.0.1']], + binary=[self.options.testbinary]) + + def run_test(self): + test = TestManager() + test.add_new_connection(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test)) + NetworkThread().start() # Start up network handling in another thread + test.run() + +if __name__ == '__main__': + MaxBlocksInFlightTest().main() diff --git a/code/train/Python/0116741_generateConfig.py b/code/train/Python/0116741_generateConfig.py new file mode 100644 index 0000000000000000000000000000000000000000..ead5dd95f758b46354ed7d6501e233fe394e291b --- /dev/null +++ b/code/train/Python/0116741_generateConfig.py @@ -0,0 +1,141 @@ +#! python3 +import argparse +import csv +import codecs +import datetime +import re +from os import listdir + +# set up arguments +parser = argparse.ArgumentParser(description='Generate a config.jason file for a project from an Illumina *SeqOutput folder.') +parser.add_argument("path", type=str, help='path to the *SeqOutput folder') +parser.add_argument("-o", metavar="PATH", type=str, help='path to the config file') +parser.add_argument("--rules", type=str, help='path to the NFWS rules directory', default="NFWS/rules") +parser.add_argument("--email", metavar="MAILS", type=str, help='your email adress', default="") +parser.add_argument("--estart", metavar="DATE", type=str, help='experiment start date', default="") +parser.add_argument("--keep", metavar="DATE", type=str, help='keep data at least until DATE', default="") +parser.add_argument("--pi", metavar="NAME", type=str, help='NAME of the PI respsonsible for the experiment', default="") +parser.add_argument("--researcher", metavar="NAME", type=str, help='NAME of the researcher respsonsible for the experiment', default="") +parser.add_argument("--institution", metavar="NAME", type=str, help='NAME of the institution respsonsible for the experiment', default="") +parser.add_argument("--text", metavar="TEXT", type=str, help='some descriptive TEXT', default="") +parser.add_argument("--notify_email", metavar="MAILS", type=str, help='email address for success and error notifications', default="") + +args = parser.parse_args() +# print(args) + +# get Experiment name and sequencing date +run = "" +seq_date = "" +units_array = [] +with codecs.open(args.path + "/SampleSheet.csv", encoding='iso-8859-1') as csvfile: + samplesheet = csv.reader(csvfile) + read_samples = False + read_reads = False + for row in samplesheet: + if (len(row) > 0): + if (row[0] == "Date"): seq_date = row[1] + if (row[0] == "Experiment Name"): run = row[1] + +# get current date +today = datetime.datetime.today().strftime("%d.%m.%Y") + +# generate sample and unit dicts +units_array_tmp = listdir(args.path + "/Data/Intensities/BaseCalls") +units_array_tmp.sort(key=str.lower) +units_array = [] +for unit in units_array_tmp: + if (not "Undetermined" in unit and "fastq.gz" in unit): + units_array.append(unit) + +sample_array = list(set(map(lambda s: s[:-21], units_array))) +sample_array.sort(key=str.lower) + +# generate samples and units strings +samples = ""; +for i in range(0,len(sample_array)): + if (i > 0): + samples = samples + ",\n " + samples = samples + "\"" + sample_array[i] + "\": [ \"" + sample_array[i] + "\" ]" + +units = "" +for i in range(0,len(sample_array)): + if (i > 0): + units = units + ",\n " + units = units + "\"" + sample_array[i] + "\": [\"" + "\", \"".join(filter(lambda x:sample_array[i] in x, units_array)) + "\" ]" + +# print(run) +# print(today) +# print(units_array) +# print(sample_array) +# print(samples) +# print(units) + +# write config +with open(args.o, "w") as config: + config.write('{\n' + ' "run": "' + run + '",\n' + ' "machine": "MiSeq",\n' + ' "platform": "illumina",\n' + ' "project_management_version": "2.0",\n' + ' "notification_email": "' + args.notify_email + '",\n' + ' "path_rules": "' + args.rules + '",\n\n' + + ' "description": {\n' + ' "experiment_start": "' + args.estart + '",\n' + ' "experiment_finish": "",\n' + ' "sequencing date": "' + seq_date + '",\n' + ' "analysis_start": "' + today + '",\n' + ' "analysis_finish": "",\n' + ' "keep_until": "' + args.keep + '",\n' + ' "pi": "' + args.pi + '",\n' + ' "researcher": "' + args.researcher + '",\n' + ' "institution": "' + args.institution + '",\n' + ' "emails": [ ] ,\n' + ' "text": "' + args.text + '",\n' + ' "publication": [""]\n' + ' },\n\n' + + ' "ref_dir": "/data/references/human",\n' + ' "references": {\n' + ' "hg38": {\n' + ' "genome": "/hg38/genome/hg38.fa",\n' + ' "genome_annotation": "/hg38/genes/all.gtf",\n' + ' "transcriptome": "/hg38/genes/all.gtf.transcript.fa"\n' + ' },\n' + ' "hg19": {\n' + ' "genome": "/hg19/genome/hg19_ucsc_rm.fa",\n' + ' "genome_annotation": "/hg19/genes/all.gtf",\n' + ' "transcriptome": "/hg19/genes/all.gtf.transcript.fa"\n' + ' }\n' + ' },\n' + ' "adapter_sequences": "/data/references/illumina/adapters/TruSeq3-PE.fa",\n\n' + + ' "samples": {\n' + ' ' + samples + '\n' + ' },\n' + ' "units": {\n' + ' ' + units + '\n' + ' },\n\n' + + ' "parameters": {\n' + ' "hg19": {\n' + ' "BaseRecalibrator": [\n' + ' "--known-sites", "/data/references/human/hg19/snp/dbsnp_138.hg19.vcf",\n' + ' "--known-sites", "/data/references/human/hg19/snp/Mills_and_1000G_gold_standard.indels.hg19.sites.vcf",\n' + ' "--known-sites", "/data/references/human/hg19/snp/1000G_phase1.indels.hg19.sites.vcf"\n' + ' ],\n' + ' "HaplotypeCaller": [\n' + ' "--dbsnp", "/data/references/human/hg19/snp/dbsnp_138.hg19.vcf"\n' + ' ]\n' + ' },\n' + ' "hg38": {\n' + ' "BaseRecalibrator": [\n' + ' "--known-sites", "/data/references/human/hg38/snp/Homo_sapiens_assembly38.dbsnp138.vcf",\n' + ' "--known-sites", "/data/references/human/hg38/snp/Mills_and_1000G_gold_standard.indels.hg38.vcf"\n' + ' ],\n' + ' "HaplotypeCaller": [\n' + ' "--dbsnp", "/data/references/human/hg38/snp/Homo_sapiens_assembly38.dbsnp138.vcf"\n' + ' ]\n' + ' }\n' + ' }\n' + '}') diff --git a/code/train/Python/0116841_trim.py b/code/train/Python/0116841_trim.py new file mode 100644 index 0000000000000000000000000000000000000000..bef92f0c5b9c96d62e67dd89e46af51f47279200 --- /dev/null +++ b/code/train/Python/0116841_trim.py @@ -0,0 +1,177 @@ +from dnaio import * +from runner import * +from logger import * + +def trim_pairs(**ops): + ''' Performs quality trimming of paired-end sequences generating interleaved + (paired) and singletons fasta files. + + Example + + >>> trim_pairs( + ... # Specify file format of reads (see DnaIO for options). + ... input_format = 'qseq', # default + # ... output_format = 'fastq', # default # NOT IMPLEMENTED + ... out_right = 'right_singletons.fastq', + ... out_left = 'left_singletons.fastq', + ... out_trimmed = 'paired_trimmed.fastq', + ... # minimum length cutoff for read survival + ... cutoff = 70, # default + ... ) + + The reason that qseq is the default format for input and fastq is the + default format for output is that my Illumina machine generates qseq + files but I need fastq files to perform de novo assembly using Velvet. + + ''' + + ohai('trimming pairs') + for f in [ops['out_left'], ops['out_right'], ops['out']]: + if os.path.exists(f): + okay('skipping!') + return + + input_format = ops.get('input_format', 'qseq') + + # TODO implement this + # out_format = ops.get('output_format', 'fastq') + + out_left = open(ops['out_left'], 'w') + out_right = open(ops['out_right'], 'w') + out_trimmed = open(ops['out'], 'w') + cutoff = int(ops['cutoff']) + + from itertools import izip + + counts = { + 'pairs': 0, + 'left': 0, + 'right': 0, + } + + for h_left, h_right in zip(ops['left_mates'], ops['right_mates']): + left_mates = Dna(h_left, type=input_format) + right_mates = Dna(h_right, type=input_format) + + for left, right in izip(left_mates, right_mates): + left_trimmed, right_trimmed = Trim.trim(left), Trim.trim(right) + + if len(right_trimmed) < cutoff and len(left_trimmed) < cutoff: + # both reads suck + continue + elif len(right_trimmed) < cutoff: + # keep left pair + print >> out_left, left_trimmed.fastq + counts['left'] += 1 + elif len(left_trimmed) < cutoff: + # keep right pair + print >> out_right, right_trimmed.fastq + counts['right'] += 1 + else: + # both are good, keep both! + left_trimmed.header = left_trimmed.header + ':A' + right_trimmed.header = right_trimmed.header + ':B' + print >> out_trimmed, left_trimmed.fastq + print >> out_trimmed, right_trimmed.fastq + counts['pairs'] += 1 + + # way too many file handles :[ + out_left.close() + out_right.close() + out_trimmed.close() + + # return read counts + return counts + + +class Trim(): + ''' The Famous Trim algorithm ''' + + @classmethod + def _get_coords(self, quality, **kwargs): + ''' the trim2 algorithm ''' + + quality_cutoff = 20 + + _sum, _max, first, last, start, end = 0, 0, 0, 0, 0, 0 + for a, q in enumerate(quality): + _sum += (q - quality_cutoff) + if _sum > _max: + _max = _sum + end = a + start = first + if _sum < 0: + _sum = 0 + first = a + + return (start, end - start) + + @classmethod + def trim(self, record): + ''' an atomic method for sequence trimming ''' + + # trimming algorithm + coords = self._get_coords(record.quality) + + # truncate sequence and quality accordingly + sequence = record.sequence[coords[0]:coords[1]] + quality = record.quality[coords[0]:coords[1]] + + # quick test + assert len(sequence) == len(quality) + + # make and return a new record + new_record = Record(record.header, sequence, quality) + + return new_record + + @classmethod + def _check_seq(self, record, **kwargs): + ''' make sure sequence survives trimming ''' + + ops = { # defaults + 'min_length': 0, + 'skip_if_quality_has': [], + 'skip_if_read_has': [], + } + + ops.update(kwargs) + + for n in ops['skip_if_quality_has']: + if n in record.quality: + return False + for n in ops['skip_if_read_has']: + if n in record.sequence: + return False + + if len(record.sequence) < ops['min_length']: + return False + return True + + + +def test(): + + # this is temporarily broken because Trim() doesn't have support for + # defining ascii offset of quality scores and these are for offset + # 64 (Illumina). I temporarily need 33. + raw = \ +'''HWUSI-EAS163FR:13:2:1:4515:5372:0:1:A +GCCGCGGTAACACGTAGGGCGCGAGCGTTGTCCGGAATTATTGGGCGTAAAGAGCTCGTAGGCGGCCTGTTGCGTGCGCTGTGAAAGCCG +HWUSI-EAS163FR:13:2:1:4515:5372:0:1:A +ffffffffffaffffcfffafffafcfffffddfdPRdd]^bbbf_febaacafY^Wa^]b`XbcZJ_c\^XM^BBBBBBBBBBBBBBBB +'''.split('\n') + + trimmed = \ +'''HWUSI-EAS163FR:13:2:1:4515:5372:0:1:A +GCCGCGGTAACACGTAGGGCGCGAGCGTTGTCCGGAATTATTGGGCGTAAAGAGCTCGTAGGCGGCCTGTTGC +HWUSI-EAS163FR:13:2:1:4515:5372:0:1:A +ffffffffffaffffcfffafffafcfffffddfdPRdd]^bbbf_febaacafY^Wa^]b`XbcZJ_c\^XM +'''.split('\n') + + record = Record(raw[0], raw[1], [ (ord(i) - 64) for i in raw[3] ]) + trimmed = Record(trimmed[0], trimmed[1], [ ord(i) - 64 for i in trimmed[3] ]) + record = Trim.trim(record) + + assert record.sequence == trimmed.sequence + assert record.quality == trimmed.quality diff --git a/code/train/Python/0117078_models.py b/code/train/Python/0117078_models.py new file mode 100644 index 0000000000000000000000000000000000000000..8a1fe0da862274708acc159a628b2b4c5b022b61 --- /dev/null +++ b/code/train/Python/0117078_models.py @@ -0,0 +1,103 @@ +from datetime import datetime, date, timedelta +from django.db import models + +class Service(models.Model): + """ + A service to track. + """ + name = models.CharField(max_length=100) + slug = models.SlugField() + description = models.CharField(max_length=255) + + class Meta: + ordering = ('name',) + + def __unicode__(self): + return self.name + + @models.permalink + def get_absolute_url(self): + return ('service', [self.slug]) + + def last_five_days(self): + """ + Used on home page. + """ + lowest = Status.objects.default() + severity = lowest.severity + + yesterday = date.today() - timedelta(days=1) + ago = yesterday - timedelta(days=5) + + events = self.events.filter(start__gt=ago, start__lt=yesterday) + + stats = {} + + for i in range(5): + stats[yesterday.day] = { + "image": lowest.image, + "day": yesterday, + } + yesterday = yesterday - timedelta(days=1) + + for event in events: + if event.status.severity > severity: + if event.start.day in stats: + stats[event.start.day]["image"] = "information" + stats[event.start.day]["information"] = True + + results = [] + + keys = stats.keys() + keys.sort() + keys.reverse() + + for k in keys: + results.append(stats[k]) + + return results + + + +class StatusManager(models.Manager): + def default(self): + return self.get_query_set().filter(severity=10)[0] + +class Status(models.Model): + """ + A possible system status. + """ + name = models.CharField(max_length=100) + slug = models.SlugField() + description = models.CharField(max_length=255) + SEVERITY_CHOICES = ( + (10, 'NORMAL'), + (30, 'WARNING'), + (40, 'ERROR'), + (50, 'CRITICAL'), + ) + severity = models.IntegerField(choices=SEVERITY_CHOICES) + image = models.CharField(max_length=100) + + objects = StatusManager() + + class Meta: + ordering = ('severity',) + verbose_name_plural = 'statuses' + + def __unicode__(self): + return self.name + + +class Event(models.Model): + service = models.ForeignKey(Service, related_name='events') + status = models.ForeignKey(Status, related_name='events') + message = models.TextField() + start = models.DateTimeField(default=datetime.now) + informational = models.BooleanField(default=False) + + class Meta: + ordering = ('-start',) + get_latest_by = 'start' + + diff --git a/code/train/Python/0117235_tokpos.py b/code/train/Python/0117235_tokpos.py new file mode 100644 index 0000000000000000000000000000000000000000..afdd4bdb6219b5f2eaae7d876d25708f4645e006 --- /dev/null +++ b/code/train/Python/0117235_tokpos.py @@ -0,0 +1,89 @@ +# tokpos.py +# +# (C) 2000 Philip Hunt +# Released under the GNU General Public Licence +# +# Contains Philip Hunt's extensions to version 0.5 of +# John Aycock's SPARK parsing framework. The purpose of the +# extensions is to cause tokens (instances of PosToken) to +# remember the line and column that they started at in the +# input source file. + +# Last altered: 12-Feb-2000 +# History: +# 12-Feb-2000 PhilHunt: created + +from generic import * + +debug = 0 + +#=========================================================== +###### PosScanner ###### +#=========================================================== + +class PosScanner(GenericScanner): + + def tokenize(self, s): + colNum = 1 + rowNum = 1 + while s: + m = self.re.match(s) + assert m + groups = m.groups() + + #>>>> phil: + newColNum = self.colNum = colNum + newRowNum = self.rowNum = rowNum + for char in s[:m.end()]: + if char == '\012': + newRowNum = newRowNum + 1 + newColNum = 1 + else: + newColNum = newColNum + 1 + #<<<< + if debug: print "$ r:c %s:%s (%s)'%s' %s:%s " % ( + rowNum, colNum, m.end(), s[:m.end()], + newRowNum, newColNum + ) + + for i in range(len(groups)): + #print "$$ i=%s groups[%s]={%s} $$" % (i, i, groups[i]) + if groups[i] and self.index2func.has_key(i): + self.index2func[i](groups[i]) + #//for i + s = s[m.end():] + + rowNum = newRowNum + colNum = newColNum + #//while s + + def addToken(self, tokenType, tokenValue): + self.rv.append(PosToken(tokenType, tokenValue, + self.rowNum, self.colNum)) + +#=========================================================== +###### PosToken ###### +#=========================================================== + +class PosToken: + def __init__(self, type, attr=None, line=0, col=0): + self.type = type + self.attr = attr + self.line = line + self.col = col + + def __cmp__(self, o): + return cmp(self.type, o) + + def __repr__(self): + x = self.type + if self.attr != None: + x = '(' + x +' ' + repr(self.attr) + ')' + else: + x = self.type + if self.line > 0: + x = x + (':%s:%s' %(self.line, self.col)) + return x + + +# end tokpos.py diff --git a/code/train/Python/0117563_locking.py b/code/train/Python/0117563_locking.py new file mode 100644 index 0000000000000000000000000000000000000000..580b237798724a335c23ab41324018a9fc0d7dc1 --- /dev/null +++ b/code/train/Python/0117563_locking.py @@ -0,0 +1,54 @@ +import logging +import random + +from tornado import gen + + +log = logging.getLogger() + + +def arguments(parser): + parser.add_argument( + "--workers", "-w", type=int, default=3, + help="Number of workers to launch." + ) + parser.add_argument( + "--lock-path", "-p", type=str, default="examplelock", + help="ZNode path to use for the lock." + ) + + +@gen.coroutine +def run(client, args): + log.info("Launching %d workers.", args.workers) + + yield client.start() + + order = list(range(args.workers)) + random.shuffle(order) + + yield [work(i, client, args) for i in order] + + yield client.close() + + +@gen.coroutine +def work(number, client, args): + lock = client.recipes.Lock(args.lock_path) + + num_iterations = 3 + + log.info("[WORKER #%d] Acquiring lock...", number) + with (yield lock.acquire()) as check: + log.info("[WORKER #%d] Got lock!", number) + + for _ in range(num_iterations): + wait = random.choice([1, 2, 3]) + if not check(): + log.warn("[WORKER #%d] lost my lock!", number) + break + + log.info("[WORKER #%d] working %d secs", number, wait) + yield gen.sleep(wait) + + log.info("[WORKER #%d] Done!", number) diff --git a/code/train/Python/0117971_axon_pulse.py b/code/train/Python/0117971_axon_pulse.py new file mode 100644 index 0000000000000000000000000000000000000000..ac9e462e006c12a7799a0d7d2b24f96d9bf47c87 --- /dev/null +++ b/code/train/Python/0117971_axon_pulse.py @@ -0,0 +1,120 @@ +import math +import random +import numpy + +from effectlayer import * +from operator import itemgetter + +def myIdxgetter(axon): + return int(axon[0][1:-1]) + + +class AxonPulseLayer(EffectLayer): + ''' + Creates a pulse through the axon, from one dendrite to the other. + Direction -- 1 : lower to upper, -1: upper to lower + Note that this effect is *not* self contained - it requires someone + else to start the pulse. + ''' + + def __init__(self): + self.pulsing = False + self.timeStart = 0 + self.velocity = 20 # indices per second to traverse + #self.pulseHeight = [0.9, 1.0, 0.8, 0.6, 0.3, 0.2] + self.pulseHeight = [0.05, 0.05, 0.05, 0.05, 0.1, 0.15, 0.2, 0.3, 0.6, 0.8, 1.0, 0.9] + self.direction = 1 + self.needSetup = True + self.startIdx = 0 + self.maxi = 0; + self.maxj = 0; + self.maxframeIdx = 0; + self.orderedAxonList = [] + + def startPulse(self, direction=1): + self.pulsing = True + self.timeStart = time.time() + if direction != self.direction: + self.direction = 1 if direction == 1 else -1 + self.orderedAxonList.reverse() + print "CSW - reversing list!!\r" +# print "!!!!!!!!!!!!!!!!!!!START PULSE!!!!!!!!!!!!!\r" + + def isPulsing(self): + return self.pulsing + + + def doSetup(self, model): + # create an ordered list of the axon indices + # get axon indices + # get names of axon indices - map [name, idx] + # order names of axon indices - ordered map [name, idx] + # create tuple of idx's associated with the same axon segment + # add tuple to new list of tuples. + axonList = [[model.pointNames[idx],idx] for idx in model.axonIndices ] +# axonList.sort(key=itemgetter(0)) + axonList.sort(key=myIdxgetter) + self.orderedAxonList = [] + lastPoint = None + tempTuple = [] + i = 0 + for axonPoint in axonList: + print axonPoint[0] + "\r" + i += 1 + # I'm comparing the names - we're looking for everything but the last character. + if not lastPoint or axonPoint[0].startswith(lastPoint[0][:-1]): + tempTuple.append(axonPoint) + else: # no match + self.orderedAxonList.append(tempTuple) + tempTuple = [] + lastPoint = axonPoint + self.orderedAxonList.append(tempTuple) + + if self.direction < 0: + reversed(self.orderedAxonList) + + print "\r" + for axon in self.orderedAxonList: + print "axon is " + axon[0][0] + "\r" + # print "first axon is " + self.orderedAxonList[0][0][0] + "\r" + # print "last axon is " + self.orderedAxonList[-1][0][0] + "\r" + + self.needSetup = False + + def render(self, model, params, frame): + # immediate bail if we're not pulsing + if not self.pulsing: + return + + # okay. What do I need? I need the axon indices, and I need to know how + # many of them there are. And I need their names. + if self.needSetup : + self.doSetup(model) + # check time, move pulse down the axon + timeExpired = time.time() - self.timeStart + leadingEdgeIdx = self.startIdx + int(math.floor((self.velocity * timeExpired))) + trailingEdgeIdx = leadingEdgeIdx - (len(self.pulseHeight)) + 1 +# print "leading edge idx is " + str(leadingEdgeIdx) + "\r" + + # can I count backward in python ranges? It's probably a bad idea... + havePulse = False + for i in range(trailingEdgeIdx, leadingEdgeIdx+1): + if i < 0 or i > len(self.orderedAxonList)-1: + continue + for j in range(0,len(self.orderedAxonList[i])): +# if i > self.maxi: +# self.maxi = i +# if j > self.maxj: +# self.maxj = j +# if self.orderedAxonList[i][j][1] > self.maxframeIdx: +# self.maxframeIdx = self.orderedAxonList[i][j][1] +# print "id i is " + str(self.maxi) + "\r" +# print "id j is" + str(self.maxj) + "\r" +# print "idx in frame is " + str(self.maxframeIdx) + "\n\r" + frame[self.orderedAxonList[i][j][1]] = self.pulseHeight[i-trailingEdgeIdx] + havePulse = True + + self.pulsing = havePulse + + + \ No newline at end of file diff --git a/code/validation/C++/0000053_random_sample.cpp b/code/validation/C++/0000053_random_sample.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2f6fe9077007b98703292116d0e4672f771a2366 --- /dev/null +++ b/code/validation/C++/0000053_random_sample.cpp @@ -0,0 +1,40 @@ +#include +#include +using namespace std; + +//given an array of numbers, produce a sample of size K of them. +//algorithm: swap(array[i++],array[random]) k times -> so that the first k elements are the random sample + +void swap(int array[],int a,int b){ + if(a!=b){ + array[a]^=array[b]; + array[b]^=array[a]; + array[a]^=array[b]; + } +} + +int main(){ + + int numbers[]={1,2,3,4,5,6,7,8,9,10}; + int n=sizeof(numbers)/sizeof(int); + + random_device rd; + default_random_engine gen(rd()); + + int sampleSize=4; + + for(int i=0;i dis(i,n-1); + swap(numbers,i,dis(gen)); + } + + //print random sample of size sampleSize + for(int i=0;i + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include "analog.hpp" +#include "analogsegment.hpp" + +using std::deque; +using std::max; +using std::shared_ptr; +using std::vector; + +namespace pv { +namespace data { + +Analog::Analog() : + SignalData() +{ +} + +void Analog::push_segment(shared_ptr &segment) +{ + segments_.push_front(segment); +} + +const deque< shared_ptr >& Analog::analog_segments() const +{ + return segments_; +} + +vector< shared_ptr > Analog::segments() const +{ + return vector< shared_ptr >( + segments_.begin(), segments_.end()); +} + +void Analog::clear() +{ + segments_.clear(); +} + +uint64_t Analog::get_max_sample_count() const +{ + uint64_t l = 0; + for (const std::shared_ptr s : segments_) { + assert(s); + l = max(l, s->get_sample_count()); + } + return l; +} + +} // namespace data +} // namespace pv diff --git a/code/validation/C++/0001127_SkillHandler.cpp b/code/validation/C++/0001127_SkillHandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51e63d5fb756a4922cd8f52ad4e11f365002bbd9 --- /dev/null +++ b/code/validation/C++/0001127_SkillHandler.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2010-2012 Project SkyFire + * Copyright (C) 2010-2012 Oregon + * Copyright (C) 2008-2012 TrinityCore + * Copyright (C) 2005-2012 MaNGOS + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "Common.h" +#include "DatabaseEnv.h" +#include "Opcodes.h" +#include "Log.h" +#include "Player.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" +#include "ObjectAccessor.h" +#include "UpdateMask.h" +#include "SpellAuras.h" + +void WorldSession::HandleLearnTalentOpcode(WorldPacket & recv_data) +{ + uint32 talent_id, requested_rank; + recv_data >> talent_id >> requested_rank; + + uint32 CurTalentPoints = GetPlayer()->GetFreeTalentPoints(); + + if (CurTalentPoints == 0) + return; + + if (requested_rank > 4) + return; + + TalentEntry const *talentInfo = sTalentStore.LookupEntry(talent_id); + + if (!talentInfo) + return; + + TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); + + if (!talentTabInfo) + return; + + Player * player = GetPlayer(); + + // prevent learn talent for different class (cheating) + if ((player->getClassMask() & talentTabInfo->ClassMask) == 0) + return; + + // prevent skip talent ranks (cheating) + if (requested_rank > 0 && !player->HasSpell(talentInfo->RankID[requested_rank-1])) + return; + + // Check if it requires another talent + if (talentInfo->DependsOn > 0) + { + if (TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn)) + { + bool hasEnoughRank = false; + for (int i = talentInfo->DependsOnRank; i <= 4; i++) + { + if (depTalentInfo->RankID[i] != 0) + if (player->HasSpell(depTalentInfo->RankID[i])) + hasEnoughRank = true; + } + if (!hasEnoughRank) + return; + } + } + + // Check if it requires spell + if (talentInfo->DependsOnSpell && !player->HasSpell(talentInfo->DependsOnSpell)) + return; + + // Find out how many points we have in this field + uint32 spentPoints = 0; + + uint32 tTab = talentInfo->TalentTab; + if (talentInfo->Row > 0) + { + unsigned int numRows = sTalentStore.GetNumRows(); + for (unsigned int i = 0; i < numRows; i++) // Loop through all talents. + { + // Someday, someone needs to revamp + const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i); + if (tmpTalent) // the way talents are tracked + { + if (tmpTalent->TalentTab == tTab) + { + for (int j = 0; j <= 4; j++) + { + if (tmpTalent->RankID[j] != 0) + { + if (player->HasSpell(tmpTalent->RankID[j])) + { + spentPoints += j + 1; + } + } + } + } + } + } + } + + // not have required min points spent in talent tree + if (spentPoints < (talentInfo->Row * 5)) + return; + + // spell not set in talent.dbc + uint32 spellid = talentInfo->RankID[requested_rank]; + if (spellid == 0) + { + sLog->outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talent_id, requested_rank); + return; + } + + // already known + if (GetPlayer()->HasSpell(spellid)) + return; + + // learn! (other talent ranks will unlearned at learning) + GetPlayer()->learnSpell(spellid); + GetPlayer()->addTalent(spellid, GetPlayer()->GetActiveSpec(), true); + sLog->outDetail("TalentID: %u Rank: %u Spell: %u\n", talent_id, requested_rank, spellid); + + // learn max talent rank for instant chars + if (GetPlayer()->getCharacterMode() == CHARACTER_MODE_INSTANT) + GetPlayer()->learnHigherTalentRanks(spellid); + + // update free talent points + GetPlayer()->SetFreeTalentPoints(CurTalentPoints - 1); +} + +void WorldSession::HandleTalentWipeOpcode(WorldPacket & recv_data) +{ + sLog->outDetail("MSG_TALENT_WIPE_CONFIRM"); + uint64 guid; + recv_data >> guid; + + Creature *unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER); + if (!unit) + { + sLog->outDebug("WORLD: HandleTalentWipeOpcode - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(guid))); + return; + } + + // remove fake death + if (GetPlayer()->hasUnitState(UNIT_STAT_DIED)) + GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); + + if (!(_player->resetTalents())) + { + WorldPacket data(MSG_TALENT_WIPE_CONFIRM, 8+4); //you have not any talent + data << uint64(0); + data << uint32(0); + SendPacket(&data); + return; + } + + unit->CastSpell(_player, 14867, true); //spell: "Untalent Visual Effect" +} + +void WorldSession::HandleUnlearnSkillOpcode(WorldPacket & recv_data) +{ + uint32 skill_id; + recv_data >> skill_id; + GetPlayer()->SetSkill(skill_id, 0, 0); +} + diff --git a/code/validation/C++/0003117_NodeComponent.cpp b/code/validation/C++/0003117_NodeComponent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8846e94c23e835ffd51a299eb91e2dfd50a40f7e --- /dev/null +++ b/code/validation/C++/0003117_NodeComponent.cpp @@ -0,0 +1,167 @@ + + +#include "NodeComponent.h" + + +NodeComponent::NodeComponent(const GraphViewTheme& theme, Graph::Node* model) : theme(theme), model(model) { + + model->addListener(this); + + cNodeBackgroundCurrent = theme.cNodeBackground; + + for(auto i = 0; i < model->ins.size(); i++) { + auto pin = std::make_unique(this, model->ins[i].get()); + ins.push_back(std::move(pin)); + } + + for(auto i = 0; i < model->outs.size(); i++) { + auto pin = std::make_unique(this, model->outs[i].get()); + outs.push_back(std::move(pin)); + } + + translation = AffineTransform::translation(0, 0); + + scaleFactor = theme.initialScaleFactor; + scale = AffineTransform::scale(scaleFactor); + +} + +NodeComponent::~NodeComponent() { + model->removeListener(this); +} + +bool NodeComponent::hasIns() { + return ins.size() > 0; +} + +bool NodeComponent::hasOuts() { + return outs.size() > 0; +} + +int NodeComponent::boxHeight() { + auto h = getHeight(); + if (hasIns()) h -= theme.pinHeight; + if (hasOuts()) h -= theme.pinHeight; + return h; +} + +Rectangle NodeComponent::boxBounds() { + auto local = getLocalBounds(); + if (hasIns()) local.removeFromTop(theme.pinHeight); + if (hasOuts()) local.removeFromBottom(theme.pinHeight); + return local; +} + +void NodeComponent::paint(Graphics& g) { + Path p; + auto bounds = boxBounds(); + //p.addRectangle(bounds); + p.addRoundedRectangle(bounds, 3); + + if (selected) + g.setColour(Colour(theme.cNodeBackgroundSelected)); + else + g.setColour(Colour(cNodeBackgroundCurrent)); + + g.fillPath(p); + g.setColour(Colours::white); + g.drawText(model->name, boxBounds(), Justification::centred, true); +} + +void NodeComponent::resized() { + + { + auto x = theme.pinSpacing; + auto y = 0; + auto w = theme.pinWidth; + auto h = theme.pinHeight; + for (auto& p : ins) { + p->setBounds(x, y, w, h); + addAndMakeVisible(p.get()); + x += w + theme.pinSpacing; + } + } + + { + auto x = theme.pinSpacing; + auto y = getHeight() - theme.pinHeight; + auto w = theme.pinWidth; + auto h = theme.pinHeight; + for (auto& p : outs) { + p->setBounds(x, y, w, h); + addAndMakeVisible(p.get()); + x += w + theme.pinSpacing; + } + } + +} + +bool NodeComponent::hitTest(int x, int y) { + auto inBox = boxBounds().contains(x, y); + auto inTopPins = false; + auto inBottomPins = false; + + for (auto& p : ins) { + if (p->getBounds().contains(x, y)) { + inTopPins = true; + break; + } + } + + for (auto& p : outs) { + if (p->getBounds().contains(x, y)) { + inBottomPins = true; + break; + } + } + + return inBox || inTopPins || inBottomPins; +} + +void NodeComponent::mouseDown(const MouseEvent& e) { +} + +void NodeComponent::mouseDrag(const MouseEvent& e) { + + +} + +void NodeComponent::mouseUp(const MouseEvent& e) { +} + + +void NodeComponent::mouseMove(const MouseEvent& e) { + if (boxBounds().contains(e.x, e.y)) { + cNodeBackgroundCurrent = theme.cNodeBackgroundHover; + repaint(); + } +} + + +void NodeComponent::mouseExit(const MouseEvent& e) { + cNodeBackgroundCurrent = theme.cNodeBackground; + repaint(); +} + + +void NodeComponent::mouseDoubleClick(const MouseEvent& e) { + //model->flow(model->name); + //model->graph->dfs(model, [&](const auto& n) -> void { printf("visiting %s\n", n->name.c_str()); } ); +} + + + + + + + + + + + + + + + + + diff --git a/code/validation/C++/0005476_0950-Reveal_Cards_In_Increasing_Order.cpp b/code/validation/C++/0005476_0950-Reveal_Cards_In_Increasing_Order.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30ff4168aed5b9d97ee6d6dd6ca0c5ecbeb3eda4 --- /dev/null +++ b/code/validation/C++/0005476_0950-Reveal_Cards_In_Increasing_Order.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector deckRevealedIncreasing(vector& deck) { + sort(deck.begin(), deck.end()); + deque Q; + Q.push_back(deck.back()); + for (int i = (int)(deck.size()) - 2; i >= 0; --i) { + Q.push_front(Q.back()); + Q.pop_back(); + Q.push_front(deck[i]); + } + return vector(Q.begin(), Q.end()); + } +}; + +class Solution { +public: + vector deckRevealedIncreasing(vector& deck) { + sort(deck.begin(), deck.end()); + queue Q; + for (int i = 0; i < deck.size(); ++i) { + Q.push(i); + } + vector result(deck.size()); + for (int card : deck) { + result[Q.front()] = card; + Q.pop(); + if (Q.size()) { + Q.push(Q.front()); + Q.pop(); + } + } + return result; + } +}; diff --git a/code/validation/C++/0009552_LRUBasedLinkedList.cpp b/code/validation/C++/0009552_LRUBasedLinkedList.cpp new file mode 100644 index 0000000000000000000000000000000000000000..680cb12610fc9b7df4183b09195e06d6ae5e449d --- /dev/null +++ b/code/validation/C++/0009552_LRUBasedLinkedList.cpp @@ -0,0 +1,229 @@ +typedef int DataType; + +//定义 +class SNode +{ +public: + DataType data; + SNode * next; +}; + +class SList +{ +public: + SList(); + SList(int MaxSize); + ~SList(); + void intsertElemAtBegin(DataType x); //头部插入节点 + bool findElem(DataType x); //查找x,存在则返回1,不存在则返回0 + void deleteElemAtEnd(); //删除尾节点 + bool deleteElem(DataType x); //删除指定节点,如果存在则删除,返回1,如果不存在,则删除失败返回0 + bool isEmpty(); // 查看链表是否为空,1表示不为空,0表示为空 + bool isFull(); // 查看链表是否满,1表示不满,0表示满 + void printAll(); + + void * findElemOptim(DataType x); //针对此应用的优化,查找,返回指定元素的前一个节点的指针 + void deleteElemOptim(void * snode); //针对此应用的优化,删除 +private: + int MaxSize; // 链表可以存放最大的数据 + int length; // 链表的长度 + SNode * head; // 指向头节点 + +}; + + +/** + * 1)单链表的插入,删除,查找操作; + * 2)链表中存储的是 int 类型 + * + * Author:caozx + */ +#include +using namespace std; + +// 初始化单链表 +SList::SList(){ + head = new SNode; //申请头节点 + head -> next = NULL; + this -> MaxSize = 10; + this -> length = 0; +} +SList::SList(int MaxSize){ + head = new SNode; //申请头节点 + head -> next = NULL; + this -> MaxSize = MaxSize; + this -> length = 0; +} + +// 销毁单链表,要把开辟的空间都释放,然后再销毁。 +SList::~SList(){ + SNode * ptr, * temp; + ptr = head; + while(ptr -> next != NULL){ + temp = ptr -> next; + ptr -> next = ptr -> next -> next; + delete temp; + } + delete head ; //删除头节点 + this -> head = NULL; + this -> length = 0; +} + +//链表头部插入节点 +void SList::intsertElemAtBegin(DataType x){ + SNode * ptr = new SNode; + ptr -> data = x; + + ptr -> next = head ->next; + head -> next = ptr; + + this -> length ++; +} + +//查找x,存在则返回1,不存在则返回0 + +bool SList::findElem(DataType x) +{ + SNode * ptr; + ptr = head; + while(ptr -> next != NULL){ + if(ptr -> next ->data == x){ + return 1; + } + ptr = ptr -> next; + } + return 0; +} + +// 删除尾结点 +void SList::deleteElemAtEnd(){ + SNode * ptr , * temp; + ptr = head; + while(ptr -> next != NULL && ptr -> next -> next != NULL){ //倒数第二个节点 + ptr = ptr -> next; + } + temp = ptr -> next; + ptr -> next = temp -> next; + this -> length --; + delete temp; +} + +//删除指定节点, +//如果存在则删除,返回1,表示存在且删除成功; +//如果不存在则不删除,返回0,表示不存在该元素,不需要删除,也即删除失败 +bool SList::deleteElem(DataType x) +{ + SNode * ptr, * temp; + ptr = head; + while(ptr -> next != NULL){ + if(ptr -> next ->data == x){ + temp = ptr -> next; + ptr -> next = temp -> next; + delete temp; + this -> length --; + return 1; + } + ptr = ptr -> next; + } + return 0; +} + +// 查看链表是否为空,1表示不为空,0表示为空 +bool SList::isEmpty() +{ + if(this -> length == 0){ //空 + return 0; + } + else{ + return 1; + } +} + +// 查看链表是否满,1表示不满,0表示满 +bool SList::isFull() +{ + if(this -> length == this -> MaxSize){ //满 + return 0; + } + else{ + return 1; + } +} + +// 打印 +void SList::printAll() +{ + SNode * ptr; + ptr = head; + while(ptr -> next != NULL){ + ptr = ptr -> next; + cout << ptr-> data <<" "; + } + cout << endl; +} + +//针对此应用的优化,查找, +//若存在则返回指定元素的前一个节点的指针 +//若不存在,则返回NULL + +void * SList::findElemOptim(DataType x) +{ + SNode * ptr; + ptr = head; + while(ptr -> next != NULL){ + if(ptr -> next ->data == x){ + return (void *)ptr; + } + ptr = ptr -> next; + } + return NULL; +} + +//针对此应用的优化,删除 + +void SList::deleteElemOptim(void * snode) +{ + SNode * ptr, * temp; + ptr = (SNode *)snode; + temp = ptr -> next; + ptr -> next = temp -> next; + this -> length --; + delete temp; +} +int main(int argc, char const *argv[]) +{ + cout << "test "<< endl; + SList slist(10); //缓存最大10个。 + int num = 0; + while(1) + { + cout << "please enter a number,99999== exit" << endl; + cin >> num; + if(num == 99999) + break; + /* 未优化 + if(slist.findElem(num)){ //存在 + slist.deleteElem(num); //把原来的位置删除 + slist.intsertElemAtBegin(num); //在链表头插入 + } + */ + //优化 + SNode * prePtr = (SNode *)slist.findElemOptim(num); + if(prePtr != NULL){ //存在 + slist.deleteElemOptim(prePtr); //把原来的位置删除 + slist.intsertElemAtBegin(num); //在链表头插入 + } + else{ //不存在 + if(slist.isFull()){ //不满 + slist.intsertElemAtBegin(num); + } + else{ //满 + slist.deleteElemAtEnd(); + slist.intsertElemAtBegin(num); + } + } + slist.printAll(); + } + return 0; + system("pause"); +} diff --git a/code/validation/C++/0009937_TheDevice.cpp b/code/validation/C++/0009937_TheDevice.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1643049e9d7c085ed027dfd8aac3db2b9899b64d --- /dev/null +++ b/code/validation/C++/0009937_TheDevice.cpp @@ -0,0 +1,196 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define sz(m)((m).size()) +#define all(a)a.begin(),a.end() +#define forn(i,n)for(int i=0,i##e=n;i(cout,"\n"));cout< plates) { + int m = 0; + fori (j, plates[0]) { + int c = 0; + fori(i, plates) + c += plates[i][j] - '0'; + m = max(m, max(2 - c, 0) + max(1 - (int)plates.size() + c, 0)); + } + return m; + } +}; + + + +double test0() { + string t0[] = {"010", + "011", + "101"}; + vector p0(t0, t0+sizeof(t0)/sizeof(string)); + TheDevice * obj = new TheDevice(); + clock_t start = clock(); + int my_answer = obj->minimumAdditional(p0); + clock_t end = clock(); + delete obj; + cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" < p0(t0, t0+sizeof(t0)/sizeof(string)); + TheDevice * obj = new TheDevice(); + clock_t start = clock(); + int my_answer = obj->minimumAdditional(p0); + clock_t end = clock(); + delete obj; + cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" < p0(t0, t0+sizeof(t0)/sizeof(string)); + TheDevice * obj = new TheDevice(); + clock_t start = clock(); + int my_answer = obj->minimumAdditional(p0); + clock_t end = clock(); + delete obj; + cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" < p0(t0, t0+sizeof(t0)/sizeof(string)); + TheDevice * obj = new TheDevice(); + clock_t start = clock(); + int my_answer = obj->minimumAdditional(p0); + clock_t end = clock(); + delete obj; + cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" < p0(t0, t0+sizeof(t0)/sizeof(string)); + TheDevice * obj = new TheDevice(); + clock_t start = clock(); + int my_answer = obj->minimumAdditional(p0); + clock_t end = clock(); + delete obj; + cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" < +#include +#include "cpp/video/atom.h" +#include "cpp/video/atom_helpers.h" +#include "cpp/video/atom_reader.h" +#include "cpp/video/atom_writer.h" +#include "cpp/video/atoms/atom_moov.h" +#include "cpp/video/atoms/atom_stco.h" +#include "cpp/video/atoms/atom_trak.h" +#include "cpp/video/binary_reader_impl.h" +#include "cpp/video/binary_writer_impl.h" +#include "cpp/video/format_status.h" + +namespace vr180 { +namespace { +constexpr char kMoovType[] = "moov"; +constexpr char kMdatType[] = "mdat"; +constexpr char kFreeType[] = "free"; +constexpr int64_t kFreeAtomHeaderSize = 8; + +FormatStatus AdjustTrackOffsets(AtomMOOV* moov, const int64_t delta) { + LOG(INFO) << "Adjusting STCO offsets by " << delta << " bytes"; + for (AtomTRAK* trak : moov->tracks()) { + Atom* stbl = trak->atom_stbl(); + if (stbl == nullptr) { + return FormatStatus::Error(FormatErrorCode::FILE_FORMAT_ERROR, + "track does not contain stbl atom"); + } + AtomSTCO* stco = FindChild(*stbl); + if (stco == nullptr) { + return FormatStatus::Error(FormatErrorCode::FILE_FORMAT_ERROR, + "track does not contain stco atom"); + } + stco->AdjustChunkOffsets(delta); + } + + return FormatStatus::OkStatus(); +} + +std::vector> ReadAtoms(BinaryReader* input) { + std::vector> atoms; + while (input->Tell() < input->Size()) { + std::unique_ptr top_level_atom = ReadAtom(input); + if (top_level_atom == nullptr) break; + atoms.push_back(std::move(top_level_atom)); + } + return atoms; +} + +uint64_t GetAtomPosition( + const std::vector>& top_level_atoms, + const std::string& type) { + uint64_t position = 0; + for (const auto& top_level_atom : top_level_atoms) { + if (top_level_atom->atom_type() == type) return position; + position += top_level_atom->size(); + } + return position; +} + +int GetAtomIndex(const std::vector>& top_level_atoms, + const std::string& type) { + for (int i = 0; i < top_level_atoms.size(); ++i) { + if (top_level_atoms[i]->atom_type() == type) return i; + } + return -1; +} + +// Write a free space of the given size at the current position +FormatStatus WriteFreeSpace(const uint32_t size, BinaryWriter* output) { + RETURN_IF_FORMAT_ERROR(output->PutUInt32(size)); + return output->PutString(kFreeType); +} + +// Copy the specified atoms to memory then write to the output. +FormatStatus WriteAtomsInPlace( + const std::vector>& input_atoms, + const int input_start, const int input_end, const uint64_t output_position, + BinaryWriter* output) { + MemoryBinaryWriter memory_output; + for (int i = input_start; i < input_end; ++i) { + CHECK_NE(input_atoms[i]->atom_type(), kMdatType) << "Should not copy mdat"; + RETURN_IF_FORMAT_ERROR(WriteAtom(*input_atoms[i], &memory_output)); + } + const std::string content = memory_output.GetContents(); + MemoryBinaryReader memory_input(content); + const auto& memory_atoms = ReadAtoms(&memory_input); + if (memory_atoms.size() != input_end - input_start) { + return FormatStatus::Error(FormatErrorCode::UNEXPECTED_ERROR, + "Invalid number of atoms to write"); + } + RETURN_IF_FORMAT_ERROR(output->Seek(output_position)); + for (int i = 0; i < input_end - input_start; ++i) { + RETURN_IF_FORMAT_ERROR(WriteAtom(*memory_atoms[i], output)); + } + return FormatStatus::OkStatus(); +} + +FormatStatus ModifyMoov(const MoovModifier& modifier, BinaryReader* input, + BinaryWriter* output) { + std::vector> top_level_atoms = ReadAtoms(input); + const int moov_index = GetAtomIndex(top_level_atoms, kMoovType); + const int mdat_index = GetAtomIndex(top_level_atoms, kMdatType); + if (moov_index == -1 || mdat_index == -1) { + return FormatStatus::Error(FormatErrorCode::FILE_FORMAT_ERROR, + "Invalid video file"); + } + const uint64_t mdat_position_before_update = + GetAtomPosition(top_level_atoms, kMdatType); + + AtomMOOV* moov = static_cast(top_level_atoms[moov_index].get()); + RETURN_IF_FORMAT_ERROR(modifier(moov)); + + if (moov_index > mdat_index) { + std::swap(top_level_atoms[moov_index], top_level_atoms[mdat_index]); + } + const uint64_t mdat_position_after_update = + GetAtomPosition(top_level_atoms, kMdatType); + const int64_t delta = + mdat_position_after_update - mdat_position_before_update; + + if (delta != 0) { + RETURN_IF_FORMAT_ERROR(AdjustTrackOffsets(moov, delta)); + } + + // Output all the atoms. + for (const auto& top_level_atom : top_level_atoms) { + RETURN_IF_FORMAT_ERROR(WriteAtom(*top_level_atom, output)); + } + return FormatStatus::OkStatus(); +} + +FormatStatus ModifyMoovInPlace(const MoovModifier& modifier, + BinaryReader* input, BinaryWriter* output) { + std::vector> top_level_atoms = ReadAtoms(input); + const int moov_index = GetAtomIndex(top_level_atoms, kMoovType); + const int mdat_index = GetAtomIndex(top_level_atoms, kMdatType); + if (moov_index == -1 || mdat_index == -1) { + return FormatStatus::Error(FormatErrorCode::FILE_FORMAT_ERROR, + "Invalid video file"); + } + + // Add up all the atom sizes. + const uint64_t size_before_update = input->Size(); + // Position of the moov atom. + const uint64_t moov_position_before_update = + GetAtomPosition(top_level_atoms, kMoovType); + + /// Modify the moov box. + AtomMOOV* moov = static_cast(top_level_atoms[moov_index].get()); + const uint64_t moov_size_before_update = moov->size(); + RETURN_IF_FORMAT_ERROR(modifier(moov)); + const uint64_t moov_size_after_update = moov->size(); + const int64_t delta = moov_size_after_update - moov_size_before_update; + if (moov_index > mdat_index) { + LOG(INFO) << "Update moov and following boxes in place after mdat"; + RETURN_IF_FORMAT_ERROR( + WriteAtomsInPlace(top_level_atoms, moov_index, top_level_atoms.size(), + moov_position_before_update, output)); + if (delta < 0) { + // If MOOV is now smaller, we mark the remaining part as free. + LOG(INFO) << "Moov size is " << -delta << " bytes smaller"; + RETURN_IF_FORMAT_ERROR( + WriteFreeSpace(std::max(-delta, kFreeAtomHeaderSize), output)); + } + return FormatStatus::OkStatus(); + } + + const std::unique_ptr& next = top_level_atoms[moov_index + 1]; + const int64_t free_space_after_moov = + next->atom_type() == kFreeType ? next->size() : 0; + + if (delta == free_space_after_moov) { + // No size change. Just need to update the moov box. + LOG(INFO) << "Update moov in place"; + return WriteAtomsInPlace(top_level_atoms, moov_index, moov_index + 1, + moov_position_before_update, output); + } + + if (delta + kFreeAtomHeaderSize <= free_space_after_moov) { + // There is enough space for moov and a free box. + LOG(INFO) << "Update moov and add free"; + RETURN_IF_FORMAT_ERROR( + WriteAtomsInPlace(top_level_atoms, moov_index, moov_index + 1, + moov_position_before_update, output)); + return WriteFreeSpace(free_space_after_moov - delta, output); + } + + // Overwrite moov by a free box and move MOOV to the end of file. + LOG(INFO) << "Move moov to the end: " << size_before_update; + RETURN_IF_FORMAT_ERROR(WriteAtomsInPlace( + top_level_atoms, moov_index, moov_index + 1, size_before_update, output)); + RETURN_IF_FORMAT_ERROR(output->Seek(moov_position_before_update)); + return WriteFreeSpace(moov_size_before_update, output); +} + +template +FormatStatus ModifyMoovImpl(const MoovModifier& modifier, + const StringType& input_url, + const StringType& output_url) { + if (modifier == nullptr || input_url.empty() || output_url.empty()) { + return FormatStatus::Error( + FormatErrorCode::UNEXPECTED_ERROR, + "Must provide non-null modifier and non-empty input and output urls."); + } + if (input_url != output_url) { + FileBinaryReader reader(input_url); + FileBinaryWriter writer(output_url); + return ModifyMoov(modifier, &reader, &writer); + } else { + std::shared_ptr inout(new std::fstream( + input_url, + std::fstream::in | std::fstream::out | std::fstream::binary)); + BinaryWriterImpl writer(inout); + BinaryReaderImpl reader(inout); + return ModifyMoovInPlace(modifier, &reader, &writer); + } +} + +} // namespace + +FormatStatus ModifyMoov(const MoovModifier& modifier, const std::string& input_url, + const std::string& output_url) { + return ModifyMoovImpl(modifier, input_url, output_url); +} + +#ifdef _WIN32 +FormatStatus ModifyMoov(const MoovModifier& modifier, + const std::wstring& input_url, + const std::wstring& output_url) { + return ModifyMoovImpl(modifier, input_url, output_url); +} +#endif + +} // namespace vr180 diff --git a/code/validation/C++/0010612_binary2txt.cpp b/code/validation/C++/0010612_binary2txt.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dfa81e8a6ebf983aec14490dc46232237a135d7e --- /dev/null +++ b/code/validation/C++/0010612_binary2txt.cpp @@ -0,0 +1,266 @@ +/* ----------------------------------------------------------------------- + LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator + https://www.lammps.org/ + Steve Plimpton, sjplimp@sandia.gov, Sandia National Laboratories + + Copyright (2003) Sandia Corporation. Under the terms of Contract + DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains + certain rights in this software. This software is distributed under + the GNU General Public License. + + See the README file in the top-level LAMMPS directory. +------------------------------------------------------------------------ */ + +// Convert one or more LAMMPS binary dump files to ASCII text files +// +// this serial code must be compiled on a platform that can read the binary +// dump files since binary formats are not compatible across all platforms +// +// Syntax: binary2txt file1 file2 ... +// Creates: file1.txt file2.txt ... + +#include +#include + +// these must match settings in src/lmptype.h which builds LAMMPS with +// -DLAMMPS_SMALLBIG (the default), -DLAMMPS_BIGBIG, or -DLAMMPS_SMALLSMALL +// you can edit the tools/Makefile to enforce the same setting +// for the build of binary2txt, e.g. +// g++ -g -DLAMMPS_BIGBIG binarytxt.o -o binary2txt +// again -DLAMMPS_SMALLBIG is the default + +#include +#define __STDC_FORMAT_MACROS +#include + +#ifndef PRId64 +#define PRId64 "ld" +#endif + +#if !defined(LAMMPS_SMALLSMALL) && !defined(LAMMPS_BIGBIG) && !defined(LAMMPS_SMALLBIG) +#define LAMMPS_SMALLBIG +#endif + +#if defined(LAMMPS_SMALLBIG) +typedef int tagint; +typedef int64_t bigint; +#define BIGINT_FORMAT "%" PRId64 +#elif defined(LAMMPS_SMALLSMALL) +typedef int tagint; +typedef int bigint; +#define BIGINT_FORMAT "%d" +#else /* LAMMPS_BIGBIG */ +typedef int64_t tagint; +typedef int64_t bigint; +#define BIGINT_FORMAT "%" PRId64 +#endif + +int main(int narg, char **arg) +{ + int i, j, k, m, n; + bigint ntimestep, natoms; + int size_one, nchunk, triclinic; + double xlo, xhi, ylo, yhi, zlo, zhi, xy, xz, yz; + int boundary[3][2]; + char boundstr[9]; + + int maxbuf = 0; + double *buf = nullptr; + + if (narg == 1) { + printf("Syntax: binary2txt file1 file2 ...\n"); + return 1; + } + + // loop over files + + for (int iarg = 1; iarg < narg; iarg++) { + printf("%s:", arg[iarg]); + fflush(stdout); + FILE *fp = fopen(arg[iarg], "rb"); + if (!fp) { + printf("ERROR: Could not open %s\n", arg[iarg]); + return 1; + } + + n = strlen(arg[iarg]) + 1 + 4; + char *filetxt = new char[n]; + strcpy(filetxt, arg[iarg]); + strcat(filetxt, ".txt"); + FILE *fptxt = fopen(filetxt, "w"); + delete[] filetxt; + + // detect newer format + char *magic_string = nullptr; + char *columns = nullptr; + char *unit_style = nullptr; + + // loop over snapshots in file + + while (true) { + int endian = 0x0001; + int revision = 0x0001; + + fread(&ntimestep, sizeof(bigint), 1, fp); + + // detect end-of-file + + if (feof(fp)) { + fclose(fp); + fclose(fptxt); + break; + } + + // detect newer format + if (ntimestep < 0) { + // first bigint encodes negative format name length + bigint magic_string_len = -ntimestep; + + delete[] magic_string; + magic_string = new char[magic_string_len + 1]; + fread(magic_string, sizeof(char), magic_string_len, fp); + magic_string[magic_string_len] = '\0'; + + // read endian flag + fread(&endian, sizeof(int), 1, fp); + + // read revision number + fread(&revision, sizeof(int), 1, fp); + + // read the real ntimestep + fread(&ntimestep, sizeof(bigint), 1, fp); + } + + fread(&natoms, sizeof(bigint), 1, fp); + fread(&triclinic, sizeof(int), 1, fp); + fread(&boundary[0][0], 6 * sizeof(int), 1, fp); + fread(&xlo, sizeof(double), 1, fp); + fread(&xhi, sizeof(double), 1, fp); + fread(&ylo, sizeof(double), 1, fp); + fread(&yhi, sizeof(double), 1, fp); + fread(&zlo, sizeof(double), 1, fp); + fread(&zhi, sizeof(double), 1, fp); + if (triclinic) { + fread(&xy, sizeof(double), 1, fp); + fread(&xz, sizeof(double), 1, fp); + fread(&yz, sizeof(double), 1, fp); + } + fread(&size_one, sizeof(int), 1, fp); + + if (magic_string && revision > 0x0001) { + // newer format includes units string, columns string + // and time + int len = 0; + fread(&len, sizeof(int), 1, fp); + + if (len > 0) { + // has units + delete[] unit_style; + unit_style = new char[len + 1]; + fread(unit_style, sizeof(char), len, fp); + unit_style[len] = '\0'; + fprintf(fptxt, "ITEM: UNITS\n"); + fprintf(fptxt, "%s\n", unit_style); + } + + char flag = 0; + fread(&flag, sizeof(char), 1, fp); + + if (flag) { + double time; + fread(&time, sizeof(double), 1, fp); + fprintf(fptxt, "ITEM: TIME\n%.16g\n", time); + } + + fread(&len, sizeof(int), 1, fp); + delete[] columns; + columns = new char[len + 1]; + fread(columns, sizeof(char), len, fp); + columns[len] = '\0'; + } + + fread(&nchunk, sizeof(int), 1, fp); + + fprintf(fptxt, "ITEM: TIMESTEP\n"); + fprintf(fptxt, BIGINT_FORMAT "\n", ntimestep); + fprintf(fptxt, "ITEM: NUMBER OF ATOMS\n"); + fprintf(fptxt, BIGINT_FORMAT "\n", natoms); + + m = 0; + for (int idim = 0; idim < 3; idim++) { + for (int iside = 0; iside < 2; iside++) { + if (boundary[idim][iside] == 0) + boundstr[m++] = 'p'; + else if (boundary[idim][iside] == 1) + boundstr[m++] = 'f'; + else if (boundary[idim][iside] == 2) + boundstr[m++] = 's'; + else if (boundary[idim][iside] == 3) + boundstr[m++] = 'm'; + } + boundstr[m++] = ' '; + } + boundstr[8] = '\0'; + + if (!triclinic) { + fprintf(fptxt, "ITEM: BOX BOUNDS %s\n", boundstr); + fprintf(fptxt, "%-1.16e %-1.16e\n", xlo, xhi); + fprintf(fptxt, "%-1.16e %-1.16e\n", ylo, yhi); + fprintf(fptxt, "%-1.16e %-1.16e\n", zlo, zhi); + } else { + fprintf(fptxt, "ITEM: BOX BOUNDS xy xz yz %s\n", boundstr); + fprintf(fptxt, "%-1.16e %-1.16e %-1.16e\n", xlo, xhi, xy); + fprintf(fptxt, "%-1.16e %-1.16e %-1.16e\n", ylo, yhi, xz); + fprintf(fptxt, "%-1.16e %-1.16e %-1.16e\n", zlo, zhi, yz); + } + + if (columns) + fprintf(fptxt, "ITEM: ATOMS %s\n", columns); + else + fprintf(fptxt, "ITEM: ATOMS\n"); + + // loop over processor chunks in file + + for (i = 0; i < nchunk; i++) { + fread(&n, sizeof(int), 1, fp); + + // extend buffer to fit chunk size + + if (n > maxbuf) { + if (buf) delete[] buf; + buf = new double[n]; + maxbuf = n; + } + + // read chunk and write as size_one values per line + + fread(buf, sizeof(double), n, fp); + n /= size_one; + m = 0; + for (j = 0; j < n; j++) { + for (k = 0; k < size_one; k++) { + if (k + 1 < size_one) { + fprintf(fptxt, "%g ", buf[m++]); + } else { + fprintf(fptxt, "%g", buf[m++]); + } + } + fprintf(fptxt, "\n"); + } + } + + printf(" " BIGINT_FORMAT, ntimestep); + fflush(stdout); + } + printf("\n"); + delete[] columns; + delete[] magic_string; + delete[] unit_style; + columns = nullptr; + magic_string = nullptr; + unit_style = nullptr; + } + + if (buf) delete[] buf; + return 0; +} diff --git a/code/validation/C++/0010727_wateringGrass.cpp b/code/validation/C++/0010727_wateringGrass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c7b3a84fb454fa7a4b132fac8f98464427a7be2 --- /dev/null +++ b/code/validation/C++/0010727_wateringGrass.cpp @@ -0,0 +1,89 @@ +#include +using namespace std; +#define infinity numeric_limits::max() +#define minusInf numeric_limits::min() + +struct interval{ + double l; + double r; +}; + +bool mySort(interval a, interval b) { + if(a.l < b.l) + return true; + else if(a.l > b.l) + return false; + else if(a.l == b.l) { + if(a.r > b.r) + return true; + return false; + } +} + +int main() { + int n,l,w; + while(cin>>n>>l>>w) { + int *r,*pos; + interval *v; + v = new interval[n]; + r = new int[n]; + pos = new int[n]; + for(int i=0;i>pos[i]>>r[i]; + if(double(r[i])>double(w)/2.00) { + double dx = sqrt( pow(r[i],2) - pow((double(w)/2.00),2) ); + v[i].l = pos[i] - dx; + v[i].r = pos[i] + dx; + } + else { + v[i].l = v[i].r = pos[i]; + } + } + sort(v,v+n,mySort); //sorted intervals + + int count = 0; + double curLeft,curRight=0,bestRight; + curLeft = numeric_limits::min(); + + for(int i=0;i curRight) { //next left is disjoint set + count = -1; + break; + } + else if(v[i].r < curRight) { //this one is 'covered' by the previous sprinkler + continue; + } + else { + int j; + for(j=i;j curRight) { + i = j-1; + curRight = bestRight; + break; + } + else { + bestRight = max(bestRight,v[j].r); + } + } + if(j==n) { + if(bestRight < l) { + count=-1; + break; + } + else { + curRight = bestRight; + count++; + break; + } + } + count++; + if(bestRight >= l) break; + } + } + cout< +#include + +#include +#include +#include +#include +#include +#include + +#ifndef GEOS_DEBUG +#define GEOS_DEBUG 0 +#endif + +using namespace std; +using namespace geos::geom; + +namespace geos { +namespace noding { // geos.noding + +/* private */ +void +IteratedNoder::node(vector *segStrings, + int *numInteriorIntersections) +{ + IntersectionAdder si(li); + MCIndexNoder noder; + noder.setSegmentIntersector(&si); + noder.computeNodes(segStrings); + nodedSegStrings = noder.getNodedSubstrings(); + *numInteriorIntersections = si.numInteriorIntersections; +//System.out.println("# intersection tests: " + si.numTests); +} + +/* public */ +void +IteratedNoder::computeNodes(SegmentString::NonConstVect* segStrings) + // throw(GEOSException); +{ + int numInteriorIntersections; + nodedSegStrings = segStrings; + int nodingIterationCount = 0; + int lastNodesCreated = -1; + vector *lastStrings = 0; + do { + + // NOTE: will change this.nodedSegStrings + node(nodedSegStrings, &numInteriorIntersections); + + // Delete noded strings from previous iteration + if ( lastStrings ) { + for ( unsigned int i = 0, n = lastStrings->size(); i < n; ++i ) + delete (*lastStrings)[i]; + delete lastStrings; + } + lastStrings = nodedSegStrings; + + nodingIterationCount++; + int nodesCreated = numInteriorIntersections; + + /** + * Fail if the number of nodes created is not declining. + * However, allow a few iterations at least before doing this + */ + //cerr<<"# nodes created: "< 0 + && nodesCreated >= lastNodesCreated + && nodingIterationCount > maxIter) + { + stringstream s; + s<<"Iterated noding failed to converge after "<< + nodingIterationCount << " iterations"; + throw util::TopologyException(s.str()); + } + lastNodesCreated = nodesCreated; + + } while (lastNodesCreated > 0); + //cerr<<"# nodings = "< + +#include +#include +#include +#include + +namespace gr { +namespace network { + +tcp_sink::sptr tcp_sink::make( + size_t itemsize, size_t veclen, const std::string& host, int port, int sinkmode) +{ + return gnuradio::make_block_sptr( + itemsize, veclen, host, port, sinkmode); +} + +/* + * The private constructor + */ +tcp_sink_impl::tcp_sink_impl( + size_t itemsize, size_t veclen, const std::string& host, int port, int sinkmode) + : gr::sync_block("tcp_sink", + gr::io_signature::make(1, 1, itemsize * veclen), + gr::io_signature::make(0, 0, 0)), + d_itemsize(itemsize), + d_veclen(veclen), + d_host(host), + d_port(port), + d_sinkmode(sinkmode), + d_thread_running(false), + d_stop_thread(false), + d_listener_thread(NULL), + d_start_new_listener(false), + d_initial_connection(true) +{ + d_block_size = d_itemsize * d_veclen; + + if (d_sinkmode == TCPSINKMODE_CLIENT) { + // In this mode, we're connecting to a remote TCP service listener + // as a client. + std::stringstream msg; + + msg << "[TCP Sink] connecting to " << host << " on port " << port; + GR_LOG_INFO(d_logger, msg.str()); + + boost::system::error_code err; + d_tcpsocket = new boost::asio::ip::tcp::socket(d_io_service); + + std::string s_port = (boost::format("%d") % port).str(); + boost::asio::ip::tcp::resolver resolver(d_io_service); + boost::asio::ip::tcp::resolver::query query( + d_host, s_port, boost::asio::ip::resolver_query_base::passive); + + d_endpoint = *resolver.resolve(query, err); + + if (err) { + throw std::runtime_error( + std::string("[TCP Sink] Unable to resolve host/IP: ") + err.message()); + } + + if (d_host.find(":") != std::string::npos) + d_is_ipv6 = true; + else { + // This block supports a check that a name rather than an IP is provided. + // the endpoint is then checked after the resolver is done. + if (d_endpoint.address().is_v6()) + d_is_ipv6 = true; + else + d_is_ipv6 = false; + } + + d_tcpsocket->connect(d_endpoint, err); + if (err) { + throw std::runtime_error(std::string("[TCP Sink] Connection error: ") + + err.message()); + } + + d_connected = true; + + boost::asio::socket_base::keep_alive option(true); + d_tcpsocket->set_option(option); + } else { + // In this mode, we're starting a local port listener and waiting + // for inbound connections. + d_start_new_listener = true; + d_listener_thread = new boost::thread([this] { run_listener(); }); + } +} + +void tcp_sink_impl::run_listener() +{ + d_thread_running = true; + + while (!d_stop_thread) { + // this will block + if (d_start_new_listener) { + d_start_new_listener = false; + connect(d_initial_connection); + d_initial_connection = false; + } else + std::this_thread::sleep_for(std::chrono::microseconds(10)); + } + + d_thread_running = false; +} + +void tcp_sink_impl::accept_handler(boost::asio::ip::tcp::socket* new_connection, + const boost::system::error_code& error) +{ + if (!error) { + GR_LOG_INFO(d_logger, "Client connection received."); + + // Accept succeeded. + d_tcpsocket = new_connection; + + boost::asio::socket_base::keep_alive option(true); + d_tcpsocket->set_option(option); + d_connected = true; + + } else { + std::stringstream msg; + msg << "Error code " << error << " accepting TCP session."; + GR_LOG_ERROR(d_logger, msg.str()); + + // Boost made a copy so we have to clean up + delete new_connection; + + // safety settings. + d_connected = false; + d_tcpsocket = NULL; + } +} + +void tcp_sink_impl::connect(bool initial_connection) +{ + std::stringstream msg; + msg << "Waiting for connection on port " << d_port; + GR_LOG_INFO(d_logger, msg.str()); + + if (initial_connection) { + if (d_is_ipv6) + d_acceptor = new boost::asio::ip::tcp::acceptor( + d_io_service, + boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), d_port)); + else + d_acceptor = new boost::asio::ip::tcp::acceptor( + d_io_service, + boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), d_port)); + } else { + d_io_service.reset(); + } + + if (d_tcpsocket) { + delete d_tcpsocket; + } + d_tcpsocket = NULL; + d_connected = false; + + boost::asio::ip::tcp::socket* tmpSocket = + new boost::asio::ip::tcp::socket(d_io_service); + d_acceptor->async_accept(*tmpSocket, + boost::bind(&tcp_sink_impl::accept_handler, + this, + tmpSocket, + boost::asio::placeholders::error)); + + d_io_service.run(); +} + +/* + * Our virtual destructor. + */ +tcp_sink_impl::~tcp_sink_impl() { stop(); } + +bool tcp_sink_impl::stop() +{ + if (d_thread_running) { + d_stop_thread = true; + } + + if (d_tcpsocket) { + d_tcpsocket->close(); + delete d_tcpsocket; + d_tcpsocket = NULL; + } + + d_io_service.reset(); + d_io_service.stop(); + + if (d_acceptor) { + delete d_acceptor; + d_acceptor = NULL; + } + + if (d_listener_thread) { + while (d_thread_running) + std::this_thread::sleep_for(std::chrono::microseconds(5)); + + delete d_listener_thread; + d_listener_thread = NULL; + } + + return true; +} + +int tcp_sink_impl::work(int noutput_items, + gr_vector_const_void_star& input_items, + gr_vector_void_star& output_items) +{ + gr::thread::scoped_lock guard(d_setlock); + + if (!d_connected) + return noutput_items; + + unsigned int noi = noutput_items * d_block_size; + int bytes_written; + int bytes_remaining = noi; + + ec.clear(); + + char* p_buff; + p_buff = (char*)input_items[0]; + + while ((bytes_remaining > 0) && (!ec)) { + bytes_written = boost::asio::write( + *d_tcpsocket, boost::asio::buffer((const void*)p_buff, bytes_remaining), ec); + bytes_remaining -= bytes_written; + p_buff += bytes_written; + + if (ec == boost::asio::error::connection_reset || + ec == boost::asio::error::broken_pipe) { + + // Connection was reset + d_connected = false; + bytes_remaining = 0; + + if (d_sinkmode == TCPSINKMODE_CLIENT) { + GR_LOG_WARN(d_logger, + "Server closed the connection. Stopping processing."); + + return WORK_DONE; + } else { + GR_LOG_INFO(d_logger, "Client disconnected. Waiting for new connection."); + + // start waiting for another connection + d_start_new_listener = true; + } + } + } + + return noutput_items; +} +} /* namespace network */ +} /* namespace gr */ diff --git a/code/validation/C++/0025556_Logger.cpp b/code/validation/C++/0025556_Logger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c307bc9feda901d7f1605cb921c69ebf600d47c3 --- /dev/null +++ b/code/validation/C++/0025556_Logger.cpp @@ -0,0 +1,228 @@ +/* + Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2012 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + } +*/ + +#include "Internal.hpp" +#include "Protocol.hpp" +#include "Convert.hpp" +#include "Device/Port/Port.hpp" +#include "Operation/Operation.hpp" +#include "OS/ByteOrder.hpp" + +#include + +static bool +ParseDate(BrokenDate &date, const char *p) +{ + char *endptr; + unsigned long l = strtoul(p, &endptr, 10); + if (l < 1 || l > 31 || *endptr != '.') + return false; + + date.day = l; + + p = endptr + 1; + l = strtoul(p, &endptr, 10); + if (l < 1 || l > 12 || *endptr != '.') + return false; + + date.month = l; + + p = endptr + 1; + l = strtoul(p, &endptr, 10); + if (l >= 100 || *endptr != 0) + return false; + + date.year = 2000 + l; // Y2100 problem + return true; +} + +static bool +ParseTime(BrokenTime &time, const char *p) +{ + char *endptr; + unsigned long l = strtoul(p, &endptr, 10); + if (l >= 24 || *endptr != ':') + return false; + + time.hour = l; + + p = endptr + 1; + l = strtoul(p, &endptr, 10); + if (l >= 60 || *endptr != ':') + return false; + + time.minute = l; + + p = endptr + 1; + l = strtoul(p, &endptr, 10); + if (l >= 60 || *endptr != 0) + return false; + + time.second = l; + return true; +} + +static bool +Copy(RecordedFlightInfo &dest, const LX::FlightInfo &src) +{ + if (!ParseDate(dest.date, src.date) || + !ParseTime(dest.start_time, src.start_time) || + !ParseTime(dest.end_time, src.stop_time)) + return false; + + dest.internal.lx.start_address[0] = src.start_address.address0; + dest.internal.lx.start_address[1] = src.start_address.address1; + dest.internal.lx.start_address[2] = src.start_address.address2; + dest.internal.lx.end_address[0] = src.end_address.address0; + dest.internal.lx.end_address[1] = src.end_address.address1; + dest.internal.lx.end_address[2] = src.end_address.address2; + + return true; +} + +static bool +ReadFlightListInner(Port &port, RecordedFlightList &flight_list, + OperationEnvironment &env) +{ + if (!LX::CommandMode(port, env)) + return false; + + port.Flush(); + if (!LX::SendCommand(port, LX::READ_FLIGHT_LIST)) + return false; + + bool success = false; + while (!flight_list.full()) { + LX::FlightInfo flight; + if (!LX::ReadCRC(port, &flight, sizeof(flight), env, 20000)) + break; + + success = true; + if (!flight.IsValid()) + break; + + RecordedFlightInfo dest; + if (Copy(dest, flight)) + flight_list.append(dest); + } + + return success; +} + +bool +LXDevice::ReadFlightList(RecordedFlightList &flight_list, + OperationEnvironment &env) +{ + if (!EnableCommandMode(env)) + return false; + + assert(!busy); + mutex.Lock(); + busy = true; + mutex.Unlock(); + + bool success = ReadFlightListInner(port, flight_list, env); + + LX::CommandModeQuick(port, env); + + mutex.Lock(); + busy = false; + mutex.Unlock(); + + return success; +} + +static bool +DownloadFlightInner(Port &port, const RecordedFlightInfo &flight, + FILE *file, OperationEnvironment &env) +{ + if (!LX::CommandMode(port, env)) + return false; + + LX::SeekMemory seek; + seek.start_address = flight.internal.lx.start_address; + seek.end_address = flight.internal.lx.end_address; + if (!LX::SendPacket(port, LX::SEEK_MEMORY, &seek, sizeof(seek), env) || + !LX::ExpectACK(port, env)) + return false; + + LX::MemorySection memory_section; + if (!LX::ReceivePacket(port, LX::READ_MEMORY_SECTION, + &memory_section, sizeof(memory_section), env)) + return false; + + unsigned lengths[LX::MemorySection::N]; + unsigned total_length = 0; + for (unsigned i = 0; i < LX::MemorySection::N; ++i) { + lengths[i] = FromBE16(memory_section.lengths[i]); + total_length += lengths[i]; + } + + env.SetProgressRange(total_length); + + uint8_t *data = new uint8_t[total_length], *p = data; + for (unsigned i = 0; i < LX::MemorySection::N && lengths[i] > 0; ++i) { + if (!LX::ReceivePacket(port, (LX::Command)(LX::READ_LOGGER_DATA + i), + p, lengths[i], env, 60000)) { + free(data); + return false; + } + + p += lengths[i]; + env.SetProgressPosition(p - data); + } + + bool success = LX::ConvertLXNToIGC(data, total_length, file); + free(data); + + return success; +} + +bool +LXDevice::DownloadFlight(const RecordedFlightInfo &flight, + const TCHAR *path, + OperationEnvironment &env) +{ + if (!EnableCommandMode(env)) + return false; + + FILE *file = _tfopen(path, _T("wb")); + if (file == NULL) + return false; + + assert(!busy); + mutex.Lock(); + busy = true; + mutex.Unlock(); + + bool success = DownloadFlightInner(port, flight, file, env); + fclose(file); + + LX::CommandModeQuick(port, env); + + mutex.Lock(); + busy = false; + mutex.Unlock(); + + return success; +} diff --git a/code/validation/C++/0025906_trajectory.cpp b/code/validation/C++/0025906_trajectory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc0518d7fa3034fd56b5e69546a37dafbe833dbe --- /dev/null +++ b/code/validation/C++/0025906_trajectory.cpp @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2008-2010 Lukáš Tvrdý + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include "trajectory.h" +#include + +#include + +Trajectory::Trajectory() +{ + m_i = 0; + m_size = 0; +} + +Trajectory::~Trajectory() +{ +} + + +void Trajectory::addPoint(QPointF pos) +{ + if (m_i >= m_path.size()) { + m_path.append(pos); + m_i++; + } else { + m_path[m_i] = pos; + m_i++; + } + + m_size++; +} + + +void Trajectory::reset() +{ + m_size = 0; + m_i = 0; +} + + +const QVector &Trajectory::getLinearTrajectory(const QPointF &start, const QPointF &end, double space) +{ + Q_UNUSED(space); + reset(); + + // Width and height of the line + float xd = (end.x() - start.x()); + float yd = (end.y() - start.y()); + + int x = (int)start.x(); + int y = (int)start.y(); + float fx = start.x(); + float fy = start.y(); + float m = yd / xd; + + int y2 = (int)end.y(); + int x2 = (int)end.x(); + + //m_path.append(start); + addPoint(start); + + if (fabs(m) > 1) { + // y - directional axis + int incr; + if (yd > 0) { + m = 1.0f / m; + incr = 1; + } else { + m = -1.0f / m; + incr = -1; + } + while (y != y2) { + fx = fx + m; + y = y + incr; + x = (int)(fx + 0.5f); + addPoint(QPointF(fx, y)); + } + } else { + // x - directional axis + int incr; + if (xd > 0) { + incr = 1; + } else { + incr = -1; + m = -m; + } + while (x != x2) { + fy = fy + m; + x = x + incr; + y = (int)(fy + 0.5f); + addPoint(QPointF(x, fy)); + } + } + + addPoint(end); + return m_path; +} + +QVector Trajectory::getDDATrajectory(QPointF start, QPointF end, double space) +{ + Q_UNUSED(space); + reset(); + // Width and height of the line + int xd = (int)(end.x() - start.x()); + int yd = (int)(end.y() - start.y()); + + int x = (int)start.x(); + int y = (int)start.y(); + float fx = start.x(); + float fy = start.y(); + float m = (float)yd / (float)xd; + int y2 = (int)end.y(); + int x2 = (int)end.x(); + + if (fabs(m) > 1) { + int incr; + if (yd > 0) { + m = 1.0f / m; + incr = 1; + } + else { + m = -1.0f / m; + incr = -1; + } + while (y != y2) { + fx = fx + m; + y = y + incr; + x = (int)(fx + 0.5f); + addPoint(QPointF(x, y)); + } + } else { + int incr; + if (xd > 0) { + incr = 1; + } + else { + incr = -1; + m = -m; + } + while (x != x2) { + fy = fy + m; + x = x + incr; + y = (int)(fy + 0.5f); + addPoint(QPointF(x, y)); + } + } + + return m_path; +} + + diff --git a/code/validation/C++/0028217_over.cpp b/code/validation/C++/0028217_over.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8871455fedbf50418611ec81e00e6db331a52634 --- /dev/null +++ b/code/validation/C++/0028217_over.cpp @@ -0,0 +1,189 @@ + +#include "over.hpp" +#include "gui.hpp" +#include "snake.hpp" +#include "button.hpp" +#include "music.hpp" +#include +#include + + GameOver::GameOver(Gui* g, SDL_Surface* s, Snake* snks[max_players]) +: m_gui(g), m_scr(s), m_txt(NULL), m_back(NULL) +{ + SnkRank rank[max_players]; + int win = computeWin(snks, rank); + for(int i = 0; i < max_players; ++i) + createScr(rank, i); + + std::ostringstream oss; + if(win >= 0) + oss << "Player " << win + 1 << " won !"; + else + oss << "Equality !"; + m_txt = TTF_RenderText_Blended(m_gui->getFont(), + oss.str().c_str(), + m_gui->getPlayerColor(win)); + + m_back = new Button("End", m_gui); + SDL_Rect pos; + pos.x = m_scr->w / 8 * 7; + pos.y = m_scr->h / 8 * 7; + m_back->setPos(pos); +} + +GameOver::~GameOver() +{ + for(int i = 0; i < max_players; ++i) + { + if(m_scores[i] != NULL) + SDL_FreeSurface(m_scores[i]); + } + + if(m_txt != NULL) + SDL_FreeSurface(m_txt); + + if(m_back != NULL) + delete m_back; +} + +bool GameOver::run() +{ + SDL_Color bgc = m_gui->bgColor(); + Uint32 bg = SDL_MapRGB(m_scr->format, bgc.r, bgc.g, bgc.b); + + bool continuer = true; + SDL_Rect pos; + SDL_Event ev; + + while(continuer) + { + // Affichage + SDL_FillRect(m_scr, NULL, SDL_MapRGB(m_scr->format, 0, 0, 0)); + SDL_BlitSurface(m_gui->background(), NULL, m_scr, NULL); + + pos.x = m_scr->w / 2 - m_txt->w / 2; + pos.y = m_scr->h / 4 - m_txt->h / 2; + { + SDL_Rect tmp = pos; + tmp.x -= 10; + tmp.y -= 10; + tmp.w = m_txt->w + 20; + tmp.h = m_txt->h + 20; + SDL_FillRect(m_scr, &tmp, bg); + } + SDL_BlitSurface(m_txt, NULL, m_scr, &pos); + + pos.x = 300; pos.w = 200; + pos.y = 300; pos.h = 140; + SDL_FillRect(m_scr, &pos, bg); + + int y = pos.y + 5; + for(int i = 0; i < max_players; ++i) + { + pos.x = m_scr->w / 2 - m_scores[i]->w / 2; + y += 25; + pos.y = y - m_scores[i]->h / 2; + SDL_BlitSurface(m_scores[i], NULL, m_scr, &pos); + } + m_back->blitOn(m_scr); + SDL_Flip(m_scr); + + // Évènements + while(SDL_PollEvent(&ev)) + { + switch(ev.type) + { + case SDL_QUIT: + return false; + case SDL_KEYDOWN: + if(ev.key.keysym.sym == SDLK_BACKSPACE + || ev.key.keysym.sym == SDLK_ESCAPE) + continuer = false; + else if(ev.key.keysym.sym == SDLK_RETURN) { + music->playSound(Music::OK); + continuer = false; + } + break; + case SDL_MOUSEMOTION: + pos.x = ev.motion.x; + pos.y = ev.motion.y; + m_back->mouse(pos); + break; + case SDL_MOUSEBUTTONDOWN: + pos.x = ev.button.x; + pos.y = ev.button.y; + if(m_back->clicked(pos)) + { + music->playSound(Music::OK); + continuer = false; + } + break; + default: + break; + } + } + } + + return true; +} + +void GameOver::createScr(SnkRank snks[max_players], int idx) +{ + std::ostringstream oss; + if(snks[idx].snk != NULL) + oss << idx + 1 << ". Player " << snks[idx].idx + 1 << " : " << snks[idx].snk->getScore(true); + else + oss << "No player"; + + m_scores[idx] = TTF_RenderText_Blended(m_gui->getFont(), + oss.str().c_str(), + m_gui->getPlayerColor(snks[idx].idx)); +} + +int GameOver::computeWin(Snake* snks[max_players], SnkRank rank[max_players]) const +{ + int w = 0; + unsigned int max = 0; + for(int i = 0; i < max_players; ++i) + { + rank[i].scr = 0; + rank[i].idx = -1; + rank[i].snk = NULL; + } + + for(int i = 0; i < max_players; ++i) + { + if(snks[i] == NULL) + continue; + + // Rank + unsigned int scr = snks[i]->getScore(true); + + int j; + for(j = max_players - 1; j > 0 && rank[j - 1].scr <= scr; --j) + { + rank[j].scr = rank[j - 1].scr; + rank[j].idx = rank[j - 1].idx; + } + rank[j].scr = snks[i]->getScore(true); + rank[j].idx = i; + + // Winner + if(scr > max) + { + max = scr; + w = i; + } + else if(scr == max) + w = -1; + } + + for(int i = 0; i < max_players; ++i) + { + if(rank[i].idx >= 0) + rank[i].snk = snks[rank[i].idx]; + } + + return w; +} + diff --git a/code/validation/C++/0030591_Snake.cpp b/code/validation/C++/0030591_Snake.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b42162e9e4c0af22c586fda81e27314c97318c2 --- /dev/null +++ b/code/validation/C++/0030591_Snake.cpp @@ -0,0 +1,89 @@ +/* +Created for Milestone 2 + +Group 12 + +Jonathan Mayer 66268081 +Brian Lam 62101239 +Yu Koizumi 000975171 +Tommy Wong 71659011 +*/ + +#include "Snake.hpp" + +Snake::Snake(Coord starting_pos, Board* board) +{ + Node* n = new Node{nullptr, starting_pos}; + head = n; + tail = n; + length = 1; + direction = RIGHT; + this->board = board; +} + +Snake::~Snake() +{ + Node* current = tail; + Node* del = current; + while(current != nullptr) + { + del = current; + current = current->next; + delete del; + } +} + +void Snake::update() +{ + head->next = new Node{nullptr, head->value + direction}; + head = head->next; + int x = head->value.x; + int y = head->value.y; + if(x >= 0 &&y >= 0 && x < board->getLength() && y < board->getWidth()) + { + if(board->getItem(x, y) == food) // Check for food + { + length++; + board->setItem(x, y, empty); + board->addItem(food); + return; + } + } + Node* temp = tail; + tail = tail->next; + oldTail = temp->value; + delete temp; +} + +void Snake::changeDirection(Coord direction) +{ + if(direction != -this->direction || length == 1) + this->direction = direction; +} + +Coord Snake::getHead() +{ + return head->value; +} + +Coord Snake::getOldTail() +{ + return oldTail; +} + +int Snake::getLength() +{ + return length; +} + +std::vector Snake::getSnakePosition() +{ + std::vector snakeCoords{}; + Node* current = tail; + while(current != nullptr) + { + snakeCoords.push_back(current->value); + current = current->next; + } + return snakeCoords; +} \ No newline at end of file diff --git a/code/validation/C++/0031360_priority_queue.cpp b/code/validation/C++/0031360_priority_queue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e9c88a354dc66ab2f4520661785fe0432c04e58 --- /dev/null +++ b/code/validation/C++/0031360_priority_queue.cpp @@ -0,0 +1,65 @@ +// +// Created by 孙启龙 on 2017/4/17. +// + +#include +#include +#include +#include +#define maxn 100010 + +using namespace std; + +struct node{ + long long pos; + long long len; + bool friend operator < (const node&a, const node&b) + { + if(a.pos != b.pos) + return a.pos > b.pos; + else + return a.len > b.len; + } +}stone[maxn], now; +priority_queueque; +int n, T; + +int main (void) +{ + while(scanf("%d", &T) != EOF) + { + while(T--) + { + bool odd = true; + long long ans = 0; + while(!que.empty()) + que.pop(); + scanf("%d", &n); + for(int i = 1; i <= n; i++) + { + scanf("%lld %lld", &stone[i].pos, &stone[i].len); + que.push(stone[i]); + } + + while(!que.empty()) + { + if(odd) + { + now = que.top(); + que.pop(); + now.pos += now.len; + ans = max(ans, now.pos); + que.push(now); + odd = !odd; + } else{ + odd = !odd; + now = que.top(); + ans = max(ans, now.pos); + que.pop(); + } + } + printf("%lld\n", ans); + } + } + return 0; +} \ No newline at end of file diff --git a/code/validation/C++/0031853_PathFinder.cc b/code/validation/C++/0031853_PathFinder.cc new file mode 100644 index 0000000000000000000000000000000000000000..678157da68c0c325bdb460f258283ddb6908ddeb --- /dev/null +++ b/code/validation/C++/0031853_PathFinder.cc @@ -0,0 +1,170 @@ +/* + * PathFinder.cc + * + * Created on: May 30, 2011 + * Author: truonghuy + */ + +#include +#include +#include +//#include + +PathFinder::PathFinder() { + // TODO Auto-generated constructor stub + +} + +/** + * + * @param[in] freeSpace the 2 dimensional array of freeSpace. -1 = obstacle, >=0 free. + * */ +int PathFinder::aStar(int startX, int startY, int endX, int endY, + std::vector >& freeSpace) +{ + int i,j; // counter + std::vector::iterator it; + + std::vector openedList; + std::vector closedList; + + Node *startNode, *endNode, *currNode; + + startNode = new Node(); + endNode = new Node(); + + endNode->x = endX; + endNode->y = endY; + + startNode->x = startX; + startNode->y = startY; + startNode->_g = 0; + startNode->_h = manhattanDist(startNode, endNode); + + openedList.push_back(startNode); + + bool pathFound = false; + + while(!openedList.empty()){ + std::vector::iterator minIndex; + int currCost; + int minCost = INT_MAX; + + for (it=openedList.begin(); it < openedList.end(); ++it){ + + currCost = (*it)->_g + (*it)->_h; + + if (minCost > currCost){ + minCost = currCost; + minIndex = it; + } + } + + // moves the node with min cost from openedList to closedList + currNode = *minIndex; + closedList.push_back(currNode); + openedList.erase(minIndex); + + // if finished + if (sameNodes(endNode, currNode)){ + endNode->parent = currNode->parent; + + pathFound = true; + break; + } + + // checks the neighbourhood + int neighborX, neighborY; + Node* node2check; + for(i=-1; i<2; i++){ + for(j=-1; j<2; j++){ + // only four movement directions + if (fabs(i)+fabs(j) != 1) continue; + + neighborX = currNode->x + i; + neighborY = currNode->y + j; + + if (neighborX < 0 || neighborY < 0 || neighborX >= freeSpace.size() || neighborY >= freeSpace[0].size()) + continue; + + // obstacle + if (freeSpace[neighborX][neighborY] < 0) continue; + + node2check = new Node(); + node2check->x = neighborX; + node2check->y = neighborY; + + // if already checked + if (containsNode(openedList, node2check) || containsNode(closedList, node2check)){ + delete node2check; + continue; + } + + // calculates cost + node2check->_g = currNode->_g + manhattanDist(node2check, currNode); + node2check->_h = manhattanDist(node2check, endNode); + + // keep track of path + node2check->parent = currNode; + + openedList.push_back(node2check); + + } + } + } + + if (pathFound){ + // go back from endNode + Node *nextNodeFromStart; + nextNodeFromStart = endNode; + int action; + while (!sameNodes(nextNodeFromStart->parent, startNode)){ + getAction(startNode, nextNodeFromStart); + nextNodeFromStart = nextNodeFromStart->parent; + } + + return getAction(startNode, nextNodeFromStart); + } + else return -1; +}; + +int PathFinder::getAction(Node* startNode, Node* nextNodeFromStart){ + if (startNode->x > nextNodeFromStart->x){ + //std::cout << "~left~" << std::endl; + return 3; + } + if (startNode->x < nextNodeFromStart->x){ + //std::cout << "~right~" << std::endl; + return 1; + } + if (startNode->y > nextNodeFromStart->y){ + //std::cout << "~down~" << std::endl; + return 2; + } + if (startNode->y < nextNodeFromStart->y){ + //std::cout << "~up~" << std::endl; + return 4; + } +}; + + +int PathFinder::manhattanDist(Node* startNode, Node* endNode){ + return fabs(startNode->x - endNode->x) + fabs(startNode->y - endNode->y); +}; + +bool PathFinder::sameNodes(Node* node1, Node* node2){ + return ((node1->x == node2->x) && (node1->y == node2->y)); +}; + +bool PathFinder::containsNode(std::vector& nodeArray, Node* node){ + + for (unsigned i=0; i + +using namespace std; + +class Solution { +public: + int lengthOfLongestSubstring(string s) { + int left = 0; + int right = 0; + int maxLength = 0; + int length = 0; + int check[255] = { 0, }; + for (; right < s.length(); right++) { + if (check[s[right]] == 1) { + for (; s[left] != s[right]; left++) { + check[s[left]] = 0; + length--; + } + left++; + } else { + check[s[right]] = 1; + length++; + if (length > maxLength) { + maxLength = length; + } + } + } + + return maxLength; + } +}; + +int main() { + + Solution sol; + + cout << sol.lengthOfLongestSubstring("12342543921"); + + return 0; +} diff --git a/code/validation/C++/0035357_LiveIntervalUnion.cpp b/code/validation/C++/0035357_LiveIntervalUnion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ccb8df4bc0557335813bebf66c9af3edd321e37 --- /dev/null +++ b/code/validation/C++/0035357_LiveIntervalUnion.cpp @@ -0,0 +1,212 @@ +//===- LiveIntervalUnion.cpp - Live interval union data structure ---------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// LiveIntervalUnion represents a coalesced set of live intervals. This may be +// used during coalescing to represent a congruence class, or during register +// allocation to model liveness of a physical register. +// +//===----------------------------------------------------------------------===// + +#include "llvm/CodeGen/LiveIntervalUnion.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SparseBitVector.h" +#include "llvm/CodeGen/LiveInterval.h" +#include "llvm/CodeGen/TargetRegisterInfo.h" +#include "llvm/Support/raw_ostream.h" +#include +#include + +using namespace llvm; + +#define DEBUG_TYPE "regalloc" + +// Merge a LiveInterval's segments. Guarantee no overlaps. +void LiveIntervalUnion::unify(LiveInterval &VirtReg, const LiveRange &Range) { + if (Range.empty()) + return; + ++Tag; + + // Insert each of the virtual register's live segments into the map. + LiveRange::const_iterator RegPos = Range.begin(); + LiveRange::const_iterator RegEnd = Range.end(); + SegmentIter SegPos = Segments.find(RegPos->start); + + while (SegPos.valid()) { + SegPos.insert(RegPos->start, RegPos->end, &VirtReg); + if (++RegPos == RegEnd) + return; + SegPos.advanceTo(RegPos->start); + } + + // We have reached the end of Segments, so it is no longer necessary to search + // for the insertion position. + // It is faster to insert the end first. + --RegEnd; + SegPos.insert(RegEnd->start, RegEnd->end, &VirtReg); + for (; RegPos != RegEnd; ++RegPos, ++SegPos) + SegPos.insert(RegPos->start, RegPos->end, &VirtReg); +} + +// Remove a live virtual register's segments from this union. +void LiveIntervalUnion::extract(LiveInterval &VirtReg, const LiveRange &Range) { + if (Range.empty()) + return; + ++Tag; + + // Remove each of the virtual register's live segments from the map. + LiveRange::const_iterator RegPos = Range.begin(); + LiveRange::const_iterator RegEnd = Range.end(); + SegmentIter SegPos = Segments.find(RegPos->start); + + while (true) { + assert(SegPos.value() == &VirtReg && "Inconsistent LiveInterval"); + SegPos.erase(); + if (!SegPos.valid()) + return; + + // Skip all segments that may have been coalesced. + RegPos = Range.advanceTo(RegPos, SegPos.start()); + if (RegPos == RegEnd) + return; + + SegPos.advanceTo(RegPos->start); + } +} + +void +LiveIntervalUnion::print(raw_ostream &OS, const TargetRegisterInfo *TRI) const { + if (empty()) { + OS << " empty\n"; + return; + } + for (LiveSegments::const_iterator SI = Segments.begin(); SI.valid(); ++SI) { + OS << " [" << SI.start() << ' ' << SI.stop() + << "):" << printReg(SI.value()->reg(), TRI); + } + OS << '\n'; +} + +#ifndef NDEBUG +// Verify the live intervals in this union and add them to the visited set. +void LiveIntervalUnion::verify(LiveVirtRegBitSet& VisitedVRegs) { + for (SegmentIter SI = Segments.begin(); SI.valid(); ++SI) + VisitedVRegs.set(SI.value()->reg()); +} +#endif //!NDEBUG + +LiveInterval *LiveIntervalUnion::getOneVReg() const { + if (empty()) + return nullptr; + for (LiveSegments::const_iterator SI = Segments.begin(); SI.valid(); ++SI) { + // return the first valid live interval + return SI.value(); + } + return nullptr; +} + +// Scan the vector of interfering virtual registers in this union. Assume it's +// quite small. +bool LiveIntervalUnion::Query::isSeenInterference(LiveInterval *VirtReg) const { + return is_contained(InterferingVRegs, VirtReg); +} + +// Collect virtual registers in this union that interfere with this +// query's live virtual register. +// +// The query state is one of: +// +// 1. CheckedFirstInterference == false: Iterators are uninitialized. +// 2. SeenAllInterferences == true: InterferingVRegs complete, iterators unused. +// 3. Iterators left at the last seen intersection. +// +unsigned LiveIntervalUnion::Query:: +collectInterferingVRegs(unsigned MaxInterferingRegs) { + // Fast path return if we already have the desired information. + if (SeenAllInterferences || InterferingVRegs.size() >= MaxInterferingRegs) + return InterferingVRegs.size(); + + // Set up iterators on the first call. + if (!CheckedFirstInterference) { + CheckedFirstInterference = true; + + // Quickly skip interference check for empty sets. + if (LR->empty() || LiveUnion->empty()) { + SeenAllInterferences = true; + return 0; + } + + // In most cases, the union will start before LR. + LRI = LR->begin(); + LiveUnionI.setMap(LiveUnion->getMap()); + LiveUnionI.find(LRI->start); + } + + LiveRange::const_iterator LREnd = LR->end(); + LiveInterval *RecentReg = nullptr; + while (LiveUnionI.valid()) { + assert(LRI != LREnd && "Reached end of LR"); + + // Check for overlapping interference. + while (LRI->start < LiveUnionI.stop() && LRI->end > LiveUnionI.start()) { + // This is an overlap, record the interfering register. + LiveInterval *VReg = LiveUnionI.value(); + if (VReg != RecentReg && !isSeenInterference(VReg)) { + RecentReg = VReg; + InterferingVRegs.push_back(VReg); + if (InterferingVRegs.size() >= MaxInterferingRegs) + return InterferingVRegs.size(); + } + // This LiveUnion segment is no longer interesting. + if (!(++LiveUnionI).valid()) { + SeenAllInterferences = true; + return InterferingVRegs.size(); + } + } + + // The iterators are now not overlapping, LiveUnionI has been advanced + // beyond LRI. + assert(LRI->end <= LiveUnionI.start() && "Expected non-overlap"); + + // Advance the iterator that ends first. + LRI = LR->advanceTo(LRI, LiveUnionI.start()); + if (LRI == LREnd) + break; + + // Detect overlap, handle above. + if (LRI->start < LiveUnionI.stop()) + continue; + + // Still not overlapping. Catch up LiveUnionI. + LiveUnionI.advanceTo(LRI->start); + } + SeenAllInterferences = true; + return InterferingVRegs.size(); +} + +void LiveIntervalUnion::Array::init(LiveIntervalUnion::Allocator &Alloc, + unsigned NSize) { + // Reuse existing allocation. + if (NSize == Size) + return; + clear(); + Size = NSize; + LIUs = static_cast( + safe_malloc(sizeof(LiveIntervalUnion)*NSize)); + for (unsigned i = 0; i != Size; ++i) + new(LIUs + i) LiveIntervalUnion(Alloc); +} + +void LiveIntervalUnion::Array::clear() { + if (!LIUs) + return; + for (unsigned i = 0; i != Size; ++i) + LIUs[i].~LiveIntervalUnion(); + free(LIUs); + Size = 0; + LIUs = nullptr; +} diff --git a/code/validation/C++/0035999_determine-print-stats.cc b/code/validation/C++/0035999_determine-print-stats.cc new file mode 100644 index 0000000000000000000000000000000000000000..13629b454a037cd0690dac10b9da78fb0764384f --- /dev/null +++ b/code/validation/C++/0035999_determine-print-stats.cc @@ -0,0 +1,154 @@ +/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*- + * (c) 2013, 2014 Henner Zeller + * + * This file is part of BeagleG. http://github.com/hzeller/beagleg + * + * BeagleG is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * BeagleG is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with BeagleG. If not, see . + */ +#include "determine-print-stats.h" + +#include +#include +#include +#include +#include + +#include "gcode-machine-control.h" +#include "gcode-parser/gcode-parser.h" +#include "hardware-mapping.h" +#include "segment-queue.h" +#include "spindle-control.h" + +namespace { +// An event receiver for GCodeParser events that are intercepted, stats +// recorded, then further delegated to an original GCodeParser::Events +// receiver +class StatsCollectingEventDelegator : public GCodeParser::EventReceiver { + public: + StatsCollectingEventDelegator(BeagleGPrintStats *stats, + GCodeParser::EventReceiver *delegatee) + : stats_(stats), delegatee_(delegatee) {} + + // GCodeParser::EventReceiver callbacks + void gcode_start(GCodeParser *p) final { delegatee_->gcode_start(p); } + void gcode_finished(bool eos) final { delegatee_->gcode_finished(eos); } + + // GCode parser event receivers, that forward calls to the delegate + // but also determine relevant height information. + void set_speed_factor(float f) final { delegatee_->set_speed_factor(f); } + void set_temperature(float f) final { delegatee_->set_temperature(f); } + void set_fanspeed(float speed) final { delegatee_->set_fanspeed(speed); } + void wait_temperature() final { delegatee_->wait_temperature(); } + void motors_enable(bool b) final { delegatee_->motors_enable(b); } + void go_home(AxisBitmap_t axes) final { /* ignore */ + } + void inform_origin_offset(const AxesRegister &axes, const char *n) final { + delegatee_->inform_origin_offset(axes, n); + } + + void dwell(float value) final { + stats_->total_time_seconds += value / 1000.0f; + // We call the original dell() with zero time as we don't want to spend + // _real_ time. + delegatee_->dwell(0); + } + + bool rapid_move(float feed, const AxesRegister &axes) final { + update_coordinate_stats(axes); + return delegatee_->rapid_move(feed, axes); + } + bool coordinated_move(float feed, const AxesRegister &axes) final { + update_coordinate_stats(axes); + return delegatee_->coordinated_move(feed, axes); + } + + const char *unprocessed(char letter, float value, const char *remain) final { + return delegatee_->unprocessed(letter, value, remain); + } + + private: + static inline void set_min_max(float value, float *min, float *max) { + if (value < *min) *min = value; + if (value > *max) *max = value; + } + void update_coordinate_stats(const AxesRegister &axis) { + set_min_max(axis[AXIS_X], &stats_->x_min, &stats_->x_max); + set_min_max(axis[AXIS_Y], &stats_->y_min, &stats_->y_max); + set_min_max(axis[AXIS_Z], &stats_->z_min, &stats_->z_max); + if (axis[AXIS_E] > stats_->filament_len) { + stats_->last_z_extruding = axis[AXIS_Z]; + } + stats_->filament_len = axis[AXIS_E]; + } + + struct BeagleGPrintStats *const stats_; + GCodeParser::EventReceiver *const delegatee_; +}; + +class StatsSegmentQueue : public SegmentQueue { + public: + explicit StatsSegmentQueue(BeagleGPrintStats *stats) : print_stats_(stats) {} + + bool Enqueue(const LinearSegmentSteps ¶m) final { + int max_steps = 0; + for (int i = 0; i < BEAGLEG_NUM_MOTORS; ++i) { + int steps = abs(param.steps[i]); + if (steps > max_steps) max_steps = steps; + } + + // max_steps = a/2*t^2 + v0*t; a = (v1-v0)/t + print_stats_->total_time_seconds += 2 * max_steps / (param.v0 + param.v1); + // printf("HZ:v0=%7.1f v1=%7.1f steps=%d\n", param.v0, param.v1, max_steps); + return true; + } + + void MotorEnable(bool on) final {} + void WaitQueueEmpty() final {} + bool GetPhysicalStatus(PhysicalStatus *status) final { return false; } + void SetExternalPosition(int axis, int pos) final {} + + private: + BeagleGPrintStats *const print_stats_; +}; +} // namespace + +bool determine_print_stats(int input_fd, const MachineControlConfig &config, + FILE *msg_out, struct BeagleGPrintStats *result) { + memset(result, 0x00, sizeof(*result)); + result->x_min = 1e7; + result->y_min = 1e7; + result->y_min = 1e7; + HardwareMapping hardware; // We never initialize, just sim mode. + + // Motor control that just determines the time spent turning the motor. + // We do that by intercepting the motor operations by replacing the + // implementation with our own. + StatsSegmentQueue stats_motor_ops(result); + GCodeMachineControl *machine_control = GCodeMachineControl::Create( + config, &stats_motor_ops, &hardware, nullptr, nullptr); + if (!machine_control) return false; + + // We intercept gcode events to update some stats, then pass on to + // machine event receiver. + StatsCollectingEventDelegator stats_event_receiver( + result, machine_control->ParseEventReceiver()); + GCodeParser::Config parser_cfg; + GCodeParser::Config::ParamMap parameters; + parser_cfg.parameters = ¶meters; + GCodeParser parser(parser_cfg, &stats_event_receiver); + const bool success = parser.ReadFile(fdopen(input_fd, "r"), msg_out) && + parser.error_count() == 0; + delete machine_control; + return success; +} diff --git a/code/validation/C++/0037162_select_thread.cpp b/code/validation/C++/0037162_select_thread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f96b0514ca4ce03a2dfe712c0b8795db716a311c --- /dev/null +++ b/code/validation/C++/0037162_select_thread.cpp @@ -0,0 +1,204 @@ +/* + Copyright (c) 2007-2009 FastMQ Inc. + + This file is part of 0MQ. + + 0MQ is free software; you can redistribute it and/or modify it under + the terms of the Lesser GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + 0MQ is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + Lesser GNU General Public License for more details. + + You should have received a copy of the Lesser GNU General Public License + along with this program. If not, see . +*/ + +#include + +#include + +#ifdef ZMQ_HAVE_WINDOWS +#include "winsock2.h" +#elif defined ZMQ_HAVE_HPUX +#include +#include +#include +#elif defined ZMQ_HAVE_OPENVMS +#include +#include +#else +#include +#endif + +#include +#include +#include + +zmq::select_t::select_t () : + maxfd (retired_fd), + retired (false) +{ + // Clear file descriptor sets. + FD_ZERO (&source_set_in); + FD_ZERO (&source_set_out); + FD_ZERO (&source_set_err); +} + +zmq::handle_t zmq::select_t::add_fd (fd_t fd_, i_pollable *engine_) +{ + // Store the file descriptor. + fd_entry_t entry = {fd_, engine_}; + fds.push_back (entry); + + // Start polling on errors. + FD_SET (fd_, &source_set_err); + + // Adjust maxfd if necessary. + if (fd_ > maxfd) + maxfd = fd_; + + handle_t handle; + handle.fd = fd_; + return handle; +} + +void zmq::select_t::rm_fd (handle_t handle_) +{ + // Get file descriptor. + fd_t fd = handle_.fd; + + // Stop polling on the descriptor. + FD_CLR (fd, &source_set_in); + FD_CLR (fd, &source_set_out); + FD_CLR (fd, &source_set_err); + + // Discard all events generated on this file descriptor. + FD_CLR (fd, &readfds); + FD_CLR (fd, &writefds); + FD_CLR (fd, &exceptfds); + + // Adjust the maxfd attribute if we have removed the + // highest-numbered file descriptor. + if (fd == maxfd) { + maxfd = 0; + for (fd_set_t::iterator it = fds.begin (); it != fds.end (); it ++) + if (it->fd > maxfd) + maxfd = it->fd; + } + + // Mark the descriptor as retired. + fd_set_t::iterator it; + for (it = fds.begin (); it != fds.end (); it ++) + if (it->fd == fd) + break; + assert (it != fds.end ()); + it->fd = retired_fd; + retired = true; +} + +void zmq::select_t::set_pollin (handle_t handle_) +{ + FD_SET (handle_.fd, &source_set_in); +} + +void zmq::select_t::reset_pollin (handle_t handle_) +{ + FD_CLR (handle_.fd, &source_set_in); +} + +void zmq::select_t::set_pollout (handle_t handle_) +{ + FD_SET (handle_.fd, &source_set_out); +} + +void zmq::select_t::reset_pollout (handle_t handle_) +{ + FD_CLR (handle_.fd, &source_set_out); +} + +bool zmq::select_t::process_events (poller_t *poller_, bool timers_) +{ + // Intialise the pollsets. + memcpy (&readfds, &source_set_in, sizeof source_set_in); + memcpy (&writefds, &source_set_out, sizeof source_set_out); + memcpy (&exceptfds, &source_set_err, sizeof source_set_err); + + // Wait for events. + while (true) { + + // Compute the timout interval. Select is free to overwrite the + // value so have to compute it each time anew. + timeval timeout = {max_timer_period / 1000, + (max_timer_period % 1000) * 1000}; + + // Wait for events. + int rc; + while (true) { + rc = select (maxfd + 1, &readfds, &writefds, &exceptfds, + timers_ ? &timeout : NULL); + +#ifdef ZMQ_HAVE_WINDOWS + wsa_assert (rc != SOCKET_ERROR); + break; +#else + if (!(rc == -1 && errno == EINTR)) { + errno_assert (rc != -1); + break; + } +#endif + } + + // Handle timer. + if (timers_ && !rc) { + poller_->timer_event (); + return false; + } + + // TODO: Select sometimes returns 0 even though no event have occured + // and no timeout was set. Document this situation in detail... + if (rc > 0) + break; + } + + // handle to be used as a parameter in in/out_event in process_event call. + handle_t handle; + + for (fd_set_t::size_type i = 0; i < fds.size (); i ++) { + if (fds [i].fd == retired_fd) + continue; + + // Store actual fd into handle union. + handle.fd = fds [i].fd; + + if (FD_ISSET (fds [i].fd, &writefds)) + if (poller_->process_event (handle, fds [i].engine, event_out)) + return true; + if (fds [i].fd == retired_fd) + continue; + if (FD_ISSET (fds [i].fd, &readfds)) + if (poller_->process_event (handle, fds [i].engine, event_in)) + return true; + if (fds [i].fd == retired_fd) + continue; + if (FD_ISSET (fds [i].fd, &exceptfds)) + if (poller_->process_event (handle, fds [i].engine, event_err)) + return true; + } + + // Destroy retired event sources. + if (retired) { + for (fd_set_t::size_type i = 0; i < fds.size (); i ++) { + if (fds [i].fd == retired_fd) { + fds.erase (fds.begin () + i); + i --; + } + } + retired = false; + } + + return false; +} diff --git a/code/validation/C++/0037534_agc021_b.cpp b/code/validation/C++/0037534_agc021_b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2be032830de8ca03b64c53df77d3262ef7fcd7d8 --- /dev/null +++ b/code/validation/C++/0037534_agc021_b.cpp @@ -0,0 +1,53 @@ +#include + +using namespace std; +typedef long long int ll; +typedef pair P; +typedef pair Pll; +typedef vector Vi; +//typedef tuple T; +#define FOR(i,s,x) for(int i=s;i<(int)(x);i++) +#define REP(i,x) FOR(i,0,x) +#define ALL(c) c.begin(), c.end() +#define DUMP( x ) cerr << #x << " = " << ( x ) << endl +#define UNIQUE(c) sort(ALL(c)), c.erase(unique(ALL(c)), c.end()) + +const int dr[4] = {-1, 0, 1, 0}; +const int dc[4] = {0, 1, 0, -1}; + +int main() { + // use scanf in CodeForces! + cin.tie(0); + ios_base::sync_with_stdio(false); + + int N; cin >> N; + vector> points; + REP(i, N) { + int x, y; cin >> x >> y; + points.emplace_back(x, y); + } + + vector count(N, 0); + const int n_trial = 1e6; + const double PI = acos(-1); + const double delta = 2 * PI / n_trial; + for (double i = 0; i < 2 * PI; i += delta) { + double x = 1e12 * cos(i), y = 1e12 * sin(i); + //cout << x << ' ' << y << endl; + int idx = 0; + double dist = 1e13; + REP(i, N) { + double a, b; tie(a, b) = points[i]; + double cand = hypot(x - a, y - b); + if (cand < dist) { + dist = cand; + idx = i; + } + } + count[idx]++; + } + //REP(i, N) cout << count[i] << (i == N - 1 ? '\n' : ' '); + cout << setprecision(20); + for (int c : count) cout << 1.0 * c / n_trial << endl; + return 0; +} diff --git a/code/validation/C++/0037607_intro.cpp b/code/validation/C++/0037607_intro.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b684a7e4f211d1dd5da98af1f324a08acae3d7e9 --- /dev/null +++ b/code/validation/C++/0037607_intro.cpp @@ -0,0 +1,292 @@ +// Copyright (c) 2011-2014 The Bitcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "intro.h" +#include "ui_intro.h" + +#include "guiutil.h" + +#include "util.h" + +#include + +#include +#include +#include + +/* Minimum free space (in bytes) needed for data directory */ +static const uint64_t GB_BYTES = 1000000000LL; +static const uint64_t BLOCK_CHAIN_SIZE = 20LL * GB_BYTES; + +/* Check free space asynchronously to prevent hanging the UI thread. + + Up to one request to check a path is in flight to this thread; when the check() + function runs, the current path is requested from the associated Intro object. + The reply is sent back through a signal. + + This ensures that no queue of checking requests is built up while the user is + still entering the path, and that always the most recently entered path is checked as + soon as the thread becomes available. +*/ +class FreespaceChecker : public QObject +{ + Q_OBJECT + +public: + FreespaceChecker(Intro *intro); + + enum Status { + ST_OK, + ST_ERROR + }; + +public slots: + void check(); + +signals: + void reply(int status, const QString &message, quint64 available); + +private: + Intro *intro; +}; + +#include "intro.moc" + +FreespaceChecker::FreespaceChecker(Intro *intro) +{ + this->intro = intro; +} + +void FreespaceChecker::check() +{ + namespace fs = boost::filesystem; + QString dataDirStr = intro->getPathToCheck(); + fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); + uint64_t freeBytesAvailable = 0; + int replyStatus = ST_OK; + QString replyMessage = tr("A new data directory will be created."); + + /* Find first parent that exists, so that fs::space does not fail */ + fs::path parentDir = dataDir; + fs::path parentDirOld = fs::path(); + while(parentDir.has_parent_path() && !fs::exists(parentDir)) + { + parentDir = parentDir.parent_path(); + + /* Check if we make any progress, break if not to prevent an infinite loop here */ + if (parentDirOld == parentDir) + break; + + parentDirOld = parentDir; + } + + try { + freeBytesAvailable = fs::space(parentDir).available; + if(fs::exists(dataDir)) + { + if(fs::is_directory(dataDir)) + { + QString separator = "" + QDir::toNativeSeparators("/") + tr("name") + ""; + replyStatus = ST_OK; + replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); + } else { + replyStatus = ST_ERROR; + replyMessage = tr("Path already exists, and is not a directory."); + } + } + } catch(fs::filesystem_error &e) + { + /* Parent directory does not exist or is not accessible */ + replyStatus = ST_ERROR; + replyMessage = tr("Cannot create data directory here."); + } + emit reply(replyStatus, replyMessage, freeBytesAvailable); +} + + +Intro::Intro(QWidget *parent) : + QDialog(parent), + ui(new Ui::Intro), + thread(0), + signalled(false) +{ + ui->setupUi(this); + ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE/GB_BYTES)); + startThread(); +} + +Intro::~Intro() +{ + delete ui; + /* Ensure thread is finished before it is deleted */ + emit stopThread(); + thread->wait(); +} + +QString Intro::getDataDirectory() +{ + return ui->dataDirectory->text(); +} + +void Intro::setDataDirectory(const QString &dataDir) +{ + ui->dataDirectory->setText(dataDir); + if(dataDir == getDefaultDataDirectory()) + { + ui->dataDirDefault->setChecked(true); + ui->dataDirectory->setEnabled(false); + ui->ellipsisButton->setEnabled(false); + } else { + ui->dataDirCustom->setChecked(true); + ui->dataDirectory->setEnabled(true); + ui->ellipsisButton->setEnabled(true); + } +} + +QString Intro::getDefaultDataDirectory() +{ + return GUIUtil::boostPathToQString(GetDefaultDataDir()); +} + +void Intro::pickDataDirectory() +{ + namespace fs = boost::filesystem; + QSettings settings; + /* If data directory provided on command line, no need to look at settings + or show a picking dialog */ + if(!GetArg("-datadir", "").empty()) + return; + /* 1) Default data directory for operating system */ + QString dataDir = getDefaultDataDirectory(); + /* 2) Allow QSettings to override default dir */ + dataDir = settings.value("strDataDir", dataDir).toString(); + + if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false)) + { + /* If current default data directory does not exist, let the user choose one */ + Intro intro; + intro.setDataDirectory(dataDir); + intro.setWindowIcon(QIcon(":icons/emercoin")); + + while(true) + { + if(!intro.exec()) + { + /* Cancel clicked */ + exit(0); + } + dataDir = intro.getDataDirectory(); + try { + TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir)); + break; + } catch(fs::filesystem_error &e) { + QMessageBox::critical(0, tr("Emercoin Core"), + tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); + /* fall through, back to choosing screen */ + } + } + + settings.setValue("strDataDir", dataDir); + } + /* Only override -datadir if different from the default, to make it possible to + * override -datadir in the bitcoin.conf file in the default data directory + * (to be consistent with bitcoind behavior) + */ + if(dataDir != getDefaultDataDirectory()) + SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting +} + +void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) +{ + switch(status) + { + case FreespaceChecker::ST_OK: + ui->errorMessage->setText(message); + ui->errorMessage->setStyleSheet(""); + break; + case FreespaceChecker::ST_ERROR: + ui->errorMessage->setText(tr("Error") + ": " + message); + ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); + break; + } + /* Indicate number of bytes available */ + if(status == FreespaceChecker::ST_ERROR) + { + ui->freeSpace->setText(""); + } else { + QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES); + if(bytesAvailable < BLOCK_CHAIN_SIZE) + { + freeString += " " + tr("(of %n GB needed)", "", BLOCK_CHAIN_SIZE/GB_BYTES); + ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); + } else { + ui->freeSpace->setStyleSheet(""); + } + ui->freeSpace->setText(freeString + "."); + } + /* Don't allow confirm in ERROR state */ + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); +} + +void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) +{ + /* Disable OK button until check result comes in */ + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); + checkPath(dataDirStr); +} + +void Intro::on_ellipsisButton_clicked() +{ + QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); + if(!dir.isEmpty()) + ui->dataDirectory->setText(dir); +} + +void Intro::on_dataDirDefault_clicked() +{ + setDataDirectory(getDefaultDataDirectory()); +} + +void Intro::on_dataDirCustom_clicked() +{ + ui->dataDirectory->setEnabled(true); + ui->ellipsisButton->setEnabled(true); +} + +void Intro::startThread() +{ + thread = new QThread(this); + FreespaceChecker *executor = new FreespaceChecker(this); + executor->moveToThread(thread); + + connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64))); + connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); + /* make sure executor object is deleted in its own thread */ + connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); + connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); + + thread->start(); +} + +void Intro::checkPath(const QString &dataDir) +{ + mutex.lock(); + pathToCheck = dataDir; + if(!signalled) + { + signalled = true; + emit requestCheck(); + } + mutex.unlock(); +} + +QString Intro::getPathToCheck() +{ + QString retval; + mutex.lock(); + retval = pathToCheck; + signalled = false; /* new request can be queued now */ + mutex.unlock(); + return retval; +} diff --git a/code/validation/C++/0039193_computation_tree.cpp b/code/validation/C++/0039193_computation_tree.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aea93716c5985387f228b04a514bb1129b5d728f --- /dev/null +++ b/code/validation/C++/0039193_computation_tree.cpp @@ -0,0 +1,72 @@ +// Copyright (C) 2005 Douglas Gregor. + +// Use, modification and distribution is subject to the Boost Software +// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +// Compute parents, children, levels, etc. to effect a parallel +// computation tree. + +#include + +namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace mpi { namespace detail { + +int computation_tree::default_branching_factor = 3; + +computation_tree +::computation_tree(int rank, int size, int root, int branching_factor) + : rank(rank), size(size), root(root), + branching_factor_(branching_factor > 1? branching_factor + /* default */: default_branching_factor), + level_(0) +{ + // The position in the tree, once we've adjusted for non-zero + // roots. + int n = (rank + size - root) % size; + int sum = 0; + int term = 1; + + /* The level is the smallest value of k such that + + f^0 + f^1 + ... + f^k > n + + for branching factor f and index n in the tree. */ + while (sum <= n) { + ++level_; + term *= branching_factor_; + sum += term; + } +} + +int computation_tree::level_index(int n) const +{ + int sum = 0; + int term = 1; + while (n--) { + sum += term; + term *= branching_factor_; + } + return sum; +} + +int computation_tree::parent() const +{ + if (rank == root) return rank; + int n = rank + size - 1 - root; + return ((n % size / branching_factor_) + root) % size ; +} + +int computation_tree::child_begin() const +{ + // Zero-based index of this node + int n = (rank + size - root) % size; + + // Compute the index of the child (in a zero-based tree) + int child_index = level_index(level_ + 1) + + branching_factor_ * (n - level_index(level_)); + + if (child_index >= size) return root; + else return (child_index + root) % size; +} + +} } } // end namespace pdalboost::mpi::detail diff --git a/code/validation/C++/0040636_Selection_Activity.cpp b/code/validation/C++/0040636_Selection_Activity.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dfeea4e7912091d1b2e2ff01d381ab191ffa1546 --- /dev/null +++ b/code/validation/C++/0040636_Selection_Activity.cpp @@ -0,0 +1,63 @@ +#include + +int main(void) +{ + int n; + int a[100]; + int start[100]; + int finish[100]; + printf("Enter number of activities: "); + scanf("%d",&n); + printf("Enter starting time and finishing time\n"); + for(int i=0;i=1;i--) + { + int t=0; + for(int j=1;j<=i;j++) + { + if(finish[a[j]]>finish[a[t]]) + { + t=j; + } + } + + int temp=a[t]; + a[t]=a[i]; + a[i]=temp; + } + + + int count=0; + int A[100]; + int i=0; + A[count]=a[0]; + count+=1; + for(int m=1;m=finish[a[i]]) + { + + A[count]=a[m]; + i=m; + count++; + + } + } + + printf("Result\n"); + for(int i=0;i + +#include +#include +#include + +#include "poclu.h" + +#define WINDOW_SIZE 32 +#define WORK_ITEMS 2 +#define BUFFER_SIZE (WORK_ITEMS + WINDOW_SIZE) + +// adding before the first for-loop produces another crash +// " if (result[gid] == 0) return; \n" + +// increasing the loop counter to 32 produces yet another crash + +static char +kernelSourceCode[] = +"kernel \n" +"void test_kernel(__global float *input, \n" +" __global int *result) {\n" +" int gid = get_global_id(0);\n" +" float global_sum = 0.0f;\n" +" int i;\n" +"\n" +" result[gid] = global_sum;\n" +" for (i=0; i < 32; ++i) {\n" +" float value = input[gid+i];\n" +" global_sum += value;\n" +" }\n" +" result[gid] = result[gid] + global_sum;\n" +" barrier(CLK_GLOBAL_MEM_FENCE);\n" +" \n" +" for (i=0; i < 32; ++i) {\n" +" float value = input[gid+i];\n" +" global_sum += value;\n" +" }\n" +" result[gid] = result[gid] + global_sum;\n" +"}\n"; + +int +main(void) +{ + cl_float A[BUFFER_SIZE]; + cl_int R[WORK_ITEMS]; + cl_int err = 0; + + for (int i = 0; i < BUFFER_SIZE; i++) { + A[i] = i; + } + + for (int i = 0; i < WORK_ITEMS; i++) { + R[i] = i; + } + + try { + std::vector platformList; + + // Pick platform + cl::Platform::get(&platformList); + + // Pick first platform + cl_context_properties cprops[] = { + CL_CONTEXT_PLATFORM, (cl_context_properties)(platformList[0])(), 0}; + cl::Context context(CL_DEVICE_TYPE_CPU | CL_DEVICE_TYPE_GPU, cprops); + + // Query the set of devices attched to the context + std::vector devices = context.getInfo(); + + // Create and program from source + cl::Program::Sources sources(1, std::make_pair(kernelSourceCode, 0)); + cl::Program program(context, sources); + + cl_device_id dev_id = devices.at(0)(); + + poclu_bswap_cl_float_array(dev_id, A, BUFFER_SIZE); + poclu_bswap_cl_int_array(dev_id, R, WORK_ITEMS); + + // Build program + program.build(devices); + + // Create buffer for A and copy host contents + cl::Buffer aBuffer = cl::Buffer( + context, + CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, + BUFFER_SIZE * sizeof(float), + (void *) &A[0]); + + // Create buffer for that uses the host ptr C + cl::Buffer cBuffer = cl::Buffer( + context, + CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, + WORK_ITEMS * sizeof(int), + (void *) &R[0]); + + // Create kernel object + cl::Kernel kernel(program, "test_kernel"); + + // Set kernel args + kernel.setArg(0, aBuffer); + kernel.setArg(1, cBuffer); + + // Create command queue + cl::CommandQueue queue(context, devices[0], 0); + + // Do the work + queue.enqueueNDRangeKernel( + kernel, + cl::NullRange, + cl::NDRange(WORK_ITEMS), + cl::NullRange); + + + // Map cBuffer to host pointer. This enforces a sync with + // the host backing space, remember we choose GPU device. + int * output = (int *) queue.enqueueMapBuffer( + cBuffer, + CL_TRUE, // block + CL_MAP_READ, + 0, + WORK_ITEMS * sizeof(int)); + + bool ok = true; + for (int i = 0; i < WORK_ITEMS; i++) { + + float global_sum = 0.0f; + int j; + float result; + + result = global_sum; + for (j=0; j < 32; ++j) { + float value = poclu_bswap_cl_float (dev_id, A[i+j]); + global_sum += value; + } + result = result + global_sum; + for (j=0; j < 32; ++j) { + float value = poclu_bswap_cl_float (dev_id, A[i+j]); + global_sum += value; + } + result = result + global_sum; + + if ((int)result != poclu_bswap_cl_int (dev_id, R[i])) { + std::cout + << "F(" << i << ": " << (int)result << " != " << R[i] + << ") "; + ok = false; + } + } + if (ok) + return EXIT_SUCCESS; + else + return EXIT_FAILURE; + + // Finally release our hold on accessing the memory + err = queue.enqueueUnmapMemObject( + cBuffer, + (void *) output); + + // There is no need to perform a finish on the final unmap + // or release any objects as this all happens implicitly with + // the C++ Wrapper API. + } + catch (cl::Error err) { + std::cerr + << "ERROR: " + << err.what() + << "(" + << err.err() + << ")" + << std::endl; + + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/code/validation/C++/0044109_traj_smoothing_test.cc b/code/validation/C++/0044109_traj_smoothing_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..d9c4a2c9b635562d0f664db1c19b57bc0da737ef --- /dev/null +++ b/code/validation/C++/0044109_traj_smoothing_test.cc @@ -0,0 +1,144 @@ +/*********************************************************************** + + Copyright 2007-2010 Carnegie Mellon University and Intel Corporation + Author: Mike Vande Weghe + + This file is part of owd. + + owd is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 3 of the License, or (at your + option) any later version. + + owd is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . + + ***********************************************************************/ + +#include "ParaJointTraj.hh" +#include + +int main(int argc, char **argv) { + if (argc < 2) { + printf("Usage: traj_smoothing_test \n"); + exit(1); + } + FILE *csv = fopen(argv[1],"r"); + if (!csv) { + printf("Cannot open csv file %s\n",argv[1]); + exit(1); + } + TrajPoint tp; + TrajType traj; + tp.resize(7); + while (fscanf(csv,"%lf, %lf, %lf, %lf, %lf, %lf, %lf\n", + &tp[0],&tp[1],&tp[2],&tp[3],&tp[4],&tp[5],&tp[6]) == 7) { + traj.push_back(tp); + } + fclose(csv); + ParaJointTraj *pjt; + vector joint_vels, joint_accels; + joint_vels.resize(7); joint_accels.resize(7); + joint_vels[0]= 60.0; joint_accels[0]=30.0; + joint_vels[1]= 40.0; joint_accels[1]=20.0; + joint_vels[2]= 80.0; joint_accels[2]=40.0; + joint_vels[3]= 80.0; joint_accels[3]=40.0; + joint_vels[4]= 40.0; joint_accels[4]=20.0; + joint_vels[5]= 40.0; joint_accels[5]=20.0; + joint_vels[6]= 40.0; joint_accels[6]=20.0; + try { + pjt= new ParaJointTraj(traj,joint_vels,joint_accels,true,false,0); + } catch(int e) { + printf("Could not construct ParaJointTraj from these points\n"); + exit(1); + } + printf("Trajectory created; %zd points, %zd segments, %3.3g secs\n",traj.size(),pjt->parsegs[0].size(),pjt->traj_duration); + csv = fopen("smoothed.csv","w"); + if (!csv) { + printf("Cannot output to smoothed.csv\n"); + exit(1); + } + double y[8],yd[8],ydd[8]; + pjt->run(); + int stopped=50; + double stop_time=pjt->traj_duration/2; + double elapsed_time = 0.0f; + while (pjt->state() != ParaJointTraj::DONE) { + if (elapsed_time > stop_time) { + stopped++; + } + if (stopped==1 || stopped==21) { + pjt->stop(); + printf("Trajectory stopped at time %3.3f\n",elapsed_time); + } else if (stopped==6 || stopped==26) { + pjt->run(); + printf("Trajectory restarted at time %3.3f\n",elapsed_time); + } + pjt->evaluate(y,yd,ydd,0.01); + elapsed_time += .01f; + fprintf(csv,"%3.3f, ",elapsed_time); + for (int j=1; j<8; ++j) { + fprintf(csv,"%2.8f, ",y[j]); + } + for (int j=1; j<8; ++j) { + fprintf(csv,"%2.8f, ",yd[j]); + } + for (int j=1; j<8; ++j) { + fprintf(csv,"%2.8f, ",ydd[j]); + } + fprintf(csv,"0.0 0.0 0.0 0.0 0.0 0.0 0.0\n"); // torq + } + fclose(csv); + csv = fopen("orig.csv","w"); + if (!csv) { + printf("Cannot output to orig.csv"); + exit(1); + } + int segment=0; + for (int i=0; i < traj.size(); ++i) { + // we'll just find the time that joint one hit each original + // joint value, and output all the points at that time, so that we + // can plot to see how well they line up with the traj curves + + // first, find what segment each point is in + while ((segment+1 < pjt->parsegs[0].size()) && + (i>pjt->parsegs[0][segment+1].start_index)) { + segment++; + } + // now find an appropriate joint to use (one without a CONST segment) + int jnt=0; + int max_jump_jnt=0; + double max_jump=0.0f; + for (jnt=0; jnt<7; jnt++) { + double jump = fabs(pjt->parsegs[jnt][segment].end_pos - + pjt->parsegs[jnt][segment].start_pos); + if (jump > max_jump) { + max_jump = jump; + max_jump_jnt = jnt; + } + } + // while ((pjt->parsegs[jnt][segment].dir == ParabolicSegment::CONST) && + // (jnt<6)) { + // jnt++; + // } // if they're all CONST we'll just end up using jnt=6. + double time = pjt->parsegs[max_jump_jnt][segment].calc_time(traj[i][max_jump_jnt]); + if (time == -1.0f) { + printf("Warning: no time available for point %d within segment %d of joint %d\n",i,segment,max_jump_jnt); + } + fprintf(csv,"%3.3f, ",time); + for (int j=0; j<6; j++) { + fprintf(csv,"%2.8f, ",traj[i][j]); + } + fprintf(csv,"%2.8f\n",traj[i][6]); + } + fclose(csv); + delete pjt; + exit(0); +} + + diff --git a/code/validation/C++/0045967_text-interface.cc b/code/validation/C++/0045967_text-interface.cc new file mode 100644 index 0000000000000000000000000000000000000000..d930cdaa372868622e4624883c4ace2f5539e2a9 --- /dev/null +++ b/code/validation/C++/0045967_text-interface.cc @@ -0,0 +1,208 @@ +/* + This file is part of LilyPond, the GNU music typesetter. + + Copyright (C) 1998--2015 Han-Wen Nienhuys + Jan Nieuwenhuizen + + LilyPond is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + LilyPond is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with LilyPond. If not, see . +*/ + +#include "text-interface.hh" +#include "skyline-pair.hh" + +#include "lookup.hh" +#include "config.hh" +#include "font-interface.hh" +#include "grob.hh" +#include "main.hh" +#include "misc.hh" +#include "modified-font-metric.hh" +#include "output-def.hh" +#include "pango-font.hh" +#include "program-option.hh" +#include "international.hh" +#include "warn.hh" +#include "lily-imports.hh" + +static void +replace_special_characters (string &str, SCM props) +{ + SCM replacement_alist = ly_chain_assoc_get (ly_symbol2scm ("replacement-alist"), + props, + SCM_EOL); + + int max_length = 0; + for (SCM s = replacement_alist; scm_is_pair (s); s = scm_cdr (s)) + { + max_length = max (max_length, scm_to_int + (scm_string_length (scm_caar (s)))); + } + + for (vsize i = 0; i < str.size (); i++) + { + /* Don't match in mid-UTF-8 */ + if ((str[i] & 0xc0) == 0x80) + continue; + for (vsize j = max_length + 1; j--;) + { + if (j > str.size () - i) + continue; + string dummy = str.substr (i, j); + SCM ligature = ly_assoc_get (ly_string2scm (dummy), + replacement_alist, SCM_BOOL_F); + if (scm_is_true (ligature)) + str.replace (i, j, robust_scm2string (ligature, "")); + } + } +} + +MAKE_SCHEME_CALLBACK (Text_interface, interpret_string, 3); +SCM +Text_interface::interpret_string (SCM layout_smob, + SCM props, + SCM markup) +{ + LY_ASSERT_SMOB (Output_def, layout_smob, 1); + LY_ASSERT_TYPE (scm_is_string, markup, 3); + + string str = ly_scm2string (markup); + Output_def *layout = unsmob (layout_smob); + Font_metric *fm = select_encoded_font (layout, props); + + replace_special_characters (str, props); + + /* + We want to filter strings with a music font that pass through + the text interface. Here the font encoding is checked to see + if it matches one of the music font encodings. --pmccarty + */ + SCM encoding = ly_chain_assoc_get (ly_symbol2scm ("font-encoding"), + props, + SCM_BOOL_F); + SCM music_encodings = Lily::all_music_font_encodings; + + bool is_music = scm_is_true (scm_memq (encoding, music_encodings)); + return fm->text_stencil (layout, str, is_music).smobbed_copy (); +} + +static size_t markup_depth = 0; + +void markup_up_depth (void *) { ++markup_depth; } +void markup_down_depth (void *) { --markup_depth; } + +MAKE_SCHEME_CALLBACK_WITH_OPTARGS (Text_interface, interpret_markup, 3, 0, + "Convert a text markup into a stencil." + " Takes three arguments, @var{layout}, @var{props}, and @var{markup}.\n" + "\n" + "@var{layout} is a @code{\\layout} block; it may be obtained from a grob with" + " @code{ly:grob-layout}. @var{props} is an alist chain, i.e. a list of" + " alists. This is typically obtained with" + " @code{(ly:grob-alist-chain grob (ly:output-def-lookup layout 'text-font-defaults))}." + " @var{markup} is the markup text to be processed."); +SCM +Text_interface::interpret_markup (SCM layout_smob, SCM props, SCM markup) +{ + if (scm_is_string (markup)) + return interpret_string (layout_smob, props, markup); + else if (is_markup (markup)) + { + SCM func = scm_car (markup); + SCM args = scm_cdr (markup); + + /* Check for non-terminating markups, e.g. recursive calls with + * changing arguments */ + SCM opt_depth = ly_get_option (ly_symbol2scm ("max-markup-depth")); + size_t max_depth = robust_scm2int (opt_depth, 1024); + + // Don't use SCM_F_DYNWIND_REWINDABLE since it may be expensive + // without any obvious use for retaining continuations into + // markup expansion + scm_dynwind_begin ((scm_t_dynwind_flags)0); + // scm_dynwind_rewind_handler (markup_up_depth, 0, SCM_F_WIND_EXPLICITLY); + markup_up_depth (0); + scm_dynwind_unwind_handler (markup_down_depth, 0, SCM_F_WIND_EXPLICITLY); + if (markup_depth > max_depth) + { + scm_dynwind_end (); + string name = ly_symbol2string (scm_procedure_name (func)); + // TODO: Also print the arguments of the markup! + non_fatal_error (_f ("Markup depth exceeds maximal value of %d; " + "Markup: %s", max_depth, name.c_str ())); + return Stencil ().smobbed_copy (); + } + + SCM retval = scm_apply_2 (func, layout_smob, props, args); + scm_dynwind_end (); + return retval; + } + else + { + programming_error ("Object is not a markup."); + scm_puts ("This object should be a markup: ", scm_current_error_port ()); + scm_display (markup, scm_current_error_port ()); + scm_puts ("\n", scm_current_error_port ()); + + return Stencil ().smobbed_copy (); + } +} + +MAKE_SCHEME_CALLBACK (Text_interface, print, 1); +SCM +Text_interface::print (SCM grob) +{ + Grob *me = unsmob (grob); + + SCM t = me->get_property ("text"); + SCM chain = Font_interface::text_font_alist_chain (me); + return interpret_markup (me->layout ()->self_scm (), chain, t); +} + +/* Ugh. Duplicated from Scheme. */ +bool +Text_interface::is_markup (SCM x) +{ + return scm_is_string (x) + || (scm_is_pair (x) + && scm_is_true + (scm_object_property (scm_car (x), + ly_symbol2scm ("markup-signature"))) + && scm_is_false + (scm_object_property (scm_car (x), + ly_symbol2scm ("markup-list-command")))); +} + +bool +Text_interface::is_markup_list (SCM x) +{ + return scm_is_true (Lily::markup_list_p (x)); +} + +ADD_INTERFACE (Text_interface, + "A Scheme markup text, see @ruser{Formatting text} and" + " @rextend{New markup command definition}.\n" + "\n" + "There are two important commands:" + " @code{ly:text-interface::print}, which is a" + " grob callback, and" + " @code{ly:text-interface::interpret-markup}.", + + /* properties */ + "baseline-skip " + "replacement-alist " + "text " + "word-space " + "text-direction " + "flag-style " + ); + diff --git a/code/validation/C++/0046462_intro.cpp b/code/validation/C++/0046462_intro.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8384b94b37f784663fdf3f1ce3369bb237c5a9ac --- /dev/null +++ b/code/validation/C++/0046462_intro.cpp @@ -0,0 +1,283 @@ +// Copyright (c) 2011-2014 The Bitcoin developers +// Copyright (c) 2014-2015 The Dash developers +// Copyright (c) 2015-2017 The PIVX developers +// Copyright (c) 2015-2017 The AmsterdamCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "intro.h" +#include "ui_intro.h" + +#include "guiutil.h" + +#include "util.h" + +#include + +#include +#include +#include + +/* Minimum free space (in bytes) needed for data directory */ +static const uint64_t GB_BYTES = 1000000000LL; +static const uint64_t BLOCK_CHAIN_SIZE = 1LL * GB_BYTES; + +/* Check free space asynchronously to prevent hanging the UI thread. + + Up to one request to check a path is in flight to this thread; when the check() + function runs, the current path is requested from the associated Intro object. + The reply is sent back through a signal. + + This ensures that no queue of checking requests is built up while the user is + still entering the path, and that always the most recently entered path is checked as + soon as the thread becomes available. +*/ +class FreespaceChecker : public QObject +{ + Q_OBJECT + +public: + FreespaceChecker(Intro* intro); + + enum Status { + ST_OK, + ST_ERROR + }; + +public slots: + void check(); + +signals: + void reply(int status, const QString& message, quint64 available); + +private: + Intro* intro; +}; + +#include "intro.moc" + +FreespaceChecker::FreespaceChecker(Intro* intro) +{ + this->intro = intro; +} + +void FreespaceChecker::check() +{ + namespace fs = boost::filesystem; + QString dataDirStr = intro->getPathToCheck(); + fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); + uint64_t freeBytesAvailable = 0; + int replyStatus = ST_OK; + QString replyMessage = tr("A new data directory will be created."); + + /* Find first parent that exists, so that fs::space does not fail */ + fs::path parentDir = dataDir; + fs::path parentDirOld = fs::path(); + while (parentDir.has_parent_path() && !fs::exists(parentDir)) { + parentDir = parentDir.parent_path(); + + /* Check if we make any progress, break if not to prevent an infinite loop here */ + if (parentDirOld == parentDir) + break; + + parentDirOld = parentDir; + } + + try { + freeBytesAvailable = fs::space(parentDir).available; + if (fs::exists(dataDir)) { + if (fs::is_directory(dataDir)) { + QString separator = "" + QDir::toNativeSeparators("/") + tr("name") + ""; + replyStatus = ST_OK; + replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); + } else { + replyStatus = ST_ERROR; + replyMessage = tr("Path already exists, and is not a directory."); + } + } + } catch (fs::filesystem_error& e) { + /* Parent directory does not exist or is not accessible */ + replyStatus = ST_ERROR; + replyMessage = tr("Cannot create data directory here."); + } + emit reply(replyStatus, replyMessage, freeBytesAvailable); +} + + +Intro::Intro(QWidget* parent) : QDialog(parent), + ui(new Ui::Intro), + thread(0), + signalled(false) +{ + ui->setupUi(this); + ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE / GB_BYTES)); + startThread(); +} + +Intro::~Intro() +{ + delete ui; + /* Ensure thread is finished before it is deleted */ + emit stopThread(); + thread->wait(); +} + +QString Intro::getDataDirectory() +{ + return ui->dataDirectory->text(); +} + +void Intro::setDataDirectory(const QString& dataDir) +{ + ui->dataDirectory->setText(dataDir); + if (dataDir == getDefaultDataDirectory()) { + ui->dataDirDefault->setChecked(true); + ui->dataDirectory->setEnabled(false); + ui->ellipsisButton->setEnabled(false); + } else { + ui->dataDirCustom->setChecked(true); + ui->dataDirectory->setEnabled(true); + ui->ellipsisButton->setEnabled(true); + } +} + +QString Intro::getDefaultDataDirectory() +{ + return GUIUtil::boostPathToQString(GetDefaultDataDir()); +} + +bool Intro::pickDataDirectory() +{ + namespace fs = boost::filesystem; + QSettings settings; + /* If data directory provided on command line, no need to look at settings + or show a picking dialog */ + if (!GetArg("-datadir", "").empty()) + return true; + /* 1) Default data directory for operating system */ + QString dataDir = getDefaultDataDirectory(); + /* 2) Allow QSettings to override default dir */ + dataDir = settings.value("strDataDir", dataDir).toString(); + + if (!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false)) { + /* If current default data directory does not exist, let the user choose one */ + Intro intro; + intro.setDataDirectory(dataDir); + intro.setWindowIcon(QIcon(":icons/bitcoin")); + + while (true) { + if (!intro.exec()) { + /* Cancel clicked */ + return false; + } + dataDir = intro.getDataDirectory(); + try { + TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir)); + break; + } catch (fs::filesystem_error& e) { + QMessageBox::critical(0, tr("AmsterdamCoin Core"), + tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); + /* fall through, back to choosing screen */ + } + } + + settings.setValue("strDataDir", dataDir); + } + /* Only override -datadir if different from the default, to make it possible to + * override -datadir in the amsterdamcoin.conf file in the default data directory + * (to be consistent with amsterdamcoind behavior) + */ + if (dataDir != getDefaultDataDirectory()) + SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting + return true; +} + +void Intro::setStatus(int status, const QString& message, quint64 bytesAvailable) +{ + switch (status) { + case FreespaceChecker::ST_OK: + ui->errorMessage->setText(message); + ui->errorMessage->setStyleSheet(""); + break; + case FreespaceChecker::ST_ERROR: + ui->errorMessage->setText(tr("Error") + ": " + message); + ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); + break; + } + /* Indicate number of bytes available */ + if (status == FreespaceChecker::ST_ERROR) { + ui->freeSpace->setText(""); + } else { + QString freeString = tr("%1 GB of free space available").arg(bytesAvailable / GB_BYTES); + if (bytesAvailable < BLOCK_CHAIN_SIZE) { + freeString += " " + tr("(of %1 GB needed)").arg(BLOCK_CHAIN_SIZE / GB_BYTES); + ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); + } else { + ui->freeSpace->setStyleSheet(""); + } + ui->freeSpace->setText(freeString + "."); + } + /* Don't allow confirm in ERROR state */ + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); +} + +void Intro::on_dataDirectory_textChanged(const QString& dataDirStr) +{ + /* Disable OK button until check result comes in */ + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); + checkPath(dataDirStr); +} + +void Intro::on_ellipsisButton_clicked() +{ + QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); + if (!dir.isEmpty()) + ui->dataDirectory->setText(dir); +} + +void Intro::on_dataDirDefault_clicked() +{ + setDataDirectory(getDefaultDataDirectory()); +} + +void Intro::on_dataDirCustom_clicked() +{ + ui->dataDirectory->setEnabled(true); + ui->ellipsisButton->setEnabled(true); +} + +void Intro::startThread() +{ + thread = new QThread(this); + FreespaceChecker* executor = new FreespaceChecker(this); + executor->moveToThread(thread); + + connect(executor, SIGNAL(reply(int, QString, quint64)), this, SLOT(setStatus(int, QString, quint64))); + connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); + /* make sure executor object is deleted in its own thread */ + connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); + connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); + + thread->start(); +} + +void Intro::checkPath(const QString& dataDir) +{ + mutex.lock(); + pathToCheck = dataDir; + if (!signalled) { + signalled = true; + emit requestCheck(); + } + mutex.unlock(); +} + +QString Intro::getPathToCheck() +{ + QString retval; + mutex.lock(); + retval = pathToCheck; + signalled = false; /* new request can be queued now */ + mutex.unlock(); + return retval; +} diff --git a/code/validation/C++/0047902_ovpCDetectingMinMax.cpp b/code/validation/C++/0047902_ovpCDetectingMinMax.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96d42e773de8851b4e0b85b959d3291f110a99ae --- /dev/null +++ b/code/validation/C++/0047902_ovpCDetectingMinMax.cpp @@ -0,0 +1,110 @@ +#include "ovpCDetectingMinMax.h" + +#include +#include +#include +#include + +using namespace OpenViBE; +using namespace OpenViBE::Kernel; +using namespace OpenViBE::Plugins; + +using namespace OpenViBEPlugins; +using namespace OpenViBEPlugins::SignalProcessingGpl; +using namespace std; +// ________________________________________________________________________________________________________________ +// + +boolean CDetectingMinMax::initialize(void) +{ + ip_pSignalMatrix.initialize(getInputParameter(OVP_Algorithm_DetectingMinMax_InputParameterId_SignalMatrix)); + ip_ui64SamplingFrequency.initialize(getInputParameter(OVP_Algorithm_DetectingMinMax_InputParameterId_SamplingFrequency)); + ip_f64TimeWindowStart.initialize(getInputParameter(OVP_Algorithm_DetectingMinMax_InputParameterId_TimeWindowStart)); + ip_f64TimeWindowEnd.initialize(getInputParameter(OVP_Algorithm_DetectingMinMax_InputParameterId_TimeWindowEnd)); + + op_pSignalMatrix.initialize(getOutputParameter(OVP_Algorithm_DetectingMinMax_OutputParameterId_SignalMatrix)); + + return true; +} + +boolean CDetectingMinMax::uninitialize(void) +{ + op_pSignalMatrix.uninitialize(); + + ip_f64TimeWindowEnd.uninitialize(); + ip_f64TimeWindowStart.uninitialize(); + ip_ui64SamplingFrequency.uninitialize(); + ip_pSignalMatrix.uninitialize(); + + return true; +} + +// ________________________________________________________________________________________________________________ +// + +boolean CDetectingMinMax::process(void) +{ + // signal input vars + IMatrix* l_pSignalInputMatrix=ip_pSignalMatrix; + float64* l_pSignalInput = l_pSignalInputMatrix->getBuffer(); + + // signal output vars + IMatrix* l_pSignalOutputMatrix=op_pSignalMatrix; + l_pSignalOutputMatrix->setDimensionCount(2); + l_pSignalOutputMatrix->setDimensionSize(0,1); + l_pSignalOutputMatrix->setDimensionSize(1, 1); + + float64* l_pSignalOutput = l_pSignalOutputMatrix->getBuffer(); + + if(isInputTriggerActive(OVP_Algorithm_DetectingMinMax_InputTriggerId_Initialize)) + { + } + + if(isInputTriggerActive(OVP_Algorithm_DetectingMinMax_InputTriggerId_DetectsMin)) + { + // dimension of input signal biuffer + uint32 l_ui32SignalInputMatrixDimensionNbChannels=ip_pSignalMatrix->getDimensionSize(0); + uint32 l_ui32SignalInputMatrixDimensionSizeEpoch=ip_pSignalMatrix->getDimensionSize(1); + + // Must be changed + float64 l_f64MinValue = 1E10; + + for (uint64 i=0; i < l_ui32SignalInputMatrixDimensionNbChannels; i++) + { + for(uint64 j=0 ; jgetDimensionSize(0); + uint32 l_ui32SignalInputMatrixDimensionSizeEpoch=ip_pSignalMatrix->getDimensionSize(1); + + // Must be changed + float64 l_f64MaxValue = -1E10; + + for (uint64 i=0; i < l_ui32SignalInputMatrixDimensionNbChannels; i++) + { + uint64 l_ui64Start=static_cast(floor(ip_f64TimeWindowStart/1000.*ip_ui64SamplingFrequency)); + uint64 l_ui64Stop=static_cast(floor(ip_f64TimeWindowEnd/1000.*ip_ui64SamplingFrequency)); + for(uint64 j=l_ui64Start; j l_f64MaxValue) + { + l_f64MaxValue = l_pSignalInput[i*l_ui32SignalInputMatrixDimensionSizeEpoch+j]; + } + } + } + l_pSignalOutput[0] = l_f64MaxValue; + } + + return true; +} diff --git a/code/validation/C++/0048277_main.cpp b/code/validation/C++/0048277_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62c9ea99f265cce24146d7d051a1df36250a70d4 --- /dev/null +++ b/code/validation/C++/0048277_main.cpp @@ -0,0 +1,268 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +/* + * File: main.cpp + * Author: yurec + * + * Created on 21 липня 2016, 9:55 + */ + +#include +#include +#include +#include + +#include "String.h" +#include "Arr.h" +//#include "Arr.cpp" +#define LINE cout << "-------------------------------------------------------------\n\n"; + + +using namespace std; + +//template +//void generateArray(T (&arr)[N], T(*randFunc)()){ +// for (int i = 0; i < N; ++i) +// arr[i] = randFunc(); +//} + +template +void generateArray1(T (&arr)[N], T(*randFunc)()){ + for (int i = 0; i < N; ++i) + arr[i] = randFunc(); +} + + +void testString(); +void testEx1(); +void testArr(); +void testEx3(); + + +void func1(); +void func2(); +void func3(); +template +struct result +{ + T minimum, maximum; +}; + +template +result max_min(const std::initializer_list &list); + +int main(int argc, char** argv) { + //testEx1(); + testArr(); + //testEx3(); + //testString(); + return 0; +} + + +template +result max_min(const std::initializer_list &list) +{ + T min = *(list.begin()); + T max = *(list.end()-1); + + for (auto i : list){ + if (i > max) + max = i; + + if (i < min) + min = i; + } + + return result {min, max}; + +} + + + +void func1(){ + cout << "Start func1! " << endl; + cout << " func1 catch exception with char type\n"; + cout << "Menu :\n" + << " 1 - for throw int type \n" + << " 2 - for throw double type\n" + << " 3 - for thro char* type\n"; + + String s; + + while (1){ + try{ + s.input("Enter your choice: "); + if (s == "2") + throw 1.0; + + if (s == "1") + throw 1; + + if (s == "3") + throw "choice numbe 3"; + + cout << "Unknown choice. Repeate please." << endl;; + } + catch (const char* c){ + cout << "Func1 has caught exception type char and value = " << c << endl; + } + catch (...){ + cout << "Func1 has caught exception unknown type, throwing forward." << endl; + throw; + } + } + + cout << "End func1! " << endl; + +} + +void func2(){ + cout << "Start func2! " << endl; + cout << " func2 start func1 and catch exception with double type" << endl; + try{ + func1(); + } + catch (double d){ + cout << "Func2 has caught exception type double and value = " << d << endl; + } + catch (...){ + cout << "Func2 has caught exception unknown type, throwing forward." << endl; + throw; + } + + + cout << "End func2! " << endl; +} + +void testEx1(){ + cout << "-------------------------------------------------------------\n"; + cout << "--------------- Testing ------------------\n"; + cout << "-------------------------------------------------------------\n"; + cout << endl; + + try{ + func2(); + } + catch (int d){ + cout << "Have caught exception type int and value = " << d << endl; + } + catch (...){ + cout << "Have caught exception unknown type, throwing forward." << endl; + throw; + } +} + +template bool logicF(T t){ + if (t>10) + return true; + else + return false; +} + +template T replaceF(T t){ + return t*10; +} + +template void printArr(T* arr, int n){ + for(int i = 0; i < n; ++i) + cout << arr[i] << " "; + + cout << endl; +} + +void testArr(){ + cout << "-------------------------------------------------------------\n"; + cout << "------------------- Testing --------------------\n"; + cout << "-------------------------------------------------------------\n"; + cout << endl; + + double arr_d1[20]; + double arr_d2[11]; + int arr_i1[20]; + int arr_i2[20]; + string arr_s2[5]; + + generateArray(arr_d1, rnd); + generateArray(arr_i1, rnd); + generateArray(&arr_d2[0], 11, rnd); + generateArray(&arr_i2[0], 20, rnd); + generateArray(&arr_s2[0], 5, rnd); + + ofstream f; + f.open("array.txt", ios::out); + printArrayToFile(f, arr_i1); + printArrayToFile(f, arr_d1); + printArrayToFile(f, &arr_s2[0], 5); + printArrayToFile(f, &arr_d2[0], 11); + printArrayToFile(f, &arr_i2[0], 20); + f.close(); + + cout << "\n arr_d1 \n"; + printArr(arr_d1, 20); + + cout << "\n arr_i1 \n"; + printArr(arr_i1, 20); + + cout << "\n arr_s2 \n"; + printArr(arr_s2, 5); + LINE + + cout << "/n countInArrayIf(arr_d1, logicF) = " << countInArrayIf(arr_d1, logicF) << endl; + cout << "/n countInArrayIf(arr_i1, logicF) = " << countInArrayIf(arr_i1, logicF) << endl; + LINE + + replacetInArrayIf(arr_d1, replaceF); + replacetInArrayIf(arr_i1, replaceF); + cout << " After fuction replacetInArrayIf() \n" << endl; + printArr(arr_d1, 20); + cout << endl; + printArr(arr_i1, 20); + LINE + + + +} + +void testEx3(){ + cout << "-------------------------------------------------------------\n"; + cout << "--------------- Testing ------------------\n"; + cout << "-------------------------------------------------------------\n"; + cout << endl; + + result res = max_min({10,2,3,-40,5,6,7,8,9,10}); + cout << "result res = max_min({1,2,3,4,5,6,7,8,9,10}); \n"; + cout << "res.minimum = " << res.minimum << endl; + cout << "res.maximum = " << res.maximum << endl; + + result res2 = max_min({1.10,1.2,0.3,6.40,5.,6.,7.,8.,9.,10.}); + cout << "result res2 = max_min({1.10,1.2,0.3,6.40,5.,6.,7.,8.,9.,10.}); \n"; + cout << "res2.minimum = " << res2.minimum << endl; + cout << "res2.maximum = " << res2.maximum << endl; + +} + +void testString(){ + cout << "-------------------------------------------------------------\n"; + cout << "-------------- Testing class ------------------\n"; + cout << "-------------------------------------------------------------\n"; + cout << endl; + + String s("Helllo World!!"); + cout << "String s(\"Helllo World!!\");" << endl; + cout << "s.countChars({'e', 'l', 'd', '!'}) = " + << s.countChars({'e', 'l', 'd', '!'}) + << endl; + + s.removeChars({2, 6, 13}); + cout << "s.removeChars({2, 6, 13});" << endl; + cout << "s = " << s << endl; + +} + + + diff --git a/code/validation/C++/0048437_AttributeDetector.cpp b/code/validation/C++/0048437_AttributeDetector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6fc5bbd4f6671d189c7aa69e00d0c49316f2b1cf --- /dev/null +++ b/code/validation/C++/0048437_AttributeDetector.cpp @@ -0,0 +1,170 @@ +#include "AttributeDetector.h" + +AttributeDetector::AttributeDetector(std::string attribute, float weight, Parts::Location attLoc) { + _attribute = attribute; + _weight = weight; + _attributeLoc = attLoc; + + _svm = new OcvSvm(); + + _threshold = 0.0; + _hogExtractor = new HogFeatureExtractor(); + _siftExtractor = new SiftFeatureExtractor(); + _hogExtractor->setQuantized(false); + _siftExtractor->setQuantized(true); + _useHOG = true; + _useSIFT = false; +} + +AttributeDetector::~AttributeDetector() { + delete _svm; + delete _hogExtractor; + delete _siftExtractor; +} + +void AttributeDetector::load() { + std::string directory = Util::env("SVM_MODELS"); + _svm->load(directory + "/" + _attribute + ".svm"); + + std::string file = directory + "/" + _attribute + ".vcb"; + ifstream fh(file.c_str()); + if(!fh.good()) { + printf("WARNING: Attribute detector file %s doesn't exist.\n", file.c_str()); + throw -1; + } + YAML::Parser parser(fh); + YAML::Node node; + parser.GetNextDocument(node); + assert(node.size() > 0); + int i = 0; + if(_useSIFT) { + node[i++] >> *_siftExtractor; + } + if(_useHOG) { + node[i++] >> *_hogExtractor; + } + fh.close(); +} + +void AttributeDetector::save() { + std::string directory = Util::env("SVM_MODELS"); + _svm->save(directory + "/" + _attribute + ".svm"); + + std::string file = directory + "/" + _attribute + ".vcb"; + ofstream fh(file.c_str()); + YAML::Emitter emitter; + emitter << YAML::BeginSeq; + if(_useSIFT) + emitter << *_siftExtractor; + if(_useHOG) + emitter << *_hogExtractor; + emitter << YAML::EndSeq; + fh << emitter.c_str(); + fh.close(); +} + +void AttributeDetector::train(const std::vector& imageFiles, const std::vector& labels) { + std::vector boxes; + for(int i = 0 ; i < imageFiles.size(); i++) + boxes.push_back(cv::Rect(0,0,1000000,1000000)); + train(imageFiles, boxes, labels); +} + +void AttributeDetector::train(const std::vector& imageFiles, const std::vector& boxes, const std::vector& labels) { + int maxFile = 1000; + if(maxFile >= imageFiles.size()) maxFile = imageFiles.size() - 1; + if(_useHOG) { + _hogExtractor->setQuantizePoint(maxFile); + _hogExtractor->setLabels(labels); + } + if(_useSIFT) { + _siftExtractor->setQuantizePoint(maxFile); + _siftExtractor->setLabels(labels); + } + for(int i = 0; i < imageFiles.size(); i++) { + std::string file = imageFiles[i]; + // Use this function to avoid memory leaks + IplImage* imageP = cvLoadImage(file.c_str()); + cv::Mat image = imageP; + cv::Rect box = boxes[i]; + box = Util::correctBoundingBox(box, image); + cv::Mat roi = image(box); + cv::Mat gray(roi.size(), CV_8U); + if(roi.channels() != 1) + cv::cvtColor(roi, gray, CV_RGB2GRAY, 1); + else + gray = roi.clone(); + if(_useSIFT) _siftExtractor->processImage(gray); + if(_useHOG) _hogExtractor->processImage(gray); + cvReleaseImage(&imageP); + } + FeatureSet fset; + if(_useSIFT) { + fset.push_back(_siftExtractor->getFeatures()); + _siftExtractor->clearFeatures(); + } + if(_useHOG) { + fset.push_back(_hogExtractor->getFeatures()); + _hogExtractor->clearFeatures(); + } + std::vector combined = FeatureExtractor::combine(fset); + assert(combined.size() == labels.size()); + _svm->train(combined, labels); +} + +void AttributeDetector::normalize(std::vector& features) { + BOOST_FOREACH(PidMat& feature, features) { + normalize(feature); + } +} + +void AttributeDetector::normalize(PidMat& feature) { + float max = 0; + for(int i = 0; i < feature.rows; i++) { + for(int j = 0; j < feature.cols; j++) { + float temp = feature(i,j); + if(max < temp) max = temp; + } + } + for(int i = 0; i < feature.rows; i++) + for(int j = 0; j < feature.cols; j++) + feature(i,j) /= max; +} + +bool AttributeDetector::hasAttribute(cv::Mat& image, cv::Rect box) { + float prediction; + return hasAttribute(image, box, prediction); +} + +bool AttributeDetector::hasAttribute(cv::Mat& image, cv::Rect box, float& prediction) { + cv::Mat roi = image(box); + if(roi.channels() != 1) + cv::cvtColor(roi, roi, CV_RGB2GRAY, 1); + PidMat feature; + if(_useSIFT) { + assert(!_siftExtractor->isQuantized() || _siftExtractor->vocabularyBuilt()); + feature.push_back(_siftExtractor->extractFeature(roi)); + } + if(_useHOG) { + assert(!_hogExtractor->isQuantized() || _hogExtractor->vocabularyBuilt()); + feature.push_back(_hogExtractor->extractFeature(roi)); + } + prediction = _svm->predict(feature); + if(prediction > _threshold) + return true; + else + return false; +} + +float AttributeDetector::getWeight() { + return _weight; +} + +Parts::Location AttributeDetector::getDetectLoc() +{ + return _attributeLoc; +} + +std::string AttributeDetector::getAttribute() { + return _attribute; +} diff --git a/code/validation/C++/0049079_Model.cpp b/code/validation/C++/0049079_Model.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc21b035360ec657210708a885f9c4076e4758c5 --- /dev/null +++ b/code/validation/C++/0049079_Model.cpp @@ -0,0 +1,53 @@ +#include "data/Model.hpp" +#include + +#include + + +Model::Geometry::Geometry() + : flags(0) +{ + +} + +Model::Geometry::~Geometry() +{ + +} + +ModelFrame::ModelFrame(unsigned int index, ModelFrame* parent, glm::mat3 dR, glm::vec3 dT) + : index(index), defaultRotation(dR), defaultTranslation(dT), parentFrame(parent) +{ + if(parent != nullptr) { + parent->childs.push_back(this); + } + reset(); +} + +void ModelFrame::reset() +{ + matrix = glm::translate(glm::mat4(), defaultTranslation) * glm::mat4(defaultRotation); +} + +void ModelFrame::addGeometry(size_t idx) +{ + geometries.push_back(idx); +} + + +Model::~Model() +{ + for(auto mf : frames) { + delete mf; + } +} + +void Model::recalculateMetrics() +{ + boundingRadius = std::numeric_limits::min(); + for (size_t g = 0; g < geometries.size(); g++) + { + RW::BSGeometryBounds& bounds = geometries[g]->geometryBounds; + boundingRadius = std::max(boundingRadius, glm::length(bounds.center) + bounds.radius); + } +} diff --git a/code/validation/C++/0049432_bookmark_index.cc b/code/validation/C++/0049432_bookmark_index.cc new file mode 100644 index 0000000000000000000000000000000000000000..18c31340c035617c07fff0199d0821e009fab22a --- /dev/null +++ b/code/validation/C++/0049432_bookmark_index.cc @@ -0,0 +1,239 @@ +// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/bookmarks/bookmark_index.h" + +#include +#include + +#include "app/l10n_util.h" +#include "chrome/browser/bookmarks/bookmark_model.h" +#include "chrome/browser/bookmarks/bookmark_utils.h" +#include "chrome/browser/history/history_database.h" +#include "chrome/browser/history/query_parser.h" +#include "chrome/browser/profile.h" + +BookmarkIndex::NodeSet::const_iterator + BookmarkIndex::Match::nodes_begin() const { + return nodes.empty() ? terms.front()->second.begin() : nodes.begin(); +} + +BookmarkIndex::NodeSet::const_iterator BookmarkIndex::Match::nodes_end() const { + return nodes.empty() ? terms.front()->second.end() : nodes.end(); +} + +void BookmarkIndex::Add(const BookmarkNode* node) { + if (!node->is_url()) + return; + std::vector terms = ExtractQueryWords(node->GetTitle()); + for (size_t i = 0; i < terms.size(); ++i) + RegisterNode(terms[i], node); +} + +void BookmarkIndex::Remove(const BookmarkNode* node) { + if (!node->is_url()) + return; + + std::vector terms = ExtractQueryWords(node->GetTitle()); + for (size_t i = 0; i < terms.size(); ++i) + UnregisterNode(terms[i], node); +} + +void BookmarkIndex::GetBookmarksWithTitlesMatching( + const std::wstring& query, + size_t max_count, + std::vector* results) { + std::vector terms = ExtractQueryWords(query); + if (terms.empty()) + return; + + Matches matches; + for (size_t i = 0; i < terms.size(); ++i) { + if (!GetBookmarksWithTitleMatchingTerm(terms[i], i == 0, &matches)) + return; + } + + NodeTypedCountPairs node_typed_counts; + SortMatches(matches, &node_typed_counts); + + // We use a QueryParser to fill in match positions for us. It's not the most + // efficient way to go about this, but by the time we get here we know what + // matches and so this shouldn't be performance critical. + QueryParser parser; + ScopedVector query_nodes; + parser.ParseQuery(query, &query_nodes.get()); + + // The highest typed counts should be at the beginning of the results vector + // so that the best matches will always be included in the results. The loop + // that calculates result relevance in HistoryContentsProvider::ConvertResults + // will run backwards to assure higher relevance will be attributed to the + // best matches. + for (NodeTypedCountPairs::const_iterator i = node_typed_counts.begin(); + i != node_typed_counts.end() && results->size() < max_count; ++i) + AddMatchToResults(i->first, &parser, query_nodes.get(), results); +} + +void BookmarkIndex::SortMatches(const Matches& matches, + NodeTypedCountPairs* node_typed_counts) const { + HistoryService* const history_service = profile_ ? + profile_->GetHistoryService(Profile::EXPLICIT_ACCESS) : NULL; + + history::URLDatabase* url_db = history_service ? + history_service->InMemoryDatabase() : NULL; + + for (Matches::const_iterator i = matches.begin(); i != matches.end(); ++i) + ExtractBookmarkNodePairs(url_db, *i, node_typed_counts); + + std::sort(node_typed_counts->begin(), node_typed_counts->end(), + &NodeTypedCountPairSortFunc); +} + +void BookmarkIndex::ExtractBookmarkNodePairs( + history::URLDatabase* url_db, + const Match& match, + NodeTypedCountPairs* node_typed_counts) const { + + for (NodeSet::const_iterator i = match.nodes_begin(); + i != match.nodes_end(); ++i) { + history::URLRow url; + if (url_db) + url_db->GetRowForURL((*i)->GetURL(), &url); + NodeTypedCountPair pair(*i, url.typed_count()); + node_typed_counts->push_back(pair); + } +} + +void BookmarkIndex::AddMatchToResults( + const BookmarkNode* node, + QueryParser* parser, + const std::vector& query_nodes, + std::vector* results) { + bookmark_utils::TitleMatch title_match; + // Check that the result matches the query. The previous search + // was a simple per-word search, while the more complex matching + // of QueryParser may filter it out. For example, the query + // ["thi"] will match the bookmark titled [Thinking], but since + // ["thi"] is quoted we don't want to do a prefix match. + if (parser->DoesQueryMatch(node->GetTitle(), query_nodes, + &(title_match.match_positions))) { + title_match.node = node; + results->push_back(title_match); + } +} + +bool BookmarkIndex::GetBookmarksWithTitleMatchingTerm(const std::wstring& term, + bool first_term, + Matches* matches) { + Index::const_iterator i = index_.lower_bound(term); + if (i == index_.end()) + return false; + + if (!QueryParser::IsWordLongEnoughForPrefixSearch(term)) { + // Term is too short for prefix match, compare using exact match. + if (i->first != term) + return false; // No bookmarks with this term. + + if (first_term) { + Match match; + match.terms.push_back(i); + matches->push_back(match); + return true; + } + CombineMatchesInPlace(i, matches); + } else if (first_term) { + // This is the first term and we're doing a prefix match. Loop through + // index adding all entries that start with term to matches. + while (i != index_.end() && + i->first.size() >= term.size() && + term.compare(0, term.size(), i->first, 0, term.size()) == 0) { + Match match; + match.terms.push_back(i); + matches->push_back(match); + ++i; + } + } else { + // Prefix match and not the first term. Loop through index combining + // current matches in matches with term, placing result in result. + Matches result; + while (i != index_.end() && + i->first.size() >= term.size() && + term.compare(0, term.size(), i->first, 0, term.size()) == 0) { + CombineMatches(i, *matches, &result); + ++i; + } + matches->swap(result); + } + return !matches->empty(); +} + +void BookmarkIndex::CombineMatchesInPlace(const Index::const_iterator& index_i, + Matches* matches) { + for (size_t i = 0; i < matches->size(); ) { + Match* match = &((*matches)[i]); + NodeSet intersection; + std::set_intersection(match->nodes_begin(), match->nodes_end(), + index_i->second.begin(), index_i->second.end(), + std::inserter(intersection, intersection.begin())); + if (intersection.empty()) { + matches->erase(matches->begin() + i); + } else { + match->terms.push_back(index_i); + match->nodes.swap(intersection); + ++i; + } + } +} + +void BookmarkIndex::CombineMatches(const Index::const_iterator& index_i, + const Matches& current_matches, + Matches* result) { + for (size_t i = 0; i < current_matches.size(); ++i) { + const Match& match = current_matches[i]; + NodeSet intersection; + std::set_intersection(match.nodes_begin(), match.nodes_end(), + index_i->second.begin(), index_i->second.end(), + std::inserter(intersection, intersection.begin())); + if (!intersection.empty()) { + result->push_back(Match()); + Match& combined_match = result->back(); + combined_match.terms = match.terms; + combined_match.terms.push_back(index_i); + combined_match.nodes.swap(intersection); + } + } +} + +std::vector BookmarkIndex::ExtractQueryWords( + const std::wstring& query) { + std::vector terms; + if (query.empty()) + return terms; + QueryParser parser; + // TODO: use ICU normalization. + parser.ExtractQueryWords(l10n_util::ToLower(query), &terms); + return terms; +} + +void BookmarkIndex::RegisterNode(const std::wstring& term, + const BookmarkNode* node) { + if (std::find(index_[term].begin(), index_[term].end(), node) != + index_[term].end()) { + // We've already added node for term. + return; + } + index_[term].insert(node); +} + +void BookmarkIndex::UnregisterNode(const std::wstring& term, + const BookmarkNode* node) { + Index::iterator i = index_.find(term); + if (i == index_.end()) { + // We can get here if the node has the same term more than once. For + // example, a bookmark with the title 'foo foo' would end up here. + return; + } + i->second.erase(node); + if (i->second.empty()) + index_.erase(i); +} diff --git a/code/validation/C++/0049608_dvbt_demod_reference_signals_impl.cc b/code/validation/C++/0049608_dvbt_demod_reference_signals_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..e9ee86436b78569f3e82438cd9761d60af949d88 --- /dev/null +++ b/code/validation/C++/0049608_dvbt_demod_reference_signals_impl.cc @@ -0,0 +1,152 @@ +/* -*- c++ -*- */ +/* + * Copyright 2015 Free Software Foundation, Inc. + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3, or (at your option) + * any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "dvbt_demod_reference_signals_impl.h" + +namespace gr { + namespace dtv { + + dvbt_demod_reference_signals::sptr + dvbt_demod_reference_signals::make(int itemsize, int ninput, int noutput, \ + dvb_constellation_t constellation, dvbt_hierarchy_t hierarchy, \ + dvb_code_rate_t code_rate_HP, dvb_code_rate_t code_rate_LP, \ + dvb_guardinterval_t guard_interval, dvbt_transmission_mode_t transmission_mode, \ + int include_cell_id, int cell_id) + { + return gnuradio::get_initial_sptr + (new dvbt_demod_reference_signals_impl(itemsize, ninput, \ + noutput, constellation, hierarchy, code_rate_HP, code_rate_LP, \ + guard_interval, transmission_mode, include_cell_id, cell_id)); + } + + /* + * The private constructor + */ + dvbt_demod_reference_signals_impl::dvbt_demod_reference_signals_impl(int itemsize, int ninput, int noutput, \ + dvb_constellation_t constellation, dvbt_hierarchy_t hierarchy, dvb_code_rate_t code_rate_HP,\ + dvb_code_rate_t code_rate_LP, dvb_guardinterval_t guard_interval,\ + dvbt_transmission_mode_t transmission_mode, int include_cell_id, int cell_id) + : block("dvbt_demod_reference_signals", + io_signature::make(1, 1, itemsize * ninput), + io_signature::make(1, 1, itemsize * noutput)), + config(constellation, hierarchy, code_rate_HP, code_rate_LP, \ + guard_interval, transmission_mode, include_cell_id, cell_id), + d_pg(config), + d_init(0), + d_fi_start(0) + { + d_ninput = ninput; + d_noutput = noutput; + + // TODO - investigate why this is happening + if ((config.d_constellation == MOD_64QAM) && (config.d_transmission_mode == T8k)) + d_fi_start = 2; + else + d_fi_start = 3; + } + + /* + * Our virtual destructor. + */ + dvbt_demod_reference_signals_impl::~dvbt_demod_reference_signals_impl() + { + } + + void + dvbt_demod_reference_signals_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required) + { + int ninputs = ninput_items_required.size(); + + for (int i = 0; i < ninputs; i++) + ninput_items_required[i] = 2 * noutput_items; + } + + int + dvbt_demod_reference_signals_impl::is_sync_start(int nitems) + { + std::vector tags; + const uint64_t nread = this->nitems_read(0); //number of items read on port 0 + this->get_tags_in_range(tags, 0, nread, nread + nitems, pmt::string_to_symbol("sync_start")); + + return tags.size() ? 1 : 0; + } + + int + dvbt_demod_reference_signals_impl::general_work (int noutput_items, + gr_vector_int &ninput_items, + gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) + { + const gr_complex *in = (const gr_complex *) input_items[0]; + gr_complex *out = (gr_complex *) output_items[0]; + + int symbol_index, frame_index; + int to_out = 0; + + for (int i = 0; i < noutput_items; i++) { + to_out += d_pg.parse_input(&in[i * d_ninput], &out[i * d_noutput], &symbol_index, &frame_index); + } + + /* + * Wait for a sync_start tag from upstream that signals when to start. + * Allways consume until to a superframe start. + */ + if (is_sync_start(noutput_items)) { + d_init = 0; + } + + if (d_init == 0) { + // This is super-frame start + if (((symbol_index % 68) == 0) && ((frame_index % 4) == d_fi_start)) { + d_init = 1; + + const uint64_t offset = this->nitems_written(0); + pmt::pmt_t key = pmt::string_to_symbol("superframe_start"); + pmt::pmt_t value = pmt::from_long(0xaa); + this->add_item_tag(0, offset, key, value); + } + else { + consume_each(1); + return (0); + } + } + + // Send a tag for each OFDM symbol informing about + // symbol index. + const uint64_t offset = this->nitems_written(0); + pmt::pmt_t key = pmt::string_to_symbol("symbol_index"); + pmt::pmt_t value = pmt::from_long(symbol_index); + this->add_item_tag(0, offset, key, value); + + // Consume from input stream + consume_each (noutput_items); + + // Tell runtime system how many output items we produced. + return to_out; + } + + } /* namespace dtv */ +} /* namespace gr */ + diff --git a/code/validation/C++/0050094_TSVecTDMatMult.cpp b/code/validation/C++/0050094_TSVecTDMatMult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38a363b79ad50bb7312f8f55513ce34a711cba13 --- /dev/null +++ b/code/validation/C++/0050094_TSVecTDMatMult.cpp @@ -0,0 +1,297 @@ +//================================================================================================= +/*! +// \file src/blaze/TSVecTDMatMult.cpp +// \brief Source file for the transpose sparse vector/transpose dense matrix multiplication benchmark +// +// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved +// +// This file is part of the Blaze library. You can redistribute it and/or modify it under +// the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors +// may be used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +// DAMAGE. +*/ +//================================================================================================= + + +//************************************************************************************************* +// Includes +//************************************************************************************************* + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +//************************************************************************************************* +// Using declarations +//************************************************************************************************* + +using blazemark::Benchmarks; +using blazemark::DynamicSparseRun; +using blazemark::Parser; + + + + +//================================================================================================= +// +// TYPE DEFINITIONS +// +//================================================================================================= + +//************************************************************************************************* +/*!\brief Type of a benchmark run. +// +// This type definition specifies the type of a single benchmark run for the transpose sparse +// vector/transpose dense matrix multiplication benchmark. +*/ +typedef DynamicSparseRun Run; +//************************************************************************************************* + + + + +//================================================================================================= +// +// UTILITY FUNCTIONS +// +//================================================================================================= + +//************************************************************************************************* +/*!\brief Estimating the necessary number of steps for each benchmark. +// +// \param run The parameters for the benchmark run. +// \return void +// +// This function estimates the necessary number of steps for the given benchmark based on the +// performance of the Blaze library. +*/ +void estimateSteps( Run& run ) +{ + using blazemark::element_t; + using blaze::rowVector; + using blaze::columnMajor; + + ::blaze::setSeed( ::blazemark::seed ); + + const size_t N( run.getSize() ); + const size_t F( run.getNonZeros() ); + + blaze::CompressedVector a( N, F ); + blaze::DynamicMatrix A( N, N ); + blaze::DynamicVector b( N ); + blaze::timing::WcTimer timer; + double wct( 0.0 ); + size_t steps( 1UL ); + + blazemark::blaze::init( a, F ); + blazemark::blaze::init( A ); + + while( true ) { + timer.start(); + for( size_t i=0UL; i= 0.2 ) break; + steps *= 2UL; + } + + if( b.size() != N ) + std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n"; + + run.setSteps( blaze::max( 1UL, ( blazemark::runtime * steps ) / timer.last() ) ); +} +//************************************************************************************************* + + +//************************************************************************************************* +/*!\brief Estimating the necessary number of floating point operations. +// +// \param run The parameters for the benchmark run. +// \return void +// +// This function estimates the number of floating point operations required for a single +// computation of the (composite) arithmetic operation. +*/ +void estimateFlops( Run& run ) +{ + const size_t N( run.getSize() ); + const size_t F( run.getNonZeros() ); + + run.setFlops( 2UL*N*F - N ); +} +//************************************************************************************************* + + + + +//================================================================================================= +// +// BENCHMARK FUNCTIONS +// +//================================================================================================= + + +//************************************************************************************************* +/*!\brief Transpose sparse vector/transpose dense matrix multiplication benchmark function. +// +// \param runs The specified benchmark runs. +// \param benchmarks The selection of benchmarks. +// \return void +*/ +void tsvectdmatmult( std::vector& runs, Benchmarks benchmarks ) +{ + std::cout << std::left; + + std::sort( runs.begin(), runs.end() ); + + size_t slowSize( blaze::inf ); + for( std::vector::iterator run=runs.begin(); run!=runs.end(); ++run ) + { + estimateFlops( *run ); + + if( run->getSteps() == 0UL ) { + if( run->getSize() < slowSize ) { + estimateSteps( *run ); + if( run->getSteps() == 1UL ) + slowSize = run->getSize(); + } + else run->setSteps( 1UL ); + } + } + + if( benchmarks.runBlaze ) { + std::vector::iterator run=runs.begin(); + while( run != runs.end() ) { + const float fill( run->getFillingDegree() ); + std::cout << " Blaze (" << fill << "% filled) [MFlop/s]:\n"; + for( ; run!=runs.end(); ++run ) { + if( run->getFillingDegree() != fill ) break; + const size_t N ( run->getSize() ); + const size_t F ( run->getNonZeros() ); + const size_t steps( run->getSteps() ); + run->setBlazeResult( blazemark::blaze::tsvectdmatmult( N, F, steps ) ); + const double mflops( run->getFlops() * steps / run->getBlazeResult() / 1E6 ); + std::cout << " " << std::setw(12) << N << mflops << std::endl; + } + } + } + + if( benchmarks.runBoost ) { + std::vector::iterator run=runs.begin(); + while( run != runs.end() ) { + const float fill( run->getFillingDegree() ); + std::cout << " Boost uBLAS (" << fill << "% filled) [MFlop/s]:\n"; + for( ; run!=runs.end(); ++run ) { + if( run->getFillingDegree() != fill ) break; + const size_t N ( run->getSize() ); + const size_t F ( run->getNonZeros() ); + const size_t steps( run->getSteps() ); + run->setBoostResult( blazemark::boost::tsvectdmatmult( N, F, steps ) ); + const double mflops( run->getFlops() * steps / run->getBoostResult() / 1E6 ); + std::cout << " " << std::setw(12) << N << mflops << std::endl; + } + } + } + + for( std::vector::iterator run=runs.begin(); run!=runs.end(); ++run ) { + std::cout << *run; + } +} +//************************************************************************************************* + + + + +//================================================================================================= +// +// MAIN FUNCTION +// +//================================================================================================= + +//************************************************************************************************* +/*!\brief The main function for the transpose sparse vector/transpose dense matrix multiplication +// benchmark. +// +// \param argc The total number of command line arguments. +// \param argv The array of command line arguments. +// \return void +*/ +int main( int argc, char** argv ) +{ + std::cout << "\n Transpose Sparse Vector/Transpose Dense Matrix Multiplication:\n"; + + Benchmarks benchmarks; + + try { + parseCommandLineArguments( argc, argv, benchmarks ); + } + catch( std::exception& ex ) { + std::cerr << " " << ex.what() << "\n"; + return EXIT_FAILURE; + } + + const std::string installPath( INSTALL_PATH ); + const std::string parameterFile( installPath + "/params/tsvectdmatmult.prm" ); + Parser parser; + std::vector runs; + + try { + parser.parse( parameterFile.c_str(), runs ); + } + catch( std::exception& ex ) { + std::cerr << " Error during parameter extraction: " << ex.what() << "\n"; + return EXIT_FAILURE; + } + + try { + tsvectdmatmult( runs, benchmarks ); + } + catch( std::exception& ex ) { + std::cerr << " Error during benchmark execution: " << ex.what() << "\n"; + return EXIT_FAILURE; + } +} +//************************************************************************************************* diff --git a/code/validation/C++/0050505_detect-multiscale.cpp b/code/validation/C++/0050505_detect-multiscale.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4024f8c083b156479c387350b213f06bbed43236 --- /dev/null +++ b/code/validation/C++/0050505_detect-multiscale.cpp @@ -0,0 +1,167 @@ +#include +#include +#include + +#include +#include + +#include +#include +#include + +using namespace cv; +using namespace std; + +char iKey = 0; + +int detect( string imagePath, string cascadePath, vector & rois, int minNbr, bool equalize, bool greyscale, int aspect_x, int aspect_y, bool interactive, string windowName) { + Mat img = imread(imagePath.c_str(),1); + Size sz = img.size(); + if ( sz.height < 1 || sz.width < 1 ) { + return -1; + } + CascadeClassifier cascade; + + if (cascade.load(cascadePath)) { + //vector rois; + //std::vector v; + Mat frame_gray; + cvtColor( img, frame_gray, COLOR_BGR2GRAY ); + equalizeHist( frame_gray, frame_gray ); + cascade.detectMultiScale(frame_gray, rois, 1.2, minNbr, CV_HAAR_FIND_BIGGEST_OBJECT, Size(aspect_x, aspect_y), Size((aspect_x*70),(aspect_y*70))); + //rois = &v; + if ( interactive ) { + for (int i = 0; i < rois.size(); i++) { + Rect r = rois[i]; + rectangle(img, r, Scalar(0,255,0), 2); + } + imshow( windowName, img ); + iKey=waitKey(0); + if (iKey == 27 ) { + img.release(); + exit(1); + } + } + + } + img.release(); + return 0; +} + +void printJSON(string imagePath, vector & rois){ + printf("{\n"); + printf("\"path\": \"%s\",\n", imagePath.c_str()); + printf("\"count\": %zd", rois.size()); + if ( rois.size() > 0 ) { + printf(",\n\"objects\": [\n"); + for (int i = 0; i < rois.size(); i++) { + Rect r = rois[i]; + printf("\t{\"x\": %d, \"y\": %d, \"width\": %d, \"height\": %d }", r.x, r.y, r.width, r.height); + if (i < (rois.size() - 1)) { + printf(",\n"); + } + } + printf("\n\t]"); + } + printf("\n}\n"); +} + +int main (int argc, char** argv) { + + int c; + string optString = "c:n:x:y:ieg"; + string needsArgs = "cxyn"; + string cascadeXML = ""; + string inputNode = ""; + int minNbr = 3; + int aspect_x = 24; + int aspect_y = 24; + bool interactive = false; + bool equalize = false; + bool greyscale = false; + struct stat nodeStat; + struct dirent *dir_entry_p; + string imagePath = ""; + string windowName = "Detect Multiscale"; + bool firstFile = true; + std::vector rois; + + while ( optind < argc) { + if ((c = getopt(argc, argv, optString.c_str())) != -1 ) { + switch (c) + { + case 'c': + cascadeXML = optarg; + break; + case 'i': + interactive = true; + break; + case 'e': + equalize = true; + break; + case 'g': + greyscale = true; + break; + case 'x': + aspect_x = std::stoi(optarg); + break; + case 'y': + aspect_y = std::stoi(optarg); + break; + case 'n': + minNbr = std::stoi(optarg); + break; + case '?': + if (needsArgs.find(optopt) != std::string::npos) + fprintf (stderr, "Option -%c requires an argument.\n", optopt); + else if (isprint (optopt)) + fprintf (stderr, "Unknown option `-%c'.\n", optopt); + else + fprintf (stderr, + "Unknown option character `\\x%x'.\n", + optopt); + return 1; + default: + abort (); + } + } else { + inputNode = argv[optind]; + optind++; + } + } + + // Hit our input node and see what we're dealing with + if( stat(inputNode.c_str(),&nodeStat) == 0 ) { + if( nodeStat.st_mode & S_IFDIR ) { // Directory + DIR *dir_p = opendir( inputNode.c_str() ); + printf("{\n\"files\": [\n" ); + while((dir_entry_p = readdir(dir_p)) != NULL) { + // Skip directories + string relPath = inputNode + "/" + dir_entry_p->d_name; + if ( stat( relPath.c_str(), &nodeStat ) == -1 ) continue; + if (S_ISDIR( nodeStat.st_mode )) continue; + if(!strcmp(dir_entry_p->d_name, "")) continue; + if ( detect(relPath, cascadeXML, rois, minNbr, equalize, greyscale, aspect_x, aspect_y, interactive, windowName) != -1 ) { + if (!firstFile) + printf(",\n"); + printJSON(relPath, rois); + firstFile = false; + } + } + printf("]\n}\n"); + } else if( nodeStat.st_mode & S_IFREG ) { // Single file + detect(inputNode, cascadeXML, rois, minNbr, equalize, greyscale, aspect_x, aspect_y, interactive, windowName); + } else { + fprintf(stderr, "%s is neither a file nor directory\n", inputNode.c_str()); + } + } else { + fprintf(stderr, "Could not open %s\n", inputNode.c_str()); + } + + if (interactive) + destroyWindow(windowName); + + return 0; +} + + diff --git a/code/validation/C++/0053179_qgsmaptoolmovefeature.cpp b/code/validation/C++/0053179_qgsmaptoolmovefeature.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b52dac6e5ab91510a76746b4c9deed34d8faf40 --- /dev/null +++ b/code/validation/C++/0053179_qgsmaptoolmovefeature.cpp @@ -0,0 +1,250 @@ +/*************************************************************************** + qgsmaptoolmovefeature.cpp - map tool for translating features by mouse drag + --------------------- + begin : Juli 2007 + copyright : (C) 2007 by Marco Hugentobler + email : marco dot hugentobler at karto dot baug dot ethz dot ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgisapp.h" +#include "qgsadvanceddigitizingdockwidget.h" +#include "qgsfeatureiterator.h" +#include "qgsgeometry.h" +#include "qgslogger.h" +#include "qgsmapcanvas.h" +#include "qgsmaptoolmovefeature.h" +#include "qgsrubberband.h" +#include "qgstolerance.h" +#include "qgsvectorlayer.h" +#include "qgsvectorlayertools.h" +#include "qgssnapindicator.h" +#include "qgsmapmouseevent.h" + +#include +#include +#include + + +QgsMapToolMoveFeature::QgsMapToolMoveFeature( QgsMapCanvas *canvas, MoveMode mode ) + : QgsMapToolAdvancedDigitizing( canvas, QgisApp::instance()->cadDockWidget() ) + , mSnapIndicator( std::make_unique< QgsSnapIndicator>( canvas ) ) + , mMode( mode ) +{ + mToolName = tr( "Move feature" ); +} + +QgsMapToolMoveFeature::~QgsMapToolMoveFeature() +{ + delete mRubberBand; +} + +void QgsMapToolMoveFeature::cadCanvasMoveEvent( QgsMapMouseEvent *e ) +{ + if ( mRubberBand ) + { + QgsPointXY pointCanvasCoords = e->mapPoint(); + double offsetX = pointCanvasCoords.x() - mStartPointMapCoords.x(); + double offsetY = pointCanvasCoords.y() - mStartPointMapCoords.y(); + mRubberBand->setTranslationOffset( offsetX, offsetY ); + mRubberBand->updatePosition(); + mRubberBand->update(); + mSnapIndicator->setMatch( e->mapPointMatch() ); + } + else + { + mSnapIndicator->setMatch( e->mapPointMatch() ); + } +} + +void QgsMapToolMoveFeature::cadCanvasReleaseEvent( QgsMapMouseEvent *e ) +{ + QgsVectorLayer *vlayer = currentVectorLayer(); + if ( !vlayer || !vlayer->isEditable() ) + { + delete mRubberBand; + mRubberBand = nullptr; + mSnapIndicator->setMatch( QgsPointLocator::Match() ); + cadDockWidget()->clear(); + notifyNotEditableLayer(); + return; + } + + if ( !mRubberBand ) + { + //find first geometry under mouse cursor and store iterator to it + QgsPointXY layerCoords = toLayerCoordinates( vlayer, e->mapPoint() ); + double searchRadius = QgsTolerance::vertexSearchRadius( mCanvas->currentLayer(), mCanvas->mapSettings() ); + QgsRectangle selectRect( layerCoords.x() - searchRadius, layerCoords.y() - searchRadius, + layerCoords.x() + searchRadius, layerCoords.y() + searchRadius ); + + if ( vlayer->selectedFeatureCount() == 0 ) + { + QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( selectRect ).setNoAttributes() ); + + //find the closest feature + QgsGeometry pointGeometry = QgsGeometry::fromPointXY( layerCoords ); + if ( pointGeometry.isNull() ) + { + cadDockWidget()->clear(); + return; + } + + double minDistance = std::numeric_limits::max(); + + QgsFeature cf; + QgsFeature f; + while ( fit.nextFeature( f ) ) + { + if ( f.hasGeometry() ) + { + double currentDistance = pointGeometry.distance( f.geometry() ); + if ( currentDistance < minDistance ) + { + minDistance = currentDistance; + cf = f; + } + } + } + + if ( minDistance == std::numeric_limits::max() ) + { + cadDockWidget()->clear(); + return; + } + + mMovedFeatures.clear(); + mMovedFeatures << cf.id(); //todo: take the closest feature, not the first one... + + mRubberBand = createRubberBand( vlayer->geometryType() ); + mRubberBand->setToGeometry( cf.geometry(), vlayer ); + } + else + { + mMovedFeatures = vlayer->selectedFeatureIds(); + + mRubberBand = createRubberBand( vlayer->geometryType() ); + QgsFeature feat; + QgsFeatureIterator it = vlayer->getSelectedFeatures( QgsFeatureRequest().setNoAttributes() ); + + bool allFeaturesInView = true; + QgsRectangle viewRect = mCanvas->mapSettings().mapToLayerCoordinates( vlayer, mCanvas->extent() ); + + while ( it.nextFeature( feat ) ) + { + mRubberBand->addGeometry( feat.geometry(), vlayer, false ); + + if ( allFeaturesInView && !viewRect.intersects( feat.geometry().boundingBox() ) ) + allFeaturesInView = false; + } + mRubberBand->updatePosition(); + mRubberBand->update(); + + if ( !allFeaturesInView ) + { + // for extra safety to make sure we are not modifying geometries by accident + + int res = QMessageBox::warning( mCanvas, tr( "Move features" ), + tr( "Some of the selected features are outside of the current map view. Would you still like to continue?" ), + QMessageBox::Yes | QMessageBox::No ); + if ( res != QMessageBox::Yes ) + { + mMovedFeatures.clear(); + delete mRubberBand; + mRubberBand = nullptr; + mSnapIndicator->setMatch( QgsPointLocator::Match() ); + return; + } + } + } + + mStartPointMapCoords = e->mapPoint(); + mRubberBand->show(); + } + else + { + // copy and move mode + if ( e->button() != Qt::LeftButton ) + { + cadDockWidget()->clear(); + delete mRubberBand; + mRubberBand = nullptr; + mSnapIndicator->setMatch( QgsPointLocator::Match() ); + return; + } + + QgsPointXY startPointLayerCoords = toLayerCoordinates( ( QgsMapLayer * )vlayer, mStartPointMapCoords ); + QgsPointXY stopPointLayerCoords = toLayerCoordinates( ( QgsMapLayer * )vlayer, e->mapPoint() ); + + double dx = stopPointLayerCoords.x() - startPointLayerCoords.x(); + double dy = stopPointLayerCoords.y() - startPointLayerCoords.y(); + + vlayer->beginEditCommand( mMode == Move ? tr( "Feature moved" ) : tr( "Feature copied and moved" ) ); + + switch ( mMode ) + { + case Move: + for ( QgsFeatureId id : std::as_const( mMovedFeatures ) ) + { + vlayer->translateFeature( id, dx, dy ); + + if ( QgsProject::instance()->topologicalEditing() ) + { + if ( mSnapIndicator && ( mSnapIndicator->match().layer() != nullptr ) ) + { + mSnapIndicator->match().layer()->addTopologicalPoints( vlayer->getGeometry( id ) ); + } + vlayer->addTopologicalPoints( vlayer->getGeometry( id ) ); + } + } + delete mRubberBand; + mRubberBand = nullptr; + mSnapIndicator->setMatch( QgsPointLocator::Match() ); + cadDockWidget()->clear(); + break; + + case CopyMove: + QgsFeatureRequest request; + request.setFilterFids( mMovedFeatures ); + QString *errorMsg = new QString(); + if ( !QgisApp::instance()->vectorLayerTools()->copyMoveFeatures( vlayer, request, dx, dy, errorMsg, QgsProject::instance()->topologicalEditing(), mSnapIndicator->match().layer() ) ) + { + emit messageEmitted( *errorMsg, Qgis::Critical ); + delete mRubberBand; + mRubberBand = nullptr; + mSnapIndicator->setMatch( QgsPointLocator::Match() ); + } + break; + } + + vlayer->endEditCommand(); + vlayer->triggerRepaint(); + } +} + +void QgsMapToolMoveFeature::deactivate() +{ + //delete rubber band + delete mRubberBand; + mRubberBand = nullptr; + mSnapIndicator->setMatch( QgsPointLocator::Match() ); + + QgsMapTool::deactivate(); +} + +void QgsMapToolMoveFeature::keyReleaseEvent( QKeyEvent *e ) +{ + if ( mRubberBand && e->key() == Qt::Key_Escape ) + { + cadDockWidget()->clear(); + delete mRubberBand; + mRubberBand = nullptr; + mSnapIndicator->setMatch( QgsPointLocator::Match() ); + } +} diff --git a/code/validation/C++/0055538_inter4.cc b/code/validation/C++/0055538_inter4.cc new file mode 100644 index 0000000000000000000000000000000000000000..0e8bb8ce7305fff9b1412cd22085d45362fca144 --- /dev/null +++ b/code/validation/C++/0055538_inter4.cc @@ -0,0 +1,18 @@ +#include +#include +#include +#include + +using namespace std; + +int main() +{ + istream_iterator cin_it(cin); + istream_iterator end_of_stream; + vector vec(cin_it, end_of_stream); + sort(vec.begin(), vec.end()); + ostream_iterator output(cout, " "); + unique_copy(vec.begin(), vec.end(), output); + cout << endl; + return 0; +} diff --git a/code/validation/C++/0056605_fetchkey.cc b/code/validation/C++/0056605_fetchkey.cc new file mode 100644 index 0000000000000000000000000000000000000000..c4a06bf4cc1251ba336bc9c046e1f0cbb1e6fe21 --- /dev/null +++ b/code/validation/C++/0056605_fetchkey.cc @@ -0,0 +1,66 @@ +#include "keyfetcher.ih" + +bool SEEPost::KeyFetcher::fetchKey(string &server) { + + int fd; + try { + FBB::ClientSocket conn(server, 9012); + fd = conn.connect(); + } catch (FBB::Errno const &e) { + cout << "I SEE ERROR FOR " << server << endl; + cout << "Error: " << e.what() << endl; + return false; + } + FBB::IFdStream in(fd, 1024*1024); + FBB::OFdStream out(fd, 1024*1024); + + // Send header + out << "SEEPOST RESOLVER " << PROTOCOL_VERSION << endl; + + string response; + + // Get response + getline(in, response); + + if(response != "OK") { + Log::instance() << "Error from resolver: " << response; + return false; + } + + // Send query for key + out << "GET " << server << endl; + + // Response to the query + getline(in, response); + + if(response != "FOUND") { + cout << "Response from keyserver: " << response << endl; + out << "QUIT bye" << endl; + return false; + } + + + int prev = 0; + + ostringstream cert; + while(true) { + int a = in.get(); + if(a == -1) break; + cert << (char)a; + + if(a == '\n' && prev == '\n') break; + prev = a; + } + + out << "QUIT bye" << endl; + + try { + Botan::DataSource_Memory cert_dsm(cert.str()); + d_pubkey = Botan::X509::load_key(cert_dsm); + } catch (Botan::Decoding_Error e) { + cerr << e.what() << endl; + return false; + } + + return true; +} diff --git a/code/validation/C++/0058904_networkTest.cpp b/code/validation/C++/0058904_networkTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcbd8a921a12120aaf5456c4e737897dffe4a45d --- /dev/null +++ b/code/validation/C++/0058904_networkTest.cpp @@ -0,0 +1,111 @@ +/****************************************************************************** + * Copyright (C) 2011 by Jerome Maye * + * jerome.maye@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the Lesser GNU General Public License as published by* + * the Free Software Foundation; either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * Lesser GNU General Public License for more details. * + * * + * You should have received a copy of the Lesser GNU General Public License * + * along with this program. If not, see . * + ******************************************************************************/ + +#include "Platform.h" + +#include + +#include +#include +#include +#include +#include +#include + +using namespace std; + +static vector timeVector; + +static uint32_t getMsCount() { + struct timeval now; + if (gettimeofday(&now, 0L)) { + perror("get_ms_count"); + raise(SIGINT); + return 0; + } + else + return ((now.tv_sec * 1000000) + (now.tv_usec)) / 1000; +} + +static void terminationHandler(int signum, siginfo_t *siginfo, void* data) +{ + double f64Mean = 0; + uint32_t u32Max = 0; + uint32_t u32Min = INT_MAX; + for (uint32_t i = 0; i < timeVector.size(); i++) { + f64Mean += timeVector[i]; + if (timeVector[i] > u32Max) + u32Max = timeVector[i]; + if (timeVector[i] < u32Min) + u32Min = timeVector[i]; + } + f64Mean /= (double)timeVector.size(); + double f64Variance = 0; + for (uint32_t i = 0; i < timeVector.size(); i++) + f64Variance += (timeVector[i] - f64Mean) * (timeVector[i] - f64Mean); + f64Variance /= (double)timeVector.size(); + cout << "Mean time: " << f64Mean << endl; + cout << "Variance time: " << f64Variance << endl; + cout << "Min time: " << u32Min << endl; + cout << "Max time: " << u32Max << endl; + exit(0); +} + +int main(int argc, char **argv) { + if (argc != 3) { + cerr << "Usage: " << argv[0] << " " << endl; + return -1; + } + + Platform proxy(argv[1], atoi(argv[2])); + proxy.open(); + proxy.login("User", "none"); + proxy.configureLocalization(false); + + struct sigaction signal_handling; + signal_handling.sa_sigaction = terminationHandler; + signal_handling.sa_flags = SA_SIGINFO; + + if (sigaction(SIGINT, &signal_handling, NULL)) { + perror("sigaction"); + return -1; + } + + while (1) { + uint32_t u32Before = getMsCount(); + try { + Pose pose = proxy.odometryGetPose(); + } catch (IOException &e) { + cout << "Exception occured" << endl; + cout << "Closing proxy" << endl; + proxy.close(); + cout << "Opening proxy" << endl; + proxy.open(); + cout << "Login proxy" << endl; + proxy.login("User", "none"); + cout << "Confiure loc" << endl; + proxy.configureLocalization(false); + continue; + } + uint32_t u32After = getMsCount(); + timeVector.push_back(u32After - u32Before); + //proxy.motionSetSpeed(0, 0); + } + + return 0; +} diff --git a/code/validation/C++/0059904_vector_cluster.cpp b/code/validation/C++/0059904_vector_cluster.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f75f0959cd37d29c5532870992e3a9250499a2e --- /dev/null +++ b/code/validation/C++/0059904_vector_cluster.cpp @@ -0,0 +1,156 @@ +/* vector_cluster.cpp + * + * Copyright (C) 2014 Santosh Thoduka + * + * This software may be modified and distributed under the terms + * of the MIT license. See the LICENSE file for details. + */ + +#include +#include + +VectorCluster::VectorCluster() +{ +} + +VectorCluster::~VectorCluster() +{ +} + +void VectorCluster::addVector(const cv::Vec4d & vector) +{ + cluster_.push_back(vector); +} + +double VectorCluster::getClosestDistance(const cv::Vec4d &vector) +{ + double min_distance = std::numeric_limits::max(); + for (int i = 0; i < cluster_.size(); i++) + { + double distance = getDistance(vector, cluster_.at(i)); + if (distance < min_distance) + { + min_distance = distance; + } + } + return min_distance; +} +double VectorCluster::getClosestOrientation(const cv::Vec4d &vector) +{ + double min_angular_distance = std::numeric_limits::max(); + for (int i = 0; i < cluster_.size(); i++) + { + double angular_distance = abs(getAngularDistance(vector, cluster_.at(i))); + if (angular_distance < min_angular_distance) + { + min_angular_distance = angular_distance; + } + } + return min_angular_distance; +} + +cv::Point2f VectorCluster::getCentroid() +{ + double x_sum = 0.0; + double y_sum = 0.0; + for (int i = 0; i < cluster_.size(); i++) + { + x_sum += cluster_.at(i)[0]; + y_sum += cluster_.at(i)[1]; + } + x_sum /= cluster_.size(); + y_sum /= cluster_.size(); + cv::Point2f centroid(x_sum, y_sum); + return centroid; +} + +double VectorCluster::getMeanOrientation() +{ + double angle_sum = 0.0; + for (int i = 0; i < cluster_.size(); i++) + { + angle_sum += getAngle(cluster_.at(i)); + } + angle_sum /= cluster_.size(); + return angle_sum; +} + +std::vector VectorCluster::getCluster() +{ + return cluster_; +} + +std::vector VectorCluster::getClusterPoints() +{ + std::vector cluster_points; + for (int i = 0; i < cluster_.size(); i++) + { + cv::Point2f p(cluster_.at(i)[0], cluster_.at(i)[1]); + cluster_points.push_back(p); + } + return cluster_points; +} + +std::vector VectorCluster::getMeanVector() +{ + cv::Point2f centroid = getCentroid(); + double orientation = getMeanOrientation(); + double magnitude = 50.0; + cv::Point2f diff; + diff.x = magnitude * cos(orientation); + diff.y = magnitude * sin(orientation); + std::vector mean_vector; + cv::Vec4d v; + v[0] = centroid.x; + v[1] = centroid.y; + v[2] = diff.x; + v[3] = diff.y; + //std::cout << "centroid: " << v[0] << ", " << v[1] << std::endl; + mean_vector.push_back(v); + return mean_vector; + +} + +int VectorCluster::size() +{ + return cluster_.size(); +} +double VectorCluster::getDistance(const cv::Vec4d &one, const cv::Vec4d &two) +{ + return sqrt((one[0] - two[0])*(one[0] - two[0]) + (one[1] - two[1]) * (one[1] - two[1])); +} + +double VectorCluster::getAngularDistance(const cv::Vec4d &one, const cv::Vec4d &two) +{ + + double angle1 = getAngle(one); + double angle2 = getAngle(two); + return atan2(sin(angle1 - angle2), cos(angle1 - angle2)); +} + +double VectorCluster::getAngle(const cv::Vec4d &vector) +{ + double ang = atan2(vector[3], vector[2]); + if (ang < 0.0) + { + ang += 2 * M_PI; + } + return ang; +} + +void VectorCluster::getMinMax(double &min_x, double &max_x, double &min_y, double &max_y) +{ + min_x = std::numeric_limits::max(); + max_x = -1.0; + min_y = std::numeric_limits::max(); + max_y = -1.0; + for (int i = 0; i < cluster_.size(); i++) + { + double x = cluster_.at(i)[0]; + double y = cluster_.at(i)[1]; + if (x < min_x) min_x = x; + if (y < min_y) min_y = y; + if (x > max_x) max_x = x; + if (y > max_y) max_y = y; + } +} diff --git a/code/validation/C++/0059942_quicksort_p.cpp b/code/validation/C++/0059942_quicksort_p.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d290a11f95b7588164e1a511d83ccb660e531785 --- /dev/null +++ b/code/validation/C++/0059942_quicksort_p.cpp @@ -0,0 +1,135 @@ +/* C++ implementation QuickSort using Lomuto's partition +Scheme.*/ +#include +#include +#include +#include +#include + +using namespace std; + +/* This function takes last element as pivot, places +the pivot element at its correct position in sorted +array, and places all smaller (smaller than pivot) +to left of pivot and all greater elements to right +of pivot */ +int partition(int arr[], int low, int high) +{ + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element + + for (int j = low; j <= high - 1; j++) { + + // If current element is smaller than or + // equal to pivot + if (arr[j] <= pivot) { + + i++; // increment index of smaller element + swap(arr[i], arr[j]); + } + } + swap(arr[i + 1], arr[high]); + return (i + 1); +} + +// Generates Random Pivot, swaps pivot with +// end element and calls the partition function +int partition_r(int arr[], int low, int high) +{ + // Generate a random number in between + // low .. high + int random = low + rand() % (high - low); + + // Swap A[random] with A[high] + swap(arr[random], arr[high]); + + return partition(arr, low, high); +} + + +void quickSort_seq(int arr[], int low, int high) +{ + if (low < high) { + + /* pi is partitioning index, arr[p] is now + at right place */ + int pi = partition_r(arr, low, high); + + // Separately sort elements before + // partition and after partition + + + quickSort_seq(arr, low, pi - 1); + quickSort_seq(arr, pi + 1, high); + + } +} + +/* The main function that implements QuickSort +arr[] --> Array to be sorted, +low --> Starting index, +high --> Ending index */ +void quickSort_par(int arr[], int low, int high) +{ + std::thread t1,t2; + if (low < high) { + + /* pi is partitioning index, arr[p] is now + at right place */ + int pi = partition_r(arr, low, high); + + // Separately sort elements before + // partition and after partition + + // if no of elements in subarray is < 2028 + // switch to sequential quicksort + int K = 1000; + + if ( high-low < K) { + //switch to seq version + quickSort_seq(arr,0, pi-1); + quickSort_seq(arr, pi+1, high); + + } else { + // Use parallelization + std::thread t1(quickSort_par, arr, 0, pi-1); + quickSort_par(arr, pi+1, high); + t1.join(); + } + } +} + + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i = 0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// Driver program to test above functions +int main() +{ + + srand(time(NULL)); + //fill array with large random numbers + int values[100000]; + int n = sizeof(values)/sizeof(values[0]); + generate(values, values+n, []() { return rand()%100; }); + + + auto start = std::chrono::high_resolution_clock::now(); + quickSort_par(values, 0, n - 1); + auto stop = std::chrono::high_resolution_clock::now(); + auto duration = std::chrono::duration_cast(stop-start); + + //printf("Sorted array: \n"); + //printArray(values.data(), n); + + cout << "Sorting took: " << duration.count() + << " microseconds"<< endl; + + return 0; +} diff --git a/code/validation/C++/0060421_StrongestBehaviour.cpp b/code/validation/C++/0060421_StrongestBehaviour.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4781b991779543b4be04ea50124f16f43406a579 --- /dev/null +++ b/code/validation/C++/0060421_StrongestBehaviour.cpp @@ -0,0 +1,88 @@ +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include "StrongestBehaviour.h" + +using namespace gmtl; +using namespace ufo; +using namespace std; + + ufoplugin::StrongestBehaviour::StrongestBehaviour( const std::vector children) +: children(children) +{ +} + +ufoplugin::StrongestBehaviour::~StrongestBehaviour() +{ +} + +SteeringDecision ufoplugin::StrongestBehaviour::yield ( const float elapsedTime) +{ + assert( myPilot != 0 ); + + SteeringDecision retval; + float maxls=0; + // whenever we find a "stronger" Behaviour, use that instead of the current one: + for (vector::const_iterator it = children.begin(); + it != children.end(); ++it) + { + SteeringDecision tmp = (*it)->yield(elapsedTime); + float tmpls = lengthSquared(tmp.direction); + if ( tmpls > maxls ) + { + retval= tmp; + maxls = tmpls; + } + } + + return retval; +} + +void ufoplugin::StrongestBehaviour::print () const +{ + cout << "BEGIN StrongestBehaviour " <::const_iterator it = children.begin(); + it != children.end(); ++it) + { + (*it)->print(); + } + cout << "END StrongestBehaviour" <::const_iterator it = children.begin(); + it != children.end(); ++it) + { + (*it)->registerPilot(p); + } +} + +ufo::Behaviour *ufoplugin::StrongestBehaviourFactory(std::vector children, std::vector > *params) +{ + if ( children.size() == 0 ) + { + cout << "ERROR: StrongestBehaviour without children!\n" << endl; + return 0; + } + if ( params->size() > 0 ) + { + cout << "WARNING: StrongestBehaviour has parameters" << endl; + } + return new StrongestBehaviour(children); +} + +MAKEPLUGIN(BEHAVIOUR, Behaviour, StrongestBehaviour, &ufoplugin::StrongestBehaviourFactory) diff --git a/code/validation/C++/0060444_46_permutations.cpp b/code/validation/C++/0060444_46_permutations.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1648d0e92220ac9a4a39f91d3249476468f1c37 --- /dev/null +++ b/code/validation/C++/0060444_46_permutations.cpp @@ -0,0 +1,62 @@ +#define CATCH_CONFIG_MAIN +#include +#include +#include + +/* ref: + * http://en.cppreference.com/w/cpp/algorithm/next_permutation + */ + +using namespace std; +vector nextPermuate(vector &nums) +{ + if(nums.empty()) return vector({}); + + int size = nums.size(); + int curNum = nums[size-1]; + bool valid(false); + + for(int i=size-2; i>=0; --i) { + if(nums[i] i; --j) { + if(nums[j] > nums[i]) { + std::swap(nums[i], nums[j]); + std::sort(nums.begin()+i+1, nums.end()); + valid = true; + break; + } + } + break; + } + curNum = nums[i]; + } + + if(!valid) return vector({}); + + return nums; +} + +vector> permute(vector &nums) +{ + if(nums.empty()) return vector>({}); + std::sort(nums.begin(), nums.end()); + + vector> res; + res.push_back(nums); + while(!nextPermuate(nums).empty()) { + res.push_back(nums); + } + return res; +} + +TEST_CASE("", "") +{ + /* + vector vec1 = {1,2,3,5,4}; + std::cout<<"nextPermuate:"< vec2 = {1,2,3};//,4,5}; + auto res2 = permute(vec2); + std::cout<<"res2:"< + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/register.h" +#include "kernel/log.h" +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct FsmPass : public Pass { + FsmPass() : Pass("fsm", "extract and optimize finite state machines") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" fsm [options] [selection]\n"); + log("\n"); + log("This pass calls all the other fsm_* passes in a useful order. This performs\n"); + log("FSM extraction and optimization. It also calls opt_clean as needed:\n"); + log("\n"); + log(" fsm_detect unless got option -nodetect\n"); + log(" fsm_extract\n"); + log("\n"); + log(" fsm_opt\n"); + log(" opt_clean\n"); + log(" fsm_opt\n"); + log("\n"); + log(" fsm_expand if got option -expand\n"); + log(" opt_clean if got option -expand\n"); + log(" fsm_opt if got option -expand\n"); + log("\n"); + log(" fsm_recode unless got option -norecode\n"); + log("\n"); + log(" fsm_info\n"); + log("\n"); + log(" fsm_export if got option -export\n"); + log(" fsm_map unless got option -nomap\n"); + log("\n"); + log("Options:\n"); + log("\n"); + log(" -expand, -norecode, -export, -nomap\n"); + log(" enable or disable passes as indicated above\n"); + log("\n"); + log(" -fullexpand\n"); + log(" call expand with -full option\n"); + log("\n"); + log(" -encoding type\n"); + log(" -fm_set_fsm_file file\n"); + log(" -encfile file\n"); + log(" passed through to fsm_recode pass\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + bool flag_nomap = false; + bool flag_norecode = false; + bool flag_nodetect = false; + bool flag_expand = false; + bool flag_fullexpand = false; + bool flag_export = false; + std::string fm_set_fsm_file_opt; + std::string encfile_opt; + std::string encoding_opt; + + log_header(design, "Executing FSM pass (extract and optimize FSM).\n"); + log_push(); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-fm_set_fsm_file" && argidx+1 < args.size() && fm_set_fsm_file_opt.empty()) { + fm_set_fsm_file_opt = " -fm_set_fsm_file " + args[++argidx]; + continue; + } + if (arg == "-encfile" && argidx+1 < args.size() && encfile_opt.empty()) { + encfile_opt = " -encfile " + args[++argidx]; + continue; + } + if (arg == "-encoding" && argidx+1 < args.size() && encoding_opt.empty()) { + encoding_opt = " -encoding " + args[++argidx]; + continue; + } + if (arg == "-nodetect") { + flag_nodetect = true; + continue; + } + if (arg == "-norecode") { + flag_norecode = true; + continue; + } + if (arg == "-nomap") { + flag_nomap = true; + continue; + } + if (arg == "-expand") { + flag_expand = true; + continue; + } + if (arg == "-fullexpand") { + flag_fullexpand = true; + continue; + } + if (arg == "-export") { + flag_export = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + if (!flag_nodetect) + Pass::call(design, "fsm_detect"); + Pass::call(design, "fsm_extract"); + + Pass::call(design, "fsm_opt"); + Pass::call(design, "opt_clean"); + Pass::call(design, "fsm_opt"); + + if (flag_expand || flag_fullexpand) { + Pass::call(design, flag_fullexpand ? "fsm_expand -full" : "fsm_expand"); + Pass::call(design, "opt_clean"); + Pass::call(design, "fsm_opt"); + } + + if (!flag_norecode) + Pass::call(design, "fsm_recode" + fm_set_fsm_file_opt + encfile_opt + encoding_opt); + Pass::call(design, "fsm_info"); + + if (flag_export) + Pass::call(design, "fsm_export"); + + if (!flag_nomap) + Pass::call(design, "fsm_map"); + + log_pop(); + } +} FsmPass; + +PRIVATE_NAMESPACE_END diff --git a/code/validation/C++/0060544_main.cpp b/code/validation/C++/0060544_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b6fac8e8670c5469b8c889c1ce11eaac3ae56c27 --- /dev/null +++ b/code/validation/C++/0060544_main.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) Facebook, Inc. and its affiliates. + * + * 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. + */ + +#include +#include +#include + +#include +#include + +using apache::thrift::test::Client; + +DEFINE_string(host, "::1", "Server host [default: '::1']"); +DEFINE_int32(port, 7777, "Server port [default: 7777]"); +DEFINE_uint32(rps, 100, "Request per second [default: 100]"); +DEFINE_uint32( + duration_s, + 60, + "Number of microseconds a server will spend per request [default: 100ms]"); + +int main(int argc, char* argv[]) { + folly::init(&argc, &argv); + + Client client("::1", FLAGS_port); + + std::atomic loggerEnabled{true}; + std::thread logger([&client, &loggerEnabled] { + auto last = std::chrono::system_clock::now(); + while (loggerEnabled) { + auto sleepTime = std::chrono::seconds(1); + std::this_thread::sleep_for(sleepTime); + auto now = std::chrono::system_clock::now(); + auto elapsed = + std::chrono::duration_cast(now - last); + last = now; + + uint64_t count = client.getResponseCount(); + double rate = + static_cast(client.getSuccess()) / std::max(1UL, count); + + LOG(INFO) << "RPS: " << (client.getResponseCount() / elapsed.count()) + << ", success rate: " << (round(100 * rate) / 100) + << ", success: " << client.getSuccess() + << ", errors: " << client.getError() + << ", Latency p50: " << (client.getLatencyPercentile(0.5)) + << ", p90: " << (client.getLatencyPercentile(0.9)) + << ", p99: " << (client.getLatencyPercentile(0.99)); + client.clearStats(); + } + }); + + auto duration = std::chrono::seconds(FLAGS_duration_s); + LOG(INFO) << "Running load test at " << FLAGS_rps << " RPS for " + << FLAGS_duration_s << "s"; + client.runSynchronously(FLAGS_rps, duration); + + loggerEnabled = false; + logger.join(); + return 0; +} diff --git a/code/validation/C++/0061627_1st_solution.cpp b/code/validation/C++/0061627_1st_solution.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ec5fadfd31ae4a1f2f61dd0e4d61107cb3ed6ea --- /dev/null +++ b/code/validation/C++/0061627_1st_solution.cpp @@ -0,0 +1,141 @@ +/* + +-+ +-+ +-+ + |R| |.| |S| + +-+ +-+ +-+ +*/ + +#include + +#define pii pair +#define sc scanf +#define pf printf +#define Pi 2*acos(0.0) +#define ms(a,b) memset(a, b, sizeof(a)) +#define pb(a) push_back(a) +#define MP make_pair +#define db double +#define ll long long +#define EPS 10E-10 +#define ff first +#define ss second +#define sqr(x) (x)*(x) +#define D(x) cout<<#x " = "<<(x)< +#define DBG pf("Hi\n") +#define MOD 100007 +#define MAX 10000 +#define CIN ios_base::sync_with_stdio(0); cin.tie(0) +#define SZ(a) (int)a.size() +#define sf(a) scanf("%d",&a) +#define sfl(a) scanf("%lld",&a) +#define sff(a,b) scanf("%d %d",&a,&b) +#define sffl(a,b) scanf("%lld %lld",&a,&b) +#define sfff(a,b,c) scanf("%d %d %d",&a,&b,&c) +#define sfffl(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) +#define loop(i,n) for(int i=0;iv,print_ans; +int n=0; + +int L[1000000]; +int I[1000000]; + +int LIS_NlogK() +{ + loop(i,n+2) I[i]=inf; + I[0]=-inf; + + int length=0; + + for(int i=1;i<=n;i++) + { + int low=0, hi=length, mid; + + while(low<=hi) + { + mid=(low+hi)/2; + if(v[i]>I[mid]) + low=mid+1; + else + hi=mid-1; + } + + I[low]=v[i]; + L[i]=low; + length=max(length,low); + } + return length; +} + + +int main() +{ +// freopen("in.txt","r",stdin); + ///freopen("out.txt","w",stdout); + + v.pb(-100000); + + int a; + while(sf(a)==1) + { + n++; + v.pb(a); + } + + int ans=LIS_NlogK(); + + int i; + + int temp=ans; + + for(i=n;i>0;i--) + { + if(L[i]==temp) + { + temp--; + print_ans.pb(v[i]); + break; + } + } + + for(--i;i>0 && temp ;i--) + { + if(v[i]=0;i--) + printf("%d\n",print_ans[i]); + + return 0; +} diff --git a/code/validation/C++/0062445_NextPermutation.cpp b/code/validation/C++/0062445_NextPermutation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b811568cc74685af5605283b41963b46d09da9e --- /dev/null +++ b/code/validation/C++/0062445_NextPermutation.cpp @@ -0,0 +1,65 @@ +/** + * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. + + * If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). + + * The replacement must be in-place, do not allocate extra memory. + + * Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. + * 1,2,3 ¡ú 1,3,2 + * 3,2,1 ¡ú 1,2,3 + * 1,1,5 ¡ú 1,5,1 + */ + +// ¾ßÌå½²½â¼ûEvernoteÖÐLeetCode/NextPermutation + +#include +#include +using namespace std; + +class Solution { +public: + void nextPermutation(vector &num) { + int size = num.size(); + int i; + for (i = size - 1; i >= 1; --i) { + if (num[i - 1] < num[i]) break; + } + if (0 == i) reverse(num.begin(), num.end() - 1); + else { + i--; + int j = size - 1; + while (num[j] <= num[i]) --j; + swap(num[i], num[j]); + reverse(num.begin() + i + 1, num.end() - 1); + } + } +private: + void reverse(vector::iterator it, vector::iterator end) { + while (it < end) swap(*it++, *end--); + } + void swap(int& a, int& b) { + a = a^b; + b = a^b; + a = a^b; + } +}; + +int main(void) { + vector v; + v.push_back(7); + v.push_back(6); + v.push_back(5); + v.push_back(4); + v.push_back(3); + v.push_back(2); + v.push_back(1); + + Solution so; + so.nextPermutation(v); + for (int i = 0; i < v.size(); ++i) + cout << v[i] << " "; + cout << endl; + + return 0; +} \ No newline at end of file diff --git a/code/validation/C++/0063422_simulated_time_controller.cc b/code/validation/C++/0063422_simulated_time_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..a81083b4fb9c66cf404c181667da28f18750807e --- /dev/null +++ b/code/validation/C++/0063422_simulated_time_controller.cc @@ -0,0 +1,227 @@ +/* + * Copyright 2019 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ +#include "test/time_controller/simulated_time_controller.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/strings/string_view.h" +#include "test/time_controller/simulated_process_thread.h" +#include "test/time_controller/simulated_task_queue.h" +#include "test/time_controller/simulated_thread.h" + +namespace webrtc { +namespace { +// Helper function to remove from a std container by value. +template +bool RemoveByValue(C* vec, typename C::value_type val) { + auto it = std::find(vec->begin(), vec->end(), val); + if (it == vec->end()) + return false; + vec->erase(it); + return true; +} +} // namespace + +namespace sim_time_impl { + +SimulatedTimeControllerImpl::SimulatedTimeControllerImpl(Timestamp start_time) + : thread_id_(rtc::CurrentThreadId()), current_time_(start_time) {} + +SimulatedTimeControllerImpl::~SimulatedTimeControllerImpl() = default; + +std::unique_ptr +SimulatedTimeControllerImpl::CreateTaskQueue( + absl::string_view name, + TaskQueueFactory::Priority priority) const { + // TODO(srte): Remove the const cast when the interface is made mutable. + auto mutable_this = const_cast(this); + auto task_queue = std::unique_ptr( + new SimulatedTaskQueue(mutable_this, name)); + ; + mutable_this->Register(task_queue.get()); + return task_queue; +} + +std::unique_ptr SimulatedTimeControllerImpl::CreateProcessThread( + const char* thread_name) { + rtc::CritScope lock(&lock_); + auto process_thread = + std::make_unique(this, thread_name); + Register(process_thread.get()); + return process_thread; +} + +std::unique_ptr SimulatedTimeControllerImpl::CreateThread( + const std::string& name, + std::unique_ptr socket_server) { + auto thread = + std::make_unique(this, name, std::move(socket_server)); + Register(thread.get()); + return thread; +} + +void SimulatedTimeControllerImpl::YieldExecution() { + if (rtc::CurrentThreadId() == thread_id_) { + TaskQueueBase* yielding_from = TaskQueueBase::Current(); + // Since we might continue execution on a process thread, we should reset + // the thread local task queue reference. This ensures that thread checkers + // won't think we are executing on the yielding task queue. It also ensure + // that TaskQueueBase::Current() won't return the yielding task queue. + TokenTaskQueue::CurrentTaskQueueSetter reset_queue(nullptr); + // When we yield, we don't want to risk executing further tasks on the + // currently executing task queue. If there's a ready task that also yields, + // it's added to this set as well and only tasks on the remaining task + // queues are executed. + auto inserted = yielded_.insert(yielding_from); + RTC_DCHECK(inserted.second); + RunReadyRunners(); + yielded_.erase(inserted.first); + } +} + +void SimulatedTimeControllerImpl::RunReadyRunners() { + // Using a dummy thread rather than nullptr to avoid implicit thread creation + // by Thread::Current(). + SimulatedThread::CurrentThreadSetter set_current(dummy_thread_.get()); + rtc::CritScope lock(&lock_); + RTC_DCHECK_EQ(rtc::CurrentThreadId(), thread_id_); + Timestamp current_time = CurrentTime(); + // Clearing |ready_runners_| in case this is a recursive call: + // RunReadyRunners -> Run -> Event::Wait -> Yield ->RunReadyRunners + ready_runners_.clear(); + + // We repeat until we have no ready left to handle tasks posted by ready + // runners. + while (true) { + for (auto* runner : runners_) { + if (yielded_.find(runner->GetAsTaskQueue()) == yielded_.end() && + runner->GetNextRunTime() <= current_time) { + ready_runners_.push_back(runner); + } + } + if (ready_runners_.empty()) + break; + while (!ready_runners_.empty()) { + auto* runner = ready_runners_.front(); + ready_runners_.pop_front(); + // Note that the RunReady function might indirectly cause a call to + // Unregister() which will recursively grab |lock_| again to remove items + // from |ready_runners_|. + runner->RunReady(current_time); + } + } +} + +Timestamp SimulatedTimeControllerImpl::CurrentTime() const { + rtc::CritScope lock(&time_lock_); + return current_time_; +} + +Timestamp SimulatedTimeControllerImpl::NextRunTime() const { + Timestamp current_time = CurrentTime(); + Timestamp next_time = Timestamp::PlusInfinity(); + rtc::CritScope lock(&lock_); + for (auto* runner : runners_) { + Timestamp next_run_time = runner->GetNextRunTime(); + if (next_run_time <= current_time) + return current_time; + next_time = std::min(next_time, next_run_time); + } + return next_time; +} + +void SimulatedTimeControllerImpl::AdvanceTime(Timestamp target_time) { + rtc::CritScope time_lock(&time_lock_); + RTC_DCHECK_GE(target_time, current_time_); + current_time_ = target_time; +} + +void SimulatedTimeControllerImpl::Register(SimulatedSequenceRunner* runner) { + rtc::CritScope lock(&lock_); + runners_.push_back(runner); +} + +void SimulatedTimeControllerImpl::Unregister(SimulatedSequenceRunner* runner) { + rtc::CritScope lock(&lock_); + bool removed = RemoveByValue(&runners_, runner); + RTC_CHECK(removed); + RemoveByValue(&ready_runners_, runner); +} + +void SimulatedTimeControllerImpl::StartYield(TaskQueueBase* yielding_from) { + auto inserted = yielded_.insert(yielding_from); + RTC_DCHECK(inserted.second); +} + +void SimulatedTimeControllerImpl::StopYield(TaskQueueBase* yielding_from) { + yielded_.erase(yielding_from); +} +} // namespace sim_time_impl + +GlobalSimulatedTimeController::GlobalSimulatedTimeController( + Timestamp start_time) + : sim_clock_(start_time.us()), impl_(start_time), yield_policy_(&impl_) { + global_clock_.SetTime(start_time); + auto main_thread = std::make_unique(&impl_); + impl_.Register(main_thread.get()); + main_thread_ = std::move(main_thread); +} + +GlobalSimulatedTimeController::~GlobalSimulatedTimeController() = default; + +Clock* GlobalSimulatedTimeController::GetClock() { + return &sim_clock_; +} + +TaskQueueFactory* GlobalSimulatedTimeController::GetTaskQueueFactory() { + return &impl_; +} + +std::unique_ptr +GlobalSimulatedTimeController::CreateProcessThread(const char* thread_name) { + return impl_.CreateProcessThread(thread_name); +} + +std::unique_ptr GlobalSimulatedTimeController::CreateThread( + const std::string& name, + std::unique_ptr socket_server) { + return impl_.CreateThread(name, std::move(socket_server)); +} + +rtc::Thread* GlobalSimulatedTimeController::GetMainThread() { + return main_thread_.get(); +} + +void GlobalSimulatedTimeController::AdvanceTime(TimeDelta duration) { + rtc::ScopedYieldPolicy yield_policy(&impl_); + Timestamp current_time = impl_.CurrentTime(); + Timestamp target_time = current_time + duration; + RTC_DCHECK_EQ(current_time.us(), rtc::TimeMicros()); + while (current_time < target_time) { + impl_.RunReadyRunners(); + Timestamp next_time = std::min(impl_.NextRunTime(), target_time); + impl_.AdvanceTime(next_time); + auto delta = next_time - current_time; + current_time = next_time; + sim_clock_.AdvanceTimeMicroseconds(delta.us()); + global_clock_.AdvanceTime(delta); + } + // After time has been simulated up until |target_time| we also need to run + // tasks meant to be executed at |target_time|. + impl_.RunReadyRunners(); +} + +} // namespace webrtc diff --git a/code/validation/C++/0063993_main.cpp b/code/validation/C++/0063993_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d01afeea5d7dcb85679374d2bf7983b1359503db --- /dev/null +++ b/code/validation/C++/0063993_main.cpp @@ -0,0 +1,211 @@ +#include +#include +#include +#include +#include +using Striter = std::string::const_iterator; + +class Computer +{ + // Коды ошибок: + // 1 - невалидное выражение + public: + int ErrorCode = 1; + int compute(std::string str) { + s = str.begin(); + end = str.end(); + int res = expr(); + if (bracket_count != 0) + throw std::invalid_argument("Bracket count error"); + return res; + } + using Operation = std::function; + + + protected: + const double + Pi = 3.14, + e = 2.7; + + enum class Lexem + { + nop, + eof, + add = '+', + sub = '-', + mul = '*', + div = '/' + }; + + Striter s, end; + int bracket_count = 0; + int + expr () { + Operation op = add; + Lexem lex = Lexem::add; + int res = term(lex, op); + while (lex != Lexem::eof) { + if (lex == Lexem::add || lex == Lexem::sub) { + Operation op1 = op; + int k = term(lex, op); + res = op1(res, k); + } else { + throw std::invalid_argument("error in expr"); + return 0; + } + } + + return res; + } + + + static inline int + add (int a, int b) + { + return a + b; + } + + + static inline int + sub (int a, int b) + { + return a - b; + } + + + static inline int + mul (int a, int b) + { + return a * b; + } + + + static inline int + divi (int a, int b) + { + if (b == 0) { + throw std::invalid_argument("zero devision"); + } + return a / b; + } + + + + void + skip_trash() + { + while (s != end && isspace(*s)) { + s++; + } + } + + + int + get_number() + { + skip_trash(); + if (s == end) { + throw std::invalid_argument("no number"); + } + bool flag = false; + int value; + int sign = 1; + if (*s == '-') { + s++; + sign = -1; + } + if (*s == '(') { + s++; + bracket_count++; + return expr() * sign; + } + if (*s == 'P') { + if (++s != end && *s == 'i'){ + s++; + return Pi * sign; + } else { + throw std::invalid_argument("bad number"); + } + } + if (*s == 'e') { + s++; + return e * sign; + } + value = 0; + while (s != end && *s <= '9' && *s >= '0') { + value *= 10; + value += *s - '0'; + flag = true; + s++; + } + if (!flag) { + throw std::invalid_argument("bad number"); + } + value *= sign; + return value; + } + + Lexem + next_elem(Operation &op) + { + skip_trash(); + if (s == end) { + return Lexem::eof; + } + char c = *s; + s++; + switch (c) { + case (int)Lexem::add: + op = add; + return Lexem::add; + case (int)Lexem::sub: + op = sub; + return Lexem::sub; + case (int)Lexem::mul: + op = mul; + return Lexem::mul; + case (int)Lexem::div: + op = divi; + return Lexem::div; + case ')': + bracket_count--; + return Lexem::eof; + default: + return Lexem::nop; + } + } + + + int + term (Lexem &lex, Operation &op) { + int n = 0, res = 0; + res = get_number(); + lex = next_elem(op); + while (lex == Lexem::mul || lex == Lexem::div) { + n = get_number(); + res = op(res, n); + lex = next_elem(op); + } + return res; + } + + +}; +int +main(int argc, char *argv[]) +{ + if (argc < 2) { + std::cout << "Usage: " << argv[0] << " Expr." << std::endl; + return 0; + } + + std::string str = std::string(argv[1]); + Computer c = Computer(); + try { + std::cout << c.compute(str) << std::endl; + } catch (std::invalid_argument &e) { + std::cout << e.what() << std::endl; + return c.ErrorCode; + } + return 0; +} diff --git a/code/validation/C++/0066443_cppFunctions.cpp b/code/validation/C++/0066443_cppFunctions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6048b7aaad20aefda87417b587a00d17ea278122 --- /dev/null +++ b/code/validation/C++/0066443_cppFunctions.cpp @@ -0,0 +1,139 @@ +// +// cppFunctions.cpp +// +// Author: Alexandre Brehmer +// @alexnesnes + +/** + With the help of code samples seen on: + - http://stackoverflow.com/questions/1126790/how-to-get-network-adapter-stats-in-linux-mac-osx + - http://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process + - http://mogproject.blogspot.co.uk/2014/09/c-how-to-get-per-core-cpu-usage-in-mac.html + +*/ + + +#include "cppFunctions.h" + +void cppFunctions::getCpu(float* returnTab){ + Ticks prev = updated_ticks_(); + usleep(0.5*1000000); + Ticks t = updated_ticks_(); + unsigned long long int used = (t.used() - prev.used())*2; //the calcul work for a 1s sleep, + unsigned long long int user = (t.usertime - prev.usertime)*2; //so we are waiting 0.5s and adding a x2 on the result + returnTab[0] = (float)used; + returnTab[1] = (float)user; +} + +cppFunctions::Ticks cppFunctions::updated_ticks_() { + unsigned int cpu_count; + processor_cpu_load_info_t cpu_load; + mach_msg_type_number_t cpu_msg_count; + int rc = host_processor_info(mach_host_self( ),PROCESSOR_CPU_LOAD_INFO,&cpu_count, + (processor_info_array_t *) &cpu_load,&cpu_msg_count); + if (rc != 0) { + //printf("Error: failed to scan processor info (rc=%d)\n", rc); + Ticks t = {1,1,1,1}; + return t; + } + unsigned long long int usertime = 0; + unsigned long long int nicetime = 0; + unsigned long long int systemtime = 0; + unsigned long long int idletime = 0; + for(int i=0;i< cpu_count;i++) { + usertime += cpu_load[i].cpu_ticks[CPU_STATE_USER]; + nicetime += cpu_load[i].cpu_ticks[CPU_STATE_NICE]; + systemtime += cpu_load[i].cpu_ticks[CPU_STATE_SYSTEM]; + idletime += cpu_load[i].cpu_ticks[CPU_STATE_IDLE]; + } + Ticks t = {usertime/cpu_count, nicetime/cpu_count, systemtime/cpu_count, idletime/cpu_count}; + return t; +} + +void cppFunctions::getRam(float* returnTab){ + vm_size_t page_size; + mach_port_t mach_port; + mach_msg_type_number_t count; + vm_statistics64_data_t vm_stats; + long long used_memory = 0; + mach_port = mach_host_self(); + count = sizeof(vm_stats) / sizeof(natural_t); + if (KERN_SUCCESS == host_page_size(mach_port, &page_size) && + KERN_SUCCESS == host_statistics64(mach_port, HOST_VM_INFO, + (host_info64_t)&vm_stats, &count)) + { + //long long free_memory = (int64_t)vm_stats.free_count * (int64_t)page_size; + used_memory = ((int64_t)vm_stats.active_count + + (int64_t)vm_stats.inactive_count + + (int64_t)vm_stats.wire_count) * (int64_t)page_size; + } + int mib[2]; + int64_t physical_memory; + mib[0] = CTL_HW; + mib[1] = HW_MEMSIZE; + unsigned long length = sizeof(int64_t); + sysctl(mib, 2, &physical_memory, &length, NULL, 0); + returnTab[0] = physical_memory/1024/1024; + returnTab[1] = used_memory/1024/1024; +} + +void cppFunctions::getNetwork(float* returnTab){ + long long int bytesCountT1[2]; + cppFunctions::getIOByteCount((long long**)&bytesCountT1); + usleep(0.5*1000000); + long long int bytesCountT2[2]; + cppFunctions::getIOByteCount((long long**)&bytesCountT2); + returnTab[0] = (bytesCountT2[0] - bytesCountT1[0])*2; //speed in (bit/s) + returnTab[1] = (bytesCountT2[1] - bytesCountT1[1])*2; //speed out (bit/s) +} + +void cppFunctions::getIOByteCount(long long int* bytesCount[2]) { + bytesCount[0] = 0 ; + bytesCount[1] = 0 ; + int mib[] = {CTL_NET,PF_ROUTE,0,0,NET_RT_IFLIST2, 0}; + size_t len; + if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { + return ; + } + char *buf = (char *)malloc(len); + if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { + return ; + } + char *lim = buf + len; + char *next = NULL; + for (next = buf; next < lim; ) { + struct if_msghdr *ifm = (struct if_msghdr *)next; + next += ifm->ifm_msglen; + if (ifm->ifm_type == RTM_IFINFO2) { + struct if_msghdr2 *if2m = (struct if_msghdr2 *)ifm; + bytesCount[0] += if2m->ifm_data.ifi_ibytes; + bytesCount[1] += if2m->ifm_data.ifi_obytes; + } + } + free(buf); +} + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/code/validation/C++/0066806_10608_-_Friends.cpp b/code/validation/C++/0066806_10608_-_Friends.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5562c9ac3b834592ff3dbf563f24a53467532982 --- /dev/null +++ b/code/validation/C++/0066806_10608_-_Friends.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +using namespace std; + +vector v[30005]; +queue q; +int visited[30005]; +int N; +int bfs(int num) +{ + + int cnt = 1; + q.push(num); + while(!q.empty()) { + for(vector::iterator i = v[q.front()].begin(); i != v[q.front()].end(); i++) { + if(!visited[*i]) { + visited[*i] = 1; + q.push(*i); + cnt++; + } + } + q.pop(); + } + return cnt; +} + +int main(void) +{ + int T, M; + int from, to; + int cnt, max; + scanf("%d", &T); + + while(T--) { + + + max = 0; + for(int i = 0; i < 30005; i++) { + v[i].clear(); + visited[i] = 0; + } + + scanf("%d %d", &N, &M); + + for(int i = 0; i < M; i++) { + scanf("%d %d", &from, &to); + if(find(v[from].begin(), v[from].end(), to) == v[from].end()) + v[from].push_back(to); + if(find(v[to].begin(), v[to].end(), from) == v[to].end()) + v[to].push_back(from); + } + + for(int i = 0; i < N; i++) { + if(!visited[i]) { + visited[i] = 1; + cnt = bfs(i); + } + if(cnt > max) + max = cnt; + } + printf("%d", max); + if(T) + puts(""); + } + + return 0; +} \ No newline at end of file diff --git a/code/validation/C++/0067638_test-runner.cc b/code/validation/C++/0067638_test-runner.cc new file mode 100644 index 0000000000000000000000000000000000000000..e8bf122d468cf2d5f50e7e11c753e4f73bb85c31 --- /dev/null +++ b/code/validation/C++/0067638_test-runner.cc @@ -0,0 +1,279 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2009 University of Washington + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation; + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "ns3/test.h" + +#include +#include +#include + +using namespace ns3; + +// +// Run one of the test suites. Returns an integer with the boolean sense of +// "an error has occurred." That is, 0 == false -> no error; 1 == true -> an +// error occurred. +// +int +main (int argc, char *argv[]) +{ + bool doVerbose = false; + bool doList = false; + bool doMultiple = false; + bool doHelp = false; + bool doSuite = false; + bool doKinds = false; + + bool haveBasedir = false; + bool haveTempdir = false; + bool haveOutfile = false; + bool haveType = false; + + std::string suiteName; + std::string basedir; + std::string tempdir; + std::string outfileName; + std::string typeName; + + for (int i = 1; i < argc; ++i) + { + std::string arg(argv[i]); + + if (arg.find ("--basedir=") != std::string::npos) + { + basedir = arg.substr (arg.find_first_of ("=") + 1, 9999); + haveBasedir = true; + } + + if (arg.find ("--constrain=") != std::string::npos) + { + typeName = arg.substr (arg.find_first_of ("=") + 1, 9999); + haveType = true; + } + + if (arg.compare ("--help") == 0) + { + doHelp = true; + } + + if (arg.compare ("--kinds") == 0) + { + doKinds = true; + } + + if (arg.compare ("--list") == 0) + { + doList = true; + } + + if (arg.compare ("--multiple") == 0) + { + doMultiple = true; + } + + if (arg.find ("--out=") != std::string::npos) + { + outfileName = arg.substr (arg.find_first_of ("=") + 1, 9999); + haveOutfile = true; + } + + if (arg.find ("--suite=") != std::string::npos) + { + suiteName = arg.substr (arg.find_first_of ("=") + 1, 9999); + doSuite = true; + } + + if (arg.find ("--tempdir=") != std::string::npos) + { + tempdir = arg.substr (arg.find_first_of ("=") + 1, 9999); + haveTempdir = true; + } + + if (arg.compare ("--verbose") == 0) + { + doVerbose = true; + } + } + + // + // A help request trumps everything else. If we have one, just print the help + // and leave. + // + if (doHelp) + { + std::cout << " --basedir=dir: Set the base directory (where to find src) to \"dir\"" << std::endl; + std::cout << " --tempdir=dir: Set the temporary directory (where to find data files) to \"dir\"" << std::endl; + std::cout << " --constrain=test-type: Constrain checks to test suites of type \"test-type\"" << std::endl; + std::cout << " --help: Print this message" << std::endl; + std::cout << " --kinds: List all of the available kinds of tests" << std::endl; + std::cout << " --list: List all of the test suites (optionally constrained by test-type)" << std::endl; + std::cout << " --multiple: Allow test suites and cases to produce multiple failures" << std::endl; + std::cout << " --out=file-name: Set the test status output file to \"file-name\"" << std::endl; + std::cout << " --suite=suite-name: Run the test suite named \"suite-name\"" << std::endl; + std::cout << " --verbose: Turn on messages in the run test suites" << std::endl; + + return false; + } + + // + // A kinds request trumps everything remaining. If we are asked, just + // print the list of types and leave. + // + if (doKinds) + { + // + // Coming up with a string to represent a test type is completely up to + // us here. We just define the types as being a string composed of the + // enum defined in test.h converted to lower case. + // + std::cout << " bvt: Build Verification Tests (to see if build completed successfully)" << std::endl; + std::cout << " core: Run all TestSuite-based tests (exclude examples)" << std::endl; + std::cout << " example: Examples (to see if example programs run successfully)" << std::endl; + std::cout << " performance: Performance Tests (check to see if the system is as fast as expected)" << std::endl; + std::cout << " system: System Tests (spans modules to check integration of modules)" << std::endl; + std::cout << " unit: Unit Tests (within modules to check basic functionality)" << std::endl; + + return false; + } + + // + // A list request is the first functional request. It trumps running the + // actual tests. If we get a list request, we don't run anything, we just + // do the requested list which may or may not be qualified by a typename. + // + if (doList) + { + for (uint32_t i = 0; i < TestRunner::GetNTestSuites (); ++i) + { + TestSuite *suite = TestRunner::GetTestSuite (i); + + // + // Filter the tests listed by type if requested. The special typeName + // "core" means any TestSuite. + // + if (haveType && typeName != "core") + { + TestSuite::TestType type = suite->GetTestType (); + if (typeName == "bvt" && type != TestSuite::BVT) + { + continue; + } + + if (typeName == "unit" && type != TestSuite::UNIT) + { + continue; + } + + if (typeName == "system" && type != TestSuite::SYSTEM) + { + continue; + } + + if (typeName == "example" && type != TestSuite::EXAMPLE) + { + continue; + } + + if (typeName == "performance" && type != TestSuite::PERFORMANCE) + { + continue; + } + } + + // + // This creates a list of test suite names that can be used by the + // high level test manager to get a list of all tests. It will then + // typically launch individual tests in parallel, calling back here + // with a specific "suite=" to run. + // + std::cout << suite->GetName () << std::endl; + } + + return false; + } + + // + // If we haven't been asked to run a test suite, we are just going to happily + // try and run everything. Test suites are possibly going to need to figure + // out where there source directory is, and to do that they will need to know + // where the base directory of the distribution is (the directory in which + // "src" is found). We could try and run without it, but when it is needed, + // the test will fail with an assertion. So to be safe, we require a basedir + // to proceed. + // + + if (haveBasedir == false) + { + std::cout << "Must specify a base directory to run tests (use --basedir option)" << std::endl; + return true; + } + + // + // If given an output file, we just append the output of each test suite + // we're asked to run to the end of that file. We need to append since the + // higher level test runner may be just running a number of tests back to + // back. We leave it up to that code to decide how to deal with possible + // parallel operation -- we just append to a file here. If no output file + // is specified, we don't do any output and just return the sense of error + // given by the test. + // + std::ofstream *pofs = 0; + std::ofstream ofs; + + if (!outfileName.empty ()) + { + ofs.open (outfileName.c_str (), std::fstream::out | std::fstream::app); + pofs = &ofs; + } + + // + // If we have a specified test suite to run, then we only run that suite. + // The default case is to "run everything. We don't expect this to be done + // much since typically higher level code will be running suites in parallel + // but we'll do it if asked. + // + bool result = false; + bool suiteRan = false; + + for (uint32_t i = 0; i < TestRunner::GetNTestSuites (); ++i) + { + TestSuite *testSuite = TestRunner::GetTestSuite (i); + if (doSuite == false || (doSuite == true && suiteName == testSuite->GetName ())) + { + testSuite->SetBaseDir (basedir); + testSuite->SetTempDir (tempdir); + testSuite->SetStream (pofs); + testSuite->SetVerbose (doVerbose); + testSuite->SetContinueOnFailure (doMultiple); + result |= testSuite->Run (); + suiteRan = true; + } + } + + ofs.close(); + + // + // If we couldn't figure out how to run at least one test, then return an error + // + if (suiteRan == false) + { + return true; + } + + return result; +} diff --git a/code/validation/C++/0067907_5042677_WA.cc b/code/validation/C++/0067907_5042677_WA.cc new file mode 100644 index 0000000000000000000000000000000000000000..0f94b58122393bd81685c049b60cd644a6df87f5 --- /dev/null +++ b/code/validation/C++/0067907_5042677_WA.cc @@ -0,0 +1,205 @@ +/********************************************************************** +* Online Judge : POJ +* Problem Title : Prime Test +* ID : 1811 +* Date : 4/24/2009 +* Time : 22:46:1 +* Computer Name : EVERLASTING-PC +***********************************************************************/ +#include +#include +#include +using namespace std; + +long long n; +int t; + +long long BitLength(long long x) +{ + long long d = 0; + while (x > 0) { + x >>= 1; + d++; + } + return d; +} + +long long BitAt(long long x, long long i) +{ + return ( x & (1 << (i-1)) ); +} + +long long Modular_Expoent(long long a,long long b,long long n) +{ + long long i, y=1; + for(i = BitLength(b); i > 0; i--) + { + y = (y*y)%n; + if(BitAt(b,i) > 0) + y = (y*a)%n; + } + return y; +} + +long long gcd(long long a,long long b) +{ + while(b) + { + long long t=a; + a=b; + b=t%b; + } + return a; +} + +long long Gen_rand(long long range_min,long long range_max) +{ + return (double)rand() / (RAND_MAX + 1) * (range_max - range_min) + + range_min; +} + + +long long Mul64(long long a,long long b,long long c) +{ + if(b<10) + { + return (a*b)%c; + } + return ((Mul64(a,b/2,c)*2)%c+a*(b%2))%c; +} + +/* +int Witness(long long a,long long n) +{ +long long i,x0,x1; +x0=a; +for(i = (long long)ceil(log((double)n-1)/log(2.0))-1; i >= 0; i--) +{ +//x1=Modular_Expoent(x0,2,n); +x1=Mul64(x0,x0,n); +if(x1==1&&x0!=1&&x0!=n-1) +{ +return true; +} +x0=x1; +} +return (x1==1?0:1); +} +*/ + +int Witness(long long a,long long n) +{ + long long i,d=1,x; + for(i = (long long)ceil(log((double)n-1)/log(2.0))-1; i >= 0; i--) + { + x=d, d=Mul64(d,d,n);/*(d*d)%n;*/ + if ((d==1)&&(x!=1)&&(x!=n-1)) + return 1; + if (((n-1)&(1<0) + d=Mul64(d,a,n);/*(d*a)%n;*/ + } + return (d==1?0:1); +} + +long long Miller_Rabin(long long n,long long s) +{ + long long j,a; + for(j = 0; j < s; j++) + { + //a = rand()*(n-2) / RAND_MAX + 1; + a=Gen_rand(1,n-1); + if(Witness(a,n)) + return 0; + } + return 1; +} + +__int64 PollardRho (const __int64 &test) +{ + __int64 y,x,x2,Gcd; + int i,k; + const __int64 &c=1; + y = x =x2= 43; + i = 1; + k = 2; + do + { + i++; + if(i>500000) + { + return -1; + } + Gcd = gcd (2 * test + y - x,test); + if (Gcd > 1 && Gcd < test) + { + return Gcd; + } + if (i == k) + { + y = x; + k *= 2; + } + //x = (x * x + test - c) % test; + //x=(Modular_Expoent(x,2,test) + c)%test; + x=(Mul64(x,x,test)+c)%test; + }while (x != y); + + return test; +} + +/* +long long Pollard_rho(long long n) +{ +srand(time(NULL)); +long long i=1; +long long x=43;//Gen_rand(0,n-1); +long long y=x; +long long k=2; +while(1) +{ +i++; +x=(x*x-1)%n; +long long d=gcd(y>=x?y-x:x-y,n); +if(d!=1&&d!=n) +{ +return d; +break; +} +if(i==k) +{ +y=x; +k<<=1; +} +} +} +*/ +int main() +{ + //freopen("in_1811.txt","r",stdin); + srand(time(NULL)); + //cin>>t; + //cout<>n; + scanf("%I64d",&n); + if(Miller_Rabin(n,3)) + { + printf("Prime\n"); + } + else + { + long long ans=PollardRho(n); + if(ans==-1) + { + printf("Prime\n"); + } + else + { + printf("%I64d\n",ans); + } + } + } + return 0; +} diff --git a/code/validation/C++/0068696_insertsort.cpp b/code/validation/C++/0068696_insertsort.cpp new file mode 100644 index 0000000000000000000000000000000000000000..33e93ed7c48a57f780bf905868a1fc710a0ee51f --- /dev/null +++ b/code/validation/C++/0068696_insertsort.cpp @@ -0,0 +1,24 @@ +#include +#include + +#include "insertsort.hpp" + +using namespace std; + +template +void Swap(T& a, T& b) { + T t = b; + b = a; + a = t; +} + +void insertSort(std::vector &v){ + int j = 0; + for(int i = 1; i < v.size(); i++){ + j = i; + while((j > 0) && v[j-1] > v[j]){ + Swap(v[j-1], v[j]); + j--; + } + } +} diff --git a/code/validation/C++/0068901_EstadisticasCandidatos.cpp b/code/validation/C++/0068901_EstadisticasCandidatos.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a9889caf50ca721d45b10dc67759e87b6de5cba --- /dev/null +++ b/code/validation/C++/0068901_EstadisticasCandidatos.cpp @@ -0,0 +1,130 @@ +#include "EstadisticasCandidatos.h" + +unsigned int SEGUNDOS_PARA_RESETEAR = 86400; //86400 = un dia +using namespace std; + +int EstadisticasCandidatos::limiteCandidatos; +const double EstadisticasCandidatos::porcentajeUsuariosPopulares = 0.01; + +EstadisticasCandidatos::EstadisticasCandidatos(){ + /*thread resetear(resetearDia, this); + resetear.detach(); + */ + this->tiempoInicio = time(NULL); +} + +/* +void EstadisticasCandidatos::resetearDia(EstadisticasCandidatos* estadisticas){ + while(true){ + std::this_thread::sleep_for( (std::chrono::seconds(SEGUNDOS_PARA_RESETEAR))); + Logger::Instance()->log(INFO, "Se resetea el contador de candidatos"); + estadisticas->resetearContadorCandidatos(); + } +} +*/ + +void EstadisticasCandidatos::resetearContadorCandidatos(){ + this->tiempoInicio = time(NULL); + for( map::iterator it = this->estadisticasPorUsuario.begin() ; it != this->estadisticasPorUsuario.end(); ++it){ + it->second.cantidadDeCandidatosPedidos = 0; + } +} + +EstadisticasCandidatos::~EstadisticasCandidatos(){ +} + +int EstadisticasCandidatos::getCantidadVotosPara(string usuario){ + if (this->existeUsuario(usuario)){ + return this->estadisticasPorUsuario[usuario].cantidadDeVotosPositivos; + } + else{ + return 0; + } +} + +string EstadisticasCandidatos::buscarUsuarioPopularConMenosVotos(){ + int votosDeUsuarioPopular = 100000; //Un numero muy grande + string usuarioPopularConMenosVotos = ""; + for( set::iterator it = this->usuariosPopulares.begin() ; it != this->usuariosPopulares.end(); ++it){ + int votosAux = this->getCantidadVotosPara(*it); + if ( votosAux < votosDeUsuarioPopular ){ + usuarioPopularConMenosVotos = (*it); + votosDeUsuarioPopular = votosAux; + } + } + return usuarioPopularConMenosVotos; +} + +void EstadisticasCandidatos::contabilizarVotoPara(string usuario){ + if (this->existeUsuario(usuario)){ + this->estadisticasPorUsuario[usuario].cantidadDeVotosPositivos++; + this->actualizarUsuariosPopulares(usuario); + } +} + +void EstadisticasCandidatos::actualizarUsuariosPopulares(string usuario){ + if (!this->usuarioEsPopular(usuario)){ + string usuarioPopularConMenosVotos = this->buscarUsuarioPopularConMenosVotos(); + if ( (usuarioPopularConMenosVotos != "") && (this->getCantidadVotosPara(usuario) > this->getCantidadVotosPara(usuarioPopularConMenosVotos)) ){ + this->usuariosPopulares.erase(usuarioPopularConMenosVotos); + this->usuariosPopulares.insert(usuario); + Logger::Instance()->log(DEBUG, "El usuario popular eliminado es: " + usuarioPopularConMenosVotos); + Logger::Instance()->log(DEBUG, "El nuevo usuario popular es: " + usuario); + } + } +} + +bool EstadisticasCandidatos::usuarioEsPopular(string usuario){ + return (this->usuariosPopulares.find(usuario) != this->usuariosPopulares.end()); +} + + +void EstadisticasCandidatos::contabilizarCandidatoPara(string usuario){ + if (this->existeUsuario(usuario)){ + this->estadisticasPorUsuario[usuario].cantidadDeCandidatosPedidos++; + } +} + +bool EstadisticasCandidatos::usuarioSuperoLimiteDeCandidatos(string usuario){ + if (!this->existeUsuario(usuario)){ + return false; + } + else{ + time_t segundosTranscurridos = time(NULL) - this->tiempoInicio; + if( segundosTranscurridos >= SEGUNDOS_PARA_RESETEAR ){ + this->resetearContadorCandidatos(); + } + return ( this->estadisticasPorUsuario[usuario].cantidadDeCandidatosPedidos >= limiteCandidatos ); + } +} + + +bool EstadisticasCandidatos::existeUsuario(string usuario){ + return (this->estadisticasPorUsuario.find(usuario) != this->estadisticasPorUsuario.end() ); +} + +void EstadisticasCandidatos::inicializarUsuario(string usuario){ + + if( !this->existeUsuario(usuario)){ + Logger::Instance()->log(INFO, "Se inicializan las estadisticas de " + usuario ); + Estadisticas estadisticas; + estadisticas.cantidadDeCandidatosPedidos = 0; + estadisticas.cantidadDeVotosPositivos = 0; + this->estadisticasPorUsuario[usuario] = estadisticas; + + if ( floor(this->estadisticasPorUsuario.size()*porcentajeUsuariosPopulares) > this->usuariosPopulares.size()){ + //buscar al usuario con mas votos que no este en la lista de los populares y agregarlo a la lista de los populares + string usuarioConMasVotos = ""; + for( map::iterator it = this->estadisticasPorUsuario.begin() ; it != this->estadisticasPorUsuario.end(); ++it){ + string usuarioAux = it->first; + if ( ( this->getCantidadVotosPara(usuarioAux) >= this->getCantidadVotosPara(usuarioConMasVotos)) && + ( !this->usuarioEsPopular(usuarioAux) ) ){ + usuarioConMasVotos = usuarioAux; + } + } + if (usuarioConMasVotos != ""){ + this->usuariosPopulares.insert(usuarioConMasVotos); + } + } + } +} diff --git a/code/validation/C++/0069633_MonotoneChainConvexHull.cpp b/code/validation/C++/0069633_MonotoneChainConvexHull.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eea30d4a17d339fdfa3f967c26c5f21a11b361f9 --- /dev/null +++ b/code/validation/C++/0069633_MonotoneChainConvexHull.cpp @@ -0,0 +1,98 @@ +#include +#include +#include + +typedef int coord_t; + +typedef long long coord2_t; + +struct Point +{ + Point() : + m_x(0), + m_y(0) + { + + } + + Point(const coord_t & p_x, const coord_t & p_y) : + m_x(p_x), + m_y(p_y) + { + + } + + ~Point() + { + + } + + coord_t m_x, m_y; + + bool operator<(const Point & p_point) + { + return (m_x < p_point.m_x) ? m_x < p_point.m_x:(m_x == p_point.m_x ? m_y < p_point.m_y:false); + } + + bool operator>(const Point & p_point) + { + return (m_x > p_point.m_x) ? m_x > p_point.m_x:(m_x == p_point.m_x ? m_y > p_point.m_y:false); + } +}; + +std::vector ConvexHull(std::vector & p_points); + +int main() +{ + srand(static_cast(time(NULL))); + + std::vector points; + + for (int i = 0; i < 32; ++i) + { + points.push_back(Point((-100 + (std::rand() % (100 - (-100)) + 1)), (-100 + (std::rand() % (100 - (-100)) + 1)))); + } + + points = ConvexHull(points); + + return 0; +} + +coord2_t cross(const Point & p_O, const Point & p_A, const Point & p_B) +{ + return ((p_A.m_x - p_O.m_x) * (coord2_t)(p_B.m_y - p_O.m_y) - (p_A.m_y - p_O.m_y) * (coord2_t)(p_B.m_x - p_O.m_x)); +} + +std::vector ConvexHull(std::vector & p_points) +{ + int n = p_points.size(); + int k = 0; + + std::vector H(2*n); + + std::sort(p_points.begin(), p_points.end()); + + + //lower + for (int i = 0; i < n; ++i) + { + while(k >= 2 && cross(H[k-2], H[k-1], p_points[i]) <= 0) + { + k--; + } + H[k++] = p_points[i]; + } + + + //upper + for (int i = n-2, t = k+1; i >= 0; i--) { + while (k >= t && cross(H[k-2], H[k-1], p_points[i]) <= 0) + { + k--; + } + H[k++] = p_points[i]; + } + + H.resize(k); + return H; +} \ No newline at end of file diff --git a/code/validation/C++/0070923_cmd_tracks.cpp b/code/validation/C++/0070923_cmd_tracks.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4010c2c45a71b58b7cbf0ab55fed8b981d71210 --- /dev/null +++ b/code/validation/C++/0070923_cmd_tracks.cpp @@ -0,0 +1,237 @@ +#include "track_analyzing/track.hpp" +#include "track_analyzing/utils.hpp" + +#include "routing_common/car_model.hpp" +#include "routing_common/vehicle_model.hpp" + +#include "routing/edge_estimator.hpp" +#include "routing/geometry.hpp" + +#include "storage/routing_helpers.hpp" +#include "storage/storage.hpp" + +#include "platform/platform.hpp" + +#include "coding/file_name_utils.hpp" + +#include "base/logging.hpp" +#include "base/timer.hpp" + +#include +#include +#include + +using namespace routing; +using namespace std; +using namespace track_analyzing; + +namespace +{ +class TrackStats final +{ +public: + void AddUsers(uint64_t numUsers) { m_numUsers += numUsers; } + void AddTracks(uint64_t numTracks) { m_numTracks += numTracks; } + void AddPoints(uint64_t numPoints) { m_numPoints += numPoints; } + + void Add(TrackStats const & rhs) + { + m_numUsers += rhs.m_numUsers; + m_numTracks += rhs.m_numTracks; + m_numPoints += rhs.m_numPoints; + } + + string GetSummary() const + { + ostringstream out; + out << "users: " << m_numUsers << ", tracks: " << m_numTracks << ", points: " << m_numPoints; + return out.str(); + } + + bool IsEmpty() const { return m_numPoints == 0; } + +private: + uint64_t m_numUsers = 0; + uint64_t m_numTracks = 0; + uint64_t m_numPoints = 0; +}; + +class ErrorStat final +{ +public: + void Add(double value) + { + m_count += 1.0; + m_squares += value * value; + m_min = min(m_min, value); + m_max = max(m_max, value); + } + + double GetStdDev() const + { + CHECK_GREATER(m_count, 1.0, ()); + return std::sqrt(m_squares / (m_count - 1.0)); + } + + string GetStdDevString() const + { + if (m_count <= 1.0) + return "N/A"; + + return to_string(GetStdDev()); + } + + double GetMin() const { return m_min; } + double GetMax() const { return m_max; } + +private: + double m_count = 0.0; + double m_squares = 0.0; + double m_min = numeric_limits::max(); + double m_max = numeric_limits::min(); +}; + +bool TrackHasTrafficPoints(MatchedTrack const & track) +{ + for (MatchedTrackPoint const & point : track) + { + size_t const index = static_cast(point.GetDataPoint().m_traffic); + CHECK_LESS(index, static_cast(traffic::SpeedGroup::Count), ()); + if (traffic::kSpeedGroupThresholdPercentage[index] != 100) + return true; + } + + return false; +} + +double EstimateDuration(MatchedTrack const & track, shared_ptr estimator, + Geometry & geometry) +{ + double result = 0.0; + Segment segment; + + for (MatchedTrackPoint const & point : track) + { + if (point.GetSegment() == segment) + continue; + + segment = point.GetSegment(); + result += estimator->CalcSegmentWeight(segment, geometry.GetRoad(segment.GetFeatureId())); + } + + return result; +} +} // namespace + +namespace track_analyzing +{ +void CmdTracks(string const & filepath, string const & trackExtension, StringFilter mwmFilter, + StringFilter userFilter, TrackFilter const & filter, bool noTrackLogs, + bool noMwmLogs, bool noWorldLogs) +{ + storage::Storage storage; + auto numMwmIds = CreateNumMwmIds(storage); + + map mwmToStats; + ErrorStat absoluteError; + ErrorStat relativeError; + + auto processMwm = [&](string const & mwmName, UserToMatchedTracks const & userToMatchedTracks) { + if (mwmFilter(mwmName)) + return; + + TrackStats & mwmStats = mwmToStats[mwmName]; + + shared_ptr vehicleModel = + CarModelFactory({}).GetVehicleModelForCountry(mwmName); + + Geometry geometry( + GeometryLoader::CreateFromFile(GetCurrentVersionMwmFile(storage, mwmName), vehicleModel)); + + shared_ptr estimator = + EdgeEstimator::Create(VehicleType::Car, *vehicleModel, nullptr /* trafficStash */); + + for (auto it : userToMatchedTracks) + { + string const & user = it.first; + if (userFilter(user)) + continue; + + vector const & tracks = it.second; + if (!noTrackLogs) + cout << mwmName << ", user: " << user << endl; + + bool thereAreUnfilteredTracks = false; + for (MatchedTrack const & track : tracks) + { + DataPoint const & start = track.front().GetDataPoint(); + DataPoint const & finish = track.back().GetDataPoint(); + + double const length = CalcTrackLength(track, geometry); + uint64_t const duration = finish.m_timestamp - start.m_timestamp; + double const speed = CalcSpeedKMpH(length, duration); + bool const hasTrafficPoints = TrackHasTrafficPoints(track); + + if (!filter.Passes(duration, length, speed, hasTrafficPoints)) + continue; + + double const estimatedDuration = EstimateDuration(track, estimator, geometry); + double const timeError = estimatedDuration - static_cast(duration); + + if (!noTrackLogs) + { + cout << fixed << setprecision(1) << " points: " << track.size() << ", length: " << length + << ", duration: " << duration << ", estimated duration: " << estimatedDuration + << ", speed: " << speed << ", traffic: " << hasTrafficPoints + << ", departure: " << base::SecondsSinceEpochToString(start.m_timestamp) + << ", arrival: " << base::SecondsSinceEpochToString(finish.m_timestamp) + << setprecision(numeric_limits::max_digits10) + << ", start: " << start.m_latLon.lat << ", " << start.m_latLon.lon + << ", finish: " << finish.m_latLon.lat << ", " << finish.m_latLon.lon << endl; + } + + mwmStats.AddTracks(1); + mwmStats.AddPoints(track.size()); + absoluteError.Add(timeError); + relativeError.Add(timeError / static_cast(duration)); + thereAreUnfilteredTracks = true; + } + + if (thereAreUnfilteredTracks) + mwmStats.AddUsers(1); + } + }; + + auto processFile = [&](string const & filename, MwmToMatchedTracks const & mwmToMatchedTracks) { + LOG(LINFO, ("Processing", filename)); + ForTracksSortedByMwmName(mwmToMatchedTracks, *numMwmIds, processMwm); + }; + + ForEachTrackFile(filepath, trackExtension, numMwmIds, processFile); + + if (!noMwmLogs) + { + cout << endl; + for (auto const & it : mwmToStats) + { + if (!it.second.IsEmpty()) + cout << it.first << ": " << it.second.GetSummary() << endl; + } + } + + if (!noWorldLogs) + { + TrackStats worldStats; + for (auto const & it : mwmToStats) + worldStats.Add(it.second); + + cout << endl << "World: " << worldStats.GetSummary() << endl; + cout << fixed << setprecision(1) + << "Absolute error: deviation: " << absoluteError.GetStdDevString() + << ", min: " << absoluteError.GetMin() << ", max: " << absoluteError.GetMax() << endl; + cout << fixed << setprecision(3) + << "Relative error: deviation: " << relativeError.GetStdDevString() + << ", min: " << relativeError.GetMin() << ", max: " << relativeError.GetMax() << endl; + } +} +} // namespace track_analyzing diff --git a/code/validation/C++/0071773_CJOJ_2217.cpp b/code/validation/C++/0071773_CJOJ_2217.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b87bcb97db47c7b2f4b70ce578857d30ba4a6b8 --- /dev/null +++ b/code/validation/C++/0071773_CJOJ_2217.cpp @@ -0,0 +1,199 @@ +#include +#include +#include +#include +#include +using namespace std; + +#define mem(Arr,x) memset(Arr,x,sizeof(Arr)) + +class EDGE +{ +public: + int u,v,w; +}; + +bool operator < (EDGE a,EDGE b) +{ + return a.w>n>>m>>K; + cnt=0; + init(); + for (int i=1;i<=n;i++) + Mayuri[i]=i; + for (int i=1;i<=m;i++) + { + scanf("%d%d%d",&Edge[i].u,&Edge[i].v,&Edge[i].w); + } + + sort(&Edge[1],&Edge[m+1]); + + int tot=0; + cnt=0; + for (int i=1;i<=m;i++) + { + int u=Edge[i].u; + int v=Edge[i].v; + int w=Edge[i].w; + if (Find(u)!=Find(v)) + { + tot++; + Union(u,v); + Add_Edge(u,v,w); + Add_Edge(v,u,w); + if (tot>n-1) + break; + } + } + + //cout<<"MST"<>a>>b; + //cout<<"lca "< +#include +#include +#include +#include +#define maxn (100010) +#define left lleft +#define right rright + +using namespace std; + +typedef long long lint; + +int a[maxn], _top, left[maxn], right[maxn]; +pair _stack[maxn]; +lint sum[maxn]; + +int main() +{ + int n, first = 1; + while(cin >> n) + { + if(first) first = 0; + else cout << endl; + for(int i = 1; i <= n; i++) + scanf("%d", &a[i]); + sum[0] = 0; + for(int i = 1; i <= n; i++) + sum[i] = sum[i - 1] + a[i]; + _top = 0; + for(int i = 1; i <= n; i++) + { + while(_top > 0) + { + if(_stack[_top].first < a[i]) + break; + _top--; + } + if(!_top) + left[i] = 0; + else + left[i] = _stack[_top].second; + ++_top; + _stack[_top] = make_pair(a[i], i); + } + _top = 0; + for(int i = n; i >= 1; i--) + { + while(_top > 0) + { + if(_stack[_top].first < a[i]) + break; + _top--; + } + if(!_top) + right[i] = n + 1; + else + right[i] = _stack[_top].second; + ++_top; + _stack[_top] = make_pair(a[i], i); + } + lint o = -1, cmp; + int l, r; + for(int i = 1; i <= n; i++) + { + cmp = (sum[right[i] - 1] - sum[left[i]]) * a[i]; + if(cmp > o) + { + o = cmp; + l = left[i] + 1; + r = right[i] - 1; + } + } + cout << o << endl; + cout << l << " " << r << endl; + } + return 0; +} \ No newline at end of file diff --git a/code/validation/C++/0072381_mitkImageToPointCloudFilter.cpp b/code/validation/C++/0072381_mitkImageToPointCloudFilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..235f5a99726b9294a6d5e0e88e11d0677e46802d --- /dev/null +++ b/code/validation/C++/0072381_mitkImageToPointCloudFilter.cpp @@ -0,0 +1,166 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include "mitkImageToPointCloudFilter.h" + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +mitk::ImageToPointCloudFilter::ImageToPointCloudFilter() : m_NumberOfExtractedPoints(0) +{ + m_Method = DetectionMethod(0); + + this->SetNumberOfRequiredInputs(1); + + this->SetNumberOfIndexedOutputs(1); +} + +mitk::ImageToPointCloudFilter::~ImageToPointCloudFilter() +{ +} + +void mitk::ImageToPointCloudFilter::GenerateData() +{ + mitk::Image::ConstPointer image = ImageToUnstructuredGridFilter::GetInput(); + m_Geometry = image->GetGeometry(); + + if (image.IsNull()) + { + MITK_ERROR << "mitk::ImageToContourFilter: No input available. " + "Please set the input!" + << std::endl; + return; + } + + mitk::Image::Pointer notConstImage = const_cast(image.GetPointer()); + + switch (m_Method) + { + case 0: + AccessByItk_1(notConstImage.GetPointer(), StdDeviations, 2) break; + + case 1: + AccessByItk_1(notConstImage.GetPointer(), StdDeviations, 3) break; + + case 2: + AccessByItk_1(notConstImage.GetPointer(), StdDeviations, 4) break; + + default: + AccessByItk_1(notConstImage.GetPointer(), StdDeviations, 2) break; + } +} + +template +void mitk::ImageToPointCloudFilter::StdDeviations(itk::Image *image, int amount) +{ + typedef itk::Image InputImageType; + typedef itk::CastImageFilter ImagePTypeToFloatPTypeCasterType; + typedef itk::LaplacianImageFilter LaplacianFilterType; + typename LaplacianFilterType::Pointer lapFilter = LaplacianFilterType::New(); + + typename ImagePTypeToFloatPTypeCasterType::Pointer caster = ImagePTypeToFloatPTypeCasterType::New(); + caster->SetInput(image); + caster->Update(); + FloatImageType::Pointer fImage = caster->GetOutput(); + + lapFilter->SetInput(fImage); + lapFilter->UpdateLargestPossibleRegion(); + mitk::Image::Pointer edgeImage = mitk::ImportItkImage(lapFilter->GetOutput()); + + mitk::ImageStatisticsCalculator::Pointer statCalc = + mitk::ImageStatisticsCalculator::New(); + statCalc->SetInputImage(edgeImage); + mitk::ImageStatisticsCalculator::StatisticsContainer::Pointer stats = statCalc->GetStatistics(); + double mean = stats->GetMean(); + double stdDev = stats->GetStd(); + + double upperThreshold = mean + stdDev * amount; + double lowerThreshold = mean - stdDev * amount; + + typename itk::ImageRegionIterator it(lapFilter->GetOutput(), + lapFilter->GetOutput()->GetRequestedRegion()); + + vtkSmartPointer points = vtkSmartPointer::New(); + + double greatX = 0, greatY = 0, greatZ = 0; + + it.GoToBegin(); + while (!it.IsAtEnd()) + { + if (it.Get() > lowerThreshold && it.Get() < upperThreshold) + { + it.Set(0); + } + else + { + it.Set(1); + + mitk::Point3D imagePoint; + mitk::Point3D worldPoint; + + imagePoint[0] = it.GetIndex()[0]; + imagePoint[1] = it.GetIndex()[1]; + imagePoint[2] = it.GetIndex()[2]; + + m_Geometry->IndexToWorld(imagePoint, worldPoint); + + if (worldPoint[0] > greatX) + greatX = worldPoint[0]; + if (worldPoint[1] > greatY) + greatY = worldPoint[1]; + if (worldPoint[2] > greatZ) + greatZ = worldPoint[2]; + + points->InsertNextPoint(worldPoint[0], worldPoint[1], worldPoint[2]); + m_NumberOfExtractedPoints++; + } + ++it; + } + + /*need to build the UnstructuredGrid with at least one vertex otherwise its + not visible*/ + vtkSmartPointer verts = vtkSmartPointer::New(); + + verts->GetPointIds()->SetNumberOfIds(m_NumberOfExtractedPoints); + for (int i = 0; i < m_NumberOfExtractedPoints; i++) + { + verts->GetPointIds()->SetId(i, i); + } + + vtkSmartPointer uGrid = vtkSmartPointer::New(); + uGrid->Allocate(1); + + uGrid->InsertNextCell(verts->GetCellType(), verts->GetPointIds()); + uGrid->SetPoints(points); + + mitk::UnstructuredGrid::Pointer outputGrid = mitk::UnstructuredGrid::New(); + outputGrid->SetVtkUnstructuredGrid(uGrid); + this->SetNthOutput(0, outputGrid); +} + +void mitk::ImageToPointCloudFilter::GenerateOutputInformation() +{ + Superclass::GenerateOutputInformation(); +} diff --git a/code/validation/C++/0073099_PlainTextRange.cpp b/code/validation/C++/0073099_PlainTextRange.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d0b7331c88f13c3fc93344b61a51b3799831046f --- /dev/null +++ b/code/validation/C++/0073099_PlainTextRange.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved. + * Copyright (C) 2005 Alexey Proskuryakov. + * + * 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "core/editing/PlainTextRange.h" + +#include "core/dom/ContainerNode.h" +#include "core/dom/Document.h" +#include "core/dom/Range.h" +#include "core/editing/EphemeralRange.h" +#include "core/editing/VisiblePosition.h" +#include "core/editing/VisibleUnits.h" +#include "core/editing/iterators/TextIterator.h" + +namespace blink { + +PlainTextRange::PlainTextRange() + : m_start(kNotFound) + , m_end(kNotFound) +{ +} + +PlainTextRange::PlainTextRange(int location) + : m_start(location) + , m_end(location) +{ + ASSERT(location >= 0); +} + +PlainTextRange::PlainTextRange(int start, int end) + : m_start(start) + , m_end(end) +{ + ASSERT(start >= 0); + ASSERT(end >= 0); + ASSERT(start <= end); +} + +EphemeralRange PlainTextRange::createRange(const ContainerNode& scope) const +{ + return createRangeFor(scope, ForGeneric); +} + +EphemeralRange PlainTextRange::createRangeForSelection(const ContainerNode& scope) const +{ + return createRangeFor(scope, ForSelection); +} + +EphemeralRange PlainTextRange::createRangeFor(const ContainerNode& scope, GetRangeFor getRangeFor) const +{ + ASSERT(isNotNull()); + + size_t docTextPosition = 0; + bool startRangeFound = false; + + Position textRunStartPosition; + Position textRunEndPosition; + + TextIteratorBehaviorFlags behaviorFlags = TextIteratorEmitsObjectReplacementCharacter; + if (getRangeFor == ForSelection) + behaviorFlags |= TextIteratorEmitsCharactersBetweenAllVisiblePositions; + auto range = EphemeralRange::rangeOfContents(scope); + TextIterator it(range.startPosition(), range.endPosition(), behaviorFlags); + + // FIXME: the atEnd() check shouldn't be necessary, workaround for + // . + if (!start() && !length() && it.atEnd()) + return EphemeralRange(Position(it.currentContainer(), 0)); + + Position resultStart = Position(&scope.document(), 0); + Position resultEnd = resultStart; + + for (; !it.atEnd(); it.advance()) { + int len = it.length(); + + textRunStartPosition = it.startPositionInCurrentContainer(); + textRunEndPosition = it.endPositionInCurrentContainer(); + + bool foundStart = start() >= docTextPosition && start() <= docTextPosition + len; + bool foundEnd = end() >= docTextPosition && end() <= docTextPosition + len; + + // Fix textRunRange->endPosition(), but only if foundStart || foundEnd, because it is only + // in those cases that textRunRange is used. + if (foundEnd) { + // FIXME: This is a workaround for the fact that the end of a run + // is often at the wrong position for emitted '\n's or if the + // layoutObject of the current node is a replaced element. + if (len == 1 && (it.text().characterAt(0) == '\n' || it.isInsideAtomicInlineElement())) { + it.advance(); + if (!it.atEnd()) { + textRunEndPosition = it.startPositionInCurrentContainer(); + } else { + Position runEnd = nextPositionOf(createVisiblePosition(textRunStartPosition)).deepEquivalent(); + if (runEnd.isNotNull()) + textRunEndPosition = runEnd; + } + } + } + + if (foundStart) { + startRangeFound = true; + if (textRunStartPosition.computeContainerNode()->isTextNode()) { + int offset = start() - docTextPosition; + resultStart = Position(textRunStartPosition.computeContainerNode(), offset + textRunStartPosition.offsetInContainerNode()); + } else { + if (start() == docTextPosition) + resultStart = textRunStartPosition; + else + resultStart = textRunEndPosition; + } + } + + if (foundEnd) { + if (textRunStartPosition.computeContainerNode()->isTextNode()) { + int offset = end() - docTextPosition; + resultEnd = Position(textRunStartPosition.computeContainerNode(), offset + textRunStartPosition.offsetInContainerNode()); + } else { + if (end() == docTextPosition) + resultEnd = textRunStartPosition; + else + resultEnd = textRunEndPosition; + } + docTextPosition += len; + break; + } + docTextPosition += len; + } + + if (!startRangeFound) + return EphemeralRange(); + + if (length() && end() > docTextPosition) { // end() is out of bounds + resultEnd = textRunEndPosition; + } + + return EphemeralRange(resultStart.toOffsetInAnchor(), resultEnd.toOffsetInAnchor()); +} + +PlainTextRange PlainTextRange::create(const ContainerNode& scope, const EphemeralRange& range) +{ + if (range.isNull()) + return PlainTextRange(); + + // The critical assumption is that this only gets called with ranges that + // concentrate on a given area containing the selection root. This is done + // because of text fields and textareas. The DOM for those is not + // directly in the document DOM, so ensure that the range does not cross a + // boundary of one of those. + Node* startContainer = range.startPosition().computeContainerNode(); + if (startContainer != &scope && !startContainer->isDescendantOf(&scope)) + return PlainTextRange(); + Node* endContainer = range.endPosition().computeContainerNode(); + if (endContainer != scope && !endContainer->isDescendantOf(&scope)) + return PlainTextRange(); + + size_t start = TextIterator::rangeLength(Position(&const_cast(scope), 0), range.startPosition()); + size_t end = TextIterator::rangeLength(Position(&const_cast(scope), 0), range.endPosition()); + + return PlainTextRange(start, end); +} + +PlainTextRange PlainTextRange::create(const ContainerNode& scope, const Range& range) +{ + return create(scope, EphemeralRange(&range)); +} + +} diff --git a/code/validation/C++/0074040_Bob.cpp b/code/validation/C++/0074040_Bob.cpp new file mode 100644 index 0000000000000000000000000000000000000000..76a355afa5a5ea55115885d082c61df941d420d1 --- /dev/null +++ b/code/validation/C++/0074040_Bob.cpp @@ -0,0 +1,199 @@ +#include +#include +#include +#include +#include + +using namespace std; + +int compare(int i, int j) + { + if (i < j) + return (-1); + if (i == j) + return (0); + if (i > j) + return (1); + } + +int main() + { + int index; + int day; + int turn; + int slash_index; + int to_die; + int num_alive; + int mine_alive; + int turn_to_return; + bool returned; + string line; + vector last_returns; + vector today_returns; + + getline(cin, line); + + if (line.compare(0, 6, "INDEX ") != 0) + { + cerr << "INVALID INDEX LINE \"" << line << "\"" << endl; + + return (-1); + } + + index = atoi(line.substr(6).c_str()) - 1; + + while (1) // Day loop + { + getline(cin, line); + if (line.compare(0, 4, "EXIT") == 0) + { + return (0); + } + else if (line.compare(0, 9, "START_DAY") != 0 || (slash_index = line.find('/')) == string::npos) + { + cerr << "INVALID START_DAY \"" << line << "\"" << endl; + return (-1); + } + + day = atoi(line.substr(10, slash_index - 10).c_str()); + to_die = atoi(line.substr(slash_index + 1, line.length() - slash_index - 1).c_str()); + + if (day != 1) + { + if (to_die > num_alive) + { + turn_to_return = 30; + } + else + { + turn_to_return = last_returns[last_returns.size() - to_die] - 1; + } + } + + returned = false; + + for (turn = 1; turn <= 30; ++turn) + { + getline(cin, line); + + if (line.compare(0, 4, "EXIT") == 0) + { + return (0); + } + if (line.compare(0, 7, "END_DAY") == 0) + { + goto end_day; + } + if (line.compare(0, 10, "START_TURN") != 0) + { + cerr << "INVALID START_TURN \"" << line << "\"" << endl; + } + + if (day == 1) + { + switch (compare(turn, 30)) + { + case -1: + cout << "S,S,S,S,S" << endl; + break; + + case 0: + cout << "R,R,R,R,R" << endl; + break; + + case 1: + cout << "N,N,N,N,N" << endl; + break; + } + } + else + { + if (returned) + { + cout << "N,N,N,N,N" << endl; + } + /* + else if (num_alive - today_returns.size() < to_die) + { + cout << "R,R,R,R,R" << endl; + returned = true; + } + */ + else if (turn >= turn_to_return) + { + cout << "R,R,R,R,R" << endl; + returned = true; + } + else + { + cout << "S,S,S,S,S" << endl; + } + } + + getline(cin, line); + + if (line.compare(0, 4, "EXIT") == 0) + { + return (0); + } + if (line.compare(0, 8, "END_TURN") != 0) + { + cerr << "INVALID END_TURN \"" << line << "\"" << endl; + } + + stringstream ss(line); + string item; + int i = 0; + while (getline(ss, item, ' ')) + { + i++; + if (i > 2 && i - 3 != index) + { + int num_to_add = count(item.begin(), item.end(), 'R'); // Add turn to today_returns for each servant that returned + for (int j = 0; j < num_to_add; j++) + { + today_returns.push_back(turn); + } + } + } + + } + + getline(cin, line); + + end_day: + + if (line.compare(0, 4, "EXIT") == 0) + { + return (0); + } + else if (line.compare(0, 7, "END_DAY") != 0) + { + cerr << "INVALID END_DAY \"" << line << "\"" << endl; + return (-1); + } + + stringstream ss(line); + string item; + int i = 0; + num_alive = 0; + while (getline(ss, item, ' ')) + { + i++; + if (i > 2 && i - 3 != index) + { + num_alive += count(item.begin(), item.end(), 'A'); + } + else if (i - 3 == index) + { + mine_alive = count(item.begin(), item.end(), 'A'); + } + } + + last_returns = today_returns; + today_returns.clear(); + + } + + return (0); + } diff --git a/code/validation/C++/0074218_tile.cpp b/code/validation/C++/0074218_tile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcf80c403275306095ec86844580aa714045113e --- /dev/null +++ b/code/validation/C++/0074218_tile.cpp @@ -0,0 +1,142 @@ +/*============================================================================= + Copyright (c) 2016-2019 Joel de Guzman + + Distributed under the MIT License [ https://opensource.org/licenses/MIT ] +=============================================================================*/ +#include +#include + +namespace cycfi { namespace photon +{ + //////////////////////////////////////////////////////////////////////////// + // Vertical Tiles + //////////////////////////////////////////////////////////////////////////// + view_limits vtile_element::limits(basic_context const& ctx) const + { + view_limits limits{ { 0.0, 0.0 }, { full_extent, 0.0 } }; + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto el = at(ix).limits(ctx); + + limits.min.y += el.min.y; + limits.max.y += el.max.y; + clamp_min(limits.min.x, el.min.x); + clamp_max(limits.max.x, el.max.x); + } + + clamp_min(limits.max.x, limits.min.x); + clamp_max(limits.max.y, full_extent); + return limits; + } + + void vtile_element::layout(context const& ctx) + { + _left = ctx.bounds.left; + _right = ctx.bounds.right; + + _tiles.resize(size()+1); + + double min_y = 0.0; + double max_y = 0.0; + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto el = at(ix).limits(ctx); + min_y += el.min.y; + max_y += el.max.y; + } + + double height = ctx.bounds.height(); + double extra = max_y - height; + double m_size = max_y - min_y; + double curr = ctx.bounds.top; + auto i = _tiles.begin(); + + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto& elem = at(ix); + auto limits = elem.limits(ctx); + + *i++ = curr; + auto prev = curr; + curr += limits.max.y; + + if ((extra != 0) && (m_size != 0)) + curr -= extra * (limits.max.y - limits.min.y) / m_size; + + rect ebounds = { _left, float(prev), _right, float(curr) }; + elem.layout(context{ ctx, &elem, ebounds }); + } + *i = curr; + } + + rect vtile_element::bounds_of(context const& ctx, std::size_t index) const + { + return rect{ _left, _tiles[index], _right, _tiles[index+1] }; + } + + //////////////////////////////////////////////////////////////////////////// + // Horizontal Tiles + //////////////////////////////////////////////////////////////////////////// + view_limits htile_element::limits(basic_context const& ctx) const + { + view_limits limits{ { 0.0, 0.0 }, { 0.0, full_extent } }; + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto el = at(ix).limits(ctx); + + limits.min.x += el.min.x; + limits.max.x += el.max.x; + clamp_min(limits.min.y, el.min.y); + clamp_max(limits.max.y, el.max.y); + } + + clamp_min(limits.max.y, limits.min.y); + clamp_max(limits.max.x, full_extent); + return limits; + } + + void htile_element::layout(context const& ctx) + { + _top = ctx.bounds.top; + _bottom = ctx.bounds.bottom; + + _tiles.resize(size()+1); + + double min_x = 0.0; + double max_x = 0.0; + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto el = at(ix).limits(ctx); + min_x += el.min.x; + max_x += el.max.x; + } + + double width = ctx.bounds.width(); + double extra = max_x - width; + double m_size = max_x - min_x; + double curr = ctx.bounds.left; + auto i = _tiles.begin(); + + for (std::size_t ix = 0; ix != size(); ++ix) + { + auto& elem = at(ix); + auto limits = elem.limits(ctx); + + *i++ = curr; + auto prev = curr; + curr += limits.max.x; + + if ((extra != 0) && (m_size != 0)) + curr -= extra * (limits.max.x - limits.min.x) / m_size; + + rect ebounds = { float(prev), _top, float(curr), _bottom }; + elem.layout(context{ ctx, &elem, ebounds }); + } + *i = curr; + } + + rect htile_element::bounds_of(context const& ctx, std::size_t index) const + { + return rect{ _tiles[index], _top, _tiles[index + 1], _bottom }; + } +}} diff --git a/code/validation/C++/0074915_main.cpp b/code/validation/C++/0074915_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f84a860540c09a9497bab45f1debc163a97b72f7 --- /dev/null +++ b/code/validation/C++/0074915_main.cpp @@ -0,0 +1,89 @@ +#include + +using namespace std; + + +int maxP; +int N; +int sn; +int person[9]; + +int ans[23]; +int maxE; +struct ticket +{ + int s,d,people; +} ticket1[23]; + +void backtrack(int index) +{ + if(index == N) + { + + int sum = 0; + for(int i = 0 ; i maxE) + { + maxE = sum; + } + + return; + } + else + { + + ans[index] = 1; + int ok = 1; + int backup[23]; + for(int j = ticket1[index].s; j < ticket1[index].d;++j) + { + backup[j] = person[j]; + } + for(int j = ticket1[index].s; j < ticket1[index].d;++j) + { + person[j] += ticket1[index].people; + + if(person[j] > maxP) + { + ok = 0; + break; + } + } + if(ok) + backtrack(index+1); + ans[index] = 0; + for(int j = ticket1[index].s; j < ticket1[index].d;++j) + { + person[j] = backup[j] ; + } + backtrack(index+1); + } + return ; +} + +int main() +{ + while((cin >> maxP) && (cin >> sn) && (cin >> N)) + { + if(!maxP && !sn && !N) break; + maxE = 0; + for(int i = 0 ;i < N;++i) + { + cin >> ticket1[i].s; + cin >> ticket1[i].d; + cin >> ticket1[i].people; + ans[i] = 0; + } + for(int i = 0 ; i <= sn;++i) + { + person[i] = 0; + } + backtrack(0); + cout << maxE< +#include +#include +#include +#include +#include +#include + +using namespace std; + +//#define DEBUG //comment this line to pull out print statements +#ifdef DEBUG +#define TAB '\t' +#define debug(a, end) cout << #a << ": " << a << end +#define dbg(end) end +#else +#define debug(a, end) +#define dbg(end) +#endif + +typedef pair point; +typedef long long int64; //for clarity +typedef vector vi; //? +typedef vector vp; //? +template void chmin(T &t, T f) { if (t > f) t = f; } //change min +template void chmax(T &t, T f) { if (t < f) t = f; } //change max + +#define UN(v) SORT(v),v.erase(unique(v.begin(),v.end()),v.end()) +#define SORT(c) sort((c).begin(),(c).end()) +#define FOR(i,a,b) for (int i=(a); i < (b); i++) +#define REP(i,n) FOR(i,0,n) +#define CL(a,b) memset(a,b,sizeof(a)) +#define CL2d(a,b,x,y) memset(a, b, sizeof(a[0][0])*x*y) + +/*global variables*/ +int N; +string line[20]; +/*global variables*/ + +void dump() +{ + //dump data +} + +int c_ws(const string& s) +{ + size_t pos = s.find_first_of(" "); + int count = 0; + while (pos != string::npos) + { + ++count; + pos = s.find_first_of(" ", pos+1); + } + + return count; +} + +bool getInput() +{ + //get input + scanf("%d\n", &N); + if (N == 0) return false; + return true; +} + +void process() +{ + //process input + int min_ws = numeric_limits::max(); + + REP(i, N) + { + getline(cin, line[i]); + debug(line[i], endl); + min_ws = min(c_ws(line[i]), min_ws); + } + debug(min_ws, endl); + int total = 0; + REP(i, N) + total += c_ws(line[i])-min_ws; + + printf("%d\n", total); +} + +int main() +{ + while (getInput()) + { + + process(); + + /*CLEAR GLOBAL VARIABLES!*/ + + /*CLEAR GLOBAL VARIABLES!*/ + } + + return 0; +} diff --git a/code/validation/C++/0077018_ageing_clustered_ba.cpp b/code/validation/C++/0077018_ageing_clustered_ba.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60ae256516df0fb780ccfde81f7b9b83cb744ac7 --- /dev/null +++ b/code/validation/C++/0077018_ageing_clustered_ba.cpp @@ -0,0 +1,202 @@ +/***************************************************************************** + * Copyright (C) 2004-2013 The PaGMO development team, * + * Advanced Concepts Team (ACT), European Space Agency (ESA) * + * http://apps.sourceforge.net/mediawiki/pagmo * + * http://apps.sourceforge.net/mediawiki/pagmo/index.php?title=Developers * + * http://apps.sourceforge.net/mediawiki/pagmo/index.php?title=Credits * + * act@esa.int * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + + +#include "../exceptions.h" +#include "../rng.h" +#include "ageing_clustered_ba.h" +#include "base.h" + +namespace pagmo { namespace topology { + +/// Constructor from kernel size, maximum number of edges, connection probability and maximum node age +/** + * Build a BA network with clustering and ageing mechanisms applied. The initial kernel has size m0 and the elements + * being inserted after the construction of the kernel is completed are connected randomly to a maximum of m nodes. These nodes + * are then connected to eachother with probability p. Nodes cease to make node connections when their 'age' (the number of time + * steps for which they have been a part of the network) is greater than a. + * Will fail if m0 < 2, if m < 1 or if m > m0 or if p < 0 or p > 1 or a < m. + * + * @param[in] m0 size of the kernel + * @param[in] m number of random connections to be established when a new node is added. + * @param[in] p probability that a connection is established between two nodes that are adjacent to a new node. + * @param[in] a 'age' at which a node ceases to make new connections. + */ +ageing_clustered_ba::ageing_clustered_ba(int m0, int m, double p, int a): + m_m0(boost::numeric_cast(m0)),m_m(boost::numeric_cast(m)), m_p(double(p)), m_a(int(a)), + m_drng(rng_generator::get()),m_urng(rng_generator::get()) +{ + if (m0 < 2 || m < 1 || m > m0) { + pagmo_throw(value_error,"the value of m and m0 must be at least 1 and 2, and m must not be greater than m0"); + } + if(a < m) { + pagmo_throw(value_error,"the value a must be greater than the value of m"); + } + if(p < 0 || p > 1) { + pagmo_throw(value_error,"the value of p must be between 0 and 1"); + } +} + + +base_ptr ageing_clustered_ba::clone() const +{ + return base_ptr(new ageing_clustered_ba(*this)); +} + +void ageing_clustered_ba::connect(const vertices_size_type &idx) +{ + pagmo_assert(get_number_of_vertices() > 0); + const vertices_size_type prev_size = get_number_of_vertices() - 1; + if (prev_size < m_m0) { + // If we had not built the initial m0 nodes, do it. + // We want to connect the newcomer island with high probability, and make sure that + // at least one connection exists (otherwise the island stays isolated). + // NOTE: is it worth to make it a user-tunable parameter? + const double prob = 0.0; + // Flag indicating if at least 1 connection was added. + bool connection_added = false; + // Main loop. + for (std::pair vertices = get_vertices(); vertices.first != vertices.second; ++vertices.first) { + // Do not consider the new vertex itself. + if (*vertices.first != idx) { + if (m_drng() < prob) { + connection_added = true; + // Add the connections + add_edge(*vertices.first,idx); + add_edge(idx,*vertices.first); + } + } + } + // If no connections were established and this is not the first island being inserted, + // establish at least one connection with a random island other than n. + if ((!connection_added) && (prev_size != 0)) { + // Get a random vertex index between 0 and n_vertices - 1. Keep on repeating the procedure if by + // chance we end up on idx again. + boost::uniform_int uni_int(0,get_number_of_vertices() - 1); + vertices_size_type rnd; + do { + rnd = uni_int(m_urng); + } while (rnd == idx); + // Add connections to the random vertex. + add_edge(rnd,idx); + add_edge(idx,rnd); + } + } else { + // Now we need to add j edges, choosing the nodes with a probability + // proportional to their number of connections. We keep track of the + // connection established in order to avoid connecting twice to the same + // node. + // j is a random integer in the range 1 to m. + boost::uniform_int uni_int2(1,m_m); + std::size_t i = 0; + std::size_t j = uni_int2(m_urng); + std::pair vertices; + std::pair adj_vertices; + // Determine the lower bound (used by ageing mechanism) + int min_n_edges = 0; + vertices = get_vertices(); + for(; vertices.first != vertices.second; ++vertices.first) { + int a = *vertices.first; + int b = idx - m_a; + if(a < b) { + min_n_edges += get_num_adjacent_vertices(*vertices.first); + } + } + while (i < j) { + // Let's find the current total number of edges. + edges_size_type n_edges = get_number_of_edges(); + pagmo_assert(n_edges > 0); + boost::uniform_int uni_int(min_n_edges,n_edges - 1 - i); + // Here we choose a random number between min_n_edges and n_edges - 1 - i. + const edges_size_type rn = uni_int(m_urng); + edges_size_type n = 0; + // Iterate over all vertices and accumulate the number of edges for each of them. Stop when the accumulated number of edges is greater + // than rn. This is equivalent to giving a chance of connection to vertex v directly proportional to the number of edges departing from v. + // You can think of this process as selecting a random edge among all the existing edges and connecting to the vertex from which the + // selected edge departs. + vertices = get_vertices(); + for (; vertices.first != vertices.second; ++vertices.first) { + // Do not consider it_n. + if (*vertices.first != idx) { + adj_vertices = get_adjacent_vertices(*vertices.first); + n += boost::numeric_cast(std::distance(adj_vertices.first,adj_vertices.second)); + if (n > rn) { + break; + } + } + } + pagmo_assert(vertices.first != vertices.second); + // If the candidate was not already connected, then add it. + if (!are_adjacent(idx,*vertices.first)) { + // Connect to nodes that are already adjacent to idx with probability p. + // This step increases clustering in the network. + adj_vertices = get_adjacent_vertices(idx); + for(;adj_vertices.first != adj_vertices.second; ++adj_vertices.first) { + if(m_drng() < m_p && *adj_vertices.first != *vertices.first && !are_adjacent(*adj_vertices.first,*vertices.first)) { + add_edge(*adj_vertices.first, *vertices.first); + add_edge(*vertices.first, *adj_vertices.first); + } + } + // Connect to idx + add_edge(*vertices.first,idx); + add_edge(idx,*vertices.first); + ++i; + } + } + } +} + +/// Topology-specific human readable info. +/** + * Will return a formatted string containing the size of the kernel, the maximum number of connections for newly-inserted nodes, + * the connection probability and the maximum node age. + * + * @return string containing the parameters of the Ageing Clustered BA model. + */ +std::string ageing_clustered_ba::human_readable_extra() const +{ + std::ostringstream oss; + oss << "\tm0 = " << m_m0 << '\n'; + oss << "\tm = " << m_m << '\n'; + oss << "\tp = " << m_p << '\n'; + oss << "\ta = " << m_a << '\n'; + return oss.str(); +} + +std::string ageing_clustered_ba::get_name() const +{ + return "Ageing Clustered Barabasi-Albert"; +} + +}} //namespaces + +BOOST_CLASS_EXPORT_IMPLEMENT(pagmo::topology::ageing_clustered_ba) diff --git a/code/validation/C++/0078550_remove_element.cpp b/code/validation/C++/0078550_remove_element.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a4d29b64d22a5e46a0357defc62305aa741edae --- /dev/null +++ b/code/validation/C++/0078550_remove_element.cpp @@ -0,0 +1,76 @@ +/* + Remove Element + + Given an array and a value, remove all instances of that value + in place and return the new length. + + The order of elements can be changed. + It doesn't matter what you leave beyond the new length. + + */ + +#include +#include + +using namespace std; + +class Solution +{ +public: + int removeElement(int A[], int n, int elem) + { + if (n <= 0) + return n; // + + if (n == 1) + return A[0] == elem ? 0 : 1; + + int start = 0, end = n - 1; + while (start < end) { + if (A[start] != elem) { + start++; + } else if (A[end] == elem) { + end--; + } else { + swap(A[start], A[end]); + start++; + end--; + } + } + return start + (A[start] == elem ? 0 : 1); // + } + + int removeElement2(int A[], int n, int elem) + { + int i = 0, j = 0; + while (j < n) { + if (A[j] != elem) A[i++] = A[j]; + j++; + } + return i; + } + + int removeElement3(int A[], int n, int elem) + { + int idx = 0; + + for (int i = 0; i < n; i++) { + if (A[i] != elem) A[idx++] = A[i]; + } + + return idx; + } +}; + +int main(int argc, char *argv[]) +{ + int a[] = { 3, 3, 5, 4, 5 }; + Solution sol; + + cout << sol.removeElement(a, sizeof(a) / sizeof(int), 5) << endl; + + for (auto t : a) + cout << t << ends; + + return 0; +} diff --git a/code/validation/C++/0079862_JobSystem.cpp b/code/validation/C++/0079862_JobSystem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..95edb717d3869135c3ba5e83fbecd5d43619897f --- /dev/null +++ b/code/validation/C++/0079862_JobSystem.cpp @@ -0,0 +1,205 @@ +#include "JobSystem.h" +#include "log.h" + + +std::vector JobSystem::m_jobs; +std::mutex JobSystem::m_jobsMutex; +std::vector JobSystem::m_workerThreads; +bool JobSystem::m_hasInitBeenCalled; + +std::atomic_int JobSystem::m_jobCount; + +std::queue JobSystem::m_freeIDs; +std::map JobSystem::m_activeJobs; +std::mutex JobSystem::m_activeJobsMutex; + +uint32 JobSystem::m_currentMaxID; + +WorkerThread::WorkerThread( uint a_threadID ) : + workerThread( &WorkerThread::WorkerMainFunction , this ) , + threadID( a_threadID ) +{ + JobSystemDebugInfo* debugInfo = JobSystemDebugInfo::GI(); + if( debugInfo ) + { + debugThreadInfo = debugInfo->registerThread(); + if( !debugThreadInfo.expired() ) + { + auto info = debugThreadInfo.lock(); + info->threadID = threadID; + } + } +} + +void WorkerThread::WorkerMainFunction() +{ + runningFlag.test_and_set(); + LOGS( "Thread %d is now running" , threadID ); + + while( runningFlag.test_and_set() ) + { + if( JobSystem::m_jobCount > 0 ) + { + currentJob = JobSystem::GetAnyAvaidableJob(); + if( currentJob ) + { + jobTimer.Reset(); + jobTimer.Start(); + currentJob->taskFunction( currentJob->jobParams ); + JobSystem::JobCompleted( currentJob ); + if( currentJob->threadCleanUpJob ) + delete currentJob; + currentJob = nullptr; + + double time = jobTimer.IntervalMS(); + if( !debugThreadInfo.expired() ) + { + auto threadInfo = debugThreadInfo.lock(); + std::lock_guard lock( threadInfo->infoLock ); + threadInfo->jobTimeTotal += time; + threadInfo->jobTimeSamplesCount++; + threadInfo->jobsCompleted++; + + } + } + + } + else + std::this_thread::yield(); + } + LOGW( "Thread %d has now ended" , threadID ); +} + +void JobSystem::Init( uint a_threadCount ) +{ + m_hasInitBeenCalled = true; + m_workerThreads.reserve( a_threadCount ); + + for( uint i = 0; i < a_threadCount; i++ ) + m_workerThreads.push_back( new WorkerThread( i ) ); + m_currentMaxID = 1; +} + + + + +bool JobSystem::CheckJobConditions( Job* a_job ) +{ + if( !a_job ) + return false; + switch( a_job->jobCondition ) + { + case JobCondition::NONE: + { + return true; + } + case JobCondition::ONE_AT_A_TIME: + { + if( !a_job->typeHashCode ) + { + LOGW( "Job doesnt have a hashcode" ); + } + std::lock_guard lock( m_activeJobsMutex ); + for( auto activeJob = m_activeJobs.begin(); activeJob != m_activeJobs.end(); activeJob++ ) + { + if( activeJob->second->typeHashCode == a_job->typeHashCode ) + return false; + } + return true; + } + default: + return true; + break; + } +} + +Job* JobSystem::GetAnyAvaidableJob() +{ + Job* returningJob = nullptr; + if( !m_jobsMutex.try_lock() ) + return nullptr; + for( auto job = m_jobs.begin(); job != m_jobs.end(); ) + { + if( CheckJobConditions( *job ) ) + { + returningJob = *job; + m_jobs.erase( job ); + m_jobCount--; + AddActiveJob( returningJob ); + break; + } + job++; + } + m_jobsMutex.unlock(); + return returningJob; +} + +void JobSystem::AddActiveJob( Job* a_job ) +{ + if( a_job ) + { + std::lock_guard lock( m_activeJobsMutex ); + m_activeJobs[ a_job->jobID ] = a_job; + } + +} +void JobSystem::JobCompleted( Job* a_job ) +{ + m_activeJobsMutex.lock(); + if( a_job && m_activeJobs[ a_job->jobID ] ) + { + m_activeJobs[ a_job->jobID ] = nullptr; + m_activeJobs.erase( a_job->jobID ); + } + m_activeJobsMutex.unlock(); + +} + +void JobSystem::UnInit() +{ + if( m_hasInitBeenCalled ) + { + m_hasInitBeenCalled = false; + for( uint i = 0; i < m_workerThreads.size(); i++ ) + m_workerThreads[ i ]->runningFlag.clear(); + + for( uint i = 0; i < m_workerThreads.size(); i++ ) + { + if( !m_workerThreads[ i ]->workerThread.joinable() ) + continue; + else + m_workerThreads[ i ]->workerThread.join(); + } + m_workerThreads.clear(); + } +} + +uint32 JobSystem::ScheduleJob( Job* a_jobToAdd ) +{ + int32 jobID = 0; + + if( m_hasInitBeenCalled ) + { + if( !a_jobToAdd ) + { + LOGE( "I recieved a null job!" ); + return jobID; + } + std::lock_guard lock( m_jobsMutex ); + if( !m_freeIDs.empty() ) + { + jobID = m_freeIDs.front(); + m_freeIDs.pop(); + } + jobID = m_currentMaxID; + m_currentMaxID++; + a_jobToAdd->jobID = jobID; + m_jobs.push_back( a_jobToAdd ); + m_jobCount++; + + } + else + LOGE( "Tried to schedule job but jobsystem has not be initialized" ); + return jobID; +} + diff --git a/code/validation/C++/0080946_client.cpp b/code/validation/C++/0080946_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a6a2f2087c73a68ec03c11937c49a5566b3df894 --- /dev/null +++ b/code/validation/C++/0080946_client.cpp @@ -0,0 +1,225 @@ +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS +#endif + +#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS +#define _WINSOCK_DEPRECATED_NO_WARNINGS +#endif + +#include "client.hpp" + +#include +#pragma comment(lib, "ws2_32") + +#include + +namespace network +{ + client::client(unsigned short port) + : sock(INVALID_SOCKET), port(port) + { + + } + + client::~client() + { + if (this->sock != INVALID_SOCKET) + { + this->uninitialize(); + } + } + + bool client::make_interaction(interaction_handler finalize_handler) + { + if (!this->initialize()) + { + this->output_wsa_error(error_type::connect); + return false; + } + + bool result = finalize_handler(this); + + this->uninitialize(); + return result; + } + + int client::read(unsigned char* buffer, std::size_t assumed_size) + { + unsigned short data_length = 0; + int data_length_size = this->raw_read(reinterpret_cast(&data_length), sizeof(unsigned short)); + + if (!data_length_size || data_length_size != sizeof(unsigned short)) + { + return 0; + } + + if (assumed_size && data_length != assumed_size) + { + return 0; + } + + unsigned char data_buffer[16384]; + + for (int data_read = 0, offset = 0, data_to_read = data_length; data_to_read > 0; data_to_read -= data_read, offset += data_read) + { + data_read = this->raw_read(data_buffer + offset, data_to_read); + + if (!data_read || data_read == SOCKET_ERROR) + { + return 0; + } + } + + memcpy(buffer, data_buffer, data_length); + return data_length; + } + + bool client::write(unsigned char const* buffer, std::size_t size) + { + unsigned short data_length = static_cast(size); + + if (!this->raw_write(reinterpret_cast(&data_length), sizeof(unsigned short))) + { + return false; + } + + unsigned char* data_buffer = new unsigned char[size]; + memcpy(data_buffer, buffer, size); + + if (!this->raw_write(data_buffer, size)) + { + delete[] data_buffer; + return false; + } + + delete[] data_buffer; + return true; + } + + bool client::initialize() + { + if (WSAStartup(MAKEWORD(2, 0), new WSADATA)) + { + return false; + } + + this->sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + + if (this->sock == INVALID_SOCKET) + { + return false; + } + + sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(this->port); + addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // inet_addr("127.0.0.1"); + std::fill(addr.sin_zero, addr.sin_zero + sizeof(addr.sin_zero), 0); + + return (connect(this->sock, reinterpret_cast(&addr), sizeof(sockaddr_in)) != SOCKET_ERROR); + } + + bool client::uninitialize() + { + return (shutdown(this->sock, SD_BOTH) != SOCKET_ERROR && closesocket(this->sock) != SOCKET_ERROR && WSACleanup() == 0); + } + + int client::raw_read(unsigned char* buffer, std::size_t size) + { + int bytes_read = recv(this->sock, reinterpret_cast(buffer), size, 0); + + if (bytes_read == 0 || bytes_read == SOCKET_ERROR) + { + if (bytes_read == SOCKET_ERROR) + { + this->output_wsa_error(error_type::read); + } + + return bytes_read; + } + else if (bytes_read < static_cast(size)) + { + int remaining_bytes_read = recv(this->sock, reinterpret_cast(buffer + bytes_read), size - bytes_read, 0); + + if (remaining_bytes_read == 0 || remaining_bytes_read == SOCKET_ERROR) + { + if (remaining_bytes_read == SOCKET_ERROR) + { + this->output_wsa_error(error_type::read, false); + } + + return remaining_bytes_read; + } + + bytes_read += remaining_bytes_read; + } + + return bytes_read; + } + + bool client::raw_write(unsigned char const* buffer, std::size_t size) + { + for (int data_sent = 0, offset = 0, data_to_send = size; data_to_send > 0; data_to_send -= data_sent, offset += data_sent) + { + data_sent = send(this->sock, reinterpret_cast(buffer) + offset, data_to_send, 0); + + if (data_sent == 0 || data_sent == SOCKET_ERROR) + { + if (data_sent == SOCKET_ERROR) + { + this->output_wsa_error(error_type::write); + } + + return false; + } + } + + return true; + } + + void client::output_wsa_error(error_type type, bool first) + { + int error_code = WSAGetLastError(); + + char error_message[1024]; + memset(error_message, 0, sizeof(error_message)); + + strcpy(error_message, "Failed to "); + + switch (type) + { + case error_type::connect: + strcat(error_message, "connect to "); + break; + + case error_type::read: + strcat(error_message, (first ? "receive (0) data from " : "receive (1) data from ")); + break; + + case error_type::write: + strcat(error_message, "send data to "); + break; + } + + strcat(error_message, "the server.\nReason: "); + + switch (error_code) + { + case WSAECONNRESET: + strcat(error_message, "You've been disconnected; the server terminated the connection."); + break; + + case WSAETIMEDOUT: + strcat(error_message, "You've timed out; it took you more than 10 seconds to communicate with the server."); + break; + + default: + strcat(error_message, "Unknown. Error code: "); + strcat(error_message, std::to_string(error_code).c_str()); + strcat(error_message, "."); + break; + } + + printf("Client networking error: %s\n", error_message); + } +} \ No newline at end of file diff --git a/code/validation/C++/0083408_partialOrderShuffle.cpp b/code/validation/C++/0083408_partialOrderShuffle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aaa2562bdb5c48c1f0ac56e07e232acd3c2eb99b --- /dev/null +++ b/code/validation/C++/0083408_partialOrderShuffle.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +void Shuffle(vector &a) { + int n=a.size(); + for(int i=1;ia[i-1]) swap(a[i],a[i-1]); + } + else{ + if (a[i] a(aa,aa+sizeof(aa)/sizeof(aa[0])); + Shuffle(a); + for(int i=0;i& Rhist) +{ + boost::timer timer; + + BAMCP mcts(Simulator, SearchParams, samplerFact); + + + double undiscountedReturn = 0.0; + double discountedReturn = 0.0; + double discount = 1.0; + bool terminal = false; + int t; + + uint state = Real.CreateStartState(); + if (SearchParams.Verbose >= 1) + Real.DisplayState(state, cout); + + for (t = 0; t < ExpParams.NumSteps; t++) + { + uint observation; + double reward; + uint action = mcts.SelectAction(state); + terminal = Real.Step(state, action, observation, reward); + Rhist.push_back(reward); + + //std::cout << state << " " << action << " " << observation << " " << reward << std::endl; + + Results.Reward.Add(reward); + undiscountedReturn += reward; + discountedReturn += reward * discount; + discount *= Real.GetDiscount(); + + if (SearchParams.Verbose >= 1) + { + Real.DisplayAction(action, cout); + Real.DisplayState(state, cout); + Real.DisplayObservation(state, observation, cout); + Real.DisplayReward(reward, cout); + } + + if (terminal) + { + cout << "Terminated" << endl; + break; + } + mcts.Update(state, action, observation, reward); + + //For MDP: + state = observation; + + + if (timer.elapsed() > ExpParams.TimeOut) + { + cout << "Timed out after " << t << " steps in " + << Results.Time.GetTotal() << "seconds" << endl; + break; + } + } + + Results.Time.Add(timer.elapsed()); + Results.UndiscountedReturn.Add(undiscountedReturn); + Results.DiscountedReturn.Add(discountedReturn); + cout << "(" << discountedReturn << "," + << Results.DiscountedReturn.GetMean() << ":" + << undiscountedReturn << "," << Results.UndiscountedReturn.GetMean() + << ") " << flush; + +} + +//FIXME Code repetition... +//Same code as in Run() but with Bandit specific argument +void EXPERIMENT::RunBandit(std::vector& Rhist, std::vector& optArm, uint bestArm) +{ + boost::timer timer; + + BAMCP mcts(Simulator, SearchParams, samplerFact); + + + double undiscountedReturn = 0.0; + double discountedReturn = 0.0; + double discount = 1.0; + bool terminal = false; + int t; + + uint state = Real.CreateStartState(); + if (SearchParams.Verbose >= 1) + Real.DisplayState(state, cout); + + for (t = 0; t < ExpParams.NumSteps; t++) + { + uint observation; + double reward; + uint action = mcts.SelectAction(state); + terminal = Real.Step(state, action, observation, reward); + + + Rhist.push_back(reward); + if(action==bestArm) + optArm.push_back(1); + else + optArm.push_back(0); + + Results.Reward.Add(reward); + undiscountedReturn += reward; + discountedReturn += reward * discount; + discount *= Real.GetDiscount(); + + if (SearchParams.Verbose >= 1) + { + Real.DisplayAction(action, cout); + Real.DisplayState(state, cout); + Real.DisplayObservation(state, observation, cout); + Real.DisplayReward(reward, cout); + } + + if (terminal) + { + cout << "Terminated" << endl; + break; + } + //state --> 0 + mcts.Update(state, action, observation, reward); + + + if (timer.elapsed() > ExpParams.TimeOut) + { + cout << "Timed out after " << t << " steps in " + << Results.Time.GetTotal() << "seconds" << endl; + break; + } + } + + Results.Time.Add(timer.elapsed()); + Results.UndiscountedReturn.Add(undiscountedReturn); + Results.DiscountedReturn.Add(discountedReturn); + cout << "Discounted return = " << discountedReturn + << ", average = " << Results.DiscountedReturn.GetMean() << endl; + cout << "Undiscounted return = " << undiscountedReturn + << ", average = " << Results.UndiscountedReturn.GetMean() << endl; +} + +//---------------------------------------------------------------------------- diff --git a/code/validation/C++/0085522_olsenupdt.cc b/code/validation/C++/0085522_olsenupdt.cc new file mode 100644 index 0000000000000000000000000000000000000000..c57eb3bed54a589d7d923f844b2b023c494b1c20 --- /dev/null +++ b/code/validation/C++/0085522_olsenupdt.cc @@ -0,0 +1,135 @@ +/* + * @BEGIN LICENSE + * + * Psi4: an open-source quantum chemistry software package + * + * Copyright (c) 2007-2018 The Psi4 Developers. + * + * The copyrights for code used from other parties are included in + * the corresponding files. + * + * This file is part of Psi4. + * + * Psi4 is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, version 3. + * + * Psi4 is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License along + * with Psi4; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * @END LICENSE + */ + +/*! \file + \ingroup DETCI + \brief Enter brief description of file here +*/ + +/* +** OLSENUPDT.C +** +** Contains some code related to the Olsen iterative scheme +** +** David Sherrill +** Center for Computational Quantum Chemistry +** February 1996 +*/ + +#include +#include +#include "psi4/detci/structs.h" +#include "psi4/detci/ci_tol.h" + +namespace psi { namespace detci { + +/* +** buf_xy1() +** +** Do some of the work to get x and y +** +** x = C^(i) * (Hd - E)^-1 * C^(i) +** y = C^(i) * (Hd - E)^-1 * sigma^(i) +** +** Specifically this function replaces the buffer +** (not the vector on disk) of Hd vector +** with the vector C^(i) * (Hd - E)^-1 for use in +** the evaluation of x and y as described above +** while tx returns the result of C^(i) * the new +** Hd vector (i.e. x from above) +** +*/ +double buf_xy1(double *c, double *hd, double E, int len) +{ + int i; + double ci, tval1, tval2; + double tx = 0.0; + + for (i=0; iPrintf("C_0[%d] = %14.12lf " \ + "C_1[%d] = %14.12lf C_new[%d] = %14.12lf\n",i,c[i],i,a[i],i,tval2); + */ + c[i] = tval2; + nx += tval2 * tval2; + ox += tval2 * tval1; + c1norm += a[i] * a[i]; + } + + *norm = nx; + *ovrlap = ox; + *tmpnorm = c1norm; +} + +}} // namespace psi::detci diff --git a/code/validation/C++/0087523_tuple.cpp b/code/validation/C++/0087523_tuple.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0a3fa574567ecd66ba1fc807a2208cf27ce1dc08 --- /dev/null +++ b/code/validation/C++/0087523_tuple.cpp @@ -0,0 +1,241 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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. + +#include "runtime/tuple.h" + +#include + +#include "exprs/expr.h" +#include "util/mem_util.hpp" +#include "runtime/descriptors.h" +#include "runtime/mem_pool.h" +#include "runtime/raw_value.h" +#include "runtime/tuple_row.h" +#include "runtime/string_value.h" + +namespace doris { + +const char* Tuple::_s_llvm_class_name = "class.doris::Tuple"; + +int64_t Tuple::total_byte_size(const TupleDescriptor& desc) const { + int64_t result = desc.byte_size(); + if (!desc.has_varlen_slots()) { + return result; + } + result += varlen_byte_size(desc); + return result; +} + +int64_t Tuple::varlen_byte_size(const TupleDescriptor& desc) const { + int64_t result = 0; + std::vector::const_iterator slot = desc.string_slots().begin(); + for (; slot != desc.string_slots().end(); ++slot) { + DCHECK((*slot)->type().is_string_type()); + if (is_null((*slot)->null_indicator_offset())) { + continue; + } + const StringValue* string_val = get_string_slot((*slot)->tuple_offset()); + result += string_val->len; + } + + return result; +} + +Tuple* Tuple::deep_copy(const TupleDescriptor& desc, MemPool* pool, bool convert_ptrs) { + Tuple* result = reinterpret_cast(pool->allocate(desc.byte_size())); + deep_copy(result, desc, pool, convert_ptrs); + return result; +} + +void Tuple::deep_copy(Tuple* dst, const TupleDescriptor& desc, MemPool* pool, + bool convert_ptrs) { + memory_copy(dst, this, desc.byte_size()); + + // allocate in the same pool and then copy all non-null string slots + for (std::vector::const_iterator i = desc.string_slots().begin(); + i != desc.string_slots().end(); ++i) { + DCHECK((*i)->type().is_string_type()); + + if (!dst->is_null((*i)->null_indicator_offset())) { + StringValue* string_v = dst->get_string_slot((*i)->tuple_offset()); + if (string_v->len != 0) { + int offset = pool->total_allocated_bytes(); + char* string_copy = reinterpret_cast(pool->allocate(string_v->len)); + memory_copy(string_copy, string_v->ptr, string_v->len); + string_v->ptr = (convert_ptrs ? reinterpret_cast(offset) : string_copy); + } + } + } +} + +Tuple* Tuple::dcopy_with_new(const TupleDescriptor& desc, MemPool* pool, int64_t* bytes) { + Tuple* result = reinterpret_cast(pool->allocate(desc.byte_size())); + *bytes = dcopy_with_new(result, desc); + return result; +} + +int64_t Tuple::dcopy_with_new(Tuple* dst, const TupleDescriptor& desc) { + memory_copy(dst, this, desc.byte_size()); + + int64_t bytes = 0; + // allocate in the same pool and then copy all non-null string slots + for (auto slot : desc.string_slots()) { + DCHECK(slot->type().is_string_type()); + + if (!dst->is_null(slot->null_indicator_offset())) { + StringValue* string_v = dst->get_string_slot(slot->tuple_offset()); + bytes += string_v->len; + if (string_v->len != 0) { + char* string_copy = new char[string_v->len]; + memory_copy(string_copy, string_v->ptr, string_v->len); + string_v->ptr = string_copy; + } else { + string_v->ptr = nullptr; + } + } + } + return bytes; +} + +int64_t Tuple::release_string(const TupleDescriptor& desc) { + int64_t bytes = 0; + for (auto slot : desc.string_slots()) { + if (!is_null(slot->null_indicator_offset())) { + StringValue* string_v = get_string_slot(slot->tuple_offset()); + delete[] string_v->ptr; + bytes += string_v->len; + } + } + return bytes; +} + +void Tuple::deep_copy( + const TupleDescriptor& desc, char** data, int* offset, bool convert_ptrs) { + Tuple* dst = reinterpret_cast(*data); + memory_copy(dst, this, desc.byte_size()); + *data += desc.byte_size(); + *offset += desc.byte_size(); + + for (auto slot_desc : desc.string_slots()) { + DCHECK(slot_desc->type().is_string_type()); + if (!dst->is_null(slot_desc->null_indicator_offset())) { + StringValue* string_v = dst->get_string_slot(slot_desc->tuple_offset()); + memory_copy(*data, string_v->ptr, string_v->len); + string_v->ptr = (convert_ptrs ? reinterpret_cast(*offset) : *data); + *data += string_v->len; + *offset += string_v->len; + } + } +} + +template +void Tuple::materialize_exprs( + TupleRow* row, const TupleDescriptor& desc, + const std::vector& materialize_expr_ctxs, MemPool* pool, + std::vector* non_null_var_len_values, int* total_var_len) { + if (collect_string_vals) { + non_null_var_len_values->clear(); + *total_var_len = 0; + } + memset(this, 0, desc.num_null_bytes()); + // Evaluate the output_slot_exprs and place the results in the tuples. + int mat_expr_index = 0; + for (int i = 0; i < desc.slots().size(); ++i) { + SlotDescriptor* slot_desc = desc.slots()[i]; + if (!slot_desc->is_materialized()) { + continue; + } + // The FE ensures we don't get any TYPE_NULL expressions by picking an arbitrary type + // when necessary, but does not do this for slot descs. + // TODO: revisit this logic in the FE + PrimitiveType slot_type = slot_desc->type().type; + PrimitiveType expr_type = materialize_expr_ctxs[mat_expr_index]->root()->type().type; + if ((slot_type == TYPE_CHAR) || (slot_type == TYPE_VARCHAR) || (slot_type == TYPE_HLL)) { + DCHECK((expr_type == TYPE_CHAR) || (expr_type == TYPE_VARCHAR) || (expr_type == TYPE_HLL)); + } else if ((slot_type == TYPE_DATE) || (slot_type == TYPE_DATETIME)) { + DCHECK((expr_type == TYPE_DATE) || (expr_type == TYPE_DATETIME)); + } else { + DCHECK(slot_type == TYPE_NULL || slot_type == expr_type); + } + void* src = materialize_expr_ctxs[mat_expr_index]->get_value(row); + if (src != NULL) { + void* dst = get_slot(slot_desc->tuple_offset()); + RawValue::write(src, dst, slot_desc->type(), pool); + if (collect_string_vals) { + if (slot_desc->type().is_string_type()) { + StringValue* string_val = reinterpret_cast(dst); + non_null_var_len_values->push_back(string_val); + *total_var_len += string_val->len; + } + } + } else { + set_null(slot_desc->null_indicator_offset()); + } + ++mat_expr_index; + } + + DCHECK_EQ(mat_expr_index, materialize_expr_ctxs.size()); +} + +template void Tuple::materialize_exprs(TupleRow* row, const TupleDescriptor& desc, + const std::vector& materialize_expr_ctxs, MemPool* pool, + std::vector* non_null_var_values, int* total_var_len); + +template void Tuple::materialize_exprs(TupleRow* row, const TupleDescriptor& desc, + const std::vector& materialize_expr_ctxs, MemPool* pool, + std::vector* non_null_var_values, int* total_var_len); + +std::string Tuple::to_string(const TupleDescriptor& d) const { + std::stringstream out; + out << "("; + + bool first_value = true; + for (auto slot : d.slots()) { + if (!slot->is_materialized()) { + continue; + } + if (first_value) { + first_value = false; + } else { + out << " "; + } + + if (is_null(slot->null_indicator_offset())) { + out << "null"; + } else { + std::string value_str; + RawValue::print_value( + get_slot(slot->tuple_offset()), + slot->type(), + -1, + &value_str); + out << value_str; + } + } + + out << ")"; + return out.str(); +} + +std::string Tuple::to_string(const Tuple* t, const TupleDescriptor& d) { + if (t == nullptr) { + return "null"; + } + return t->to_string(d); +} + +} diff --git a/code/validation/C++/0087880_Location.cpp b/code/validation/C++/0087880_Location.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b41df52e7c8f995c6a630ce44c5619fc64019a29 --- /dev/null +++ b/code/validation/C++/0087880_Location.cpp @@ -0,0 +1,180 @@ +/* This file is part of RTags (https://github.com/Andersbakken/rtags). + + RTags is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + RTags is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with RTags. If not, see . */ + +#include "Location.h" + +#include "rct/Rct.h" +#include "RTags.h" +#include "Server.h" +#include "Project.h" +#include "ClangIndexer.h" + +Hash Location::sPathsToIds; +Hash Location::sIdsToPaths; +uint32_t Location::sLastId = 0; +std::mutex Location::sMutex; +static inline uint64_t createMask(int startBit, int bitCount) +{ + uint64_t mask = 0; + for (int i=startBit; i(1) << i); + } + return mask; +} + +const uint64_t Location::FILEID_MASK = createMask(0, FileBits); +const uint64_t Location::LINE_MASK = createMask(FileBits, LineBits); +const uint64_t Location::COLUMN_MASK = createMask(FileBits + LineBits, ColumnBits); + +String Location::toString(Flags flags, Hash *contextCache) const +{ + if (isNull()) + return String(); + const unsigned int l = line(); + const unsigned int c = column(); + int extra = RTags::digits(l) + RTags::digits(c) + 3; + String ctx; + if (flags & Location::ShowContext) { + ctx += '\t'; + ctx += context(flags, contextCache); + extra += ctx.size(); + } + + Path p = path(); + if (flags & ConvertToRelative) { + Sandbox::encode(p); + } else if (!(flags & AbsolutePath) && Server::instance()) { + Server *server = Server::instance(); + if (std::shared_ptr pp = server->currentProject()) { + const Path projectPath = pp->path(); + if (!projectPath.isEmpty() && p.startsWith(projectPath)) + p.remove(0, projectPath.size()); + } + } + + String ret(p.size() + extra, ' '); + + const int w = snprintf(ret.data(), ret.size() + extra + 1, "%s:%d:%d:", p.constData(), l, c); + if (!ctx.isEmpty()) { + memcpy(ret.data() + w, ctx.constData(), ctx.size()); + } + return ret; +} + +String Location::context(Flags flags, Hash *cache) const +{ + String copy; + String *code = nullptr; + const Path p = path(); + + auto readAll = [&p, this]() { + if (Server::instance()) { + if (auto project = Server::instance()->currentProject()) { + const Path f = project->sourceFilePath(fileId(), "unsaved"); + String contents = f.readAll(); + if (!contents.isEmpty()) + return contents; + } + } + return p.readAll(); + }; + if (cache) { + String &ref = (*cache)[p]; + if (ref.isEmpty()) { + ref = readAll(); + } + code = &ref; + } else { + copy = readAll(); + code = © + } + + String ret; + if (!code->isEmpty()) { + unsigned int l = line(); + if (!l) + return String(); + const char *ch = code->constData(); + while (--l) { + ch = strchr(ch, '\n'); + if (!ch) + return String(); + ++ch; + } + const char *end = strchr(ch, '\n'); + if (!end) + return String(); + + ret.assign(ch, end - ch); + // error() << "foobar" << ret << bool(flags & NoColor); + if (!(flags & NoColor)) { + const size_t col = column() - 1; + if (col + 1 < ret.size()) { + size_t last = col; + if (ret.at(last) == '~') + ++last; + while (ret.size() > last && (isalnum(ret.at(last)) || ret.at(last) == '_')) + ++last; + static const char *color = "\x1b[32;1m"; // dark yellow + static const char *resetColor = "\x1b[0;0m"; + // error() << "foobar"<< end << col << ret.size(); + ret.insert(last, resetColor); + ret.insert(col, color); + } + // printf("[%s]\n", ret.constData()); + } + } + return ret; +} + +void Location::saveFileIds() +{ + assert(Server::instance()); + Server::instance()->saveFileIds(); +} + +bool Location::init(const Hash &pathsToIds) +{ + LOCK(); + sPathsToIds = pathsToIds; + sIdsToPaths.clear(); + sLastId = 0; + for (const auto &it : sPathsToIds) { + assert(!it.first.isEmpty()); + Path &ref = sIdsToPaths[it.second]; + if (!ref.isEmpty()) { + sPathsToIds.clear(); + sIdsToPaths.clear(); + sLastId = 0; + return false; + } + ref = it.first; + sLastId = std::max(sLastId, it.second); + } + return true; +} + +void Location::init(const Hash &idsToPaths) +{ + LOCK(); + sIdsToPaths = idsToPaths; + sPathsToIds.clear(); + sLastId = 0; + for (const auto &it : sIdsToPaths) { + sPathsToIds[it.second] = it.first; + assert(!it.second.isEmpty()); + sLastId = std::max(sLastId, it.first); + } +} diff --git a/code/validation/C++/0090738_SampleView.cpp b/code/validation/C++/0090738_SampleView.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a8052b7f5a3c111480b36b3c63b18d2eebfddfe9 --- /dev/null +++ b/code/validation/C++/0090738_SampleView.cpp @@ -0,0 +1,71 @@ + +#include "SampleView.h" +#include +#include + + + +SampleView::SampleView(BRect vframe): BView(vframe,"x",0,B_WILL_DRAW|B_FRAME_EVENTS) +{ + SetViewColor(0,0,0); + SetLowColor(0,0,0); + SetHighColor(255,255,255); + SetFontSize(8); + + data=NULL; + rev=false; + sampleCount=0; + left_p=right_p=incx=0; + + +} + +void +SampleView::Init(void *dat,int32 count,bool c) +{ + data=dat; + sampleCount=count; + rev=c; + incx=(int)(sampleCount/Bounds().Width()); + Invalidate(); +} + + +void +SampleView::Draw(BRect b) +{ + + + float y; + + //MovePenTo(0,zero); + + if(data==NULL || sampleCount==0){ + StrokeLine(BPoint(b.left,zero),BPoint(b.right,zero)); + return; + } + + + SetHighColor(10,200,10); + + for(int i=0;i. + * + * -------------------------------------------------------------------- + * + * The following copyright notices are generated automatically. If you + * have a new notice to add, please use the format: + * " * @copyright Copyright ..." + * This will properly maintain the copyright information. DigitalGlobe + * copyrights will be updated automatically. + * + * @copyright Copyright (C) 2013, 2014, 2015 DigitalGlobe (http://www.digitalglobe.com/) + */ + +// Hoot +#include +#include +#include +#include +#include +#include +#include +#include + +// Standard +#include +#include + +namespace hoot +{ + +using namespace std; + +bool greaterThanWordCount(const WordCount& left, const WordCount& right) +{ + return left.count > right.count; +} + +class PrintNamesCmd : public BaseCommand +{ +public: + static string className() { return "hoot::PrintNamesCmd"; } + + class NameCountVisitor : public ElementVisitor + { + public: + NameCountVisitor(std::map& counts) : _counts(counts) + { + _nonWord.setPattern("[^\\w]"); + } + + virtual void visit(const ConstElementPtr& e) + { + QStringList names = e->getTags().getNames(); + + for (int i = 0; i < names.size(); i++) + { + QStringList words = names[i].split(" "); + for (int i = 0; i < words.size(); i++) + { + // See wikipedia for a description of what this does, but we're trying to group words + // that are effectively the same together in the same hash bin. + // http://en.wikipedia.org/wiki/Unicode_equivalence + QString word = words[i].toLower().normalized(QString::NormalizationForm_C); + // remove all the non-word characters (e.g. "(", "-", etc.) + QString noSymbols = word; + noSymbols.replace(_nonWord, ""); + // if there is still a word left then use the word w/o symbols. + // E.g. don't remove "&" if it is all by itself. + if (noSymbols.isEmpty() == false) + { + word = noSymbols; + } + // ignore any empty words. This may happen when there are multiple consecutive spaces. + if (word.isEmpty() == false) + { + _counts[word]++; + } + } + } + } + + private: + map& _counts; + QRegExp _nonWord; + }; + + PrintNamesCmd() {} + + QString getHelp() const + { + // 80 columns + // | <--- ---> | + return getName() + " (input) [inputs...] [--write outputBase]\n" + " Reads input and write out a list of names ordered by frequency.\n" + " * input - One or more input map paths.\n" + " * outputBase - Write out the counts to a .frequent and .all dictionary."; + } + + virtual QString getName() const { return "names"; } + + int runSimple(QStringList args) + { + if (args.size() == 0) + { + cout << getHelp() << endl << endl; + throw HootException(QString("%1 takes one or more parameters.").arg(getName())); + } + + bool writeFile = false; + QString output; + if (args.size() >= 3 && args[args.size() - 2] == "--write") + { + writeFile = true; + output = args[args.size() - 1]; + } + + // adding the source datetime just makes things really slow. + conf().set(ConfigOptions().getReaderAddSourceDatetimeKey(), false); + + shared_ptr map(new OsmMap()); + + std::map counts; + NameCountVisitor v(counts); + map->visitRo(v); + + int inputCount = writeFile ? args.size() - 2 : args.size(); + for (int i = 0; i < inputCount; i++) + { + if (OsmMapReaderFactory::getInstance().hasPartialReader(args[i])) + { + shared_ptr reader = OsmMapReaderFactory::getInstance().createReader(args[i]); + shared_ptr pomr = dynamic_pointer_cast(reader); + + pomr->open(args[i]); + + while (pomr->hasMoreElements()) + { + ElementPtr e = pomr->readNextElement(); + v.visit(e); + } + } + else + { + shared_ptr map(new OsmMap()); + loadMap(map, args[i], false, Status::Unknown1); + map->visitRo(v); + } + } + + long total = 0; + QVector wc; + wc.reserve(counts.size()); + for (std::map::iterator it = counts.begin(); it != counts.end(); it++) + { + wc.push_back(WordCount(it->first, it->second)); + total += it->second; + } + + if (writeFile) + { + WordCountWriter writer(10 * 1000 * 1000); + writer.write(output, wc); + } + else + { + cout << "Total word count: " << total << endl; + + sort(wc.begin(), wc.end(), greaterThanWordCount); + + for (int i = 0; i < wc.size(); i++) + { + double p = (double)wc[i].count / (double)total; + cout << setprecision(2); + cout << wc[i].count << " (" << p << ") : " << wc[i].word.toUtf8().data() << endl; + } + } + + return 0; + } +}; + +HOOT_FACTORY_REGISTER(Command, PrintNamesCmd) + +} diff --git a/code/validation/C++/0091964_hex_file.cc b/code/validation/C++/0091964_hex_file.cc new file mode 100644 index 0000000000000000000000000000000000000000..bfebc1b44b54000ba5391fe128fbb6f2c9299356 --- /dev/null +++ b/code/validation/C++/0091964_hex_file.cc @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2007 MIPS Technologies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer; + * redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution; + * neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER 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. + * + * Authors: Jaidev Patwardhan + */ + +#include +#include +#include +#include + +#include "base/loader/hex_file.hh" +#include "base/loader/symtab.hh" +#include "base/cprintf.hh" +#include "mem/port_proxy.hh" + +using namespace std; +/* + * Load a Hex File into memory. Currently only used with MIPS + * BARE_IRON mode. A hex file consists of [Address Data] tuples that + * get directly loaded into physical memory. The address specified is + * a word address (i.e., to get the byte address, shift left by 2) The + * data is a full 32-bit hex value. +*/ +HexFile::HexFile(const string _filename) + : filename(_filename) +{ + fp = fopen(filename.c_str(), "r"); + if (fp == NULL) + panic("Unable to open %s\n", filename.c_str()); +} + +HexFile::~HexFile() +{ +} + +bool +HexFile::loadSections(PortProxy& memProxy) +{ + char Line[64]; + Addr MemAddr; + uint32_t Data; + while (!feof(fp)) { + char *ret = fgets(Line, sizeof(Line), fp); + if (!ret) + panic("malformed file"); + parseLine(Line, &MemAddr, &Data); + if (MemAddr != 0) { + // Now, write to memory + memProxy.writeBlob(MemAddr << 2, (uint8_t *)&Data, sizeof(Data)); + } + } + return true; +} + +void +HexFile::parseLine(char *Str, Addr *A, uint32_t *D) +{ + int i = 0; + bool Flag = false; + *A = 0; + *D = 0; + int Digit = 0; + unsigned Number = 0; + + /* Skip white spaces */ + while (Str[i] != '\0' && Str[i]==' ') + i++; + + /* Ok, we're at some character...process things */ + while (Str[i] != '\0') { + if (Str[i] >= '0' && Str[i] <= '9') { + Digit = Str[i] - '0'; + } else if (Str[i] >= 'a' && Str[i] <= 'f') { + Digit = Str[i] - 'a' + 10; + } else if (Str[i] >= 'A' && Str[i] <= 'F') { + Digit=Str[i]-'A'+10; + } else if (Str[i] == ' ' || Str[i] == '\n') { + if (Number == 0) + return; + if (Flag == false) { + *A = Number; + Number = 0; + Flag = true; + } else { + *D = Number; + return; + } + } else { + // Ok, we've encountered a non-hex character, cannot be a + // valid line, skip and return 0's + *A = 0; + *D = 0; + return; + } + + Number <<= 4; + Number += Digit; + i++; + } + + if (Flag != true) { + *A = 0; + *D = 0; + } else { + *D = Number; + } +} + +void +HexFile::close() +{ + fclose(fp); +} diff --git a/code/validation/C++/0094021_main.cc b/code/validation/C++/0094021_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..093b7d32e50ab0cecb9e06b466b7cd64857ae0db --- /dev/null +++ b/code/validation/C++/0094021_main.cc @@ -0,0 +1,297 @@ +// main.cc +// Driver code to initialize, selftest, and run the +// operating system kernel. +// +// Usage: nachos -d -rs +// -s -x -ci -co +// -f -cp +// -p -r -l -D +// -n -m +// -z -K -C -N +// +// -d causes certain debugging messages to be printed (see debug.h) +// -rs causes Yield to occur at random (but repeatable) spots +// -z prints the copyright message +// -s causes user programs to be executed in single-step mode +// -x runs a user program +// -ci specify file for console input (stdin is the default) +// -co specify file for console output (stdout is the default) +// -n sets the network reliability +// -m sets this machine's host id (needed for the network) +// -K run a simple self test of kernel threads and synchronization +// -C run an interactive console test +// -N run a two-machine network test (see Kernel::NetworkTest) +// +// Filesystem-related flags: +// -f forces the Nachos disk to be formatted +// -cp copies a file from UNIX to Nachos +// -p prints a Nachos file to stdout +// -r removes a Nachos file from the file system +// -l lists the contents of the Nachos directory +// -D prints the contents of the entire file system +// +// Note: the file system flags are not used if the stub filesystem +// is being used +// +// Copyright (c) 1992-1996 The Regents of the University of California. +// All rights reserved. See copyright.h for copyright notice and limitation +// of liability and disclaimer of warranty provisions. + +#define MAIN +#include "copyright.h" +#undef MAIN + +#include "main.h" +#include "filesys.h" +#include "openfile.h" +#include "sysdep.h" + +// global variables +Kernel *kernel; +Debug *debug; + + +//---------------------------------------------------------------------- +// Cleanup +// Delete kernel data structures; called when user hits "ctl-C". +//---------------------------------------------------------------------- + +static void +Cleanup(int x) +{ + cerr << "\nCleaning up after signal " << x << "\n"; + delete kernel; +} + +//------------------------------------------------------------------- +// Constant used by "Copy" and "Print" +// It is the number of bytes read from the Unix file (for Copy) +// or the Nachos file (for Print) by each read operation +//------------------------------------------------------------------- +static const int TransferSize = 128; + + +#ifndef FILESYS_STUB +//---------------------------------------------------------------------- +// Copy +// Copy the contents of the UNIX file "from" to the Nachos file "to" +//---------------------------------------------------------------------- + +static void +Copy(char *from, char *to) +{ + int fd; + OpenFile* openFile; + int amountRead, fileLength; + char *buffer; + +// Open UNIX file + if ((fd = OpenForReadWrite(from,FALSE)) < 0) { + printf("Copy: couldn't open input file %s\n", from); + return; + } + +// Figure out length of UNIX file + Lseek(fd, 0, 2); + fileLength = Tell(fd); + Lseek(fd, 0, 0); + +// Create a Nachos file of the same length + DEBUG('f', "Copying file " << from << " of size " << fileLength << " to file " << to); + if (!kernel->fileSystem->Create(to, fileLength)) { // Create Nachos file + printf("Copy: couldn't create output file %s\n", to); + Close(fd); + return; + } + + openFile = kernel->fileSystem->Open(to); + ASSERT(openFile != NULL); + +// Copy the data in TransferSize chunks + buffer = new char[TransferSize]; + while ((amountRead=ReadPartial(fd, buffer, sizeof(char)*TransferSize)) > 0) + openFile->Write(buffer, amountRead); + delete [] buffer; + +// Close the UNIX and the Nachos files + delete openFile; + Close(fd); +} + +#endif // FILESYS_STUB + +//---------------------------------------------------------------------- +// Print +// Print the contents of the Nachos file "name". +//---------------------------------------------------------------------- + +void +Print(char *name) +{ + OpenFile *openFile; + int i, amountRead; + char *buffer; + + if ((openFile = kernel->fileSystem->Open(name)) == NULL) { + printf("Print: unable to open file %s\n", name); + return; + } + + buffer = new char[TransferSize]; + while ((amountRead = openFile->Read(buffer, TransferSize)) > 0) + for (i = 0; i < amountRead; i++) + printf("%c", buffer[i]); + delete [] buffer; + + delete openFile; // close the Nachos file + return; +} + + + +//---------------------------------------------------------------------- +// main +// Bootstrap the operating system kernel. +// +// Initialize kernel data structures +// Call some test routines +// Call "Run" to start an initial user program running +// +// "argc" is the number of command line arguments (including the name +// of the command) -- ex: "nachos -d +" -> argc = 3 +// "argv" is an array of strings, one for each command line argument +// ex: "nachos -d +" -> argv = {"nachos", "-d", "+"} +//---------------------------------------------------------------------- + +int +main(int argc, char **argv) +{ + int i; + char *debugArg = ""; + char *userProgName = NULL; // default is not to execute a user prog + bool threadTestFlag = false; + bool consoleTestFlag = false; + bool networkTestFlag = false; +#ifndef FILESYS_STUB + char *copyUnixFileName = NULL; // UNIX file to be copied into Nachos + char *copyNachosFileName = NULL; // name of copied file in Nachos + char *printFileName = NULL; + char *removeFileName = NULL; + bool dirListFlag = false; + bool dumpFlag = false; +#endif //FILESYS_STUB + + // some command line arguments are handled here. + // those that set kernel parameters are handled in + // the Kernel constructor + for (i = 1; i < argc; i++) { + if (strcmp(argv[i], "-d") == 0) { + ASSERT(i + 1 < argc); // next argument is debug string + debugArg = argv[i + 1]; + i++; + } + else if (strcmp(argv[i], "-z") == 0) { + cout << copyright << "\n"; + } + else if (strcmp(argv[i], "-x") == 0) { + ASSERT(i + 1 < argc); + userProgName = argv[i + 1]; + i++; + } + else if (strcmp(argv[i], "-K") == 0) { + threadTestFlag = TRUE; + } + else if (strcmp(argv[i], "-C") == 0) { + consoleTestFlag = TRUE; + } + else if (strcmp(argv[i], "-N") == 0) { + networkTestFlag = TRUE; + } +#ifndef FILESYS_STUB + else if (strcmp(argv[i], "-cp") == 0) { + ASSERT(i + 2 < argc); + copyUnixFileName = argv[i + 1]; + copyNachosFileName = argv[i + 2]; + i += 2; + } + else if (strcmp(argv[i], "-p") == 0) { + ASSERT(i + 1 < argc); + printFileName = argv[i + 1]; + i++; + } + else if (strcmp(argv[i], "-r") == 0) { + ASSERT(i + 1 < argc); + removeFileName = argv[i + 1]; + i++; + } + else if (strcmp(argv[i], "-l") == 0) { + dirListFlag = true; + } + else if (strcmp(argv[i], "-D") == 0) { + dumpFlag = true; + } +#endif //FILESYS_STUB + else if (strcmp(argv[i], "-u") == 0) { + cout << "Partial usage: nachos [-z -d debugFlags]\n"; + cout << "Partial usage: nachos [-x programName]\n"; + cout << "Partial usage: nachos [-K] [-C] [-N]\n"; +#ifndef FILESYS_STUB + cout << "Partial usage: nachos [-cp UnixFile NachosFile]\n"; + cout << "Partial usage: nachos [-p fileName] [-r fileName]\n"; + cout << "Partial usage: nachos [-l] [-D]\n"; +#endif //FILESYS_STUB + } + + } + debug = new Debug(debugArg); + + DEBUG(dbgThread, "Entering main"); + + kernel = new Kernel(argc, argv); + + kernel->Initialize(); + + CallOnUserAbort(Cleanup); // if user hits ctl-C + + // at this point, the kernel is ready to do something + // run some tests, if requested + if (threadTestFlag) { + kernel->ThreadSelfTest(); // test threads and synchronization + } + if (consoleTestFlag) { + kernel->ConsoleTest(); // interactive test of the synchronized console + } + if (networkTestFlag) { + kernel->NetworkTest(); // two-machine test of the network + } + +#ifndef FILESYS_STUB + if (removeFileName != NULL) { + kernel->fileSystem->Remove(removeFileName); + } + if (copyUnixFileName != NULL && copyNachosFileName != NULL) { + Copy(copyUnixFileName,copyNachosFileName); + } + if (dumpFlag) { + kernel->fileSystem->Print(); + } + if (dirListFlag) { + kernel->fileSystem->List(); + } + if (printFileName != NULL) { + Print(printFileName); + } +#endif // FILESYS_STUB + + // finally, run an initial user program if requested to do so + + kernel->ExecAll(); + // If we don't run a user program, we may get here. + // Calling "return" would terminate the program. + // Instead, call Halt, which will first clean up, then + // terminate. +// kernel->interrupt->Halt(); + + ASSERTNOTREACHED(); +} + diff --git a/code/validation/C++/0094107_SampleAARects.cpp b/code/validation/C++/0094107_SampleAARects.cpp new file mode 100644 index 0000000000000000000000000000000000000000..942242b02e77d17a7ab71006adb9ffeb97e8be03 --- /dev/null +++ b/code/validation/C++/0094107_SampleAARects.cpp @@ -0,0 +1,192 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +#include "SampleCode.h" +#include "SkView.h" +#include "SkCanvas.h" +#include "SkPaint.h" +#include "SkShader.h" + +static SkBitmap createBitmap(int n) { + SkBitmap bitmap; + bitmap.allocN32Pixels(n, n); + bitmap.eraseColor(SK_ColorGREEN); + + SkCanvas canvas(bitmap); + SkRect r; + r.set(0, 0, SkIntToScalar(n), SkIntToScalar(n)); + SkPaint paint; + paint.setAntiAlias(true); + + paint.setColor(SK_ColorRED); + canvas.drawOval(r, paint); + paint.setColor(SK_ColorBLUE); + paint.setStrokeWidth(SkIntToScalar(n)/15); + paint.setStyle(SkPaint::kStroke_Style); + canvas.drawLine(0, 0, r.fRight, r.fBottom, paint); + canvas.drawLine(0, r.fBottom, r.fRight, 0, paint); + + return bitmap; +} + +class AARectView : public SampleView { + SkBitmap fBitmap; + enum { + N = 64 + }; +public: + AARectView() { + fBitmap = createBitmap(N); + + fWidth = N; + } + +protected: + // overrides from SkEventSink + virtual bool onQuery(SkEvent* evt) { + if (SampleCode::TitleQ(*evt)) { + SampleCode::TitleR(evt, "AA Rects"); + return true; + } + return this->INHERITED::onQuery(evt); + } + + virtual void onDrawContent(SkCanvas* canvas) { + canvas->translate(SkIntToScalar(10), SkIntToScalar(10)); + + SkPaint bluePaint; + bluePaint.setARGB(0xff, 0x0, 0x0, 0xff); + SkPaint bmpPaint; + bmpPaint.setShader(SkShader::MakeBitmapShader(fBitmap, SkShader::kRepeat_TileMode, + SkShader::kRepeat_TileMode)); + bluePaint.setStrokeWidth(3); + bmpPaint.setStrokeWidth(3); + + SkPaint paints[] = { bluePaint, bmpPaint }; + + SkRect rect; + + SkScalar dx = SkIntToScalar(80); + SkScalar dy = SkIntToScalar(100); + SkMatrix matrix; + for (size_t p = 0; p < SK_ARRAY_COUNT(paints); ++p) { + for (int stroke = 0; stroke < 2; ++stroke) { + paints[p].setStyle(stroke ? SkPaint::kStroke_Style : SkPaint::kFill_Style); + for (int a = 0; a < 3; ++ a) { + paints[p].setAntiAlias(a > 0); + paints[p].setAlpha(a > 1 ? 0x80 : 0xff); + + canvas->save(); + rect = SkRect::MakeLTRB(0.f, + 0.f, + 40.f, + 40.f); + canvas->drawRect(rect, paints[p]); + canvas->translate(dx, 0); + + rect = SkRect::MakeLTRB(0.5f, + 0.5f, + 40.5f, + 40.5f); + canvas->drawRect(rect, paints[p]); + canvas->translate(dx, 0); + + rect = SkRect::MakeLTRB(0.5f, + 0.5f, + 40.f, + 40.f); + canvas->drawRect(rect, paints[p]); + canvas->translate(dx, 0); + + rect = SkRect::MakeLTRB(0.75f, + 0.75f, + 40.75f, + 40.75f); + canvas->drawRect(rect, paints[p]); + canvas->translate(dx, 0); + + canvas->save(); + canvas->translate(.33f, .67f); + rect = SkRect::MakeLTRB(0.0f, + 0.0f, + 40.0f, + 40.0f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->save(); + matrix.setRotate(45.f); + canvas->concat(matrix); + canvas->translate(20.0f / sqrtf(2.f), + 20.0f / sqrtf(2.f)); + rect = SkRect::MakeLTRB(-20.0f, + -20.0f, + 20.0f, + 20.0f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->save(); + canvas->rotate(90.f); + rect = SkRect::MakeLTRB(0.0f, + 0.0f, + 40.0f, + -40.0f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->save(); + canvas->rotate(90.f); + rect = SkRect::MakeLTRB(0.5f, + 0.5f, + 40.5f, + -40.5f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->save(); + matrix.setScale(-1.f, -1.f); + canvas->concat(matrix); + rect = SkRect::MakeLTRB(0.5f, + 0.5f, + -40.5f, + -40.5f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->save(); + matrix.setScale(2.1f, 4.1f); + canvas->concat(matrix); + rect = SkRect::MakeLTRB(0.1f, + 0.1f, + 19.1f, + 9.1f); + canvas->drawRect(rect, paints[p]); + canvas->restore(); + canvas->translate(dx, 0); + + canvas->restore(); + canvas->translate(0, dy); + } + } + } + } + +private: + int fWidth; + + typedef SampleView INHERITED; +}; + +////////////////////////////////////////////////////////////////////////////// + +static SkView* MyFactory() { return new AARectView; } +static SkViewRegister reg(MyFactory); diff --git a/code/validation/C++/0095641_double.cpp b/code/validation/C++/0095641_double.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81f236ca881f8fd339e2d273172c0bd93bef2b00 --- /dev/null +++ b/code/validation/C++/0095641_double.cpp @@ -0,0 +1,105 @@ +// spreadsort double sorting example. +// +// Copyright Steven Ross 2009-2014. +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) + +// See http://www.boost.org/libs/sort for library home page. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace boost::sort::spreadsort; + +#define DATA_TYPE double +#define CAST_TYPE boost::int64_t + +//Pass in an argument to test std::sort +//Note that this converts NaNs and -0.0 to 0.0, so that sorting results are +//identical every time +int main(int argc, const char ** argv) { + size_t uCount,uSize=sizeof(DATA_TYPE); + bool stdSort = false; + unsigned loopCount = 1; + for (int u = 1; u < argc; ++u) { + if (std::string(argv[u]) == "-std") + stdSort = true; + else + loopCount = atoi(argv[u]); + } + std::ifstream input("input.txt", std::ios_base::in | std::ios_base::binary); + if (input.fail()) { + printf("input.txt could not be opened\n"); + return 1; + } + double total = 0.0; + std::vector array; + input.seekg (0, std::ios_base::end); + size_t length = input.tellg(); + uCount = length/uSize; + //Using this to support compilers that don't support 64-bit constants + CAST_TYPE exponent_mask = 0x7ff00000; + exponent_mask <<= 32; + CAST_TYPE top_exponent_bit = 0x40000000; + top_exponent_bit <<= 32; + //Run multiple loops, if requested + for (unsigned u = 0; u < loopCount; ++u) { + input.seekg (0, std::ios_base::beg); + //Conversion to a vector + array.resize(uCount); + unsigned v = 0; + while (input.good() && v < uCount) { + input.read(reinterpret_cast(&(array[v])), uSize ); + //Checking for denormalized numbers + if (!(float_mem_cast(array[v]) & exponent_mask)) { + //Make the top exponent bit high + CAST_TYPE temp = top_exponent_bit | + float_mem_cast(array[v]); + memcpy(&(array[v]), &temp, sizeof(DATA_TYPE)); + } + //Testcase doesn't sort NaNs; they just cause confusion + if (!(array[v] < 0.0) && !(0.0 < array[v])) + array[v] = 0.0; + ++v; + } + clock_t start, end; + double elapsed; + start = clock(); + if (stdSort) + //std::sort(&(array[0]), &(array[0]) + uCount); + std::sort(array.begin(), array.end()); + else + //float_sort(&(array[0]), &(array[0]) + uCount); + float_sort(array.begin(), array.end()); + end = clock(); + elapsed = static_cast(end - start) ; + std::ofstream ofile; + if (stdSort) + ofile.open("standard_sort_out.txt", std::ios_base::out | + std::ios_base::binary | std::ios_base::trunc); + else + ofile.open("boost_sort_out.txt", std::ios_base::out | + std::ios_base::binary | std::ios_base::trunc); + if (ofile.good()) { + for (unsigned v = 0; v < array.size(); ++v) { + ofile.write(reinterpret_cast(&(array[v])), sizeof(array[v]) ); + } + ofile.close(); + } + total += elapsed; + array.clear(); + } + if (stdSort) + printf("std::sort elapsed time %f\n", total / CLOCKS_PER_SEC); + else + printf("spreadsort elapsed time %f\n", total / CLOCKS_PER_SEC); + return 0; +} diff --git a/code/validation/C++/0096091_ConvertMQ0Bed.cpp b/code/validation/C++/0096091_ConvertMQ0Bed.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ea573a38ce908b9deba533b7e3f3b247a07a401 --- /dev/null +++ b/code/validation/C++/0096091_ConvertMQ0Bed.cpp @@ -0,0 +1,68 @@ +/* + * ConvertMQ0Bed.cpp + * + * Created on: Mar 16, 2015 + * Author: fsedlaze + */ + +#include "ConvertMQ0Bed.h" + +void comp_mq0bed(std::string cov_file, int border, int cov_tresh) { + size_t buffer_size = 2000000; + char*buffer = new char[buffer_size]; + std::ifstream myfile; + + myfile.open(cov_file.c_str(), std::ifstream::in); + if (!myfile.good()) { + std::cout << "Cov Parser: could not open file: " << cov_file.c_str() << std::endl; + exit(0); + } + + myfile.getline(buffer, buffer_size); + int start = 0; + int current = -1; + int prev = current; + std::string start_chr; + std::string chr; + while (!myfile.eof()) { + int count = 0; + int cov = 0; + for (size_t i = 0; i < buffer_size && buffer[i] != '\0' && buffer[i] != '\n'; i++) { + + if (count == 0 && buffer[i] != '\t') { + chr += buffer[i]; + } + if (count == 1 && buffer[i - 1] == '\t') { + current = atoi(&buffer[i]); + } + if (count == 2 && buffer[i - 1] == '\t') { + cov = atoi(&buffer[i]); + break; + } + + if (buffer[i] == '\t') { + count++; + } + } + //std::cout< cov_tresh) { + if (prev != -1 && abs(current - prev) > border) { + //print + if (start - border > 1) { + std::cout << start_chr << "\t" << start - border << "\t" << prev + border << std::endl; + } else { + std::cout << start_chr << "\t" << 1 << "\t" << prev + border << std::endl; + } + start = current; + start_chr = chr; + } else if (prev == -1) { + start = current; + start_chr = chr; + } + prev = current; + } + chr.clear(); + myfile.getline(buffer, buffer_size); + } + myfile.close(); +} diff --git a/code/validation/C++/0097676_a129.cpp b/code/validation/C++/0097676_a129.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d3baaef021e850b00ff0350ae10df489a964917 --- /dev/null +++ b/code/validation/C++/0097676_a129.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +using namespace std; +struct edge { long long int a, b, cost; }; + +bool cmp(edge c,edge d) +{ + return c.costgetMesh() == nullptr || + def.getModel()->getMaterial() == nullptr || + logic.getCoordinateSpace() != util::Coord::World) // Only world entities supported + return; + } + + { PROFILE(); + frameInfo.meshInfos.emplaceBack(logic, frameInfo.entityCount - 1); + } +} + +RenderingAnalyzer::Analysis RenderingAnalyzer::analyze() +{ + PROFILE(); + Analysis a; + + // Batch analysis + + SizeType group_begin_i= 0; + SizeType drawable_count= 0; + const int32 min_group_size= global::g_env.cfg->get("visual::minBatchEntityCount", 10); + const int32 max_group_size= global::g_env.cfg->get("visual::maxBatchEntityCount", 100); + const auto& mesh_infos= frameInfo.meshInfos; + + if (mesh_infos.empty() || min_group_size > max_group_size) + return a; + + for (SizeType i= 0; i < mesh_infos.size(); ++i) { + int32 group_size= i - group_begin_i; + + // If this mesh_infos[i] is last of a group + if (i + 1 == frameInfo.meshInfos.size() || + !batchCompatible(mesh_infos[i], mesh_infos[i + 1]) || + group_size == max_group_size || + mesh_infos[i + 1].unbatchable) { + + if (group_size >= min_group_size) { + a.batches.emplaceBack(); + Analysis::Batch& b= a.batches.back(); + + for (SizeType i2= group_begin_i; i2 < i + 1; ++i2){ + ensure(i2 < mesh_infos.size()); + + auto& mesh_info= mesh_infos[i2]; + + ensure(mesh_info.entityLogic); + ensure(mesh_info.entityLogic->getDef().getModel()); + + if (i2 == group_begin_i) { + // First round + b.material= mesh_info.entityLogic->getDef().getModel()->getMaterial(); + b.firstEntityDrawIndex= mesh_info.drawIndex; + } + + b.modelLogics.pushBack(mesh_info.entityLogic); + b.meshes.pushBack(asTriMesh(mesh_info.entityLogic->getDef().getModel()->getMesh())); + b.contentHash += mesh_info.contentHash; + } + drawable_count -= b.modelLogics.size() - 1; + } + group_begin_i= i + 1; + } + ++drawable_count; + } + + real64 ratio= (real64)drawable_count/mesh_infos.size(); + //print(debug::Ch::General, debug::Vb::Trivial, "Batch count: %zu", a.batches.size()); + //print(debug::Ch::General, debug::Vb::Trivial, "Optimized drawcount ratio: %f", ratio); + return a; +} + +RenderingAnalyzer::MeshInfo::MeshInfo(const visual::ModelEntityLogic& logic, SizeType i) +{ + PROFILE(); + entityLogic= &logic; + + contentHash= logic.getContentHash(); + batchCompatibilityHash= logic.getBatchCompatibilityHash(); + + // Batching normalmapped things could be done using some uv tricks + unbatchable= logic.getDef().getModel()->getMaterial()->hasTexture(Material::TexType_Normal) || + logic.getDef().getModel()->getMaterial()->hasTexture(Material::TexType_EnvShadow); + + drawIndex= i; +} + +bool RenderingAnalyzer::batchCompatible(const MeshInfo& m1, const MeshInfo& m2){ + return m1.batchCompatibilityHash == m2.batchCompatibilityHash; +} + +const TriMesh* RenderingAnalyzer::asTriMesh(const BaseMesh* mesh){ + // Only TriMeshes are batched + debug_ensure(dynamic_cast(mesh) != nullptr || mesh == nullptr); + return static_cast(mesh); +} + +uint32 RenderingAnalyzer::hash(const BaseMesh* mesh){ + if (mesh) + return mesh->getContentHash(); + else + return 0; +} + +uint32 RenderingAnalyzer::hash(const Material* mat){ + if (mat) + return mat->getContentHash(); + else + return 0; +} + +} // visual +} // clover diff --git a/code/validation/C++/0098694_388.cpp b/code/validation/C++/0098694_388.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0676d4fe3c3074e45e5957b44542098e8fbd005 --- /dev/null +++ b/code/validation/C++/0098694_388.cpp @@ -0,0 +1,85 @@ +/* + * String + * + */ + +// version 1: +class Solution { +public: + int lengthLongestPath(string input) { + int res = 0, n = input.size(), level = 0; + unordered_map m {{0, 0}}; + for (int i = 0; i < n; ++i) { + int start = i; + while (i < n && input[i] != '\n' && input[i] != '\t') ++i; + if (i >= n || input[i] == '\n') { + string t = input.substr(start, i - start); + if (t.find('.') != string::npos) { + res = max(res, m[level] + (int)t.size()); + } else { + ++level; + m[level] = m[level - 1] + (int)t.size() + 1; + } + level = 0; + } else { + ++level; + } + } + return res; + } +}; + +// Reference: +// http://www.cnblogs.com/grandyang/p/5806493.html + +// version 2: +class Solution { +public: + int lengthLongestPath(string input) { + int maxlen = 0, count = 0, level = 1; + bool isFile = false; + unordered_map levelLength; + + int i = 0; + int length = input.size(); + while (i < length) { + while (input[i] == '\t') { + ++level; + ++i; + } + + while (i < length && input[i] != '\n') { + if (input[i] == '.') + isFile = true; + + ++count; + ++i; + } + + if (isFile) { + maxlen = max(maxlen, levelLength[level - 1] + count); + } else { + levelLength[level] = levelLength[level - 1] + count + 1; + } + + count = 0; + level = 1; + isFile = false; + + ++i; + } + + return maxlen; + } +}; + +// Conclusion: +// +// Reference: +// https://youtu.be/5Nfbu6rg9v0 +// https://github.com/jzysheep/LeetCode/blob/master/388.%20Longest%20Absolute%20File%20Path.cpp +// +// + + + diff --git a/code/validation/C++/0098775_FeaturePrinter.cpp b/code/validation/C++/0098775_FeaturePrinter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efa446687c4addbb4ed81e595ea12c995bec713e --- /dev/null +++ b/code/validation/C++/0098775_FeaturePrinter.cpp @@ -0,0 +1,157 @@ +#include "..\include\FeaturePrinter.h" + +FeaturePrinter::FeaturePrinter(string file) +{ + m_ostream.open(file); + m_firstWrite = true; +} + +FeaturePrinter::~FeaturePrinter(void) +{ + if (m_ostream.is_open()) + m_ostream.close(); +} + +bool FeaturePrinter::initRelation(string relation) +{ + if (relation.size() && m_firstWrite) + m_relation = relation; + return (m_ostream.good() && m_relation.size()); +} + +int FeaturePrinter::initAttribute(string name, string type) +{ + int result = -1; + + if (m_ostream.good() && m_relation.size() && name.size() && type.size() && m_firstWrite) + { + m_attrib.push_back(name); + m_types.push_back(type); + + result = m_attrib.size() - 1; + } + + return result; +} + +bool FeaturePrinter::addData(int attribIndex, int value) +{ + bool result = false; + + if ((attribIndex >= 0) && (attribIndex < m_attrib.size())) + { + if (!m_data.size()) + { + for (int i = 0; i < m_attrib.size(); i++) + m_data.push_back(""); + } + if (m_data[attribIndex] == "") + { + m_data[attribIndex] = toString(value); + result = true; + } + } + + return result; +} + +bool FeaturePrinter::addData(int attribIndex, double value) +{ + bool result = false; + + if ((attribIndex >= 0) && (attribIndex < m_attrib.size())) + { + if (!m_data.size()) + { + for (int i = 0; i < m_attrib.size(); i++) + m_data.push_back(""); + } + if (m_data[attribIndex] == "") + { + m_data[attribIndex] = toString(value); + result = true; + } + } + + return result; +} + +bool FeaturePrinter::printData() +{ + bool result = false; + + if (m_attrib.size() && m_types.size() && m_data.size()) + { + // Verify if ready to write data + bool ready = true; + for (int d = 0; d < m_data.size(); d++) + if (m_data[d] == "") + ready = false; + + if (ready) + { + if (m_firstWrite) + { + std::string m_header; + + m_header.append("@RELATION "); m_header.append(m_relation); m_header.append("\n\n"); + for (int i = 0; i < m_attrib.size(); i++) + { + m_header.append("@ATTRIBUTE "); + m_header.append(m_attrib.at(i)); + m_header.append(" "); + m_header.append(m_types.at(i)); + m_header.append("\n"); + } + m_header.append("\n"); + + m_header.append("@DATA\n"); + + m_ostream.write(m_header.c_str(), m_header.size()); + + m_firstWrite = false; + } + + int n = 0; + std::string m_fileData; + + while (n < m_data.size()) + { + m_fileData.append(m_data[n]); + m_data[n] = ""; + n++; + if (n < m_data.size()) + m_fileData.append(","); + } + m_fileData.append("\n"); + result = true; + + m_ostream.write(m_fileData.c_str(), m_fileData.size()); + m_ostream.flush(); + } + } + + return result; +} + +string FeaturePrinter::toString(double number) +{ + char m_ch[100]; + sprintf(m_ch, "%.5f\0", number); + string m_string(m_ch); + return m_string; +} +string FeaturePrinter::toString(float number) +{ + char m_ch[100]; + sprintf(m_ch, "%.5f\0", number); + string m_string(m_ch); + return m_string; +} +string FeaturePrinter::toString(int number) +{ + char m_ch[100]; + sprintf(m_ch, "%d\0", number); + string m_string(m_ch); + return m_string; +} \ No newline at end of file diff --git a/code/validation/C++/0099447_Libertadores.cpp b/code/validation/C++/0099447_Libertadores.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a133983e555ff7d08c5c0a719fa6cca4ef1fd5f4 --- /dev/null +++ b/code/validation/C++/0099447_Libertadores.cpp @@ -0,0 +1,60 @@ +#include + +template T gcd(T a, T b) { + if(!b) return a; + return gcd(b, a % b); +} +template T lcm(T a, T b) { + return a * b / gcd(a, b); +} + +template void chmin(T& a, T b) { a = (a > b) ? b : a; } +template void chmax(T& a, T b) { a = (a < b) ? b : a; } +int in() { int x; scanf("%d", &x); return x; } + +using namespace std; + +typedef long long Int; +typedef unsigned uint; + +int N; + +int main(void) { + scanf("%d", &N); + + for (int i = 0; i < N; i++) { + int A = 0, B = 0; + int A_c = 0, B_c = 0; + + int x, y; + + scanf("%d x %d", &x, &y); + A += x; + B += y; + B_c += y; + scanf("%d x %d", &x, &y); + B += x; + A += y; + A_c += y; + + if (A != B) { + if (A > B) { + puts("Time 1"); + } else { + puts("Time 2"); + } + } else { + if (A_c != B_c) { + if (A_c > B_c) { + puts("Time 1"); + } else { + puts("Time 2"); + } + } else { + puts("Penaltis"); + } + } + } + + return 0; +} diff --git a/code/validation/C++/0102287_amisc.cpp b/code/validation/C++/0102287_amisc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ba27b99c0117c4afe532fb8526ffeaaf17b3246 --- /dev/null +++ b/code/validation/C++/0102287_amisc.cpp @@ -0,0 +1,111 @@ +//---------------------------------------------------------------------- +// A Misc ver.0.1.0 Time-stamp: <2016-11-24 05:06:56 kido> +// +// Copyright (c) 2016 Akira KIDO +// https://github.com/kido-akira/atools +// This software is released under the MIT License. +// http://opensource.org/licenses/mit-license.php +//---------------------------------------------------------------------- +#include +#include +#include +using namespace std; + +#include "amisc.h" + +namespace atools { + +//---------------------------------------------------------------------- +// AMisc : Miscellaneous +//---------------------------------------------------------------------- +void errlog(const char* file, int line, + const char* fmt, ...) { + va_list args; + va_start(args, fmt); + char pos[BUFSIZ]; + snprintf(pos, sizeof(pos), "%s:%d ", file, line); + char tmp[BUFSIZ]; + vsnprintf(tmp, sizeof(tmp), fmt, args); + cerr << pos << tmp << endl; + va_end(args); +} + +void errfmt(const char* fmt, ...) { + va_list args; + va_start(args, fmt); + char tmp[BUFSIZ]; + vsnprintf(tmp, sizeof(tmp), fmt, args); + cerr << tmp << endl; + va_end(args); +} + +void outfmt(const char* fmt, ...) { + va_list args; + va_start(args, fmt); + char tmp[BUFSIZ]; + vsnprintf(tmp, sizeof(tmp), fmt, args); + cout << tmp << endl; + cout.flush(); + va_end(args); +} + +void ofsfmt(ofstream& ofs, + const char* fmt, ...) { + va_list args; + va_start(args, fmt); + char tmp[BUFSIZ]; + vsnprintf(tmp, sizeof(tmp), fmt, args); + ofs << tmp << endl; + ofs.flush(); + va_end(args); +} + +string strfmt(const char* fmt, ...) { + va_list args; + va_start(args, fmt); + char tmp[BUFSIZ]; + vsnprintf(tmp, sizeof(tmp), fmt, args); + va_end(args); + return tmp; +} + +int tokenizer(const std::string& text, + std::vector& token, + const char delimiter) { + token.clear(); + const int imax = (int)text.size(); + int ipos = 0; + int istep = 1; + for(int i = 0; i < imax; i += istep) { + unsigned char a = text[i]; + if (a < 0x80) { + istep = 1; + if(a == (unsigned char)delimiter) { + token.push_back(text.substr(ipos, i - ipos)); + ipos = i + 1; + } + } else if (a < 0xE0) { + istep = 2; + } else if (a < 0xF0) { + istep = 3; + } else { + istep = 4; + } + } + if(ipos < imax) { + token.push_back(text.substr(ipos, imax - ipos)); + } + return (int)token.size(); +} + +void getlinetrim(ifstream& ifs, string& buf) { + std::getline(ifs, buf); + if(buf[buf.length() - 1] == '\n') buf.erase(buf.end() - 1); + if(buf[buf.length() - 1] == '\r') buf.erase(buf.end() - 1); +} + +} //namespace atools + +//---------------------------------------------------------------------- +// End Of File +//---------------------------------------------------------------------- diff --git a/code/validation/C++/0102901_UVa_696_-_How_Many_Knights_.cpp b/code/validation/C++/0102901_UVa_696_-_How_Many_Knights_.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b2e0a645eb24470180c95bddf1f7759e851909f --- /dev/null +++ b/code/validation/C++/0102901_UVa_696_-_How_Many_Knights_.cpp @@ -0,0 +1,72 @@ +//============================================================================ +// Name : UVA_AGAIN.cpp +// Author : Pegasus99 +// Version : +// Copyright : Your copyright notice +// Description : Hello World in C++, Ansi-style +//============================================================================ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // std::setprecision +#include +#include +#include + +#define REP(i, n) for(int i=0; iN){ + swap(M,N); + } + + if (M==1){ + res =N; + } + else if (M==2){ + if (N%2==0){ + res =calculate_res(N); + } + else{ + if ( (N+1)%4==0){ + res =calculate_res(++N); + + }else{ + res =calculate_res(++N); + res-=2; + } + } + } + else{ + res = (N*M+1)/2; + } + + printf("%d knights may be placed on a %d row %d column board.\n",res,t1,t2); + } + return 0; +} diff --git a/code/validation/C++/0103409_ImplicitFunctionParserFactory.cpp b/code/validation/C++/0103409_ImplicitFunctionParserFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f136072e0098ff059d8f3cd022e1f7964b4814c8 --- /dev/null +++ b/code/validation/C++/0103409_ImplicitFunctionParserFactory.cpp @@ -0,0 +1,81 @@ +// Mantid Repository : https://github.com/mantidproject/mantid +// +// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI, +// NScD Oak Ridge National Laboratory, European Spallation Source +// & Institut Laue - Langevin +// SPDX - License - Identifier: GPL - 3.0 + +#include "MantidAPI/ImplicitFunctionParserFactory.h" + +#include +#include +#include +#include + +namespace Mantid { +namespace API { + +boost::shared_ptr +ImplicitFunctionParserFactoryImpl::create(const std::string &xmlString) const { + UNUSED_ARG(xmlString); + throw std::runtime_error("Use of create in this context is forbidden. Use " + "createUnwrappedInstead."); +} + +ImplicitFunctionParser * +ImplicitFunctionParserFactoryImpl::createImplicitFunctionParserFromXML( + Poco::XML::Element *functionElement) const { + const std::string &name = functionElement->localName(); + if (name != "Function") { + throw std::runtime_error( + "Root node must be a Funtion element. Unable to determine parsers."); + } + + Poco::XML::Element *typeElement = functionElement->getChildElement("Type"); + std::string functionParserName = typeElement->innerText() + "Parser"; + ImplicitFunctionParser *functionParser = + this->createUnwrapped(functionParserName); + + Poco::XML::Element *parametersElement = + functionElement->getChildElement("ParameterList"); + + // Get the parameter parser for the current function parser and append that to + // the function parser. + ImplicitFunctionParameterParser *paramParser = + Mantid::API::ImplicitFunctionParameterParserFactory::Instance() + .createImplicitFunctionParameterParserFromXML(parametersElement); + functionParser->setParameterParser(paramParser); + + Poco::AutoPtr childFunctions = + functionElement->getElementsByTagName("Function"); + ImplicitFunctionParser *childParser = nullptr; + for (unsigned long i = 0; i < childFunctions->length(); i++) { + // Recursive call to handle nested parameters. + ImplicitFunctionParser *tempParser = createImplicitFunctionParserFromXML( + dynamic_cast(childFunctions->item(i))); + if (i == 0) { + childParser = tempParser; + // Add the first child function parser to the parent (composite) directly. + functionParser->setSuccessorParser(childParser); + } else { + // Add all other function parsers are added as successors to those before + // them in the loop. + childParser->setSuccessorParser(tempParser); + childParser = tempParser; + } + } + + return functionParser; +} + +ImplicitFunctionParser * +ImplicitFunctionParserFactoryImpl::createImplicitFunctionParserFromXML( + const std::string &functionXML) const { + using namespace Poco::XML; + DOMParser pParser; + AutoPtr pDoc = pParser.parseString(functionXML); + Element *pRootElem = pDoc->documentElement(); + + return createImplicitFunctionParserFromXML(pRootElem); +} +} // namespace API +} // namespace Mantid diff --git a/code/validation/C++/0103504_field_mask_utility.cc b/code/validation/C++/0103504_field_mask_utility.cc new file mode 100644 index 0000000000000000000000000000000000000000..92468959a75f45ab82518926573ec292fd9f75f5 --- /dev/null +++ b/code/validation/C++/0103504_field_mask_utility.cc @@ -0,0 +1,228 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER 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 + +#include +#include + +namespace google { + +namespace protobuf { +namespace util { +namespace converter { + +namespace { +inline util::Status CallPathSink(PathSinkCallback path_sink, + StringPiece arg) { + return path_sink->Run(arg); +} + +util::Status CreatePublicError(util::error::Code code, + const string& message) { + return util::Status(code, message); +} + +// Appends a FieldMask path segment to a prefix. +string AppendPathSegmentToPrefix(StringPiece prefix, StringPiece segment) { + if (prefix.empty()) { + return segment.ToString(); + } + if (segment.empty()) { + return prefix.ToString(); + } + // If the segment is a map key, appends it to the prefix without the ".". + if (segment.starts_with("[\"")) { + return StrCat(prefix, segment); + } + return StrCat(prefix, ".", segment); +} + +} // namespace + +string ConvertFieldMaskPath(const StringPiece path, + ConverterCallback converter) { + string result; + result.reserve(path.size() << 1); + + bool is_quoted = false; + bool is_escaping = false; + int current_segment_start = 0; + + // Loops until 1 passed the end of the input to make handling the last + // segment easier. + for (size_t i = 0; i <= path.size(); ++i) { + // Outputs quoted string as-is. + if (is_quoted) { + if (i == path.size()) { + break; + } + result.push_back(path[i]); + if (is_escaping) { + is_escaping = false; + } else if (path[i] == '\\') { + is_escaping = true; + } else if (path[i] == '\"') { + current_segment_start = i + 1; + is_quoted = false; + } + continue; + } + if (i == path.size() || path[i] == '.' || path[i] == '(' || + path[i] == ')' || path[i] == '\"') { + result += converter( + path.substr(current_segment_start, i - current_segment_start)); + if (i < path.size()) { + result.push_back(path[i]); + } + current_segment_start = i + 1; + } + if (i < path.size() && path[i] == '\"') { + is_quoted = true; + } + } + return result; +} + +util::Status DecodeCompactFieldMaskPaths(StringPiece paths, + PathSinkCallback path_sink) { + stack prefix; + int length = paths.length(); + int previous_position = 0; + bool in_map_key = false; + bool is_escaping = false; + // Loops until 1 passed the end of the input to make the handle of the last + // segment easier. + for (int i = 0; i <= length; ++i) { + if (i != length) { + // Skips everything in a map key until we hit the end of it, which is + // marked by an un-escaped '"' immediately followed by a ']'. + if (in_map_key) { + if (is_escaping) { + is_escaping = false; + continue; + } + if (paths[i] == '\\') { + is_escaping = true; + continue; + } + if (paths[i] != '\"') { + continue; + } + // Un-escaped '"' must be followed with a ']'. + if (i >= length - 1 || paths[i + 1] != ']') { + return CreatePublicError( + util::error::INVALID_ARGUMENT, + StrCat("Invalid FieldMask '", paths, + "'. Map keys should be represented as [\"some_key\"].")); + } + // The end of the map key ("\"]") has been found. + in_map_key = false; + // Skips ']'. + i++; + // Checks whether the key ends at the end of a path segment. + if (i < length - 1 && paths[i + 1] != '.' && paths[i + 1] != ',' && + paths[i + 1] != ')' && paths[i + 1] != '(') { + return CreatePublicError( + util::error::INVALID_ARGUMENT, + StrCat("Invalid FieldMask '", paths, + "'. Map keys should be at the end of a path segment.")); + } + is_escaping = false; + continue; + } + + // We are not in a map key, look for the start of one. + if (paths[i] == '[') { + if (i >= length - 1 || paths[i + 1] != '\"') { + return CreatePublicError( + util::error::INVALID_ARGUMENT, + StrCat("Invalid FieldMask '", paths, + "'. Map keys should be represented as [\"some_key\"].")); + } + // "[\"" starts a map key. + in_map_key = true; + i++; // Skips the '\"'. + continue; + } + // If the current character is not a special character (',', '(' or ')'), + // continue to the next. + if (paths[i] != ',' && paths[i] != ')' && paths[i] != '(') { + continue; + } + } + // Gets the current segment - sub-string between previous position (after + // '(', ')', ',', or the beginning of the input) and the current position. + StringPiece segment = + paths.substr(previous_position, i - previous_position); + string current_prefix = prefix.empty() ? "" : prefix.top(); + + if (i < length && paths[i] == '(') { + // Builds a prefix and save it into the stack. + prefix.push(AppendPathSegmentToPrefix(current_prefix, segment)); + } else if (!segment.empty()) { + // When the current charactor is ')', ',' or the current position has + // passed the end of the input, builds and outputs a new paths by + // concatenating the last prefix with the current segment. + RETURN_IF_ERROR(CallPathSink( + path_sink, AppendPathSegmentToPrefix(current_prefix, segment))); + } + + // Removes the last prefix after seeing a ')'. + if (i < length && paths[i] == ')') { + if (prefix.empty()) { + return CreatePublicError( + util::error::INVALID_ARGUMENT, + StrCat("Invalid FieldMask '", paths, + "'. Cannot find matching '(' for all ')'.")); + } + prefix.pop(); + } + previous_position = i + 1; + } + if (in_map_key) { + return CreatePublicError( + util::error::INVALID_ARGUMENT, + StrCat("Invalid FieldMask '", paths, + "'. Cannot find matching ']' for all '['.")); + } + if (!prefix.empty()) { + return CreatePublicError( + util::error::INVALID_ARGUMENT, + StrCat("Invalid FieldMask '", paths, + "'. Cannot find matching ')' for all '('.")); + } + return util::Status::OK; +} + +} // namespace converter +} // namespace util +} // namespace protobuf +} // namespace google diff --git a/code/validation/C++/0104924_kurtosis.cpp b/code/validation/C++/0104924_kurtosis.cpp new file mode 100644 index 0000000000000000000000000000000000000000..611573756933a437e00d7e4aefdcebfba1998d90 --- /dev/null +++ b/code/validation/C++/0104924_kurtosis.cpp @@ -0,0 +1,95 @@ +#include +#include +#include +#include +#include +#include +#include // include as well: regex, string, vector + +typedef double real_t; +typedef std::vector state_type; + +int +kernel(std::string basedir, double const start_t, double const end_t, double const step_t, bool verbose=false) +{ + //double t = start_t; + + std::vector kurtosis; + + std::regex re("...x_t(\\d+.\\d+).bin"); + + dir::tmin = start_t; + dir::tmax = end_t; + dir::step = step_t; + + state_type x, v; + + for (auto pathname: dir::search(basedir, re, [](double t){ return t >= dir::tmin && t <= dir::tmax; })) + { + md::data::load<1, state_type>(x, v, basedir + pathname); + + size_t n = x.size(); + + double xa = accumulate(x.begin(), x.end(), 0.); + double va = accumulate(v.begin(), v.end(), 0.); + double x4 = 0, x2 = 0; + double v4 = 0, v2 = 0; + + for (size_t i = 0; i < n; ++i) + { + double x2i = (x[i] - xa) * (x[i] - xa); + double v2i = (v[i] - va) * (v[i] - va); + + x4 += x2i * x2i; + x2 += x2i; + + v4 += v2i * v2i; + v2 += v2i; + } + double Kx = n * x4 / x2 / x2; + double Kv = n * v4 / v2 / v2; + + std::cmatch cm; + std::regex_match(pathname.c_str(), cm, re); + + std::cout << cm[1] << '\t' << Kx << '\t' << Kv << std::endl; + } + + + //std::string pathname = "../2DSGS/C2DA/DATA/R010/2DSGS_NP131072/sgsz_t0.00.bin"; + + + return 0; +} + +int +main(int argc, char* argv[]) +{ + int Return = 0x00; + double start_t = 0.; + double end_t = std::numeric_limits::max(); + double step_t = 1.; + std::string basedir = "./"; + + switch (argc) + { + case 5: + step_t = atof(argv[4]); + case 4: + end_t = atof(argv[3]); + case 3: + start_t = atof(argv[2]); + case 2: + basedir = std::string(argv[1]); + + if (1) //TODO: conditions + break; + default: + std::cout << "Usage: " << argv[0] << " basedir [, start_t, end_t, step_t]" << std::endl; + Return = !Return; + } + if (Return == 0x00) + Return = kernel(basedir, start_t, end_t, step_t); + + return Return; +} diff --git a/code/validation/C++/0105589_txindex.cpp b/code/validation/C++/0105589_txindex.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ebfa5d2fa47f0ee37ab8f095009fbe8534157d47 --- /dev/null +++ b/code/validation/C++/0105589_txindex.cpp @@ -0,0 +1,258 @@ +// Copyright (c) 2017-2019 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include +#include +#include +#include +#include +#include +#include + +constexpr char DB_BEST_BLOCK = 'B'; +constexpr char DB_TXINDEX = 't'; +constexpr char DB_TXINDEX_BLOCK = 'T'; + +std::unique_ptr g_txindex; + + + +/** Access to the txindex database (indexes/txindex/) */ +class TxIndex::DB : public BaseIndex::DB +{ +public: + explicit DB(size_t n_cache_size, bool f_memory = false, bool f_wipe = false); + + /// Read the disk location of the transaction data with the given hash. Returns false if the + /// transaction hash is not indexed. + bool ReadTxPos(const uint256& txid, CDiskTxPos& pos) const; + + /// Write a batch of transaction positions to the DB. + bool WriteTxs(const std::vector>& v_pos); + + /// Migrate txindex data from the block tree DB, where it may be for older nodes that have not + /// been upgraded yet to the new database. + bool MigrateData(CBlockTreeDB& block_tree_db, const CBlockLocator& best_locator); +}; + +TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe) : + BaseIndex::DB(GetDataDir() / "indexes" / "txindex", n_cache_size, f_memory, f_wipe) +{} + +bool TxIndex::DB::ReadTxPos(const uint256 &txid, CDiskTxPos& pos) const +{ + return Read(std::make_pair(DB_TXINDEX, txid), pos); +} + +bool TxIndex::DB::WriteTxs(const std::vector>& v_pos) +{ + CDBBatch batch(*this); + for (const auto& tuple : v_pos) { + batch.Write(std::make_pair(DB_TXINDEX, tuple.first), tuple.second); + } + return WriteBatch(batch); +} + +/* + * Safely persist a transfer of data from the old txindex database to the new one, and compact the + * range of keys updated. This is used internally by MigrateData. + */ +static void WriteTxIndexMigrationBatches(CDBWrapper& newdb, CDBWrapper& olddb, + CDBBatch& batch_newdb, CDBBatch& batch_olddb, + const std::pair& begin_key, + const std::pair& end_key) +{ + // Sync new DB changes to disk before deleting from old DB. + newdb.WriteBatch(batch_newdb, /*fSync=*/ true); + olddb.WriteBatch(batch_olddb); + olddb.CompactRange(begin_key, end_key); + + batch_newdb.Clear(); + batch_olddb.Clear(); +} + +bool TxIndex::DB::MigrateData(CBlockTreeDB& block_tree_db, const CBlockLocator& best_locator) +{ + // The prior implementation of txindex was always in sync with block index + // and presence was indicated with a boolean DB flag. If the flag is set, + // this means the txindex from a previous version is valid and in sync with + // the chain tip. The first step of the migration is to unset the flag and + // write the chain hash to a separate key, DB_TXINDEX_BLOCK. After that, the + // index entries are copied over in batches to the new database. Finally, + // DB_TXINDEX_BLOCK is erased from the old database and the block hash is + // written to the new database. + // + // Unsetting the boolean flag ensures that if the node is downgraded to a + // previous version, it will not see a corrupted, partially migrated index + // -- it will see that the txindex is disabled. When the node is upgraded + // again, the migration will pick up where it left off and sync to the block + // with hash DB_TXINDEX_BLOCK. + bool f_legacy_flag = false; + block_tree_db.ReadFlag("txindex", f_legacy_flag); + if (f_legacy_flag) { + if (!block_tree_db.Write(DB_TXINDEX_BLOCK, best_locator)) { + return error("%s: cannot write block indicator", __func__); + } + if (!block_tree_db.WriteFlag("txindex", false)) { + return error("%s: cannot write block index db flag", __func__); + } + } + + CBlockLocator locator; + if (!block_tree_db.Read(DB_TXINDEX_BLOCK, locator)) { + return true; + } + + int64_t count = 0; + LogPrintf("Upgrading txindex database... [0%%]\n"); + uiInterface.ShowProgress(_("Upgrading txindex database").translated, 0, true); + int report_done = 0; + const size_t batch_size = 1 << 24; // 16 MiB + + CDBBatch batch_newdb(*this); + CDBBatch batch_olddb(block_tree_db); + + std::pair key; + std::pair begin_key{DB_TXINDEX, uint256()}; + std::pair prev_key = begin_key; + + bool interrupted = false; + std::unique_ptr cursor(block_tree_db.NewIterator()); + for (cursor->Seek(begin_key); cursor->Valid(); cursor->Next()) { + if (ShutdownRequested()) { + interrupted = true; + break; + } + + if (!cursor->GetKey(key)) { + return error("%s: cannot get key from valid cursor", __func__); + } + if (key.first != DB_TXINDEX) { + break; + } + + // Log progress every 10%. + if (++count % 256 == 0) { + // Since txids are uniformly random and traversed in increasing order, the high 16 bits + // of the hash can be used to estimate the current progress. + const uint256& txid = key.second; + uint32_t high_nibble = + (static_cast(*(txid.begin() + 0)) << 8) + + (static_cast(*(txid.begin() + 1)) << 0); + int percentage_done = (int)(high_nibble * 100.0 / 65536.0 + 0.5); + + uiInterface.ShowProgress(_("Upgrading txindex database").translated, percentage_done, true); + if (report_done < percentage_done/10) { + LogPrintf("Upgrading txindex database... [%d%%]\n", percentage_done); + report_done = percentage_done/10; + } + } + + CDiskTxPos value; + if (!cursor->GetValue(value)) { + return error("%s: cannot parse txindex record", __func__); + } + batch_newdb.Write(key, value); + batch_olddb.Erase(key); + + if (batch_newdb.SizeEstimate() > batch_size || batch_olddb.SizeEstimate() > batch_size) { + // NOTE: it's OK to delete the key pointed at by the current DB cursor while iterating + // because LevelDB iterators are guaranteed to provide a consistent view of the + // underlying data, like a lightweight snapshot. + WriteTxIndexMigrationBatches(*this, block_tree_db, + batch_newdb, batch_olddb, + prev_key, key); + prev_key = key; + } + } + + // If these final DB batches complete the migration, write the best block + // hash marker to the new database and delete from the old one. This signals + // that the former is fully caught up to that point in the blockchain and + // that all txindex entries have been removed from the latter. + if (!interrupted) { + batch_olddb.Erase(DB_TXINDEX_BLOCK); + batch_newdb.Write(DB_BEST_BLOCK, locator); + } + + WriteTxIndexMigrationBatches(*this, block_tree_db, + batch_newdb, batch_olddb, + begin_key, key); + + if (interrupted) { + LogPrintf("[CANCELLED].\n"); + return false; + } + + uiInterface.ShowProgress("", 100, false); + + LogPrintf("[DONE].\n"); + return true; +} + +TxIndex::TxIndex(size_t n_cache_size, bool f_memory, bool f_wipe) + : m_db(MakeUnique(n_cache_size, f_memory, f_wipe)) +{} + +TxIndex::~TxIndex() {} + +bool TxIndex::Init() +{ + LOCK(cs_main); + + // Attempt to migrate txindex from the old database to the new one. Even if + // chain_tip is null, the node could be reindexing and we still want to + // delete txindex records in the old database. + if (!m_db->MigrateData(*pblocktree, ::ChainActive().GetLocator())) { + return false; + } + + return BaseIndex::Init(); +} + +bool TxIndex::WriteBlock(const CBlock& block, const CBlockIndex* pindex) +{ + // Exclude genesis block transaction because outputs are not spendable. + //ELEMENTS: we do index the genesis block + //if (pindex->nHeight == 0) return true; + + CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size())); + std::vector> vPos; + vPos.reserve(block.vtx.size()); + for (const auto& tx : block.vtx) { + vPos.emplace_back(tx->GetHash(), pos); + pos.nTxOffset += ::GetSerializeSize(*tx, CLIENT_VERSION); + } + return m_db->WriteTxs(vPos); +} + +BaseIndex::DB& TxIndex::GetDB() const { return *m_db; } + +bool TxIndex::FindTx(const uint256& tx_hash, uint256& block_hash, CTransactionRef& tx) const +{ + CDiskTxPos postx; + if (!m_db->ReadTxPos(tx_hash, postx)) { + return false; + } + + CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION); + if (file.IsNull()) { + return error("%s: OpenBlockFile failed", __func__); + } + CBlockHeader header; + try { + file >> header; + if (fseek(file.Get(), postx.nTxOffset, SEEK_CUR)) { + return error("%s: fseek(...) failed", __func__); + } + file >> tx; + } catch (const std::exception& e) { + return error("%s: Deserialize or I/O error - %s", __func__, e.what()); + } + if (tx->GetHash() != tx_hash) { + return error("%s: txid mismatch", __func__); + } + block_hash = header.GetHash(); + return true; +} diff --git a/code/validation/C/0001652_ex_5_15.c b/code/validation/C/0001652_ex_5_15.c new file mode 100644 index 0000000000000000000000000000000000000000..a3cc6415ae456fb77a336e8e890effb12f5918ce --- /dev/null +++ b/code/validation/C/0001652_ex_5_15.c @@ -0,0 +1,208 @@ +#include +#include + +#define ALLOCSIZE 10000 +#define MAXLINES 5000 +#define MAXLEN 1000 + +char *lineptr[MAXLINES]; + +int readlines(char *lineptr[], int nlines); +void writelines(char *lineptr[], int nlines); + +void my_qsort(void *lineptr[], int left, int right, int rev, + int (*comp)(void *, void *)); +int numcmp(char *, char *); +void reverse(char *lineptr[], int nlines); +void to_lower(char *line, char *line2); +int strcmp_lower(char *line, char *line2); + +/* sort input lines */ +int main(int argc, char *argv[]) +{ + int nlines; + int numeric = 0; + int rev = 1; + int folding = 0; + char c; + + while (--argc > 0 && (*++argv)[0] == '-') { + while ((c = *++argv[0])) { + switch(c) { + case 'n': + numeric = 1; + break; + case 'r': + rev = -1; + break; + case 'f': + folding = 1; + break; + default: + printf("sortlines: illegal option %c\n", c); + argc = -1; + break; + } + } + } + if (argc != 0) + printf("Usage: sortlines -n -r"); + else { + + if ((nlines = readlines(lineptr, MAXLINES)) >= 0) { + my_qsort((void **) lineptr, 0, nlines-1, rev, + (int (*)(void*,void*))(numeric ? numcmp : (folding ? strcmp_lower : strcmp))); + writelines(lineptr, nlines); + return 0; + } else { + printf("input too big to sort\n"); + return 1; + } + } +} + +int strcmp_lower(char *s1, char *s2) +{ + char a1[MAXLEN]; + char a2[MAXLEN]; + + to_lower(s1, a1); + to_lower(s2, a2); + + return strcmp(a1, a2); +} + + +/* to_lower: copy line to target, but with all characters in lower case */ +void to_lower(char *line, char *target) +{ + while (*line) { + if (*line <= 'Z' && *line >= 'A') + *(target++) = *(line++) - 'A' + 'a'; + else + *(target++) = *(line++); + } + *target = '\0'; +} + +void reverse(char *lineptr[], int nlines) +{ + char temp[MAXLEN]; + char **end = lineptr + nlines; + + while (lineptr < end) { + strcpy(temp, *lineptr); + strcpy(*(lineptr++), *end); + strcpy(*(end--), temp); + } +} + + +void my_qsort(void *v[], int left, int right, int rev, + int (*comp)(void *, void *)) +{ + int i, last; + void swap(void *v[], int, int); + + if (left >= right) + return; + swap(v, left, (left + right) / 2); + last = left; + for (i = left+1; i <= right; i++) { + if ((*comp)(v[i], v[left]) * rev < 0) + swap(v, ++last, i); + } + swap(v, left, last); + my_qsort(v, left, last-1, rev, comp); + my_qsort(v, last+1, right, rev, comp); +} + +#include + +int numcmp(char *s1, char *s2) +{ + double v1, v2; + + v1 = atof(s1); + v2 = atof(s2); + if (v1 < v2) + return -1; + else if (v1 > v2) + return 1; + else + return 0; +} + +void swap(void *v[], int i, int j) +{ + void *temp; + + temp = v[i]; + v[i] = v[j]; + v[j] = temp; +} + +int my_getline(char *, int); +char *alloc(int); + +int readlines(char *lineptr[], int maxlines) +{ + int len, nlines; + char *p, line[MAXLEN]; + + nlines = 0; + while ((len=my_getline(line, MAXLEN)) > 0) { + if (nlines >= maxlines || (p = alloc(len)) == NULL) + return -1; + else { + line[len-1] = '\0'; + strcpy(p, line); + lineptr[nlines++] = p; + } + } + return nlines; +} + +void writelines(char *lineptr[], int nlines) +{ + int i; + + for (i=0; i= n) { + allocp += n; + return allocp - n; + } + else + return 0; +} + +void afree(char *p) +{ + if (p >= allocbuf && p < allocbuf + ALLOCSIZE) + allocp = p; +} diff --git a/code/validation/C/0003615_4byte_time.c b/code/validation/C/0003615_4byte_time.c new file mode 100644 index 0000000000000000000000000000000000000000..136224965f92aad65c3539bbb0bfaad332ebcf0f --- /dev/null +++ b/code/validation/C/0003615_4byte_time.c @@ -0,0 +1,51 @@ +/* + * Userspace c library Example to measure delay between two 4 byte writes but this time includes cycles taken to calculate the delay + * + * Copyright (C) 2015 Apaar Gupta + * This file is licensed under the terms of the GNU General Public License + * version 2. This program is licensed "as is" without any warranty of any + * kind, whether express or implied. + */ + +#include "pru_bridge.h" +#include "pru_defs.h" + +static inline u32 read_PIEP_COUNT(void) +{ + return PIEP_COUNT; +} + +int main() +{ + + + /* configure timer */ + PIEP_GLOBAL_CFG = GLOBAL_CFG_CNT_ENABLE | + GLOBAL_CFG_DEFAULT_INC(1) | + GLOBAL_CFG_CMP_INC(1); + PIEP_CMP_STATUS = CMD_STATUS_CMP_HIT(1); + PIEP_CMP_CFG |= CMP_CFG_CMP_EN(1); + + int current = 0,last = 0,delay = 0; + + while(check_init() != 1); + + uint8_t check_flag = 0; //getting the pru to wait until we are ready to read + while(check_flag == 0) + { + read_buffer(1,&check_flag,1); + } + + while(1) + { + //if(check_index(0)) //checking if the buffer is full or not + //{ + current = read_PIEP_COUNT(); + delay = current - last; + write_buffer(0,(uint8_t*)(&delay),4); + last = current; + //} + } + +return 0; +} diff --git a/code/validation/C/0004512_lpcpatchelf.c b/code/validation/C/0004512_lpcpatchelf.c new file mode 100644 index 0000000000000000000000000000000000000000..dc63738018592c00ce9ba3aa82a77a5230e5a9b8 --- /dev/null +++ b/code/validation/C/0004512_lpcpatchelf.c @@ -0,0 +1,268 @@ +/* + * File : lpcpatchelf.c + * + * Description: Utility to compute and patch the correct flash image + * checksum into LPC17xx (and other LPC microcontrollers) + * + * Author : Nils Pipenbrinck + * Copyright : (C) Nils Pipenbrinck 2016 + * Website : http://hilbert-space.de/?p=178 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define VERSION_MAJ 1 +#define VERSION_MIN 0 +#define NUMVECTORS 8 + +static uint32_t get_lpc_signature (const uint32_t *sig, + int NumVectors, + int CheckVector) +////////////////////////////////////////////////////////////// +{ + uint32_t cksum = 0; + for (int i = 0; i < NumVectors; i++) + { + if (i != CheckVector) + cksum += sig[i]; + } + return 0-cksum; +} + + +bool check_arm (Elf *e) +/////////////////////// +{ + Elf32_Ehdr * hdr = elf32_getehdr (e); + if (!hdr) + { + fprintf (stderr, "elf32_getehdr failed %s\n", elf_errmsg(elf_errno())); + return false; + } + + if (hdr->e_machine != EM_ARM) + { + fprintf (stderr, "Sorry, this is not an ARM-binary\n"); + return false; + } + return true; +} + + +bool patch_elf (const char * filename, int CheckVector) +//////////////////////////////////////////////////////// +{ + bool patch_success = false; + + if (elf_version(EV_CURRENT) == EV_NONE) + { + fprintf (stderr, "ELF library too old\n"); + return false; + } + + int fd = open (filename, O_RDWR); + if (fd <0) + { + fprintf (stderr, "unable to open file %s\n", filename); + return false; + } + + Elf *e = elf_begin(fd, ELF_C_RDWR, (Elf *) 0); + if (!e) + { + fprintf (stderr, "elf_begin failed %s\n", elf_errmsg(elf_errno())); + return false; + } + + // We don't want libelf to mess with our layout in any way! + // libelf may break arm binaries otherwise. + if (!elf_flagelf (e, ELF_C_SET, ELF_F_LAYOUT)) + { + fprintf (stderr, "elf_flagelf failed %s\n", elf_errmsg(elf_errno())); + return false; + } + + if (!check_arm(e)) + { + return false; + } + + // find the code-section: + Elf_Scn * section = 0; + while ((section = elf_nextscn(e, section)) != 0) + { + Elf32_Shdr * hdr = elf32_getshdr (section); + if (!hdr) + { + fprintf (stderr, "elf32_getshdr failed %s\n", elf_errmsg(elf_errno())); + return false; + } + + if ( (hdr->sh_flags & SHF_ALLOC) && + (hdr->sh_flags & SHF_EXECINSTR) && + (hdr->sh_addr == 0) && + (hdr->sh_size >= NUMVECTORS*sizeof(uint32_t))) + { + Elf_Data *data = elf_getdata (section, 0); + + if (!data->d_buf) + { + fprintf (stderr, "executable section seems to be empty\n"); + return false; + } + + uint32_t signature[NUMVECTORS]; + + memcpy (signature, data->d_buf, NUMVECTORS * sizeof (uint32_t)); + uint32_t cksum = get_lpc_signature(signature, NUMVECTORS, CheckVector); + + printf ("old checksum: %08x\n", signature[CheckVector]); + printf ("new checksum: %08x\n", cksum); + signature[CheckVector] = cksum; + + // tag data-chunk as dirty. This forces recalculation of the elf checksum. + if (!elf_flagdata (data, ELF_C_SET, ELF_F_DIRTY)) + { + fprintf (stderr, "elf_flagdata failed %s\n", elf_errmsg(elf_errno())); + return false; + } + + // update ELF-file: + memcpy (data->d_buf, signature, NUMVECTORS * sizeof (uint32_t)); + + if (elf_update(e, ELF_C_WRITE) == -1) + { + fprintf (stderr, "elf_update failed %s\n", elf_errmsg(elf_errno())); + return false; + } + + // we're done: + patch_success = true; + break; + } + } + + elf_end (e); + close (fd); + return patch_success; +} + + +void help () +//////////// +{ + printf ("Usage: lpcpatchelf -f file.elf [-c PositionOfChecksum]\n"); + printf ("\n"); + printf (" PositionOfChecksum:\n"); + printf ("\n"); + printf (" The -c option tells where to place the checksum into the interrupt\n"); + printf (" table. Default is 7 for LPC17xx and most other LPC microcontrollers\n"); + printf (" for the LPC2000 family use uses position 5\n"); + printf ("\n"); + printf ("\n"); + printf ("lpcpatchelf - Updates LPC ARM processor specific checksum in elf-binaries.\n"); + printf ("\n"); + printf ("Copyright (C) 2016 Nils Pipenbrinck Email: n.pipenbrinck@hilbert-space.de\n"); + printf ("Version %d.%d, compiled %s\n", VERSION_MAJ, VERSION_MIN, __DATE__); + printf ("\n"); + printf ("This program is free software; you can redistribute it and/or\n"); + printf ("modify it under the terms of the GNU General Public License\n"); + printf ("as published by the Free Software Foundation; either version 2\n"); + printf ("of the License, or (at your option) any later version.\n"); +} + + +int main (int argc, char **argv) +///////////////////////////////// +{ + const char * elf_file = 0; + int c; + + // Defaults for LPC17xx and LPC43xx familiy + int CheckVector = 7; + + while ((c = getopt (argc, argv, "f:n:c:")) != -1) + { + switch (c) + { + case 'f': + elf_file = optarg; + break; + + case 'c': + CheckVector = atol(optarg); + break; + + case '?': + if ((optopt == 'f') || (optopt == 'c')) + { + fprintf (stderr, "Option -%c requires an argument.\n", optopt); + } + else if (isprint (optopt)) + { + fprintf (stderr, "Unknown option `-%c'.\n", optopt); + } + else + { + fprintf (stderr,"Unknown option character `\\x%x'.\n", optopt); + } + help(); + return EXIT_FAILURE; + + default: + help(); + abort (); + } + } + + if ((CheckVector <0) || (CheckVector >= NUMVECTORS)) + { + fprintf (stderr, "illegal PositionOfChecksum value\n"); + return EXIT_FAILURE; + } + + if (elf_file) + { + if (patch_elf(elf_file, CheckVector)) + { + return EXIT_SUCCESS; + } + else + { + fprintf (stderr, "something failed, probably you've passed an .elf file that this program doesn't understand\n"); + return EXIT_FAILURE; + } + } + else + { + help(); + return EXIT_FAILURE; + } +} + +/*EOF */ diff --git a/code/validation/C/0005269_gss_oid_to_str.c b/code/validation/C/0005269_gss_oid_to_str.c new file mode 100644 index 0000000000000000000000000000000000000000..a1d776877245868034fa173d52f7305024d367a1 --- /dev/null +++ b/code/validation/C/0005269_gss_oid_to_str.c @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2006 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE 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 "mech_locl.h" + +GSSAPI_LIB_FUNCTION OM_uint32 GSSAPI_LIB_CALL +gss_oid_to_str(OM_uint32 *minor_status, gss_OID oid, gss_buffer_t oid_str) +{ + int ret; + size_t size; + heim_oid o; + char *p; + + _mg_buffer_zero(oid_str); + + if (oid == GSS_C_NULL_OID) + return GSS_S_FAILURE; + + ret = der_get_oid (oid->elements, oid->length, &o, &size); + if (ret) { + *minor_status = ret; + return GSS_S_FAILURE; + } + + ret = der_print_heim_oid(&o, ' ', &p); + der_free_oid(&o); + if (ret) { + *minor_status = ret; + return GSS_S_FAILURE; + } + + oid_str->value = p; + oid_str->length = strlen(p); + + *minor_status = 0; + return GSS_S_COMPLETE; +} + +GSSAPI_LIB_FUNCTION const char * GSSAPI_LIB_CALL +gss_oid_to_name(gss_const_OID oid) +{ + size_t i; + + for (i = 0; _gss_ont_mech[i].oid; i++) { + if (gss_oid_equal(oid, _gss_ont_mech[i].oid)) + return _gss_ont_mech[i].name; + } + return NULL; +} + +GSSAPI_LIB_FUNCTION gss_OID GSSAPI_LIB_CALL +gss_name_to_oid(const char *name) +{ + size_t i, partial = (size_t)-1; + + for (i = 0; _gss_ont_mech[i].oid; i++) { + if (strcasecmp(name, _gss_ont_mech[i].short_desc) == 0) + return _gss_ont_mech[i].oid; + if (strncasecmp(name, _gss_ont_mech[i].short_desc, strlen(name)) == 0) { + if (partial != (size_t)-1) + return NULL; + partial = i; + } + } + if (partial != (size_t)-1) + return _gss_ont_mech[partial].oid; + return NULL; +} diff --git a/code/validation/C/0006174_eval_clocks.c b/code/validation/C/0006174_eval_clocks.c new file mode 100644 index 0000000000000000000000000000000000000000..0119a58c480b4452043e6990638c4683be32a498 --- /dev/null +++ b/code/validation/C/0006174_eval_clocks.c @@ -0,0 +1,200 @@ +// Evaluate cost of calling different clocks under Linux. On one machine at a +// point in time, we got these values: +// +// time : 3 cycles +// ftime : 54 cycles +// gettimeofday : 42 cycles +// +// CLOCK_MONOTONIC_COARSE : 9 cycles +// CLOCK_REALTIME_COARSE : 9 cycles +// CLOCK_MONOTONIC : 42 cycles +// CLOCK_REALTIME : 42 cycles +// CLOCK_MONOTONIC_RAW : 173 cycles +// CLOCK_BOOTTIME : 179 cycles +// CLOCK_THREAD_CPUTIME_ID : 349 cycles +// CLOCK_PROCESS_CPUTIME_ID : 370 cycles +// +// Numbers above generated on Intel Core i7-4771 CPU @ 3.50GHz on Linux 4.0. +// + +#include +#include +#include + +#include +#include +#include + +#include "tsc.h" + +#define N 100000 + +/* measure the cost to call `time`. */ +void time_overhead() +{ + int i; + uint64_t t0, t1, tsc_overhead; + uint64_t min, max, avg; + uint64_t times[N]; + + tsc_overhead = measure_tsc_overhead(); + + // we run N times and take the min + for (i = 0; i < N; i++) { + t0 = bench_start(); + time(NULL); + t1 = bench_end(); + times[i] = t1 - t0 - tsc_overhead; + } + + min = ~0, max = 0, avg = 0; + for (i = 0; i < N; i++) { + avg += times[i]; + if (times[i] < min) { min = times[i]; } + if (times[i] > max) { max = times[i]; } + } + avg /= N; + + printf("\n- TIME -\n"); + printf("time_getres: 1s\n"); + printf("Cost (min): %" PRIu64 " cycles\n", min); + printf("Cost (avg): %" PRIu64 " cycles\n", avg); + printf("Cost (max): %" PRIu64 " cycles\n", max); +} + +/* measure the cost to call `ftime`. */ +void ftime_overhead() +{ + int i; + struct timeb t; + uint64_t t0, t1, tsc_overhead; + uint64_t min, max, avg; + uint64_t times[N]; + + tsc_overhead = measure_tsc_overhead(); + + // we run N times and take the min + for (i = 0; i < N; i++) { + t0 = bench_start(); + ftime(&t); + t1 = bench_end(); + times[i] = t1 - t0 - tsc_overhead; + } + + min = ~0, max = 0, avg = 0; + for (i = 0; i < N; i++) { + avg += times[i]; + if (times[i] < min) { min = times[i]; } + if (times[i] > max) { max = times[i]; } + } + avg /= N; + + printf("\n- FTIME -\n"); + printf("ftime_getres: 1ms\n"); + printf("Cost (min): %" PRIu64 " cycles\n", min); + printf("Cost (avg): %" PRIu64 " cycles\n", avg); + printf("Cost (max): %" PRIu64 " cycles\n", max); +} + +/* measure the cost to call `gettimeofday`. */ +void gettimeofday_overhead() +{ + int i; + struct timeval t; + uint64_t t0, t1, tsc_overhead; + uint64_t min, max, avg; + uint64_t times[N]; + + tsc_overhead = measure_tsc_overhead(); + + // we run N times and take the min + for (i = 0; i < N; i++) { + t0 = bench_start(); + gettimeofday(&t, NULL); + t1 = bench_end(); + times[i] = t1 - t0 - tsc_overhead; + } + + min = ~0, max = 0, avg = 0; + for (i = 0; i < N; i++) { + avg += times[i]; + if (times[i] < min) { min = times[i]; } + if (times[i] > max) { max = times[i]; } + } + avg /= N; + + printf("\n- GETTIMEOFDAY -\n"); + printf("gettimeofday_getres: 1us (?)\n"); + printf("Cost (min): %" PRIu64 " cycles\n", min); + printf("Cost (avg): %" PRIu64 " cycles\n", avg); + printf("Cost (max): %" PRIu64 " cycles\n", max); +} + +/* measure the cost to call `clock_gettime` for the specified clock. */ +void clock_overhead(clockid_t clock) +{ + int i; + struct timespec t; + uint64_t t0, t1, tsc_overhead; + uint64_t min, max, avg; + uint64_t times[N]; + + tsc_overhead = measure_tsc_overhead(); + + // we run N times and take the min + for (i = 0; i < N; i++) { + t0 = bench_start(); + clock_gettime(clock, &t); + t1 = bench_end(); + times[i] = t1 - t0 - tsc_overhead; + } + + + min = ~0, max = 0, avg = 0; + for (i = 0; i < N; i++) { + avg += times[i]; + if (times[i] < min) { min = times[i]; } + if (times[i] > max) { max = times[i]; } + } + avg /= N; + + printf("Cost (min): %" PRIu64 " cycles\n", min); + printf("Cost (avg): %" PRIu64 " cycles\n", avg); + printf("Cost (max): %" PRIu64 " cycles\n", max); +} + +/* measure + print the cost to call `clock_gettime` for the specified clock. */ +void measure_clock(const char * ctype, clockid_t clock) +{ + struct timespec t; + + printf("\n- %s -\n", ctype); + + clock_getres(clock, &t); + printf("clock_getres: %ld seconds | %ld nanoseconds\n", t.tv_sec, t.tv_nsec); + + clock_overhead(clock); +} + +#define eval_clock(clk) \ + measure_clock(#clk, clk) + +/* benchmark various clock sources */ +int main(void) +{ + printf("=> Testing Clock...\n"); + time_overhead(); + ftime_overhead(); + gettimeofday_overhead(); + eval_clock(CLOCK_REALTIME); + eval_clock(CLOCK_REALTIME_COARSE); + eval_clock(CLOCK_MONOTONIC); + eval_clock(CLOCK_MONOTONIC_COARSE); + eval_clock(CLOCK_MONOTONIC_RAW); + eval_clock(CLOCK_BOOTTIME); + eval_clock(CLOCK_PROCESS_CPUTIME_ID); + eval_clock(CLOCK_THREAD_CPUTIME_ID); + + return 0; +} + diff --git a/code/validation/C/0007655_AT24C08_Driver.c b/code/validation/C/0007655_AT24C08_Driver.c new file mode 100644 index 0000000000000000000000000000000000000000..aca3b83081b4d1bd0e8baf388c63654551d8606a --- /dev/null +++ b/code/validation/C/0007655_AT24C08_Driver.c @@ -0,0 +1,86 @@ +/*******************************************ÉêÃ÷*************************************** +±¾Ç¶Èëʽ²Ù×÷ϵͳδ¾­ÊÚȨ£¬½ûÖ¹Ó¦ÓÃÓÚÈκÎÉÌÒµÓÃ; +°æÈ¨ËùÓУ¬ÇÖȨ±Ø¾¿ +http://www.trtos.com/ +**************************************************************************************/ +#include +#include + +void AT24C08_GPIO_Init() +{ + GPIO_InitTypeDef GPIO_InitStructure; + RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE ); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;//¿ªÂ©Êä³ö + GPIO_Init(GPIOB, &GPIO_InitStructure); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;//ÍÆÍêÊä³ö + GPIO_Init(GPIOB, &GPIO_InitStructure); + RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOE, ENABLE ); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; + GPIO_Init(GPIOE, &GPIO_InitStructure); +} + +void AT24C08_GPIO_CFG(uint8 ENOUT) +{ + GPIO_InitTypeDef GPIO_InitStructure; + RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOB, ENABLE ); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; + if(ENOUT)GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;//¿ªÂ©Êä³ö + else GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//¿ªÂ©Êä³ö + GPIO_Init(GPIOB, &GPIO_InitStructure); +} +uint8 AT24C08_IOCONTROL(uint8 ConMode) +{ + uint8 R=0; + switch(ConMode) + { + case I2C_HOST_SDA_SET: AT24C08_SDA_SET; break; + case I2C_HOST_SDA_CLR: AT24C08_SDA_CLR; break; + case I2C_HOST_SCL_SET: AT24C08_SCL_SET; break; + case I2C_HOST_SCL_CLR: AT24C08_SCL_CLR; break; + case I2C_HOST_SDA_DAT:if(AT24C08_SDA_DAT)R=1;break; + } + return R; +} +void AT24C08_Init() +{ + AT24C08_GPIO_Init(); +} +uint8 AT24C08_Write(uint16 Addr,uint8 *Buf,uint16 Length) +{ + uint8 Ack; + uint8 CmdAddr[2],CmdLen,Offset,CurLen; + AT24C08_WRITE_EN; + while(Length>0) + { + Offset=Addr%AT24CXX_PAGESIZE; //ÇóȡҳÄÚÆ«ÒƵØÖ· + if(Offset>0) + { + CurLen=AT24CXX_PAGESIZE-Offset; //Ç¿ÖÆÒ³¶ÔÆë + if(CurLen>Length)CurLen=Length; + }else CurLen=Length>AT24CXX_PAGESIZE?AT24CXX_PAGESIZE:Length; //Ò³Ãæ×Ö½Úͳ¼Æ + if(AT24CXX_MEMSIZE<2048){CmdAddr[0]=(uint8)Addr;CmdLen=1;} + else {CmdAddr[0]=Addr>>8;CmdAddr[1]=(uint8)Addr;CmdLen=2;} + Ack=I2C_WriteDatas(AT24C08_IOCONTROL,AT24CXX_ADDR,CmdAddr,CmdLen,Buf,CurLen); //ҳд²Ù×÷ + Addr+=CurLen;Length-=CurLen;Buf+=CurLen; //¸üеØÖ· + Tos_TaskDelay(20); + } + return Ack; +} +uint8 AT24C08_Read(uint16 Addr,uint8 *Buf,uint16 Length) +{ + uint8 Ack; + uint8 CmdAddr[2],CmdLen; + if(AT24CXX_MEMSIZE<2048){CmdAddr[0]=(uint8)Addr;CmdLen=1;} + else {CmdAddr[0]=Addr>>8;CmdAddr[1]=(uint8)Addr;CmdLen=2;} + Ack=I2C_ReadDatas(AT24C08_IOCONTROL,AT24CXX_ADDR,CmdAddr,CmdLen,Buf,Length); + return Ack; +} + + diff --git a/code/validation/C/0012555_lzma_encoder_optimum_fast.c b/code/validation/C/0012555_lzma_encoder_optimum_fast.c new file mode 100644 index 0000000000000000000000000000000000000000..f835f69356bd5ddbf8f391a533d340e5653ceb20 --- /dev/null +++ b/code/validation/C/0012555_lzma_encoder_optimum_fast.c @@ -0,0 +1,179 @@ +/////////////////////////////////////////////////////////////////////////////// +// +/// \file lzma_encoder_optimum_fast.c +// +// Author: Igor Pavlov +// +// This file has been put into the public domain. +// You can do whatever you want with this file. +// +/////////////////////////////////////////////////////////////////////////////// + +#include "lzma_encoder_private.h" + + +#define change_pair(small_dist, big_dist) \ + (((big_dist) >> 7) > (small_dist)) + + +extern void +lzma_lzma_optimum_fast(lzma_coder *restrict coder, lzma_mf *restrict mf, + uint32_t *restrict back_res, uint32_t *restrict len_res) +{ + const uint32_t nice_len = mf->nice_len; + + uint32_t len_main; + uint32_t matches_count; + if (mf->read_ahead == 0) { + len_main = mf_find(mf, &matches_count, coder->matches); + } else { + assert(mf->read_ahead == 1); + len_main = coder->longest_match_length; + matches_count = coder->matches_count; + } + + const uint8_t *buf = mf_ptr(mf) - 1; + const uint32_t buf_avail = my_min(mf_avail(mf) + 1, MATCH_LEN_MAX); + + if (buf_avail < 2) { + // There's not enough input left to encode a match. + *back_res = UINT32_MAX; + *len_res = 1; + return; + } + + // Look for repeated matches; scan the previous four match distances + uint32_t rep_len = 0; + uint32_t rep_index = 0; + + for (uint32_t i = 0; i < REP_DISTANCES; ++i) { + // Pointer to the beginning of the match candidate + const uint8_t *const buf_back = buf - coder->reps[i] - 1; + + // If the first two bytes (2 == MATCH_LEN_MIN) do not match, + // this rep is not useful. + if (not_equal_16(buf, buf_back)) + continue; + + // The first two bytes matched. + // Calculate the length of the match. + uint32_t len; + for (len = 2; len < buf_avail + && buf[len] == buf_back[len]; ++len) ; + + // If we have found a repeated match that is at least + // nice_len long, return it immediately. + if (len >= nice_len) { + *back_res = i; + *len_res = len; + mf_skip(mf, len - 1); + return; + } + + if (len > rep_len) { + rep_index = i; + rep_len = len; + } + } + + // We didn't find a long enough repeated match. Encode it as a normal + // match if the match length is at least nice_len. + if (len_main >= nice_len) { + *back_res = coder->matches[matches_count - 1].dist + + REP_DISTANCES; + *len_res = len_main; + mf_skip(mf, len_main - 1); + return; + } + + uint32_t back_main = 0; + if (len_main >= 2) { + back_main = coder->matches[matches_count - 1].dist; + + while (matches_count > 1 && len_main == + coder->matches[matches_count - 2].len + 1) { + if (!change_pair(coder->matches[ + matches_count - 2].dist, + back_main)) + break; + + --matches_count; + len_main = coder->matches[matches_count - 1].len; + back_main = coder->matches[matches_count - 1].dist; + } + + if (len_main == 2 && back_main >= 0x80) + len_main = 1; + } + + if (rep_len >= 2) { + if (rep_len + 1 >= len_main + || (rep_len + 2 >= len_main + && back_main > (UINT32_C(1) << 9)) + || (rep_len + 3 >= len_main + && back_main > (UINT32_C(1) << 15))) { + *back_res = rep_index; + *len_res = rep_len; + mf_skip(mf, rep_len - 1); + return; + } + } + + if (len_main < 2 || buf_avail <= 2) { + *back_res = UINT32_MAX; + *len_res = 1; + return; + } + + // Get the matches for the next byte. If we find a better match, + // the current byte is encoded as a literal. + coder->longest_match_length = mf_find(mf, + &coder->matches_count, coder->matches); + + if (coder->longest_match_length >= 2) { + const uint32_t new_dist = coder->matches[ + coder->matches_count - 1].dist; + + if ((coder->longest_match_length >= len_main + && new_dist < back_main) + || (coder->longest_match_length == len_main + 1 + && !change_pair(back_main, new_dist)) + || (coder->longest_match_length > len_main + 1) + || (coder->longest_match_length + 1 >= len_main + && len_main >= 3 + && change_pair(new_dist, back_main))) { + *back_res = UINT32_MAX; + *len_res = 1; + return; + } + } + + // In contrast to LZMA SDK, dictionary could not have been moved + // between mf_find() calls, thus it is safe to just increment + // the old buf pointer instead of recalculating it with mf_ptr(). + ++buf; + + const uint32_t limit = len_main - 1; + + for (uint32_t i = 0; i < REP_DISTANCES; ++i) { + const uint8_t *const buf_back = buf - coder->reps[i] - 1; + + if (not_equal_16(buf, buf_back)) + continue; + + uint32_t len; + for (len = 2; len < limit + && buf[len] == buf_back[len]; ++len) ; + + if (len >= limit) { + *back_res = UINT32_MAX; + *len_res = 1; + return; + } + } + + *back_res = back_main + REP_DISTANCES; + *len_res = len_main; + mf_skip(mf, len_main - 2); + return; +} diff --git a/code/validation/C/0014179_role-tests.c b/code/validation/C/0014179_role-tests.c new file mode 100644 index 0000000000000000000000000000000000000000..3aee3235412e31687e6c9a42b42d92ebe563860a --- /dev/null +++ b/code/validation/C/0014179_role-tests.c @@ -0,0 +1,154 @@ +/** + * @file + * + * Test the role queries. + * + * @author Jeremy A. Mowery jmowery@tresys.com + * @author Jason Tang jtang@tresys.com + * + * Copyright (C) 2007 Tresys Technology, LLC + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include +#include +#include +#include +#include + +#define SOURCE_POLICY TEST_POLICIES "/setools/apol/role_dom.conf" + +static apol_policy_t *sp = NULL; +static qpol_policy_t *qp = NULL; + +static void role_basic(void) +{ + apol_role_query_t *q = apol_role_query_create(); + CU_ASSERT_PTR_NOT_NULL_FATAL(q); + + apol_vector_t *v = NULL; + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 26); + apol_vector_destroy(&v); + + apol_role_query_set_role(sp, q, "sh"); + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 0); + apol_vector_destroy(&v); + + apol_role_query_set_role(sp, q, NULL); + apol_role_query_set_type(sp, q, "silly_t"); + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 2); + bool found_silly = false, found_object = false; + for (size_t i = 0; i < apol_vector_get_size(v); i++) { + qpol_role_t *r = (qpol_role_t *) apol_vector_get_element(v, i); + const char *name; + qpol_role_get_name(qp, r, &name); + if (strcmp(name, "silly_r") == 0) { + found_silly = true; + } else if (strcmp(name, "object_r") == 0) { + found_object = true; + } else { + CU_ASSERT(0); + } + } + CU_ASSERT(found_silly && found_object); + apol_vector_destroy(&v); + + apol_role_query_set_type(sp, q, "not_in_the_policy_t"); + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 0); + apol_vector_destroy(&v); + + apol_role_query_destroy(&q); +} + +static void role_regex(void) +{ + apol_role_query_t *q = apol_role_query_create(); + CU_ASSERT_PTR_NOT_NULL_FATAL(q); + apol_role_query_set_regex(sp, q, 1); + + apol_role_query_set_role(sp, q, "*"); + apol_vector_t *v = NULL; + CU_ASSERT(apol_role_get_by_query(sp, q, &v) < 0 && v == NULL); + + apol_role_query_set_role(sp, q, "^sh"); + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 2); + bool found_shirt = false, found_shoe = false; + for (size_t i = 0; i < apol_vector_get_size(v); i++) { + qpol_role_t *r = (qpol_role_t *) apol_vector_get_element(v, i); + const char *name; + qpol_role_get_name(qp, r, &name); + if (strcmp(name, "shirt_r") == 0) { + found_shirt = true; + } else if (strcmp(name, "shoe_r") == 0) { + found_shoe = true; + } else { + CU_ASSERT(0); + } + } + CU_ASSERT(found_shirt && found_shoe); + apol_vector_destroy(&v); + + apol_role_query_set_role(sp, q, NULL); + apol_role_query_set_type(sp, q, "file"); + CU_ASSERT(apol_role_get_by_query(sp, q, &v) == 0); + CU_ASSERT(v != NULL && apol_vector_get_size(v) == 1); + qpol_role_t *r = (qpol_role_t *) apol_vector_get_element(v, 0); + const char *name; + qpol_role_get_name(qp, r, &name); + CU_ASSERT_STRING_EQUAL(name, "object_r"); + apol_vector_destroy(&v); + + apol_role_query_destroy(&q); +} + +CU_TestInfo role_tests[] = { + {"basic query", role_basic} + , + {"regex query", role_regex} + , + CU_TEST_INFO_NULL +}; + +int role_init() +{ + apol_policy_path_t *ppath = apol_policy_path_create(APOL_POLICY_PATH_TYPE_MONOLITHIC, SOURCE_POLICY, NULL); + if (ppath == NULL) { + return 1; + } + + if ((sp = apol_policy_create_from_policy_path(ppath, 0, NULL, NULL)) == NULL) { + apol_policy_path_destroy(&ppath); + return 1; + } + apol_policy_path_destroy(&ppath); + + qp = apol_policy_get_qpol(sp); + + return 0; +} + +int role_cleanup() +{ + apol_policy_destroy(&sp); + return 0; +} diff --git a/code/validation/C/0015228_refresh.c b/code/validation/C/0015228_refresh.c new file mode 100644 index 0000000000000000000000000000000000000000..11fcf95ae218bcea782c720ede634950c257e08a --- /dev/null +++ b/code/validation/C/0015228_refresh.c @@ -0,0 +1,186 @@ +/* Hey EMACS -*- linux-c -*- */ +/* $Id: refresh.c 2349 2007-02-09 11:21:47Z kevinkofler $ */ + +/* TiEmu - Tiemu Is an EMUlator + * + * Copyright (c) 2000-2001, Thomas Corvazier, Romain Lievin + * Copyright (c) 2001-2003, Romain Lievin + * Copyright (c) 2003, Julien Blache + * Copyright (c) 2004, Romain Liévin + * Copyright (c) 2005, Romain Liévin + * Copyright (c) 2007, Kevin Kofler + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include +#include + +#include "intl.h" +#include "dboxes.h" +#include "tilibs.h" +#include "refresh.h" +#include "pbars.h" + +extern CalcUpdate calc_update; + +static void gt_start(void) +{ + calc_update.cnt1 = calc_update.max1 = 0; + calc_update.cnt2 = calc_update.max2 = 0; + calc_update.cnt3 = calc_update.max3 = 0; +} + +static void gt_stop(void) +{ + calc_update.cnt1 = calc_update.max1 = 0; + calc_update.cnt2 = calc_update.max2 = 0; + calc_update.cnt3 = calc_update.max3 = 0; +} + +static void filter_shift(void); +static gfloat filter_compute(gfloat input); + +static void refresh_pbar1(void) +{ + gchar buffer[32]; + gfloat rate, avg; + + if (p_win.pbar1 != NULL) + { + if(calc_update.cnt1 > calc_update.max1) + calc_update.cnt1 = calc_update.max1; + + if(calc_update.max1 != 0) + gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(p_win.pbar1), + (gdouble)calc_update.cnt1 / calc_update.max1); + + if(p_win.label_rate != NULL) + { + rate = calc_update.rate; + filter_shift(); + avg = filter_compute(rate); + + g_snprintf(buffer, 32, "Rate: %1.1f Kbytes/s", avg); + gtk_label_set_text(GTK_LABEL(p_win.label_rate), buffer); + } + GTK_REFRESH(); + } +} + +static void refresh_pbar2(void) +{ + if (p_win.pbar2 != NULL) + { + if(calc_update.cnt2 > calc_update.max2) + calc_update.cnt2 = calc_update.max2; + + if(calc_update.max2 != 0) + gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(p_win.pbar2), + (gdouble)calc_update.cnt2 / calc_update.max2); + + GTK_REFRESH(); + } +} + +static void refresh_pbar3(void) +{ + if(p_win.label_part != NULL) + { + gchar *str; + + str = g_strdup_printf("%i/%i: ", calc_update.cnt3, calc_update.max3); + gtk_label_set_text(GTK_LABEL(p_win.label_part), str); + + GTK_REFRESH(); + } +} + +static void gt_pbar(void) +{ + refresh_pbar1(); + refresh_pbar2(); + refresh_pbar3(); +} + +static void gt_label(void) +{ + if (p_win.label == NULL) + return; + + gtk_label_set_text(GTK_LABEL(p_win.label), calc_update.text); + + GTK_REFRESH(); +} + +static void gt_refresh(void) +{ + GTK_REFRESH(); +} + +CalcUpdate calc_update = +{ + "", 0, 0.0, + 0, 0, 0, 0, 0, 0, + 0, 0, + gt_start, + gt_stop, + gt_refresh, + gt_pbar, + gt_label, +}; + +void tiemu_update_set_gtk(void) +{ + extern CalcHandle *calc_handle; // defined in dbus.c + + ticalcs_update_set(calc_handle, &calc_update); +} + +///// misc + +static gfloat filter[8] = { 0 }; + +static void filter_shift(void) +{ + int i; + + for(i=7; i>0; i--) + filter[i] = filter[i-1]; +} + +static gfloat filter_compute(gfloat input) +{ + int i; + gfloat avg, min, max; + + avg = min = max = 0.0; + + filter[0] = input; + for(i=0; i<7; i++) { + if(filter[i] < min) min = filter[i]; + if(filter[i] > max) max = filter[i]; + + avg += filter[i]; + } + + avg -= min; + avg -= max; + + return (avg / 6); +} + + + + + diff --git a/code/validation/C/0017579_flop_mz.c b/code/validation/C/0017579_flop_mz.c new file mode 100644 index 0000000000000000000000000000000000000000..1e8ee15e69808007d6ad09c1e57567dc046ffdb7 --- /dev/null +++ b/code/validation/C/0017579_flop_mz.c @@ -0,0 +1,388 @@ +/* + FreeRTOS V9.0.0rc2 - Copyright (C) 2016 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. + + *************************************************************************** + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + *************************************************************************** + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. Full license text is available on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +/* + * Creates eight tasks, each of which loops continuously performing a + * floating point calculation. + * + * All the tasks run at the idle priority and never block or yield. This causes + * all eight tasks to time slice with the idle task. Running at the idle priority + * means that these tasks will get pre-empted any time another task is ready to run + * or a time slice occurs. More often than not the pre-emption will occur mid + * calculation, creating a good test of the schedulers context switch mechanism - a + * calculation producing an unexpected result could be a symptom of a corruption in + * the context of a task. + */ + +#include +#include + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" + +/* Demo program include files. */ +#include "flop_mz.h" + +#define mathSTACK_SIZE (configMINIMAL_STACK_SIZE + 100) +#define mathNUMBER_OF_TASKS ( 8 ) + +/* Four tasks, each of which performs a different floating point calculation. +Each of the four is created twice. */ +static portTASK_FUNCTION_PROTO( vCompetingMathTask1, pvParameters ); +static portTASK_FUNCTION_PROTO( vCompetingMathTask2, pvParameters ); +static portTASK_FUNCTION_PROTO( vCompetingMathTask3, pvParameters ); +static portTASK_FUNCTION_PROTO( vCompetingMathTask4, pvParameters ); + +/* These variables are used to check that all the tasks are still running. If a +task gets a calculation wrong it will +stop incrementing its check variable. */ +static volatile unsigned long ulTaskCheck[ mathNUMBER_OF_TASKS ] = { 0 }; + +/*-----------------------------------------------------------*/ + +void vStartMathTasks( unsigned portBASE_TYPE uxPriority ) +{ + xTaskCreate( vCompetingMathTask1, "Math1", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 0 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask2, "Math2", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 1 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask3, "Math3", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 2 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask4, "Math4", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 3 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask1, "Math5", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 4 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask2, "Math6", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 5 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask3, "Math7", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 6 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask4, "Math8", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 7 ] ), uxPriority, NULL ); +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask1, pvParameters ) +{ +volatile portDOUBLE d1, d2, d3, d4; +volatile unsigned long *pulTaskCheckVariable; +volatile portDOUBLE dAnswer; +short sError = pdFALSE; + + + /* Must be called before any hardware floating point operations are + performed to let the RTOS portable layer know that this task requires + a floating point context. */ + portTASK_USES_FLOATING_POINT(); + + d1 = 123.4567; + d2 = 2345.6789; + d3 = -918.222; + + dAnswer = ( d1 + d2 ) * d3; + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pulTaskCheckVariable = ( unsigned long * ) pvParameters; + + /* Keep performing a calculation and checking the result against a constant. */ + for(;;) + { + d1 = 123.4567; + d2 = 2345.6789; + d3 = -918.222; + + d4 = ( d1 + d2 ) * d3; + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* If the calculation does not match the expected constant, stop the + increment of the check variable. */ + if( fabs( d4 - dAnswer ) > 0.001 ) + { + sError = pdTRUE; + } + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know this task is still running okay. */ + ( *pulTaskCheckVariable )++; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask2, pvParameters ) +{ +volatile portDOUBLE d1, d2, d3, d4; +volatile unsigned long *pulTaskCheckVariable; +volatile portDOUBLE dAnswer; +short sError = pdFALSE; + + /* Must be called before any hardware floating point operations are + performed to let the RTOS portable layer know that this task requires + a floating point context. */ + portTASK_USES_FLOATING_POINT(); + + d1 = -389.38; + d2 = 32498.2; + d3 = -2.0001; + + dAnswer = ( d1 / d2 ) * d3; + + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pulTaskCheckVariable = ( unsigned long * ) pvParameters; + + /* Keep performing a calculation and checking the result against a constant. */ + for( ;; ) + { + d1 = -389.38; + d2 = 32498.2; + d3 = -2.0001; + + d4 = ( d1 / d2 ) * d3; + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* If the calculation does not match the expected constant, stop the + increment of the check variable. */ + if( fabs( d4 - dAnswer ) > 0.001 ) + { + sError = pdTRUE; + } + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know + this task is still running okay. */ + ( *pulTaskCheckVariable )++; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask3, pvParameters ) +{ +volatile portDOUBLE *pdArray, dTotal1, dTotal2, dDifference; +volatile unsigned long *pulTaskCheckVariable; +const size_t xArraySize = 10; +size_t xPosition; +short sError = pdFALSE; + + /* Must be called before any hardware floating point operations are + performed to let the RTOS portable layer know that this task requires + a floating point context. */ + portTASK_USES_FLOATING_POINT(); + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pulTaskCheckVariable = ( unsigned long * ) pvParameters; + + pdArray = ( portDOUBLE * ) pvPortMalloc( xArraySize * sizeof( portDOUBLE ) ); + + /* Keep filling an array, keeping a running total of the values placed in the + array. Then run through the array adding up all the values. If the two totals + do not match, stop the check variable from incrementing. */ + for( ;; ) + { + dTotal1 = 0.0; + dTotal2 = 0.0; + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + pdArray[ xPosition ] = ( portDOUBLE ) xPosition + 5.5; + dTotal1 += ( portDOUBLE ) xPosition + 5.5; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + dTotal2 += pdArray[ xPosition ]; + } + + dDifference = dTotal1 - dTotal2; + if( fabs( dDifference ) > 0.001 ) + { + sError = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know this task is still running okay. */ + ( *pulTaskCheckVariable )++; + } + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask4, pvParameters ) +{ +volatile portDOUBLE *pdArray, dTotal1, dTotal2, dDifference; +volatile unsigned long *pulTaskCheckVariable; +const size_t xArraySize = 10; +size_t xPosition; +short sError = pdFALSE; + + /* Must be called before any hardware floating point operations are + performed to let the RTOS portable layer know that this task requires + a floating point context. */ + portTASK_USES_FLOATING_POINT(); + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pulTaskCheckVariable = ( unsigned long * ) pvParameters; + + pdArray = ( portDOUBLE * ) pvPortMalloc( xArraySize * sizeof( portDOUBLE ) ); + + /* Keep filling an array, keeping a running total of the values placed in the + array. Then run through the array adding up all the values. If the two totals + do not match, stop the check variable from incrementing. */ + for( ;; ) + { + dTotal1 = 0.0; + dTotal2 = 0.0; + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + pdArray[ xPosition ] = ( portDOUBLE ) xPosition * 12.123; + dTotal1 += ( portDOUBLE ) xPosition * 12.123; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + dTotal2 += pdArray[ xPosition ]; + } + + dDifference = dTotal1 - dTotal2; + if( fabs( dDifference ) > 0.001 ) + { + sError = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know this task is still running okay. */ + ( *pulTaskCheckVariable )++; + } + } +} +/*-----------------------------------------------------------*/ + +/* This is called to check that all the created tasks are still running. */ +portBASE_TYPE xAreMathsTaskStillRunning( void ) +{ +/* Keep a history of the check variables so we know if they have been incremented +since the last call. */ +static unsigned long ulLastTaskCheck[ mathNUMBER_OF_TASKS ] = { ( unsigned short ) 0 }; +portBASE_TYPE xReturn = pdTRUE, xTask; + + /* Check the maths tasks are still running by ensuring their check variables + are still incrementing. */ + for( xTask = 0; xTask < mathNUMBER_OF_TASKS; xTask++ ) + { + if( ulTaskCheck[ xTask ] == ulLastTaskCheck[ xTask ] ) + { + /* The check has not incremented so an error exists. */ + xReturn = pdFALSE; + } + + ulLastTaskCheck[ xTask ] = ulTaskCheck[ xTask ]; + } + + return xReturn; +} + + + diff --git a/code/validation/C/0018807_common.c b/code/validation/C/0018807_common.c new file mode 100644 index 0000000000000000000000000000000000000000..bf953c2a8aad4403328d885cb12341e58612a433 --- /dev/null +++ b/code/validation/C/0018807_common.c @@ -0,0 +1,182 @@ +/*--------------------------------------------- + * modification time: 2016.12.18 01:15 + * mender: Muse +-*---------------------------------------------*/ + +/*--------------------------------------------- + * creation time: 2016.12.05 14:15 + * author: Muse +-*---------------------------------------------*/ + +/*--------------------------------------------- + * Source file content Seven part + * + * Part Zero: Include + * Part One: Define + * Part Two: Local data + * Part Three: Local function + * + * Part Four: i/o + * Part Five: string + * Part Six: random + * +-*---------------------------------------------*/ + +/*--------------------------------------------- + * Part Zero: Include +-*---------------------------------------------*/ + +#include "base.h" + + +/*--------------------------------------------- + * Part One: Define +-*---------------------------------------------*/ + +#define CHECK_STR(cond, ret) \ + if (!haystack || offset < 1 || strlen(haystack) < offset || cond) { \ + errno = EINVAL; \ + return ret; \ + } + +#define TRUN_STR() { \ + ch = haystack[offset]; \ + haystack[offset] = 0; \ +} + +#define JOIN_STR() haystack[offset] = ch; + + +/*--------------------------------------------- + * Part Four: i/o + * + * 1. readnonblock + * 2. writen + * 3. strnstr + * 4. strnchr + * 5. atoin + * +-*---------------------------------------------*/ + +/*-----readnonblock-----*/ +int32_t readnonblock(int32_t fd, void *buf, size_t count) +{ + int32_t res, offset = 0; + + while (true) { + if ((res = read(fd, buf + offset, count)) == count) { + return offset + res; + + } else if (res == CERR && errno == EAGAIN) { + return offset; + + } else { + if (res != CERR) { + offset += res; + count -= res; + } + } + } +} + + +/*-----writen-----*/ +int32_t writen(int32_t fd, void *buf, size_t count) +{ + int32_t res, offset = 0; + + while (true) { + if ((res = write(fd, buf + offset, count)) == count) { + return offset + res; + + } else if (res >= 0) { + offset += res; + count -= res; + + } else { + return offset; + } + } +} + + +/*--------------------------------------------- + * Part Five: string + * + * 1. strnstr + * 2. strnchr + * 3. atoin + * +-*---------------------------------------------*/ + +/*-----strnstr-----*/ +char *strnstr(char *haystack, const char *needle, int32_t offset) +{ + char *str, ch; + + CHECK_STR(!needle, NULL); + TRUN_STR(); + str = strstr(haystack, needle); + JOIN_STR(); + + return str; +} + + +/*-----strnchr-----*/ +char *strnchr(char *haystack, char c, int32_t offset, bool is_first) +{ + char *str, ch; + + CHECK_STR(false, NULL); + + if (haystack[offset] == c) + return &haystack[offset]; + + TRUN_STR(); + str = (is_first) ? strchr(haystack, c) : strrchr(haystack, c); + JOIN_STR(); + + return str; +} + + +/*-----atoin-----*/ +int32_t atoin(char *haystack, int32_t offset) +{ + char ch; + int32_t result; + + CHECK_STR(false, CERR); + TRUN_STR(); + result = atoi(haystack); + JOIN_STR(); + + return result; +} + + +/*--------------------------------------------- + * Part Six: random + * + * 1. trandom + * 2. clockrandom + * +-*---------------------------------------------*/ + +/*-----trandom-----*/ +int64_t trandom(int32_t mod) +{ + srand48(clock()); + + return (lrand48() % mod); +} + + +/*-----clockrandom-----*/ +int64_t clockrandom(int32_t mod) +{ + return clock() % mod; +} + + diff --git a/code/validation/C/0019213_hershey-font-gnuplot.c b/code/validation/C/0019213_hershey-font-gnuplot.c new file mode 100644 index 0000000000000000000000000000000000000000..3223bd03ba4e72aaaf381a09e1dfdc8c369e3f6c --- /dev/null +++ b/code/validation/C/0019213_hershey-font-gnuplot.c @@ -0,0 +1,192 @@ +// +// hershey-font-gnuplot.c - Copyright (C) 2013 Kamal Mostafa +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// + +#include +#include +#include +#include +#include + +int sample_sheet_mode = 1; + +char *render_text; + +void +usage() +{ + fprintf(stderr, +"usage: hershey-font-gnuplot [options] {font} 'Text to Render'\n" +" hershey-font-gnuplot [options] {font} - generate sample sheet\n" +" {font} a Hershey fontname or fontfile.jhf\n" +" [options]\n" +" -T 'gnuplot_terminal_type [opts]'\n" +" e.g.: -T 'pdf'\n" +" -T 'png crop transparent'\n" +" -h font_height (default 100)\n" +"examples:\n" +" hershey-font-gnuplot futural 'Hello World!' | gnuplot -p\n" +" hershey-font-gnuplot gothiceng 'Calligraphy' | gnuplot -p\n" +" hershey-font-gnuplot -T 'png crop' scriptc 'Nice Text' | gnuplot > out.png\n" + ); + + +} + +int +main( int argc, char **argv ) +{ + char *gnuplot_term_opts = "wxt"; + int gnuplot_height = 100; + + int opt; + while ((opt = getopt(argc, argv, "h:T:")) != -1) { + switch (opt) { + case 'h': + gnuplot_height = strtoul(optarg, 0, 0); + break; + case 'T': + gnuplot_term_opts = optarg; + break; + default: /* '?' */ + usage(); + return 1; + } + } + + opt = argc - optind; + if ( opt < 1 || opt > 2 ) { + usage(); + return 1; + } + if ( opt == 2 ) + sample_sheet_mode = 0; + + + // load a hershey_font structure either by filename or fontname + const char *fontname = argv[optind++]; + struct hershey_font *hf; + + if ( strchr(fontname,'.') ) + hf = hershey_jhf_font_load(fontname); + else + hf = hershey_font_load(fontname); + + if ( !hf ) { + perror(fontname); + return 1; + } + + // render the text + + printf("#\n# gnuplot input file generated by hershey-font-gnuplot\n#\n\n"); + + printf("\n"); + + int terminal_width, terminal_height; + + char render_text_buf[256]; + if ( sample_sheet_mode ) { + int i; + for ( i=0; i<256-32; i++ ) + render_text_buf[i] = i+32; + render_text = render_text_buf; + terminal_width = 16 * gnuplot_height; + terminal_height = 8 * gnuplot_height; + } else { + render_text = argv[optind++]; + terminal_width = 16 * gnuplot_height; + terminal_height = gnuplot_height; + } + + printf("set terminal %s size %d,%d\n", + gnuplot_term_opts, terminal_width, terminal_height); + printf("\n"); + + printf("unset xtics\n"); + printf("unset ytics\n"); + printf("unset border\n"); + printf("unset key\n"); + if ( sample_sheet_mode ) { + printf("set title \"%s\"\n", fontname ); + printf("set size ratio 0.5\n"); + printf("set xrange [0:%d]\n", 32*32); + printf("set yrange [0:%d]\n", 8*64); + } else { + printf("set size ratio 0.125\n"); + printf("set xrange [0:%d]\n", 16*16); + printf("set yrange [0:%d]\n", 2*16); + } + printf("set style arrow 1 nohead\n" ); + printf("set style line 1 lc rgb \"black\" lw 0.5\n" ); + + int x_render_pos = 0; + int y_render_pos = 8; + + const char *p; + for ( p=render_text; *p; p++ ) { + + // get the character c to be rendered + int c = *((unsigned char *)p); + + // get the hershey_glyph for ASCII character c + struct hershey_glyph *hg = hershey_font_glyph(hf, c); + + // check whether there actually is a glyph for this character + if ( hg->width == 0 ) + continue; + + // handle special placement for sample_sheet_mode + if ( sample_sheet_mode ) { + x_render_pos = (c % 32) * 32; + y_render_pos = (c / 32) * 64; + y_render_pos = 8*64 - y_render_pos; + } + + printf("# [[ %c ]] glyph(%d) width=%u npaths=%u\n", + c, c, hg->width, hg->npaths); + + // walk the paths-list for this glyph + struct hershey_path *hp; + short px, py; + for ( hp=hg->paths; hp; hp=hp->next ) { + // begin draw path + printf("#\t\tpath: nverts=%d\n", hp->nverts); + int i; + for ( i=0; inverts; i++ ) { + short x = hp->verts[i].x + x_render_pos; + short y = hp->verts[i].y + y_render_pos; + if ( i > 0 ) + printf("set arrow from %d,%d to %d,%d as 1 ls 1\n", + px, py, x, y); + px = x; + py = y; + } + // end draw path + } + + // advance the x_render_pos by the width of this glyph + x_render_pos += hg->width; + } + + printf("plot NaN notitle\n"); + + // destroy the hershey_font + hershey_font_free(hf); + + return 0; +} diff --git a/code/validation/C/0020318_flop_hercules.c b/code/validation/C/0020318_flop_hercules.c new file mode 100644 index 0000000000000000000000000000000000000000..f600dbc3e87c77e56937712259509583033d4224 --- /dev/null +++ b/code/validation/C/0020318_flop_hercules.c @@ -0,0 +1,399 @@ +/* + FreeRTOS V8.0.1 - Copyright (C) 2014 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that has become a de facto standard. * + * * + * Help yourself get started quickly and support the FreeRTOS * + * project by purchasing a FreeRTOS tutorial book, reference * + * manual, or both from: http://www.FreeRTOS.org/Documentation * + * * + * Thank you! * + * * + *************************************************************************** + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. + + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. Full license text is available from the following + link: http://www.freertos.org/a00114.html + + 1 tab == 4 spaces! + + *************************************************************************** + * * + * Having a problem? Start by reading the FAQ "My application does * + * not run, what could be wrong?" * + * * + * http://www.FreeRTOS.org/FAQHelp.html * + * * + *************************************************************************** + + http://www.FreeRTOS.org - Documentation, books, training, latest versions, + license and Real Time Engineers Ltd. contact details. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High + Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +/* + * Creates eight tasks, each of which loops continuously performing an (emulated) + * floating point calculation. + * + * All the tasks run at the idle priority and never block or yield. This causes + * all eight tasks to time slice with the idle task. Running at the idle priority + * means that these tasks will get pre-empted any time another task is ready to run + * or a time slice occurs. More often than not the pre-emption will occur mid + * calculation, creating a good test of the schedulers context switch mechanism - a + * calculation producing an unexpected result could be a symptom of a corruption in + * the context of a task. + */ + +#include +#include + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" + +/* Demo program include files. */ +#include "flop.h" + +#define mathSTACK_SIZE configMINIMAL_STACK_SIZE +#define mathNUMBER_OF_TASKS ( 8 ) + +/* Four tasks, each of which performs a different floating point calculation. +Each of the four is created twice. */ +static portTASK_FUNCTION_PROTO( vCompetingMathTask1, pvParameters ); +static portTASK_FUNCTION_PROTO( vCompetingMathTask2, pvParameters ); +static portTASK_FUNCTION_PROTO( vCompetingMathTask3, pvParameters ); +static portTASK_FUNCTION_PROTO( vCompetingMathTask4, pvParameters ); + +/* These variables are used to check that all the tasks are still running. If a +task gets a calculation wrong it will +stop incrementing its check variable. */ +static volatile unsigned long ulTaskCheck[ mathNUMBER_OF_TASKS ] = { 0 }; + +/* Must be called before any hardware floating point operations are +performed to let the RTOS portable layer know that this task requires +a floating point context. */ +#if __TI_VFP_SUPPORT__ + extern void vPortTaskUsesFPU( void ); +#endif + +/*-----------------------------------------------------------*/ + +void vStartMathTasks( unsigned portBASE_TYPE uxPriority ) +{ + xTaskCreate( vCompetingMathTask1, "Math1", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 0 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask2, "Math2", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 1 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask3, "Math3", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 2 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask4, "Math4", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 3 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask1, "Math5", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 4 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask2, "Math6", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 5 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask3, "Math7", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 6 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask4, "Math8", mathSTACK_SIZE, ( void * ) &( ulTaskCheck[ 7 ] ), uxPriority, NULL ); +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask1, pvParameters ) +{ +volatile portDOUBLE d1, d2, d3, d4; +volatile unsigned long *pulTaskCheckVariable; +volatile portDOUBLE dAnswer; +short sError = pdFALSE; + + + /* Must be called before any hardware floating point operations are + performed to let the RTOS portable layer know that this task requires + a floating point context. */ + #if __TI_VFP_SUPPORT__ + vPortTaskUsesFPU(); + #endif + + d1 = 123.4567; + d2 = 2345.6789; + d3 = -918.222; + + dAnswer = ( d1 + d2 ) * d3; + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pulTaskCheckVariable = ( unsigned long * ) pvParameters; + + /* Keep performing a calculation and checking the result against a constant. */ + for(;;) + { + d1 = 123.4567; + d2 = 2345.6789; + d3 = -918.222; + + d4 = ( d1 + d2 ) * d3; + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* If the calculation does not match the expected constant, stop the + increment of the check variable. */ + if( fabs( d4 - dAnswer ) > 0.001 ) + { + sError = pdTRUE; + } + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know this task is still running okay. */ + ( *pulTaskCheckVariable )++; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask2, pvParameters ) +{ +volatile portDOUBLE d1, d2, d3, d4; +volatile unsigned long *pulTaskCheckVariable; +volatile portDOUBLE dAnswer; +short sError = pdFALSE; + + /* Must be called before any hardware floating point operations are + performed to let the RTOS portable layer know that this task requires + a floating point context. */ + #if __TI_VFP_SUPPORT__ + vPortTaskUsesFPU(); + #endif + + d1 = -389.38; + d2 = 32498.2; + d3 = -2.0001; + + dAnswer = ( d1 / d2 ) * d3; + + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pulTaskCheckVariable = ( unsigned long * ) pvParameters; + + /* Keep performing a calculation and checking the result against a constant. */ + for( ;; ) + { + d1 = -389.38; + d2 = 32498.2; + d3 = -2.0001; + + d4 = ( d1 / d2 ) * d3; + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* If the calculation does not match the expected constant, stop the + increment of the check variable. */ + if( fabs( d4 - dAnswer ) > 0.001 ) + { + sError = pdTRUE; + } + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know + this task is still running okay. */ + ( *pulTaskCheckVariable )++; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask3, pvParameters ) +{ +volatile portDOUBLE *pdArray, dTotal1, dTotal2, dDifference; +volatile unsigned long *pulTaskCheckVariable; +const size_t xArraySize = 10; +size_t xPosition; +short sError = pdFALSE; + + /* Must be called before any hardware floating point operations are + performed to let the RTOS portable layer know that this task requires + a floating point context. */ + #if __TI_VFP_SUPPORT__ + vPortTaskUsesFPU(); + #endif + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pulTaskCheckVariable = ( unsigned long * ) pvParameters; + + pdArray = ( portDOUBLE * ) pvPortMalloc( xArraySize * sizeof( portDOUBLE ) ); + + /* Keep filling an array, keeping a running total of the values placed in the + array. Then run through the array adding up all the values. If the two totals + do not match, stop the check variable from incrementing. */ + for( ;; ) + { + dTotal1 = 0.0; + dTotal2 = 0.0; + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + pdArray[ xPosition ] = ( portDOUBLE ) xPosition + 5.5; + dTotal1 += ( portDOUBLE ) xPosition + 5.5; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + dTotal2 += pdArray[ xPosition ]; + } + + dDifference = dTotal1 - dTotal2; + if( fabs( dDifference ) > 0.001 ) + { + sError = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know this task is still running okay. */ + ( *pulTaskCheckVariable )++; + } + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask4, pvParameters ) +{ +volatile portDOUBLE *pdArray, dTotal1, dTotal2, dDifference; +volatile unsigned long *pulTaskCheckVariable; +const size_t xArraySize = 10; +size_t xPosition; +short sError = pdFALSE; + + /* Must be called before any hardware floating point operations are + performed to let the RTOS portable layer know that this task requires + a floating point context. */ + #if __TI_VFP_SUPPORT__ + vPortTaskUsesFPU(); + #endif + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pulTaskCheckVariable = ( unsigned long * ) pvParameters; + + pdArray = ( portDOUBLE * ) pvPortMalloc( xArraySize * sizeof( portDOUBLE ) ); + + /* Keep filling an array, keeping a running total of the values placed in the + array. Then run through the array adding up all the values. If the two totals + do not match, stop the check variable from incrementing. */ + for( ;; ) + { + dTotal1 = 0.0; + dTotal2 = 0.0; + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + pdArray[ xPosition ] = ( portDOUBLE ) xPosition * 12.123; + dTotal1 += ( portDOUBLE ) xPosition * 12.123; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + dTotal2 += pdArray[ xPosition ]; + } + + dDifference = dTotal1 - dTotal2; + if( fabs( dDifference ) > 0.001 ) + { + sError = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know this task is still running okay. */ + ( *pulTaskCheckVariable )++; + } + } +} +/*-----------------------------------------------------------*/ + +/* This is called to check that all the created tasks are still running. */ +portBASE_TYPE xAreMathsTaskStillRunning( void ) +{ +/* Keep a history of the check variables so we know if they have been incremented +since the last call. */ +static unsigned long ulLastTaskCheck[ mathNUMBER_OF_TASKS ] = { ( unsigned short ) 0 }; +portBASE_TYPE xReturn = pdTRUE, xTask; + + /* Check the maths tasks are still running by ensuring their check variables + are still incrementing. */ + for( xTask = 0; xTask < mathNUMBER_OF_TASKS; xTask++ ) + { + if( ulTaskCheck[ xTask ] == ulLastTaskCheck[ xTask ] ) + { + /* The check has not incremented so an error exists. */ + xReturn = pdFALSE; + } + + ulLastTaskCheck[ xTask ] = ulTaskCheck[ xTask ]; + } + + return xReturn; +} + + + diff --git a/code/validation/C/0020870_opts-std-startup.c b/code/validation/C/0020870_opts-std-startup.c new file mode 100644 index 0000000000000000000000000000000000000000..ed25a18d3184a7f46fb8a8cc83496b10784ca204 --- /dev/null +++ b/code/validation/C/0020870_opts-std-startup.c @@ -0,0 +1,178 @@ +/* Standard startup-time command line parser + + Copyright (C) 1995, 1996, 1997, 1998, 1999, 2001, 2007 + Free Software Foundation, Inc. + + Written by Miles Bader + + This file is part of the GNU Hurd. + + The GNU Hurd is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation; either version 2, or (at + your option) any later version. + + The GNU Hurd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + +#include +#include +#include +#include +#include "priv.h" + +const char *diskfs_boot_command_line; +char **_diskfs_boot_command; + +int _diskfs_boot_pause; + +extern char **diskfs_argv; + +mach_port_t diskfs_exec_server_task = MACH_PORT_NULL; + +/* ---------------------------------------------------------------- */ + +#define OPT_HOST_PRIV_PORT (-1) +#define OPT_DEVICE_MASTER_PORT (-2) +#define OPT_EXEC_SERVER_TASK (-3) +#define OPT_BOOT_CMDLINE (-4) +#define OPT_BOOT_COMMAND (-5) +#define OPT_BOOT_INIT_PROGRAM (-6) +#define OPT_BOOT_PAUSE (-7) + +static const struct argp_option +startup_options[] = +{ + {"directory", 'C', "DIRECTORY", 0, + "Use DIRECTORY as the root of the filesystem"}, + {"virtual-root", 0, 0, OPTION_ALIAS}, + {"chroot", 0, 0, OPTION_ALIAS}, + + {0,0,0,0, "Boot options:", -2}, + {"multiboot-command-line", OPT_BOOT_CMDLINE, "ARGS", 0, + "Required for bootstrap filesystem, the multiboot kernel command line"}, + {"bootflags", 0, 0, OPTION_ALIAS|OPTION_HIDDEN}, + {"boot-init-program", OPT_BOOT_INIT_PROGRAM, "FILE", 0, + "For bootstrap filesystem, init program to run (default " _HURD_STARTUP ")"}, + {"boot-debug-pause", OPT_BOOT_PAUSE, 0, 0, + "Pause for keystroke before starting bootstrap programs"}, + {"boot-command", OPT_BOOT_COMMAND, 0, 0, + "Remaining arguments form command line to run" + " at bootstrap instead of init"}, + {"host-priv-port", OPT_HOST_PRIV_PORT, "PORT"}, + {"device-master-port", OPT_DEVICE_MASTER_PORT, "PORT"}, + {"exec-server-task", OPT_EXEC_SERVER_TASK, "PORT"}, + + {0} +}; + +static error_t +parse_startup_opt (int opt, char *arg, struct argp_state *state) +{ + switch (opt) + { +#define TOGGLE(var, on, off) \ + case on: var = 1; break; \ + case off: var = 0; break; + TOGGLE (diskfs_readonly, 'r', 'w'); + TOGGLE (_diskfs_nosuid, 'S', OPT_SUID_OK); + TOGGLE (_diskfs_noexec, 'E', OPT_EXEC_OK); + TOGGLE (_diskfs_noatime, 'A', OPT_ATIME); + TOGGLE (_diskfs_no_inherit_dir_group, OPT_NO_INHERIT_DIR_GROUP, + OPT_INHERIT_DIR_GROUP); +#undef TOGGLE + + case 's': + if (arg == NULL) + diskfs_synchronous = 1; + else + diskfs_default_sync_interval = atoi (arg); + break; + case 'n': + diskfs_synchronous = 0; + diskfs_default_sync_interval = 0; + break; + + /* Boot options */ + case OPT_DEVICE_MASTER_PORT: + _hurd_device_master = atoi (arg); break; + case OPT_HOST_PRIV_PORT: + _hurd_host_priv = atoi (arg); break; + case OPT_EXEC_SERVER_TASK: + diskfs_exec_server_task = atoi (arg); break; + case OPT_BOOT_CMDLINE: + diskfs_boot_command_line = arg; break; + case OPT_BOOT_INIT_PROGRAM: + diskfs_boot_init_program = arg; break; + case OPT_BOOT_PAUSE: + _diskfs_boot_pause = 1; break; + case 'C': + _diskfs_chroot_directory = arg; break; + + case OPT_BOOT_COMMAND: + if (state->next == state->argc) + argp_error (state, "Command line must follow --boot-command option"); + _diskfs_boot_command = state->argv + state->next; + state->next = state->argc; /* stop parsing */ + {char **p; for (p = _diskfs_boot_command; *p; ++p) printf("BC %s\n",*p);} + break; + + case ARGP_KEY_END: + diskfs_argv = state->argv; break; + + default: + return ARGP_ERR_UNKNOWN; + } + + return 0; +} + +/* Suck in the common arguments. */ +static const struct argp startup_common_argp = + { diskfs_common_options, parse_startup_opt }; +static const struct argp_child startup_argp_children[] = + { {&startup_common_argp}, {0} }; + +/* This may be used with argp_parse to parse standard diskfs startup + options, possible chained onto the end of a user argp structure. */ +const struct argp +diskfs_startup_argp = +{ + startup_options, parse_startup_opt, 0, 0, startup_argp_children +}; + +static error_t +parse_store_startup_opt (int opt, char *arg, struct argp_state *state) +{ + switch (opt) + { + case ARGP_KEY_INIT: + /* Propagate our input to our STORE_ARGP child , which it will use to + return what it parses. */ + state->child_inputs[1] = state->input; break; + default: + return ARGP_ERR_UNKNOWN; + } + + return 0; +} + +static const struct argp_child store_argp_children[] = + { {&diskfs_startup_argp}, {&store_argp}, {0} }; + +/* An argp structure for the standard diskfs command line arguments plus a + store specification. The address of a location in which to return the + resulting struct store_parsed structure should be passed as the input + argument to argp_parse; see the declaration for STORE_ARGP in + for more information. */ +const struct argp +diskfs_store_startup_argp = +{ + 0, parse_store_startup_opt, 0, 0, store_argp_children +}; diff --git a/code/validation/C/0021651_time_Trsm_lut.c b/code/validation/C/0021651_time_Trsm_lut.c new file mode 100644 index 0000000000000000000000000000000000000000..f292b7bd4c5c14499f0af91f025a9fd223f6996d --- /dev/null +++ b/code/validation/C/0021651_time_Trsm_lut.c @@ -0,0 +1,164 @@ +/* + + Copyright (C) 2014, The University of Texas at Austin + + This file is part of libflame and is available under the 3-Clause + BSD license, which can be found in the LICENSE file at the top-level + directory, or at http://opensource.org/licenses/BSD-3-Clause + +*/ + +#include "FLAME.h" + +#define FLA_ALG_REFERENCE 0 +#define FLA_ALG_UNBLOCKED 1 +#define FLA_ALG_BLOCKED 2 +#define FLA_ALG_OPTIMIZED 3 + + +void time_Trsm_lut( + int variant, int type, int nrepeats, int n, int nb_alg, + FLA_Obj A, FLA_Obj B, FLA_Obj C, FLA_Obj C_ref, + double *dtime, double *diff, double *gflops ) +{ + int + irep; + + double + dtime_old = 1.0e9; + + FLA_Obj + C_old; + + fla_blocksize_t* + bp; + fla_gemm_t* + cntl_gemm_blas; + fla_trsm_t* + cntl_trsm_blas; + fla_trsm_t* + cntl_trsm_var; + + bp = FLA_Blocksize_create( nb_alg, nb_alg, nb_alg, nb_alg ); + cntl_gemm_blas = FLA_Cntl_gemm_obj_create( FLA_FLAT, FLA_SUBPROBLEM, NULL, NULL ); + cntl_trsm_blas = FLA_Cntl_trsm_obj_create( FLA_FLAT, FLA_SUBPROBLEM, NULL, NULL, NULL ); + cntl_trsm_var = FLA_Cntl_trsm_obj_create( FLA_FLAT, variant, bp, cntl_trsm_blas, cntl_gemm_blas ); + + FLA_Obj_create_conf_to( FLA_NO_TRANSPOSE, C, &C_old ); + + FLA_Copy_external( C, C_old ); + + + for ( irep = 0 ; irep < nrepeats; irep++ ) + { + FLA_Copy_external( C_old, C ); + + *dtime = FLA_Clock(); + + switch( variant ){ + + case 0: + // Time reference implementation + REF_Trsm( FLA_LEFT, FLA_UPPER_TRIANGULAR, + FLA_TRANSPOSE, FLA_NONUNIT_DIAG, + FLA_ONE, A, C ); + break; + + case 1:{ + // Time variant 1 + switch( type ){ + case FLA_ALG_UNBLOCKED: + FLA_Trsm_lut_unb_var1( FLA_NONUNIT_DIAG, FLA_ONE, A, C ); + break; + case FLA_ALG_BLOCKED: + FLA_Trsm_lut_blk_var1( FLA_NONUNIT_DIAG, FLA_ONE, A, C, cntl_trsm_var ); + break; + default: + printf("trouble\n"); + } + + break; + } + + case 2:{ + // Time variant 2 + switch( type ){ + case FLA_ALG_UNBLOCKED: + FLA_Trsm_lut_unb_var2( FLA_NONUNIT_DIAG, FLA_ONE, A, C ); + break; + case FLA_ALG_BLOCKED: + FLA_Trsm_lut_blk_var2( FLA_NONUNIT_DIAG, FLA_ONE, A, C, cntl_trsm_var ); + break; + default: + printf("trouble\n"); + } + + break; + } + + case 3:{ + // Time variant 3 + switch( type ){ + case FLA_ALG_UNBLOCKED: + FLA_Trsm_lut_unb_var3( FLA_NONUNIT_DIAG, FLA_ONE, A, C ); + break; + case FLA_ALG_BLOCKED: + FLA_Trsm_lut_blk_var3( FLA_NONUNIT_DIAG, FLA_ONE, A, C, cntl_trsm_var ); + break; + default: + printf("trouble\n"); + } + + break; + } + + case 4:{ + // Time variant 4 + switch( type ){ + case FLA_ALG_UNBLOCKED: + FLA_Trsm_lut_unb_var4( FLA_NONUNIT_DIAG, FLA_ONE, A, C ); + break; + case FLA_ALG_BLOCKED: + FLA_Trsm_lut_blk_var4( FLA_NONUNIT_DIAG, FLA_ONE, A, C, cntl_trsm_var ); + break; + default: + printf("trouble\n"); + } + + break; + } + } + + *dtime = FLA_Clock() - *dtime; + dtime_old = min( *dtime, dtime_old ); + } + + FLA_Cntl_obj_free( cntl_trsm_var ); + FLA_Cntl_obj_free( cntl_trsm_blas ); + FLA_Cntl_obj_free( cntl_gemm_blas ); + FLA_Blocksize_free( bp ); + + if ( variant == 0 ) + { + FLA_Copy_external( C, C_ref ); + *diff = 0.0; + } + else + { + *diff = FLA_Max_elemwise_diff( C, C_ref ); + } + + *gflops = 1.0 * + FLA_Obj_length( C ) * + FLA_Obj_width( C ) * + FLA_Obj_width( A ) / + dtime_old / + 1.0e9; + + *dtime = dtime_old; + + FLA_Copy_external( C_old, C ); + + FLA_Obj_free( &C_old ); +} + diff --git a/code/validation/C/0044437_dwarf_entry_breakpoints.c b/code/validation/C/0044437_dwarf_entry_breakpoints.c new file mode 100644 index 0000000000000000000000000000000000000000..1e5c1b81941d8aec50e3335ba1a74e4bd3999fe0 --- /dev/null +++ b/code/validation/C/0044437_dwarf_entry_breakpoints.c @@ -0,0 +1,178 @@ +/* Find entry breakpoint locations for a function. + Copyright (C) 2005-2009 Red Hat, Inc. + This file is part of Red Hat elfutils. + + Red Hat elfutils is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by the + Free Software Foundation; version 2 of the License. + + Red Hat elfutils is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License along + with Red Hat elfutils; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA. + + In addition, as a special exception, Red Hat, Inc. gives You the + additional right to link the code of Red Hat elfutils with code licensed + under any Open Source Initiative certified open source license + (http://www.opensource.org/licenses/index.php) which requires the + distribution of source code with any binary distribution and to + distribute linked combinations of the two. Non-GPL Code permitted under + this exception must only link to the code of Red Hat elfutils through + those well defined interfaces identified in the file named EXCEPTION + found in the source code files (the "Approved Interfaces"). The files + of Non-GPL Code may instantiate templates or use macros or inline + functions from the Approved Interfaces without causing the resulting + work to be covered by the GNU General Public License. Only Red Hat, + Inc. may make changes or additions to the list of Approved Interfaces. + Red Hat's grant of this exception is conditioned upon your not adding + any new exceptions. If you wish to add a new Approved Interface or + exception, please contact Red Hat. You must obey the GNU General Public + License in all respects for all of the Red Hat elfutils code and other + code used in conjunction with Red Hat elfutils except the Non-GPL Code + covered by this exception. If you modify this file, you may extend this + exception to your version of the file, but you are not obligated to do + so. If you do not wish to provide this exception without modification, + you must delete this exception statement from your version and license + this file solely under the GPL without exception. + + Red Hat elfutils is an included package of the Open Invention Network. + An included package of the Open Invention Network is a package for which + Open Invention Network licensees cross-license their patents. No patent + license is granted, either expressly or impliedly, by designation as an + included package. Should you wish to participate in the Open Invention + Network licensing program, please visit www.openinventionnetwork.com + . */ + +#ifdef HAVE_CONFIG_H +# include +#endif +#include "libdwP.h" +#include +#include + + +int +dwarf_entry_breakpoints (die, bkpts) + Dwarf_Die *die; + Dwarf_Addr **bkpts; +{ + int nbkpts = 0; + *bkpts = NULL; + + /* Add one breakpoint location to the result vector. */ + inline int add_bkpt (Dwarf_Addr pc) + { + Dwarf_Addr *newlist = realloc (*bkpts, ++nbkpts * sizeof newlist[0]); + if (newlist == NULL) + { + free (*bkpts); + *bkpts = NULL; + __libdw_seterrno (DWARF_E_NOMEM); + return -1; + } + newlist[nbkpts - 1] = pc; + *bkpts = newlist; + return nbkpts; + } + + /* Fallback result, break at the entrypc/lowpc value. */ + inline int entrypc_bkpt (void) + { + Dwarf_Addr pc; + return INTUSE(dwarf_entrypc) (die, &pc) < 0 ? -1 : add_bkpt (pc); + } + + /* Fetch the CU's line records to look for this DIE's addresses. */ + Dwarf_Die cudie = CUDIE (die->cu); + Dwarf_Lines *lines; + size_t nlines; + if (INTUSE(dwarf_getsrclines) (&cudie, &lines, &nlines) < 0) + { + int error = INTUSE (dwarf_errno) (); + if (error == 0) /* CU has no DW_AT_stmt_list. */ + return entrypc_bkpt (); + __libdw_seterrno (error); + return -1; + } + + /* Search a contiguous PC range for prologue-end markers. + If DWARF, look for proper markers. + Failing that, if ADHOC, look for the ad hoc convention. */ + inline int search_range (Dwarf_Addr low, Dwarf_Addr high, + bool dwarf, bool adhoc) + { + size_t l = 0, u = nlines; + while (l < u) + { + size_t idx = (l + u) / 2; + if (lines->info[idx].addr < low) + l = idx + 1; + else if (lines->info[idx].addr > low) + u = idx; + else if (lines->info[idx].end_sequence) + l = idx + 1; + else + { + l = idx; + break; + } + } + if (l < u) + { + if (dwarf) + for (size_t i = l; i < u && lines->info[i].addr < high; ++i) + if (lines->info[i].prologue_end + && add_bkpt (lines->info[i].addr) < 0) + return -1; + if (adhoc && nbkpts == 0) + while (++l < nlines && lines->info[l].addr < high) + if (!lines->info[l].end_sequence) + return add_bkpt (lines->info[l].addr); + return nbkpts; + } + __libdw_seterrno (DWARF_E_INVALID_DWARF); + return -1; + } + + /* Search each contiguous address range for DWARF prologue_end markers. */ + + Dwarf_Addr base; + Dwarf_Addr begin; + Dwarf_Addr end; + ptrdiff_t offset = INTUSE(dwarf_ranges) (die, 0, &base, &begin, &end); + if (offset < 0) + return -1; + + /* Most often there is a single contiguous PC range for the DIE. */ + if (offset == 1) + return search_range (begin, end, true, true) ?: entrypc_bkpt (); + + Dwarf_Addr lowpc = (Dwarf_Addr) -1l; + Dwarf_Addr highpc = (Dwarf_Addr) -1l; + while (offset > 0) + { + /* We have an address range entry. */ + if (search_range (begin, end, true, false) < 0) + return -1; + + if (begin < lowpc) + { + lowpc = begin; + highpc = end; + } + + offset = INTUSE(dwarf_ranges) (die, offset, &base, &begin, &end); + } + + /* If we didn't find any proper DWARF markers, then look in the + lowest-addressed range for an ad hoc marker. Failing that, + fall back to just using the entrypc value. */ + return (nbkpts + ?: (lowpc == (Dwarf_Addr) -1l ? 0 + : search_range (lowpc, highpc, false, true)) + ?: entrypc_bkpt ()); +} diff --git a/code/validation/C/0044941_machine_i2c.c b/code/validation/C/0044941_machine_i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..87b08fc9bc6e613dc33d376a26a90f72620a09c2 --- /dev/null +++ b/code/validation/C/0044941_machine_i2c.c @@ -0,0 +1,181 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 Damien P. George + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "py/runtime.h" +#include "py/mphal.h" +#include "py/mperrno.h" +#include "extmod/machine_i2c.h" +#include "modmachine.h" + +#include "driver/i2c.h" + +#define I2C_0_DEFAULT_SCL (GPIO_NUM_18) +#define I2C_0_DEFAULT_SDA (GPIO_NUM_19) +#define I2C_1_DEFAULT_SCL (GPIO_NUM_25) +#define I2C_1_DEFAULT_SDA (GPIO_NUM_26) + +#define I2C_DEFAULT_TIMEOUT_US (10000) // 10ms + +typedef struct _machine_hw_i2c_obj_t { + mp_obj_base_t base; + i2c_port_t port : 8; + gpio_num_t scl : 8; + gpio_num_t sda : 8; +} machine_hw_i2c_obj_t; + +STATIC machine_hw_i2c_obj_t machine_hw_i2c_obj[I2C_NUM_MAX]; + +STATIC void machine_hw_i2c_init(machine_hw_i2c_obj_t *self, uint32_t freq, uint32_t timeout_us, bool first_init) { + if (!first_init) { + i2c_driver_delete(self->port); + } + i2c_config_t conf = { + .mode = I2C_MODE_MASTER, + .sda_io_num = self->sda, + .sda_pullup_en = GPIO_PULLUP_ENABLE, + .scl_io_num = self->scl, + .scl_pullup_en = GPIO_PULLUP_ENABLE, + .master.clk_speed = freq, + }; + i2c_param_config(self->port, &conf); + i2c_set_timeout(self->port, I2C_APB_CLK_FREQ / 1000000 * timeout_us); + i2c_driver_install(self->port, I2C_MODE_MASTER, 0, 0, 0); +} + +int machine_hw_i2c_transfer(mp_obj_base_t *self_in, uint16_t addr, size_t n, mp_machine_i2c_buf_t *bufs, unsigned int flags) { + machine_hw_i2c_obj_t *self = MP_OBJ_TO_PTR(self_in); + + i2c_cmd_handle_t cmd = i2c_cmd_link_create(); + i2c_master_start(cmd); + i2c_master_write_byte(cmd, addr << 1 | (flags & MP_MACHINE_I2C_FLAG_READ), true); + + int data_len = 0; + for (; n--; ++bufs) { + if (flags & MP_MACHINE_I2C_FLAG_READ) { + i2c_master_read(cmd, bufs->buf, bufs->len, n == 0 ? I2C_MASTER_LAST_NACK : I2C_MASTER_ACK); + } else { + if (bufs->len != 0) { + i2c_master_write(cmd, bufs->buf, bufs->len, true); + } + } + data_len += bufs->len; + } + + if (flags & MP_MACHINE_I2C_FLAG_STOP) { + i2c_master_stop(cmd); + } + + // TODO proper timeout + esp_err_t err = i2c_master_cmd_begin(self->port, cmd, 100 * (1 + data_len) / portTICK_RATE_MS); + i2c_cmd_link_delete(cmd); + + if (err == ESP_FAIL) { + return -MP_ENODEV; + } else if (err == ESP_ERR_TIMEOUT) { + return -MP_ETIMEDOUT; + } else if (err != ESP_OK) { + return -abs(err); + } + + return data_len; +} + +/******************************************************************************/ +// MicroPython bindings for machine API + +STATIC void machine_hw_i2c_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + machine_hw_i2c_obj_t *self = MP_OBJ_TO_PTR(self_in); + int h, l; + i2c_get_period(self->port, &h, &l); + mp_printf(print, "I2C(%u, scl=%u, sda=%u, freq=%u)", + self->port, self->scl, self->sda, I2C_APB_CLK_FREQ / (h + l)); +} + +mp_obj_t machine_hw_i2c_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + MP_MACHINE_I2C_CHECK_FOR_LEGACY_SOFTI2C_CONSTRUCTION(n_args, n_kw, all_args); + + // Parse args + enum { ARG_id, ARG_scl, ARG_sda, ARG_freq, ARG_timeout }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_id, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_scl, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_sda, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 400000} }, + { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = I2C_DEFAULT_TIMEOUT_US} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + // Get I2C bus + mp_int_t i2c_id = mp_obj_get_int(args[ARG_id].u_obj); + if (!(I2C_NUM_0 <= i2c_id && i2c_id < I2C_NUM_MAX)) { + mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("I2C(%d) doesn't exist"), i2c_id); + } + + // Get static peripheral object + machine_hw_i2c_obj_t *self = (machine_hw_i2c_obj_t *)&machine_hw_i2c_obj[i2c_id]; + + bool first_init = false; + if (self->base.type == NULL) { + // Created for the first time, set default pins + self->base.type = &machine_hw_i2c_type; + self->port = i2c_id; + if (self->port == I2C_NUM_0) { + self->scl = I2C_0_DEFAULT_SCL; + self->sda = I2C_0_DEFAULT_SDA; + } else { + self->scl = I2C_1_DEFAULT_SCL; + self->sda = I2C_1_DEFAULT_SDA; + } + first_init = true; + } + + // Set SCL/SDA pins if given + if (args[ARG_scl].u_obj != MP_OBJ_NULL) { + self->scl = mp_hal_get_pin_obj(args[ARG_scl].u_obj); + } + if (args[ARG_sda].u_obj != MP_OBJ_NULL) { + self->sda = mp_hal_get_pin_obj(args[ARG_sda].u_obj); + } + + // Initialise the I2C peripheral + machine_hw_i2c_init(self, args[ARG_freq].u_int, args[ARG_timeout].u_int, first_init); + + return MP_OBJ_FROM_PTR(self); +} + +STATIC const mp_machine_i2c_p_t machine_hw_i2c_p = { + .transfer = machine_hw_i2c_transfer, +}; + +const mp_obj_type_t machine_hw_i2c_type = { + { &mp_type_type }, + .name = MP_QSTR_I2C, + .print = machine_hw_i2c_print, + .make_new = machine_hw_i2c_make_new, + .protocol = &machine_hw_i2c_p, + .locals_dict = (mp_obj_dict_t *)&mp_machine_i2c_locals_dict, +}; diff --git a/code/validation/C/0048350_cmds-rescue.c b/code/validation/C/0048350_cmds-rescue.c new file mode 100644 index 0000000000000000000000000000000000000000..f20a2068a16bc02ecdaf082f17debbded3ec8db4 --- /dev/null +++ b/code/validation/C/0048350_cmds-rescue.c @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2013 SUSE. All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public + * License v2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 021110-1307, USA. + */ + +#include "kerncompat.h" + +#include +#include "commands.h" +#include "utils.h" + +static const char * const rescue_cmd_group_usage[] = { + "btrfs rescue [options] ", + NULL +}; + +int btrfs_recover_chunk_tree(char *path, int verbose, int yes); +int btrfs_recover_superblocks(char *path, int verbose, int yes); + +const char * const cmd_chunk_recover_usage[] = { + "btrfs rescue chunk-recover [options] ", + "Recover the chunk tree by scanning the devices one by one.", + "", + "-y Assume an answer of `yes' to all questions", + "-v Verbose mode", + "-h Help", + NULL +}; + +const char * const cmd_super_recover_usage[] = { + "btrfs rescue super-recover [options] ", + "Recover bad superblocks from good copies", + "", + "-y Assume an answer of `yes' to all questions", + "-v Verbose mode", + NULL +}; + +int cmd_chunk_recover(int argc, char *argv[]) +{ + int ret = 0; + char *file; + int yes = 0; + int verbose = 0; + + while (1) { + int c = getopt(argc, argv, "yvh"); + if (c < 0) + break; + switch (c) { + case 'y': + yes = 1; + break; + case 'v': + verbose = 1; + break; + case 'h': + default: + usage(cmd_chunk_recover_usage); + } + } + + argc = argc - optind; + if (argc == 0) + usage(cmd_chunk_recover_usage); + + file = argv[optind]; + + ret = check_mounted(file); + if (ret < 0) { + fprintf(stderr, "Could not check mount status: %s\n", + strerror(-ret)); + return 1; + } else if (ret) { + fprintf(stderr, "the device is busy\n"); + return 1; + } + + ret = btrfs_recover_chunk_tree(file, verbose, yes); + if (!ret) { + fprintf(stdout, "Recover the chunk tree successfully.\n"); + } else if (ret > 0) { + ret = 0; + fprintf(stdout, "Abort to rebuild the on-disk chunk tree.\n"); + } else { + fprintf(stdout, "Fail to recover the chunk tree.\n"); + } + return ret; +} + +/* + * return codes: + * 0 : All superblocks are valid, no need to recover + * 1 : Usage or syntax error + * 2 : Recover all bad superblocks successfully + * 3 : Fail to Recover bad supeblocks + * 4 : Abort to recover bad superblocks + */ +int cmd_super_recover(int argc, char **argv) +{ + int ret; + int verbose = 0; + int yes = 0; + char *dname; + + while (1) { + int c = getopt(argc, argv, "vy"); + if (c < 0) + break; + switch (c) { + case 'v': + verbose = 1; + break; + case 'y': + yes = 1; + break; + default: + usage(cmd_super_recover_usage); + } + } + argc = argc - optind; + if (argc != 1) + usage(cmd_super_recover_usage); + + dname = argv[optind]; + ret = check_mounted(dname); + if (ret < 0) { + fprintf(stderr, "Could not check mount status: %s\n", + strerror(-ret)); + return 1; + } else if (ret) { + fprintf(stderr, "the device is busy\n"); + return 1; + } + ret = btrfs_recover_superblocks(dname, verbose, yes); + return ret; +} + +const struct cmd_group rescue_cmd_group = { + rescue_cmd_group_usage, NULL, { + { "chunk-recover", cmd_chunk_recover, cmd_chunk_recover_usage, NULL, 0}, + { "super-recover", cmd_super_recover, cmd_super_recover_usage, NULL, 0}, + { 0, 0, 0, 0, 0 } + } +}; + +int cmd_rescue(int argc, char **argv) +{ + return handle_command_group(&rescue_cmd_group, argc, argv); +} diff --git a/code/validation/C/0051008_display.c b/code/validation/C/0051008_display.c new file mode 100644 index 0000000000000000000000000000000000000000..3dc2b5b8bfd98e4ffdbf1325133cc080af411fe8 --- /dev/null +++ b/code/validation/C/0051008_display.c @@ -0,0 +1,204 @@ +#include "threads.h" +#include "ssd1306.h" +#include "menu.h" +#include "string.h" + +display_t display = {DISPLAY_OFF}; +const char version[] = VERSION; +const char enabled[] = "Enabled"; +const char disabled[] = "Disabled"; + +void showDiag(void); +void showInfo(void); +void setCutMode(void); +void setOutputMode(void); +void startBootloader(void); + +/* Settings menu */ +const menuItem_t cutModeMenuList[] = {{"Fixed", &setCutModeFixed, NULL}, + {"Adaptive", &setCutModeAdaptive, NULL}, + {"Min Time", &setCutMinTime, NULL}, + {"Max Time", &setCutMaxTime, NULL}}; + +const menuStruct_t cutModeMenu = {"Cut Mode", sizeof(cutModeMenuList)/sizeof(menuItem_t), cutModeMenuList}; + +/* Settings menu */ +const menuItem_t settingsMenuList[] = {{"Cut mode", NULL, &cutModeMenu}, + {"Output mode", &setOutputMode, NULL}, + {"Shifter sensor setup", &setShifter, NULL}}; + +const menuStruct_t settingsMenu = {"Settings Menu", sizeof(settingsMenuList)/sizeof(menuItem_t), settingsMenuList}; +/**/ + +/* Main menu */ +const menuItem_t mainMenuItemList[] = {{"Settings", NULL, &settingsMenu}, + {"Diagnostics", &showDiag, NULL}, + {"Informations", &showInfo, NULL}, + {"Update", &startBootloader, NULL}}; + +const menuStruct_t mainMenu = {"Main Menu", sizeof(mainMenuItemList)/sizeof(menuItem_t), mainMenuItemList}; +/**/ + +void startDisplay(void) { + + + ssd1306Init(SSD1306_SWITCHCAPVCC); + ssd1306TurnOn(); + display.state = DISPLAY_ON; + + ssd1306DrawString(40, 20, "OpenQS", Font_System7x8); + chThdSleepMilliseconds(100); // Fails + + serDbg("startDisplay Complete\r\n"); + + while (true) { + + serDbg("Display OFF\r\n"); + ssd1306TurnOff(); + display.state = DISPLAY_OFF; + + while (!BUTTON_SEL) /* Wait until the select button is pressed */ + { + palTogglePad(GPIOC, GPIOC_LED4); /* Display heartbeat */ + chThdSleepMilliseconds(250); + } + serDbg("Display ON\r\n"); + ssd1306ClearScreen(); + ssd1306TurnOn(); + display.state = DISPLAY_ON; + openMenu(&mainMenu); + } +} + +void drawTitle(char * str) +{ + const uint8_t len = Font_System7x8.u8Width*strlen(str); + ssd1306DrawString(64-(len/2), 0, str, Font_System7x8); +} + +void startBootloader(void) +{ +// Reset board + +} + +void showDiag(void) +{ + char str[10] = ""; + + while (!BUTTON_SEL) { + + drawTitle("Diagnostics"); + + ssd1306DrawString(0, 30, "Shifter:", Font_System5x8); + itoa(sensors.strain_gauge, str); + ssd1306DrawString(45, 30, str, Font_System5x8); + + ssd1306DrawString(0, 40, "TC Switch:", Font_System5x8); + itoa(sensors.tc_switch, str); + ssd1306DrawString(55, 40, str, Font_System5x8); + + chThdSleepMilliseconds(100); + } +} + +void showInfo(void) +{ + drawTitle("Version"); + ssd1306DrawString(0, 10, version, Font_System5x8); + + ssd1306DrawString(0, 20, "Cut mode:", Font_System5x8); + if (settings.data.functions == SETTINGS_CUT_ANALOG) + { + ssd1306DrawString(25, 20, "Analog", Font_System5x8); + } + else if (settings.data.functions == SETTINGS_CUT_NORMAL) + { + ssd1306DrawString(25, 20, "Normal", Font_System5x8); + } + else + { + ssd1306DrawString(25, 20, disabled, Font_System5x8); + } + + while (!BUTTON_SEL) chThdSleepMilliseconds(100); +} + +void setCutMode(void) +{ + drawTitle("Output Mode"); + + if (settings.data.functions == SETTINGS_CUT_FIXED) + { + ssd1306DrawString(25, 0, "Fixed", Font_System5x8); + settings.data.functions = SETTINGS_CUT_FIXED; + } + else + { + ssd1306DrawString(25, 0, "Adaptive", Font_System5x8); + settings.data.functions = SETTINGS_CUT_ADAPTIVE; + } + writeSettings(&settings); + chThdSleepMilliseconds(2000); +} + +void setOutputMode(void) +{ + drawTitle("Output Mode"); + + if (settings.data.functions == SETTINGS_OUTPUT_NORMAL) + { + ssd1306DrawString(25, 0, "Analog", Font_System5x8); + settings.data.functions = SETTINGS_OUTPUT_ANALOG; + } + else + { + ssd1306DrawString(25, 0, "Normal", Font_System5x8); + settings.data.functions = SETTINGS_OUTPUT_NORMAL; + } + writeSettings(&settings); + chThdSleepMilliseconds(2000); +} + +void setShifter(void) +{ + drawTitle("Shifter Sensor Setup"); + + uint8_t i; + uint16_t peak; + + ssd1306DrawString(0, 25, "Shift a gear", Font_System5x8); + ssd1306DrawString(10, 10, "to detect direction", Font_System5x8); + + chThdSleepMilliseconds(2000); + + peak = 0; + for (i=0; i<40; i++) + { + if (sensors.strain_gauge >= peak) + peak = sensors.strain_gauge; + + chThdSleepMilliseconds(100); + } + + ssd1306ClearScreen(); + + /* Peak >= 1.65v */ + if (peak >= 0x8000) + { + ssd1306DrawString(0, 10, "Normal direction", Font_System5x8); + settings.data.sensor_direction = SETTINGS_SENSOR_NORMAL; + } + else + { + ssd1306DrawString(0, 5, "Reverse direction", Font_System5x8); + settings.data.sensor_direction = SETTINGS_SENSOR_REVERSE; + } + + settings.data.sensor_threshold = peak; + writeSettings(&settings); + + chThdSleepMilliseconds(2000); + + while (!BUTTON_SEL) chThdSleepMilliseconds(100); +} diff --git a/code/validation/C/0051985_ufdwatch.c b/code/validation/C/0051985_ufdwatch.c new file mode 100644 index 0000000000000000000000000000000000000000..54539795b716e8141ed91e116b8b0c41d5a0bd5a --- /dev/null +++ b/code/validation/C/0051985_ufdwatch.c @@ -0,0 +1,198 @@ +/* ______ ___ ___ + * /\ _ \ /\_ \ /\_ \ + * \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___ + * \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\ + * \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \ + * \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/ + * \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/ + * /\____/ + * \_/__/ + * + * Unix fd watcher thread. + * + * By Peter Wang. + * + * See readme.txt for copyright information. + * + * This module implements a background thread that waits for data + * to arrive in file descriptors, at which point it dispatches to + * functions which will process that data. + */ + + +#include +#include +#include +#include +#include + +#include "allegro5/allegro.h" +#include "allegro5/internal/aintern.h" +#include "allegro5/internal/aintern_thread.h" +#include "allegro5/internal/aintern_vector.h" +#include "allegro5/platform/aintunix.h" + + + +typedef struct WATCH_ITEM +{ + int fd; + void (*callback)(void *); + void *cb_data; +} WATCH_ITEM; + + +static _AL_THREAD fd_watch_thread; +static _AL_MUTEX fd_watch_mutex = _AL_MUTEX_UNINITED; +static _AL_VECTOR fd_watch_list = _AL_VECTOR_INITIALIZER(WATCH_ITEM); + + + +/* fd_watch_thread_func: [fdwatch thread] + * The thread loop function. + */ +static void fd_watch_thread_func(_AL_THREAD *self, void *unused) +{ + (void)unused; + + while (!_al_get_thread_should_stop(self)) { + + fd_set rfds; + int max_fd; + + /* set up max_fd and rfds */ + _al_mutex_lock(&fd_watch_mutex); + { + WATCH_ITEM *wi; + unsigned int i; + + FD_ZERO(&rfds); + max_fd = -1; + + for (i = 0; i < _al_vector_size(&fd_watch_list); i++) { + wi = _al_vector_ref(&fd_watch_list, i); + FD_SET(wi->fd, &rfds); + if (wi->fd > max_fd) + max_fd = wi->fd; + } + } + _al_mutex_unlock(&fd_watch_mutex); + + /* wait for something to happen on one of the fds */ + { + struct timeval tv; + int retval; + + tv.tv_sec = 0; + tv.tv_usec = 250000; + + retval = select(max_fd+1, &rfds, NULL, NULL, &tv); + if (retval < 1) + continue; + } + + /* one or more of the fds has activity */ + _al_mutex_lock(&fd_watch_mutex); + { + WATCH_ITEM *wi; + unsigned int i; + + for (i = 0; i < _al_vector_size(&fd_watch_list); i++) { + wi = _al_vector_ref(&fd_watch_list, i); + if (FD_ISSET(wi->fd, &rfds)) { + /* The callback is allowed to modify the watch list so the mutex + * must be recursive. + */ + wi->callback(wi->cb_data); + } + } + } + _al_mutex_unlock(&fd_watch_mutex); + } +} + + + +/* _al_unix_start_watching_fd: [primary thread] + * + * Start watching for data on file descriptor `fd'. This is done in + * a background thread, which is started if necessary. When there is + * data waiting to be read on fd, `callback' is applied to `cb_data'. + * The callback function should read as much data off fd as possible. + * + * Note: the callback is run from the background thread. You can + * assume there is only one callback being called from the fdwatch + * module at a time. + */ +void _al_unix_start_watching_fd(int fd, void (*callback)(void *), void *cb_data) +{ + ASSERT(fd >= 0); + ASSERT(callback); + + /* start the background thread if necessary */ + if (_al_vector_size(&fd_watch_list) == 0) { + /* We need a recursive mutex to allow callbacks to modify the fd watch + * list. + */ + _al_mutex_init_recursive(&fd_watch_mutex); + _al_thread_create(&fd_watch_thread, fd_watch_thread_func, NULL); + } + + /* now add the watch item to the list */ + _al_mutex_lock(&fd_watch_mutex); + { + WATCH_ITEM *wi = _al_vector_alloc_back(&fd_watch_list); + + wi->fd = fd; + wi->callback = callback; + wi->cb_data = cb_data; + } + _al_mutex_unlock(&fd_watch_mutex); +} + + + +/* _al_unix_stop_watching_fd: [primary thread] + * + * Stop watching for data on `fd'. Once there are no more file + * descriptors to watch, the background thread will be stopped. This + * function is synchronised with the background thread, so you don't + * have to do any locking before calling it. + */ +void _al_unix_stop_watching_fd(int fd) +{ + bool list_empty = false; + + /* find the fd in the watch list and remove it */ + _al_mutex_lock(&fd_watch_mutex); + { + WATCH_ITEM *wi; + unsigned int i; + + for (i = 0; i < _al_vector_size(&fd_watch_list); i++) { + wi = _al_vector_ref(&fd_watch_list, i); + if (wi->fd == fd) { + _al_vector_delete_at(&fd_watch_list, i); + list_empty = _al_vector_is_empty(&fd_watch_list); + break; + } + } + } + _al_mutex_unlock(&fd_watch_mutex); + + /* if no more fd's are being watched, stop the background thread */ + if (list_empty) { + _al_thread_join(&fd_watch_thread); + _al_mutex_destroy(&fd_watch_mutex); + _al_vector_free(&fd_watch_list); + } +} + + + +/* + * Local Variables: + * c-basic-offset: 3 + * indent-tabs-mode: nil + * End: + */ diff --git a/code/validation/C/0052481_fc3d_TrescaFixedPoint.c b/code/validation/C/0052481_fc3d_TrescaFixedPoint.c new file mode 100644 index 0000000000000000000000000000000000000000..14d2aa78dbed44f0b229a76de45bf6cb9befeef7 --- /dev/null +++ b/code/validation/C/0052481_fc3d_TrescaFixedPoint.c @@ -0,0 +1,162 @@ +/* Siconos is a program dedicated to modeling, simulation and control + * of non smooth dynamical systems. + * + * Copyright 2022 INRIA. + * + * 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. +*/ +#include // for assert +#include // for fmax +#include // for printf, NULL +#include // for malloc +#include "FrictionContactProblem.h" // for FrictionContactProblem +#include "Friction_cst.h" // for SICONOS_FRICTION_3D_NSGS, SICONO... +#include "NumericsFwd.h" // for SolverOptions, FrictionContactPr... +#include "SiconosBlas.h" // for cblas_dnrm2 +#include "SolverOptions.h" // for SolverOptions, solver_options_cr... +#include "fc3d_Solvers.h" // for fc3d_set_internalsolver_tolerance +#include "fc3d_compute_error.h" // for fc3d_compute_error +#include "numerics_verbose.h" // for numerics_error, verbose + +void fc3d_TrescaFixedPoint(FrictionContactProblem* problem, double *reaction, double *velocity, int* info, SolverOptions* options) +{ + /* int and double parameters */ + int* iparam = options->iparam; + double* dparam = options->dparam; + + /* Number of contacts */ + int nc = problem->numberOfContacts; + + /* Maximum number of iterations */ + int itermax = iparam[SICONOS_IPARAM_MAX_ITER]; + /* Tolerance */ + double tolerance = dparam[SICONOS_DPARAM_TOL]; + double norm_q = cblas_dnrm2(nc*3, problem->q, 1); + + + if(options->numberOfInternalSolvers < 1) + { + numerics_error("fc3d_TrescaFixedpoint", "The Tresca Fixed Point method needs options for the internal solvers; please check your options."); + } + + SolverOptions * internalsolver_options = options->internalSolvers[0]; + + if(verbose) solver_options_print(options); + + /***** Fixed Point Iterations *****/ + int iter = 0; /* Current iteration number */ + double error = 1.; /* Current error */ + int hasNotConverged = 1; + + internalSolverPtr internalsolver=0; + // dwork will be used to save friction threshold + options->dWork = (double *) malloc(nc * sizeof(double)); + options->dWorkSize = nc; + double * mu = options->dWork; + // Warning : same dwork for current and internal solver !! + internalsolver_options->dWork = mu; + + + if(internalsolver_options->solverId == SICONOS_FRICTION_3D_NSGS) + { + if(verbose > 0) + printf(" ========================== Call NSGS solver for Friction-Contact 3D problem ==========================\n"); + internalsolver = &fc3d_nsgs; + } + else if(internalsolver_options->solverId == SICONOS_FRICTION_3D_CONVEXQP_PG_CYLINDER) + { + if(verbose > 0) + printf(" ========================== Call ConvexQP PG solver for Friction-Contact 3D problem ==========================\n"); + internalsolver = &fc3d_ConvexQP_ProjectedGradient_Cylinder; + } + else if(internalsolver_options->solverId == SICONOS_FRICTION_3D_VI_FPP_Cylinder) + { + if(verbose > 0) + printf(" ========================== Call VI FPP solver for Friction-Contact 3D problem ==========================\n"); + internalsolver = &fc3d_VI_FixedPointProjection_Cylinder; + } + else + { + numerics_error("fc3d_TrescaFixedpoint", "Unknown internal solver."); + } + + int cumul_internal=0; + + while((iter < itermax) && (hasNotConverged > 0)) + { + ++iter; + + /* Compute the value of the initial value friction threshold*/ + for(int ic = 0 ; ic < nc ; ic++) mu[ic] = fmax(0.0, problem->mu[ic] * reaction [ic * 3]); + + if(verbose>0) + printf("norm of mu = %10.5e \n", cblas_dnrm2(nc, mu, 1)); + + fc3d_set_internalsolver_tolerance(problem,options,internalsolver_options, error); + + (*internalsolver)(problem, reaction, velocity, info, internalsolver_options); + + cumul_internal += internalsolver_options->iparam[SICONOS_IPARAM_ITER_DONE]; + + /* **** Criterium convergence **** */ + + fc3d_compute_error(problem, reaction, velocity, tolerance, options, norm_q, &error); + + if(options->callback) + { + options->callback->collectStatsIteration(options->callback->env, nc * 3, + reaction, velocity, error, NULL); + } + + if(error < tolerance) hasNotConverged = 0; + *info = hasNotConverged; + + if(verbose > 0) + { + if(hasNotConverged) + { + printf("--------------- FC3D - TFP - Iteration %i error = %14.7e > %10.5e\n", iter, error, tolerance); + } + else + { + printf("--------------- FC3D - TFP - Iteration %i error = %14.7e < %10.5e\n", iter, error, tolerance); + printf("--------------- FC3D - TFP - # Internal iteration = %i\n", cumul_internal); + } + } + } + mu = NULL; + internalsolver_options->dWork = NULL; + dparam[SICONOS_DPARAM_RESIDU] = error; + iparam[SICONOS_IPARAM_ITER_DONE] = iter; + +} + + + +void fc3d_tfp_set_default(SolverOptions* options) +{ + + options->iparam[SICONOS_FRICTION_3D_IPARAM_INTERNAL_ERROR_STRATEGY] = SICONOS_FRICTION_3D_INTERNAL_ERROR_STRATEGY_ADAPTIVE; + options->dparam[SICONOS_FRICTION_3D_DPARAM_INTERNAL_ERROR_RATIO] =10.0; + + // internal solver + assert(options->numberOfInternalSolvers == 1); + options->internalSolvers[0] = solver_options_create(SICONOS_FRICTION_3D_NSGS); + options->internalSolvers[0]->iparam[SICONOS_IPARAM_MAX_ITER]=1000; + + // internal solver of the internal solver + assert(options->internalSolvers[0]->numberOfInternalSolvers == 1); + options->internalSolvers[0]->internalSolvers[0] = solver_options_create(SICONOS_FRICTION_3D_ONECONTACT_ProjectionOnCylinderWithLocalIteration); + options->internalSolvers[0]->internalSolvers[0]->iparam[SICONOS_IPARAM_MAX_ITER] = 50; + options->internalSolvers[0]->internalSolvers[0]->dparam[SICONOS_DPARAM_TOL] = 1e-14; +} diff --git a/code/validation/C/0052614_data.c b/code/validation/C/0052614_data.c new file mode 100644 index 0000000000000000000000000000000000000000..dbaa26f017d5b3d2885fea0254307a242c5faba6 --- /dev/null +++ b/code/validation/C/0052614_data.c @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2013 + * The President and Fellows of Harvard College. + * Written by David A. Holland. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY 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 +#include +#include +#include + +#include "data.h" + +/* + * XXX for now hardwire things we know about SFS + */ +#define BLOCKSIZE /*SFS_BLOCKSIZE*/ 512 + +static char databuf[DATA_MAXSIZE]; +static char readbuf[DATA_MAXSIZE]; + +static +void +prepdata(unsigned code, unsigned seq, char *buf, off_t len) +{ + char smallbuf[32]; + char letter; + size_t slen; + + snprintf(smallbuf, sizeof(smallbuf), "%u@%u\n", seq, code); + slen = strlen(smallbuf); + + while (len >= slen) { + memcpy(buf, smallbuf, slen); + buf += slen; + len -= slen; + } + if (len > 1) { + letter = 'A' + (code + seq) % 26; + memset(buf, letter, len - 1); + buf += len - 1; + } + if (len > 0) { + *buf = '\n'; + } +} + +static +int +matches_at(size_t start, size_t len) +{ + if (!memcmp(databuf + start, readbuf + start, len)) { + return 1; + } + return 0; +} + +static +int +byte_at(size_t start, size_t len, unsigned char val) +{ + size_t i; + + for (i=0; i 0); + assert(checklen <= len); + assert(checkstart >= 0 && checkstart < len); + assert(checkstart + checklen <= len); + assert(zerostart >= 0); + assert(zerostart <= len); + + prepdata(code, seq, databuf, len); + + ret = 1; + while (checklen > 0) { + /* check one block at a time */ + where = checkstart; + howmuch = BLOCKSIZE; + /* no more than is left to do */ + if (howmuch > checklen) { + howmuch = checklen; + } + /* if we stick over a block boundary, stop there */ + absend = regionoffset + where + howmuch; + slop = absend % BLOCKSIZE; + if (slop != 0 && slop < howmuch) { + howmuch -= slop; + } + /* if we go past the zerostart point, stop there */ + if (where < zerostart && where + howmuch > zerostart) { + howmuch = zerostart - where; + } + assert(howmuch > 0); + + if (matches_at(where, howmuch)) { + /* nothing */ + } + else if (zero_at(where, howmuch)) { + if (where >= zerostart) { + printf("WARNING: file %s range %lld-%lld is " + "zeroed\n", + namestr, regionoffset + where, + regionoffset + where + howmuch); + } + else { + ret = 0; + } + } + else if (poison_at(where, howmuch)) { + if (where >= zerostart) { + printf("ERROR: file %s range %lld-%lld is " + "poisoned\n", + namestr, regionoffset + where, + regionoffset + where + howmuch); + } + else { + ret = 0; + } + } + else { + ret = 0; + } + + checkstart += howmuch; + checklen -= howmuch; + } + return ret; +} + +void +data_check(const char *namestr, off_t regionoffset, + unsigned code, unsigned seq, off_t zerostart, off_t len, + off_t checkstart, off_t checklen) +{ + assert(zerostart >= 0); + assert(zerostart <= len); + + if (!data_matches(namestr, regionoffset, + code, seq, zerostart, len, checkstart, checklen)) { + printf("ERROR: file %s range %lld-%lld contains garbage\n", + namestr, regionoffset + checkstart, + regionoffset + checkstart + checklen); + } +} + +void * +data_map(unsigned code, unsigned seq, off_t len) +{ + assert(len <= DATA_MAXSIZE); + prepdata(code, seq, databuf, len); + return databuf; +} + +void * +data_mapreadbuf(off_t len) +{ + assert(len <= DATA_MAXSIZE); + return readbuf; +} diff --git a/code/validation/C/0053810_streams.c b/code/validation/C/0053810_streams.c new file mode 100644 index 0000000000000000000000000000000000000000..5699902e31c6313cb22b844d3697c4ee9e171999 --- /dev/null +++ b/code/validation/C/0053810_streams.c @@ -0,0 +1,65 @@ +/* + * streams.c + * + * Created on: Nov 17, 2015 + * Author: root + */ + +#include +#include +#include + +ssize_t readLine(int fd, char* line, size_t len) { + if (len >= 1) line[0] = 0; + char b = 0; + int s = 0; + int i = 0; + do { + s = read(fd, &b, 1); + if ((s == 0 && i == 0) || s < 0) { + return -1; + } + if (s == 0) { + break; + } + if (s > 0 && b != 13 && b != 10) { + line[i++] = b; + } + } while (b > -1 && s > 0 && b != 10 && i < len - 1); + line[i] = 0; + return i; +} + +ssize_t writeLine(int fd, char* line, size_t len) { + static char nl[2] = { 0x0A, 0x0D }; + int i = 0; + while (i < len) { + int x = write(fd, line + i, len - i); + if (x < 0) return -1; + i += x; + } + int i2 = 0; + while (i2 < 2) { + int y = write(fd, nl + i2, 2 - i2); + if (y < 0) return -1; + i2 += y; + } + return i; +} + +ssize_t writeLineSSL(SSL* session, char* line, size_t len) { + static char nl[2] = { 0x0A, 0x0D }; + size_t i = 0; + while (i < len) { + int x = SSL_write(session, line + i, len - i); + if (x < 0) return -1; + i += x; + } + int i2 = 0; + while (i2 < 2) { + int y = SSL_write(session, nl + i2, 2 - i2); + if (y < 0) return -1; + i2 += y; + } + return i; +} diff --git a/code/validation/C/0055995_qsimp.c b/code/validation/C/0055995_qsimp.c new file mode 100644 index 0000000000000000000000000000000000000000..cb5496b0761d4370cfbfc7405490a43aef2d45b1 --- /dev/null +++ b/code/validation/C/0055995_qsimp.c @@ -0,0 +1,24 @@ +#include +#define EPS 1.0e-6 +#define JMAX 20 + +float qsimp(float (*func)(float), float a, float b) +{ + float trapzd(float (*func)(float), float a, float b, int n); + void nrerror(char error_text[]); + int j; + float s,st,ost,os; + + ost = os = -1.0e30; + for (j=1;j<=JMAX;j++) { + st=trapzd(func,a,b,j); + s=(4.0*st-ost)/3.0; + if (fabs(s-os) < EPS*fabs(os)) return s; + os=s; + ost=st; + } + nrerror("Too many steps in routine qsimp"); + return 0.0; +} +#undef EPS +#undef JMAX diff --git a/code/validation/C/0056400_arguments.c b/code/validation/C/0056400_arguments.c new file mode 100644 index 0000000000000000000000000000000000000000..75fa1c087dbec2646ebe993861068721f91992d3 --- /dev/null +++ b/code/validation/C/0056400_arguments.c @@ -0,0 +1,166 @@ +/* -*- mode: C; c-file-style: "gnu" -*- */ +/* + * Copyright (C) 2011 Dirk Dierckx + * + * This file is part of bookie. + * + * bookie is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * bookie is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with bookie. If not, see . + */ + +#include /* assert */ +#include +#include /* malloc, free */ +#include /* printf, fprintf, sprintf */ +#include /* memset, strcmp, strlen */ +#include /* isalnum */ + +#include "arguments.h" + +static +size_t +_print_option (char *buffer, struct arguments_option *option) +{ + bool has_short = isalnum (option->short_opt); + bool has_long = NULL != option->long_opt; + bool has_arg = (no_argument != option->has_arg + && NULL != option->arg_name); + + assert (has_short || has_long); + + sprintf (buffer, "%c%c%s%s%s%s%s", + (has_short ? '-' : ' '), + (has_short ? option->short_opt : ' '), + (has_short && has_long + ? ", " + : (has_long ? " " : "")), + (has_long ? "--" : ""), + (has_long ? option->long_opt : ""), + (has_arg ? "=" : ""), + (has_arg ? option->arg_name : "")); + + return strlen (buffer); +} + +void +print_usage (struct arguments_definition *def, + const char *command) +{ + char *prev_cat = NULL; + size_t i, len, max_len = 0; + char option[80], padding[80]; + + if (NULL != def->print_usage_header) + def->print_usage_header (command); + else if (NULL == def->options[0].cat) + printf ("Usage: %s\n", command); + else + printf ("Usage: %s [OPTION]...\n", command); + + for (i = 0;NULL != def->options[i].cat;++i) { + len = _print_option (option, def->options + i); + if (len > max_len) + max_len = len; + } + + memset (padding, ' ', sizeof (padding)); + padding[sizeof (padding) - 1] = '\0'; + + for (i = 0;NULL != def->options[i].cat;++i) { + if (NULL == prev_cat || 0 != strcmp (prev_cat, def->options[i].cat)) { + printf ("\n%s:\n", def->options[i].cat); + prev_cat = def->options[i].cat; + } + len = _print_option (option, def->options + i); + padding[max_len - len] = '\0'; + printf (" %s%s %s\n", option, padding, def->options[i].desc); + padding[max_len - len] = ' '; + } + printf ("\n"); +} + +bool +get_arguments (struct arguments_definition *def, int argc, char *argv[]) +{ + bool go_on = false; + size_t i, count = 0; + struct option *opts; + char *optstring; + + assert (NULL != def); + + for (i = 0;NULL != def->options[i].cat;++i) + if (NULL != def->options[i].long_opt) + ++count; + + opts = (struct option *) malloc (sizeof (struct option) * (count + 1)); + if (NULL == opts) { + fprintf (stderr, "Could not allocate memory because: %s\n", + strerror (errno)); + } else { + memset (opts, 0, sizeof (struct option) * (count + 1)); + + for (i = 0;NULL != def->options[i].cat;++i) + if (isalnum (def->options[i].short_opt)) + ++count; + optstring = (char *) malloc ((count + 1) * 3); + if (NULL == optstring) { + fprintf (stderr, "Could not allocate memory because: %s\n", + strerror (errno)); + } else { + size_t s = 0, l = 0; + int opt; + + memset (optstring, 0, (count + 1) * 3); + for (i = 0;NULL != def->options[i].cat;++i) { + if (isalnum (def->options[i].short_opt)) { + optstring[s++] = def->options[i].short_opt; + switch (def->options[i].has_arg) { + case optional_argument: + optstring[s++] = ':'; + case required_argument: + optstring[s++] = ':'; + case no_argument: + break; + default: + assert (false); /* invalid has_arg value */ + break; + } + } + + if (NULL != def->options[i].long_opt) { + opts[l].name = def->options[i].long_opt; + opts[l].has_arg = def->options[i].has_arg; + opts[l].flag = NULL; + opts[l].val = def->options[i].short_opt; + ++l; + } + } + + for (go_on = true; + go_on + && -1 != (opt = getopt_long (argc, argv, optstring, opts, NULL));) + go_on = def->process_option (def, opt, optarg, argc, argv); + + if (go_on && optind < argc && NULL != def->process_non_options) + go_on = def->process_non_options (def, optind, argc, argv); + + free (optstring); + } + + free (opts); + } + + return go_on; +} + diff --git a/code/validation/C/0059196_autorefresh.c b/code/validation/C/0059196_autorefresh.c new file mode 100644 index 0000000000000000000000000000000000000000..defe27b28365aa277d259ef10cbcaa7ed4e402c4 --- /dev/null +++ b/code/validation/C/0059196_autorefresh.c @@ -0,0 +1,152 @@ +/* Copyright 1995 by Abacus Research and + * Development, Inc. All rights reserved. + */ + +#if !defined (OMIT_RCSID_STRINGS) +char ROMlib_rcsid_autorefresh[] = + "$Id: autorefresh.c 63 2004-12-24 18:19:43Z ctm $"; +#endif + +#include "rsys/common.h" +#include "rsys/autorefresh.h" +#include "rsys/vdriver.h" +#include "rsys/refresh.h" +#include "rsys/flags.h" +#include "rsys/prefs.h" + + +/* This file provides a mechanism to detect when applications are + * bypassing QuickDraw and writing directly to screen memory. + * It works by partitioning the screen into NUM_AUTOREFRESH_STRIPS + * horizontal strips of equal size. Each strip is periodically + * checksummed and compared against the last checksum. If the + * checksum value changes, and QuickDraw didn't change that area + * of the screen, we know we need to turn on "refresh" mode. + */ + + +static boolean_t executor_changed_screen_p[NUM_AUTOREFRESH_STRIPS]; + + +/* Check auto refresh? */ +boolean_t do_autorefresh_p; + + +/* Returns a value that will tend to change when the screen contents change + * for the specified horizontal strip on the screen. + */ +static uint32 +checksum_strip (int which_strip) +{ + int n, row_size, strip_rows, next_row_delta; + const uint32 *base; + uint32 sum; + + strip_rows = vdriver_height / NUM_AUTOREFRESH_STRIPS; + base = (const uint32 *) (vdriver_fbuf + + which_strip * strip_rows * vdriver_row_bytes); + row_size = vdriver_row_bytes / (4U * sizeof (uint32)); + next_row_delta = (vdriver_row_bytes * 2 / sizeof (uint32)) - (row_size * 4U); + + /* Sum (most of) the longs on every other row in this strip. */ + for (sum = 0, n = strip_rows; n > 0; n -= 2) + { + int r; + + for (r = row_size; r > 0; r--) + { +#if defined (i386) + uint32 t1, t2; + + /* Hand-scheduled for the Pentium. gcc does a terrible job. */ + asm ("movl (%3),%1\n\t" + "movl 4(%3),%2\n\t" + "addl %1,%0\n\t" + "movl 8(%3),%1\n\t" + "addl %2,%0\n\t" + "movl 12(%3),%2\n\t" + "addl %1,%0\n\t" + "addl $16,%3\n\t" + "addl %2,%0" + : "=r" (sum), "=r" (t1), "=r" (t2), "=r" (base) + : "0" (sum), "3" (base) + : "cc"); +#else + sum += base[0] + base[1] + base[2] + base[3]; + base += 4; +#endif + } + + base += next_row_delta; + } + + return sum; +} + + +/* Call this when part of the screen has been changed by Executor, + * so we don't mistakenly think we need refresh mode. + */ +void +note_executor_changed_screen (int top, int bottom) +{ + int i, first, last, strip_rows; + + strip_rows = vdriver_height / NUM_AUTOREFRESH_STRIPS; + first = top / strip_rows; + last = (bottom - 1) / strip_rows; + + if (first >= (int) NUM_AUTOREFRESH_STRIPS || last < 0) + return; + + if (first < 0) + first = 0; + if (last > (int) NUM_AUTOREFRESH_STRIPS - 1) + last = NUM_AUTOREFRESH_STRIPS - 1; + + for (i = first; i <= last; i++) + executor_changed_screen_p[i] = TRUE; +} + + +/* Returns TRUE if refresh should be turned on. */ +boolean_t +autodetect_refresh (void) +{ + static uint32 last_checksum[NUM_AUTOREFRESH_STRIPS]; + static boolean_t last_checksum_valid_p[NUM_AUTOREFRESH_STRIPS]; + boolean_t need_refresh_p; + int i; + + /* We don't need to autodetect refresh if we're already doing refresh + * or if we have direct screen access. + */ + if (ROMlib_refresh != 0 || !ROMlib_shadow_screen_p) + { + memset (last_checksum_valid_p, 0, sizeof last_checksum_valid_p); + return FALSE; + } + + need_refresh_p = FALSE; /* default value */ + + /* Compute checksums for the screen. */ + for (i = NUM_AUTOREFRESH_STRIPS - 1; i >= 0; i--) + { + if (executor_changed_screen_p[i]) + { + executor_changed_screen_p[i] = FALSE; /* reset it */ + last_checksum_valid_p[i] = FALSE; + } + else + { + uint32 c; + c = checksum_strip (i); + if (last_checksum_valid_p[i] && c != last_checksum[i]) + need_refresh_p = TRUE; + last_checksum[i] = c; + last_checksum_valid_p[i] = TRUE; + } + } + + return need_refresh_p; +} diff --git a/code/validation/C/0061649_slarrr.c b/code/validation/C/0061649_slarrr.c new file mode 100644 index 0000000000000000000000000000000000000000..4db671de136fbff06f9d5e3acd99ddca1f6a3513 --- /dev/null +++ b/code/validation/C/0061649_slarrr.c @@ -0,0 +1,162 @@ +#include "clapack.h" + +/* Subroutine */ int slarrr_(integer *n, real *d__, real *e, integer *info) +{ + /* System generated locals */ + integer i__1; + real r__1; + + /* Builtin functions */ + double sqrt(doublereal); + + /* Local variables */ + integer i__; + real eps, tmp, tmp2, rmin, offdig; + extern doublereal slamch_(char *); + real safmin; + logical yesrel; + real smlnum, offdig2; + + +/* -- LAPACK auxiliary routine (version 3.1) -- */ +/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ +/* November 2006 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + + +/* Purpose */ +/* ======= */ + +/* Perform tests to decide whether the symmetric tridiagonal matrix T */ +/* warrants expensive computations which guarantee high relative accuracy */ +/* in the eigenvalues. */ + +/* Arguments */ +/* ========= */ + +/* N (input) INTEGER */ +/* The order of the matrix. N > 0. */ + +/* D (input) REAL array, dimension (N) */ +/* The N diagonal elements of the tridiagonal matrix T. */ + +/* E (input/output) REAL array, dimension (N) */ +/* On entry, the first (N-1) entries contain the subdiagonal */ +/* elements of the tridiagonal matrix T; E(N) is set to ZERO. */ + +/* INFO (output) INTEGER */ +/* INFO = 0(default) : the matrix warrants computations preserving */ +/* relative accuracy. */ +/* INFO = 1 : the matrix warrants computations guaranteeing */ +/* only absolute accuracy. */ + +/* Further Details */ +/* =============== */ + +/* Based on contributions by */ +/* Beresford Parlett, University of California, Berkeley, USA */ +/* Jim Demmel, University of California, Berkeley, USA */ +/* Inderjit Dhillon, University of Texas, Austin, USA */ +/* Osni Marques, LBNL/NERSC, USA */ +/* Christof Voemel, University of California, Berkeley, USA */ + +/* ===================================================================== */ + +/* .. Parameters .. */ +/* .. */ +/* .. Local Scalars .. */ +/* .. */ +/* .. External Functions .. */ +/* .. */ +/* .. Intrinsic Functions .. */ +/* .. */ +/* .. Executable Statements .. */ + +/* As a default, do NOT go for relative-accuracy preserving computations. */ + /* Parameter adjustments */ + --e; + --d__; + + /* Function Body */ + *info = 1; + safmin = slamch_("Safe minimum"); + eps = slamch_("Precision"); + smlnum = safmin / eps; + rmin = sqrt(smlnum); +/* Tests for relative accuracy */ + +/* Test for scaled diagonal dominance */ +/* Scale the diagonal entries to one and check whether the sum of the */ +/* off-diagonals is less than one */ + +/* The sdd relative error bounds have a 1/(1- 2*x) factor in them, */ +/* x = max(OFFDIG + OFFDIG2), so when x is close to 1/2, no relative */ +/* accuracy is promised. In the notation of the code fragment below, */ +/* 1/(1 - (OFFDIG + OFFDIG2)) is the condition number. */ +/* We don't think it is worth going into "sdd mode" unless the relative */ +/* condition number is reasonable, not 1/macheps. */ +/* The threshold should be compatible with other thresholds used in the */ +/* code. We set OFFDIG + OFFDIG2 <= .999 =: RELCOND, it corresponds */ +/* to losing at most 3 decimal digits: 1 / (1 - (OFFDIG + OFFDIG2)) <= 1000 */ +/* instead of the current OFFDIG + OFFDIG2 < 1 */ + + yesrel = TRUE_; + offdig = 0.f; + tmp = sqrt((dabs(d__[1]))); + if (tmp < rmin) { + yesrel = FALSE_; + } + if (! yesrel) { + goto L11; + } + i__1 = *n; + for (i__ = 2; i__ <= i__1; ++i__) { + tmp2 = sqrt((r__1 = d__[i__], dabs(r__1))); + if (tmp2 < rmin) { + yesrel = FALSE_; + } + if (! yesrel) { + goto L11; + } + offdig2 = (r__1 = e[i__ - 1], dabs(r__1)) / (tmp * tmp2); + if (offdig + offdig2 >= .999f) { + yesrel = FALSE_; + } + if (! yesrel) { + goto L11; + } + tmp = tmp2; + offdig = offdig2; +/* L10: */ + } +L11: + if (yesrel) { + *info = 0; + return 0; + } else { + } + + +/* *** MORE TO BE IMPLEMENTED *** */ + + +/* Test if the lower bidiagonal matrix L from T = L D L^T */ +/* (zero shift facto) is well conditioned */ + + +/* Test if the upper bidiagonal matrix U from T = U D U^T */ +/* (zero shift facto) is well conditioned. */ +/* In this case, the matrix needs to be flipped and, at the end */ +/* of the eigenvector computation, the flip needs to be applied */ +/* to the computed eigenvectors (and the support) */ + + + return 0; + +/* END OF SLARRR */ + +} /* slarrr_ */ diff --git a/code/validation/C/0061708_exception.c b/code/validation/C/0061708_exception.c new file mode 100644 index 0000000000000000000000000000000000000000..b872a55a8ac6377618b9323b4e8a2d6cf94e7332 --- /dev/null +++ b/code/validation/C/0061708_exception.c @@ -0,0 +1,210 @@ +/* + * This file is part of the libpayload project. + * + * Copyright 2013 Google Inc. + * + * 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. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +uint8_t exception_stack[0x200] __attribute__((aligned(16))); + +static const char *exception_names[NUM_EXC_VIDS] = { + [EXC_VID_CUR_SP_EL0_SYNC] = "_sync_sp_el0", + [EXC_VID_CUR_SP_EL0_IRQ] = "_irq_sp_el0", + [EXC_VID_CUR_SP_EL0_FIRQ] = "_fiq_sp_el0", + [EXC_VID_CUR_SP_EL0_SERR] = "_serror_sp_el0", + [EXC_VID_CUR_SP_ELX_SYNC] = "_sync_sp_el3", + [EXC_VID_CUR_SP_ELX_IRQ] = "_irq_sp_el3", + [EXC_VID_CUR_SP_ELX_FIQ] = "_fiq_sp_el3", + [EXC_VID_CUR_SP_ELX_SERR] = "_serror_sp_el3", + [EXC_VID_LOW64_SYNC] = "_sync_elx_64", + [EXC_VID_LOW64_IRQ] = "_irq_elx_64", + [EXC_VID_LOW64_FIQ] = "_fiq_elx_64", + [EXC_VID_LOW64_SERR] = "_serror_elx_64", + [EXC_VID_LOW32_SYNC] = "_sync_elx_32", + [EXC_VID_LOW32_IRQ] = "_irq_elx_32", + [EXC_VID_LOW32_FIQ] = "_fiq_elx_32", + [EXC_VID_LOW32_SERR] = "_serror_elx_32" +}; + +static void print_regs(struct exc_state *exc_state) +{ + int i; + struct elx_state *elx = &exc_state->elx; + struct regs *regs = &exc_state->regs; + + uint64_t elx_esr = raw_read_esr_current(); + uint64_t elx_far = raw_read_far_current(); + + printk(BIOS_DEBUG, "ELR = 0x%016llx\n", elx->elr); + printk(BIOS_DEBUG, "ESR = 0x%016llx\n", elx_esr); + printk(BIOS_DEBUG, "SPSR = 0x%08llx\n", elx->spsr); + printk(BIOS_DEBUG, "FAR = 0x%016llx\n", elx_far); + printk(BIOS_DEBUG, "SP = 0x%016llx\n", regs->sp); + for (i = X0_INDEX; i < XMAX_INDEX; i++) + printk(BIOS_DEBUG, "X%02d = 0x%016llx\n", i, regs->x[i]); +} + + +static struct exception_handler *handlers[NUM_EXC_VIDS]; + + +int exception_handler_register(uint64_t vid, struct exception_handler *h) +{ + if (vid >= NUM_EXC_VIDS) + return -1; + + /* Just place at head of queue. */ + h->next = handlers[vid]; + store_release(&handlers[vid], h); + + return 0; +} + +int exception_handler_unregister(uint64_t vid, struct exception_handler *h) +{ + struct exception_handler *cur; + struct exception_handler **prev; + + if (vid >= NUM_EXC_VIDS) + return -1; + + prev = &handlers[vid]; + + for (cur = handlers[vid]; cur != NULL; cur = cur->next) { + if (cur != h) + continue; + /* Update previous pointer. */ + store_release(prev, cur->next); + return 0; + } + + /* Not found */ + return -1; +} + +static void print_exception_info(struct exc_state *state, uint64_t idx) +{ + if (idx < NUM_EXC_VIDS) + printk(BIOS_DEBUG, "exception %s\n", exception_names[idx]); + + print_regs(state); +} + +static void print_exception_and_die(struct exc_state *state, uint64_t idx) +{ + print_exception_info(state, idx); + die("exception death"); +} + + +static int handle_exception(struct exc_state *state, uint64_t idx) +{ + int ret = EXC_RET_ABORT; + + struct exception_handler *h; + + for (h = handlers[idx]; h != NULL; h = h->next) { + int hret; + + hret = h->handler(state, idx); + + if (hret > ret) + ret = hret; + } + + return ret; +} + +void exc_dispatch(struct exc_state *state, uint64_t idx) +{ + int ret; + + if (idx >= NUM_EXC_VIDS) { + printk(BIOS_DEBUG, "Bad exception index %x.\n", (int)idx); + print_exception_and_die(state, idx); + } + + ret = handle_exception(state, idx); + + if (ret == EXC_RET_ABORT) + print_exception_and_die(state, idx); + + if (ret == EXC_RET_IGNORED || ret == EXC_RET_HANDLED_DUMP_STATE) + print_exception_info(state, idx); + + exc_exit(&state->regs); +} + +static int test_exception_handler(struct exc_state *state, uint64_t vector_id) +{ + /* Update instruction pointer to next instrution. */ + state->elx.elr += sizeof(uint32_t); + raw_write_elr_current(state->elx.elr); + return EXC_RET_HANDLED; +} + +static uint64_t test_exception(void) +{ + struct exception_handler sync_elx; + struct exception_handler sync_el0; + unsigned long long *a = (void *)0xffffffff00000000ULL; + + sync_elx.handler = &test_exception_handler; + sync_el0.handler = &test_exception_handler; + + exception_handler_register(EXC_VID_CUR_SP_ELX_SYNC, &sync_elx); + exception_handler_register(EXC_VID_CUR_SP_EL0_SYNC, &sync_el0); + + force_read(*a); + + exception_handler_unregister(EXC_VID_CUR_SP_ELX_SYNC, &sync_elx); + exception_handler_unregister(EXC_VID_CUR_SP_EL0_SYNC, &sync_el0); + + return 0; +} + +void exception_init(void) +{ + /* Load the exception table and initialize SP_EL3. */ + exception_init_asm(exception_stack + ARRAY_SIZE(exception_stack)); + + printk(BIOS_DEBUG, "ARM64: Exception handlers installed.\n"); + + /* Only spend time testing on debug builds that are trying to detect more errors. */ + if (IS_ENABLED(CONFIG_FATAL_ASSERTS)) { + printk(BIOS_DEBUG, "ARM64: Testing exception\n"); + test_exception(); + printk(BIOS_DEBUG, "ARM64: Done test exception\n"); + } +} diff --git a/code/validation/C/0063794_cbuffer.c b/code/validation/C/0063794_cbuffer.c new file mode 100644 index 0000000000000000000000000000000000000000..082b0ddcd96949301b2731b425b2723b21d6b98e --- /dev/null +++ b/code/validation/C/0063794_cbuffer.c @@ -0,0 +1,231 @@ +/* Copyright (C) 2007-2008 The Android Open Source Project +** +** This software is licensed under the terms of the GNU General Public +** License version 2, as published by the Free Software Foundation, and +** may be copied, distributed, and modified under those terms. +** +** This program is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +*/ +#include "cbuffer.h" +#include "android_utils.h" +#include +#include +#include +#include + +#define DEBUG 0 + +#if DEBUG +# define ASSERT(cond,fmt,...) ({ if (!(cond)) { fprintf(stderr, fmt, __VA_ARGS__); assert(cond); } }) +#else +# define ASSERT(cond,fmt,...) ((void)0) +#endif + +#if DEBUG +void +cbuffer_assert( CBuffer* cb, const char* file, long lineno ) +{ + const char* reason = NULL; + + if (cb->rpos < 0 || cb->rpos >= cb->size) { + reason = "rpos is out of bounds"; + } + else if (cb->count < 0 || cb->count > cb->size) { + reason = "count is incorrect"; + } + if (!reason) + return; + + fprintf(stderr, "assert:%s:%ld: assertion failed: %s (pos=%d count=%d size=%d)\n", + file, lineno, reason, cb->rpos, cb->count, cb->size); + assert(0); +} +# define CBUFFER_ASSERT(cb) cbuffer_assert(cb,__FUNCTION__,__LINE__) +#else +# define CBUFFER_ASSERT(cb) ((void)0) +#endif + +int +cbuffer_write_peek( CBuffer* cb, uint8_t* *pbase ) +{ + int wpos = cb->rpos + cb->count; + int avail = cb->size - cb->count; + + CBUFFER_ASSERT(cb); + + if (wpos >= cb->size) + wpos -= cb->size; + + if (wpos + avail > cb->size) + avail = cb->size - wpos; + + *pbase = cb->buff + wpos; + return avail; +} + +void +cbuffer_write_step( CBuffer* cb, int len ) +{ + CBUFFER_ASSERT(cb); + + cb->count += len; + if (cb->count > cb->size) + cb->count = cb->size; +} + + +int +cbuffer_write( CBuffer* cb, const void* from, int len ) +{ + int len2 = len; + + CBUFFER_ASSERT(cb); + + while (len2 > 0) { + int avail = cb->size - cb->count; + int wpos = cb->rpos + cb->count; + + ASSERT(avail >= 0, "avail is negative: %d", avail); + + if (avail == 0) + break; + + if (wpos >= cb->size) + wpos -= cb->size; + + ASSERT( wpos >= 0 && wpos < cb->size, "wpos is out-of-bounds: %d (rpos=%d)", wpos, cb->rpos); + + if (wpos + avail > cb->size) + avail = cb->size - wpos; + + if (avail > len2) + avail = len2; + + memcpy( cb->buff + wpos, (const char*)from, avail ); + + from = (char*)from + avail; + len2 -= avail; + cb->count += avail; + } + return len - len2; +} + +int +cbuffer_read( CBuffer* cb, void* to, int len ) +{ + int len2 = len; + + CBUFFER_ASSERT(cb); + + while (len2 > 0) { + int avail = cb->count; + int rpos = cb->rpos; + + ASSERT(avail >= 0, "avail is negative: %d", avail); + + if (avail == 0) + break; + + ASSERT((rpos >= 0 && rpos < cb->size), "rpos is out-of-bounds: %d", rpos); + + if (rpos+avail > cb->size) + avail = cb->size - rpos; + + if (avail > len2) + avail = len2; + + memcpy( (char*)to, (const char*)cb->buff + rpos, avail ); + to = (char*)to + avail; + len2 -= avail; + cb->count -= avail; + cb->rpos += avail; + if (cb->rpos >= cb->size) + cb->rpos -= cb->size; + } + return len - len2; +} + +int +cbuffer_read_peek( CBuffer* cb, uint8_t* *pbase ) +{ + int rpos = cb->rpos; + int avail = cb->count; + + CBUFFER_ASSERT(cb); + + if (rpos + avail > cb->size) + avail = cb->size - rpos; + + *pbase = cb->buff + rpos; + return avail; +} + + +void +cbuffer_read_step( CBuffer* cb, int len ) +{ + CBUFFER_ASSERT(cb); + + if (len > cb->count) + len = cb->count; + + cb->rpos += len; + if (cb->rpos >= cb->size) + cb->rpos -= cb->size; + + cb->count -= len; +} + +const char* +cbuffer_quote( CBuffer* cb ) +{ + STRALLOC_DEFINE(s); + char* q; + + stralloc_format( s, "cbuffer %p (pos=%d count=%d size=%d)", + cb, cb->rpos, cb->count, cb->size ); + + q = tempstr_from_stralloc( s ); + stralloc_reset(s); + + return q; +} + +const char* +cbuffer_quote_data( CBuffer* cb ) +{ + STRALLOC_DEFINE(s); + int len = cb->count; + int rpos = cb->rpos; + char* result; + + while (len > 0) { + int avail = len; + + if (rpos >= cb->size) + rpos -= cb->size; + + if (rpos + avail > cb->size) + avail = cb->size - rpos; + + stralloc_add_quote_bytes( s, cb->buff + rpos, avail ); + rpos += avail; + len -= avail; + } + + result = tempstr_from_stralloc(s); + stralloc_reset(s); + + return result; +} + +void +cbuffer_print( CBuffer* cb ) +{ + /* print the content of a cbuffer */ + printf( "%s: %s", cbuffer_quote(cb), cbuffer_quote_data(cb) ); +} + diff --git a/code/validation/C/0065569_Org.c b/code/validation/C/0065569_Org.c new file mode 100644 index 0000000000000000000000000000000000000000..e2fc2f38efaf9fe5b214d9b8381821b01bf804ce --- /dev/null +++ b/code/validation/C/0065569_Org.c @@ -0,0 +1,163 @@ +//Alan Macedo Esparza A0136288 +//Karen Bolaños A0134733 + +#include +#include +#include + +#define CACHESIZE 16 + +struct cache{ + unsigned int address; + char state; +}; +struct cacheFA{ //Cache with time attribute for FA + unsigned int address; + unsigned int time; + char state; +}; + +unsigned int events = 0; + +//declare caches +struct cache myCache[CACHESIZE]; +struct cacheFA myCacheFA[CACHESIZE]; + +enum values {VALID, INVALID, EMPTY }; + +/**********************************************************************/ +/* */ +/* Name: GetAddr */ +/* */ +/* Description: This function will read the input file and returns an */ +/* hexadecimal number. It will skip over comments, which */ +/* begin the line with a # */ +/* */ +/* Inputs: The name of the input file */ +/* */ +/* Outputs: The address that will be presented to the cache */ +/* */ +/**********************************************************************/ +unsigned int GetAddr (FILE *fp) +{ + char c; /* Character read */ + unsigned int address; + + do { + c = getc (fp); /* Get next character */ + if ( c == '#' ) /* Skip the comment */ + do { + c = getc (fp); + } while ( c != '\n'); + } while (!isxdigit(c) && !feof(fp)); + + ungetc(c, fp); /* Return the character to the file */ + fscanf(fp, "%x\n",&address); + + return (address); +} + +/**********************************************************************/ +/* */ +/* Name: CacheAccess */ +/* */ +/* Description: This function will simulate a direct mapped cache */ +/* */ +/* Inputs: An address in hexadecimal format */ +/* */ +/* Outputs: The hit rate (p) */ +/* */ +/**********************************************************************/ +int CacheAccess (unsigned int address){ + + static unsigned int hit = 0; + int end = address & 0x000f; //get last 4 bits of address + + if(myCache[end].state==VALID && myCache[end].address == address) + { + hit++; //Address found correctly, no further action necessary + }else{ + myCache[end].state=VALID;//Set state to valid (checking not really necessary) + myCache[end].address=address; //set cache address to searched address + } + + + return hit; +} +/**********************************************************************/ +/* */ +/* Name: CacheAccessFA */ +/* */ +/* Description: This function will simulate a fully associative cache */ +/* */ +/* Inputs: An address in hexadecimal format */ +/* */ +/* Outputs: The hit rate (p) */ +/* */ +/**********************************************************************/ +int CacheAccessFA (unsigned int address){ + + static unsigned int hit = 0; + unsigned int minTime=99999; //Set min time to very high number + bool found=false;//found flag set to false + unsigned int minAddress; + + for(int i = 0;i < CACHESIZE;i++) + { + + if (myCacheFA[i].state==VALID && myCacheFA[i].address == address) //find hit + { + hit++; + found = true; //change found flag + myCacheFA[i].time= events+1; //events plus 1, as is end of last event. + break; + } + } + + if (!found) //hit not found + { + for(int i = 0;i < CACHESIZE;i++){ + if (myCacheFA[i].time +#include +#include +#include + +/*************************************************************************************************** + *************************************************************************************************** + ************ Funciones para manejar la lista de saltos conocidos ********************************** + *************************************************************************************************** + **************************************************************************************************/ + +/* + * Función listaSaltos_crear. + * Inicializa la estructura saltos_list_t. +*/ +void listaSaltos_crear(saltos_list_t * lista) +{ + if (lista == NULL) + { + printf("listaSaltos_crear error! Puntero nulo!\n"); + exit(EXIT_FAILURE); + } + + lista->primero = NULL; + lista->ultimo = NULL; +} + + +/* + * Función listaSaltos_insertar. + * Inserta una etiqueta de salto y la dirección en la que se encuentra + * dicha etiqueta en la lista de saltos. +*/ +void listaSaltos_insertar(saltos_list_t * lista, char * etiquetaSalto, uint32_t direccionSalto) +{ + saltos_t * temp = (saltos_t*) malloc(sizeof(saltos_t)); + + if (temp == NULL) + { + printf("listaSaltos_insertar() error! No se pudo reservar memoria!\n"); + exit(EXIT_FAILURE); + } + else + { + temp->siguiente = NULL; + temp->direccionSalto = direccionSalto; + temp->etiquetaSalto = (char *) malloc(strlen(etiquetaSalto) + 1); + if (temp->etiquetaSalto == NULL) + { + printf("listaSaltos_insertar() error! No se pudo reservar memoria!\n"); + exit(EXIT_FAILURE); + } + else + { + strcpy(temp->etiquetaSalto, etiquetaSalto); + temp->etiquetaSalto[strlen(etiquetaSalto) - 1] = '\0'; + if (lista->primero == NULL) + { + lista->primero = temp; + lista->ultimo = temp; + } + else + { + lista->ultimo->siguiente = temp; + lista->ultimo = temp; + } + } + } +} + + +/* + * Función listaSaltos_vaciar. + * Vacía y libera la memoria dinámica reservada de la + * lista de saltos. +*/ +void listaSaltos_vaciar(saltos_list_t * lista) +{ + saltos_t * l = lista->primero; + saltos_t * temp = NULL; + + while (l != NULL) + { + temp = l; + l = l->siguiente; + + if (temp->etiquetaSalto != NULL) + free(temp->etiquetaSalto); + + free(temp); + } +} + +#ifdef DEBUG +/* + * Función listaSaltos_mostrar. + * Muestra todas las etiquetas de saltos con sus direcciones de salto + * que haya almacenadas en la lista. +*/ +void listaSaltos_mostrar(saltos_list_t * lista) +{ + saltos_t * l = lista->primero; + saltos_t * temp = NULL; + + while (l != NULL) + { + temp = l; + l = l->siguiente; + + if (temp->etiquetaSalto != NULL) + printf("Salto \"%s\" en %.8x\n", temp->etiquetaSalto, temp->direccionSalto); + } +} +#endif + + + +/* + * Función listaSaltos_buscar. + * Buscar en la lista una etiqueta de salto, si tiene éxito, + * guarda la dirección de salto en el puntero direccion y devuelve 1. + * En caso contrario devuelve 0. +*/ +int listaSaltos_buscar(saltos_list_t * lista, char * etiqueta, uint32_t * direccion) +{ + saltos_t * l = lista->primero; + saltos_t * temp = NULL; + + while (l != NULL) + { + temp = l; + l = l->siguiente; + + if (strcmp(temp->etiquetaSalto, etiqueta) == 0) + { + *direccion = temp->direccionSalto; + return 1; + } + } + + return 0; +} + + + +/*************************************************************************************************** + *************************************************************************************************** + ************ Funciones para manejar la lista de instrucciones con saltos desconocidos ************* + *************************************************************************************************** + **************************************************************************************************/ + + +/* + * Función listaISaltos_crear. + * Inicializa la estructura i_saltos_list_t. +*/ +void listaISaltos_crear(i_saltos_list_t * lista) +{ + if (lista == NULL) + { + printf("listaSaltos_crear error! Puntero nulo!\n"); + exit(EXIT_FAILURE); + } + + lista->primero = NULL; + lista->ultimo = NULL; +} + + +/* + * Función listaISaltos_insertar. + * Inserta una etiqueta de salto y la dirección en la que se encuentra + * dicha etiqueta en la lista de saltos. +*/ +void listaISaltos_insertar(i_saltos_list_t * lista, char * etiquetaSalto, uint32_t posicionInstruccion) +{ + i_saltos_t * temp = (i_saltos_t*) malloc(sizeof(i_saltos_t)); + + if (temp == NULL) + { + printf("listaSaltos_insertar() error! No se pudo reservar memoria!\n"); + exit(EXIT_FAILURE); + } + else + { + temp->siguiente = NULL; + temp->posicionInstruccion = posicionInstruccion; + temp->etiquetaSalto = (char *) malloc(strlen(etiquetaSalto) + 1); + if (temp->etiquetaSalto == NULL) + { + printf("listaSaltos_insertar() error! No se pudo reservar memoria!\n"); + exit(EXIT_FAILURE); + } + else + { + strcpy(temp->etiquetaSalto, etiquetaSalto); + //temp->etiquetaSalto[strlen(etiquetaSalto)] = '\0'; + if (lista->primero == NULL) + { + lista->primero = temp; + lista->ultimo = temp; + } + else + { + lista->ultimo->siguiente = temp; + lista->ultimo = temp; + } + } + } +} + + + +/* + * Función listaISaltos_vaciar. + * Vacía y libera la memoria dinámica reservada de la + * lista de saltos. +*/ +void listaISaltos_vaciar(i_saltos_list_t * lista) +{ + i_saltos_t * l = lista->primero; + i_saltos_t * temp = NULL; + + while (l != NULL) + { + temp = l; + l = l->siguiente; + + if (temp->etiquetaSalto != NULL) + free(temp->etiquetaSalto); + + free(temp); + } +} + +#ifdef DEBUG +/* + * Función listaSaltos_mostrar. + * Muestra todas las etiquetas de saltos con sus direcciones de salto + * que haya almacenadas en la lista. +*/ +void listaISaltos_mostrar(i_saltos_list_t * lista) +{ + i_saltos_t * l = lista->primero; + i_saltos_t * temp = NULL; + + while (l != NULL) + { + temp = l; + l = l->siguiente; + + if (temp->etiquetaSalto != NULL) + printf("Modificar salto \"%s\" en %.8x\n", temp->etiquetaSalto, temp->posicionInstruccion * 4); + } +} +#endif \ No newline at end of file diff --git a/code/validation/C/0068847_10801.c b/code/validation/C/0068847_10801.c new file mode 100644 index 0000000000000000000000000000000000000000..aaf6b8577a5a34af3e4cb22120261098479ec8fb --- /dev/null +++ b/code/validation/C/0068847_10801.c @@ -0,0 +1,35 @@ +#include +int main(void) +{ + int blanks,tabs,newlines; + int c; + int done=0; + int lastchar='\n'; + + blanks=0; + tabs=0; + newlines=0; + + while(done==0) + { + c=getchar(); + + if(c==' ') + ++blanks; + if(c=='\t') + ++tabs; + if(c=='\n') + ++newlines; + if(c==EOF) + { + if(lastchar!='\n') + { + ++newlines; + } + done=1; + } + lastchar=c; + } + printf("blanks:%d,tabs:%d,newlines:%d\n",blanks,tabs,newlines); + return 0; +} diff --git a/code/validation/C/0072377_fwmpegts.c b/code/validation/C/0072377_fwmpegts.c new file mode 100644 index 0000000000000000000000000000000000000000..d2abc939ee7320e0430711beb2257d3d866677e9 --- /dev/null +++ b/code/validation/C/0072377_fwmpegts.c @@ -0,0 +1,266 @@ +/* $NetBSD: fwmpegts.c,v 1.4 2011/01/04 20:45:13 christos Exp $ */ +/* + * Copyright (C) 2005 + * Petr Holub, Hidetoshi Shimokawa. 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * + * This product includes software developed by Hidetoshi Shimokawa. + * + * 4. Neither the name of the author nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. + * + * $FreeBSD: src/usr.sbin/fwcontrol/fwmpegts.c,v 1.3 2009/02/02 21:05:12 sbruno Exp $ + */ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "fwmethods.h" + +#define DEBUG 0 + +/***************************************************************************** + +MPEG-2 Transport Stream (MPEG TS) packet format according to IEC 61883: + +31 15 0 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -------- +| len |tag| channel | tcode | sy | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1394 +| header_CRC | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -------- +|0|0| sid | dbs |fn | qpc |S|RSV| dbc | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ CIP +|1|0| fmt | fdf | fdf/syt | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -------- +| reserved | cycle_count | cycle_offset | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| | N x +. . MPEG +. MPEG TS payload 188 bytes . +. . +| | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -------- +| data_CRC | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +N.b. that CRCs are removed by firewire layer! + +The following fiels are fixed for IEEE-1394: +tag = 01b +tcode = 1010b +The length is payload length, i.e. includes CIP header and data size. + +The following fields are constant for MPEG TS: +sph = 1 (denoted as S in CIP header above) +dbs = 6 +fmt = (1<<5) +fdf = reserved +In the supported streams we also require +qpc = 0 +fn = 3 +and thus the payload is divided in 8 blocks as follows: + + +-----+-----+-----+-----+-----+-----+-----+-----+ + | db0 | db1 | db2 | db3 | db4 | db5 | db6 | db7 | + +-----+-----+-----+-----+-----+-----+-----+-----+ + +We have several cases of payload distribution based on stream +bandwidth (R): +1) R < 1.5 Mbps: any of db0..db7 may be payload, +2) 1.5 < R < 3 Mbps: db0/db1 or db2/db3 or db4/db5 or db6/db7 is payload, +3) 3 < R < 6 Mbps: db0/db1/db2/db3 or db4/db5/db6/db7 is payload, +4) R > 6 Mbps: all db0..db7 contain the payload. +Curently, only case (4) is supported in fwmpegts.c + +Each packet may contain N MPEG TS data blocks with timestamp header, +which are (4+188)B long. Experimentally, the N ranges from 0 through 3. + +*****************************************************************************/ + + +typedef uint8_t mpeg_ts_pld[188]; + +struct mpeg_pldt { +#if BYTE_ORDER == BIG_ENDIAN + uint32_t :7, + c_count:13, + c_offset:12; +#else /* BYTE_ORDER != BIG_ENDIAN */ + uint32_t c_offset:12, + c_count:13, + :7; +#endif /* BYTE_ORDER == BIG_ENDIAN */ + mpeg_ts_pld payload; +}; + + +#define NCHUNK 8 +#define PSIZE 596 +#define NPACKET_R 4096 +#define RBUFSIZE (PSIZE * NPACKET_R) + +void +mpegtsrecv(int d, const char *filename, char ich, int count) +{ + struct ciphdr *ciph; + struct fw_isochreq isoreq; + struct fw_isobufreq bufreq; + struct fw_pkt *pkt; + struct mpeg_pldt *pld; + uint32_t *ptr; + int fd, k, len, m, pkt_size, startwr, tlen; + char *buf; + + startwr = 0; + + if (strcmp(filename, "-") == 0) + fd = STDOUT_FILENO; + else { + fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0660); + if (fd == -1) + err(EX_NOINPUT, "%s: %s", __func__, filename); + } + buf = malloc(RBUFSIZE); + + bufreq.rx.nchunk = NCHUNK; + bufreq.rx.npacket = NPACKET_R; + bufreq.rx.psize = PSIZE; + bufreq.tx.nchunk = 0; + bufreq.tx.npacket = 0; + bufreq.tx.psize = 0; + if (ioctl(d, FW_SSTBUF, &bufreq) < 0) + err(EXIT_FAILURE, "%s: ioctl", __func__); + + isoreq.ch = ich & 0x3f; + isoreq.tag = (ich >> 6) & 3; + + if (ioctl(d, FW_SRSTREAM, &isoreq) < 0) + err(EXIT_FAILURE, "%s: ioctl", __func__); + + k = m = 0; + while (count <= 0 || k <= count) { + len = tlen = read(d, buf, RBUFSIZE); +#if DEBUG + fprintf(stderr, "Read %d bytes.\n", len); +#endif /* DEBUG */ + if (len < 0) { + if (errno == EAGAIN) { + fprintf(stderr, "(EAGAIN) - push 'Play'?\n"); + continue; + } + err(EXIT_FAILURE, "read failed"); + } + ptr = (uint32_t *) buf; + + do { + pkt = (struct fw_pkt *) ptr; +#if DEBUG + fprintf(stderr, "\nReading new packet.\n"); + fprintf(stderr, "%08x %08x %08x %08x\n", + htonl(ptr[0]), htonl(ptr[1]), + htonl(ptr[2]), htonl(ptr[3])); +#endif /* DEBUG */ + /* there is no CRC in the 1394 header */ + ciph = (struct ciphdr *)(ptr + 1); /* skip iso header */ + if (ciph->fmt != CIP_FMT_MPEG) + errx(EXIT_FAILURE, + "%s: unknown format 0x%x", __func__, + ciph->fmt); + if (ciph->fn != 3) { + errx(EXIT_FAILURE, + "%s: unsupported MPEG TS stream, " + "fn=%d (only fn=3 is supported)", + __func__, ciph->fn); + } + ptr = (uint32_t *) (ciph + 1); /* skip cip header */ + + if (pkt->mode.stream.len <= sizeof(struct ciphdr)) { + /* no payload */ + /* tlen needs to be decremented before end of the loop */ + goto next; + } +#if DEBUG + else { + fprintf(stderr, + "Packet net payload length (IEEE1394 header): %d\n", + pkt->mode.stream.len - sizeof(struct ciphdr)); + fprintf(stderr, "Data block size (CIP header): %d [q], %d [B]\n", + ciph->len, ciph->len * 4); + fprintf(stderr, + "Data fraction number (CIP header): %d => DBC increments with %d\n", + ciph->fn, (1<fn) ); + fprintf(stderr, "QCP (CIP header): %d\n", ciph->qpc ); + fprintf(stderr, "DBC counter (CIP header): %d\n", ciph->dbc ); + fprintf(stderr, "MPEG payload type size: %d\n", + sizeof(struct mpeg_pldt)); + } +#endif /* DEBUG */ + + /* This is a condition that needs to be satisfied to start + writing the data */ + if (ciph->dbc % (1<fn) == 0) + startwr = 1; + /* Read out all the MPEG TS data blocks from current packet */ + for (pld = (struct mpeg_pldt *)ptr; + (intptr_t)pld < (intptr_t)((char *)ptr + + pkt->mode.stream.len - sizeof(struct ciphdr)); + pld++) { + if (startwr == 1) + write(fd, pld->payload, + sizeof(pld->payload)); + } + +next: + /* CRCs are removed from both header and trailer + so that only 4 bytes of 1394 header remains */ + pkt_size = pkt->mode.stream.len + 4; + ptr = (uint32_t *)((intptr_t)pkt + pkt_size); + tlen -= pkt_size; + } while (tlen > 0); +#if DEBUG + fprintf(stderr, "\nReading a data from firewire.\n"); +#endif /* DEBUG */ + + } + if (fd != STDOUT_FILENO) + close(fd); + fprintf(stderr, "\n"); +} diff --git a/code/validation/C/0077238_simulador.c b/code/validation/C/0077238_simulador.c new file mode 100644 index 0000000000000000000000000000000000000000..da1c8f15f53ac4f0434a4a7e2f61f46d949c2a3c --- /dev/null +++ b/code/validation/C/0077238_simulador.c @@ -0,0 +1,104 @@ +#include +#include +#include +#include "headers/defines.h" +#include "headers/memoria.h" +#include "headers/cpu.h" +#include "headers/banco.h" + +void imprimeRegistradores() +{ + int i; + printf("Registradores \n"); + for (i = 0; i < 31; i += 2) { + printf("R%d = %d R%d = %d\n", i, + BANCO_GetRegister(i), i + 1, BANCO_GetRegister(i + 1)); + } + + printf("\n ------------------------------------------------\n"); +} + +void imprimeMemoria(int mS, int mF) +{ + int i; + printf("Memória \n"); + printf("Endereço - Valor\n"); + for (i = mS; i <= mF; i++) + printf("%d = %d\n", i, MEMORIA_CarregueData(i)); + printf("\n ------------------------------------------------\n"); +} + +int main(int argc, char *argv[]) +{ + char *fileName = "codigo.src"; + int mS; + int mF; + int pM = 0; + int reg = 0; + int steps = 0; + int e = 0; + int x; + for (x = 0; x < argc; x++) { + char *s = argv[x]; + if (strcmp(s, "-h") == 0 || strcmp(s, "--help") == 0) { + printf("\nSimulador arquitetura MIPS verão 0.1\n"); + printf("\nParametros: \n\n"); + printf + (" -s Para definir arquivo onde se encontra o código hexadecimal a ser executado.\n"); + printf + (" -r Imprime o valor dos registradores\n"); + printf + (" -pm Imprime uma faixa de valores da memória de dados.\n"); + printf + (" -e Imprime quantidade de instruções executadas.\n"); + printf(" --steps Imprime ciclo por ciclo."); + printf + ("\n Esse simulador possui poderes de super foca\n\n"); + } else { + if (strcmp(s, "-s") == 0) + fileName = argv[x + 1]; + if (strcmp(s, "-r") == 0) + reg = 1; + if (strcmp(s, "-pm") == 0) { + pM = 1; + mS = atoi(argv[x + 1]); + mF = atoi(argv[x + 2]); + } + if (strcmp(s, "-e") == 0) + e = 1; + if (strcmp(s, "--steps")==0) + steps = 1; + } + + } + + MEMORIA_Inicializacao1(fileName); + CPU_Inicializacao(); + if(steps){ + int i=0; + while(CPU_Ciclo()){ + i++; + printf("\033[2J"); + printf("\nCiclo %d - PC = %d\n",i,BANCO_GetPc()); + if (reg) + imprimeRegistradores(); + if (pM) + imprimeMemoria(mS, mF); + if (e) + imprimirDadosEstatisticos(); + printf("\n Enter para continuar \n"); + getchar(); + } + }else{ + CPU_Execute(); + } + if (reg) + imprimeRegistradores(); + if (pM) + imprimeMemoria(mS, mF); + if (e) + imprimirDadosEstatisticos(); + + return 1; + +} diff --git a/code/validation/C/0084850_ut_utility.c b/code/validation/C/0084850_ut_utility.c new file mode 100644 index 0000000000000000000000000000000000000000..55e95825aef3c6e9690af3480cda525640af0c3d --- /dev/null +++ b/code/validation/C/0084850_ut_utility.c @@ -0,0 +1,32 @@ + +#include "ut_utility.h" + +#include + +void ut_init_ascending_naturals(int * arr, size_t total) +{ + size_t i; + + for (i = 0; i < total; ++i) + { + arr[i] = (int)i + 1; + } +} + +void ut_permutate(int * arr, size_t total, size_t perm_loop_count) +{ + size_t i; + size_t j; + + for (j = 0; j < perm_loop_count; ++j) + { + for (i = 0; i < total; ++i) + { + int k = arr[i]; + int p = rand() % (int)total; + + arr[i] = arr[p]; + arr[p] = k; + } + } +} diff --git a/code/validation/C/0087654_shepard_shape_function.c b/code/validation/C/0087654_shepard_shape_function.c new file mode 100644 index 0000000000000000000000000000000000000000..e5bf65babfa61a3d4c8c54df863c39946f13b78d --- /dev/null +++ b/code/validation/C/0087654_shepard_shape_function.c @@ -0,0 +1,143 @@ +// Copyright (c) 2012-2016, Jeffrey N. Johnson +// All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include "polywog/shepard_shape_function.h" + +typedef struct +{ + int i; + shape_function_kernel_t* W; + point_cloud_t* domain; + stencil_t* neighborhoods; + real_t* smoothing_lengths; + + int N; + point_t* xj; + real_t* hj; +} shepard_t; + +static int shepard_neighborhood_size(void* context, int i) +{ + shepard_t* shepard = context; + return 1 + stencil_size(shepard->neighborhoods, i); +} + +static void shepard_get_neighborhood_points(void* context, int i, point_t* points) +{ + shepard_t* shepard = context; + int pos = 0, j, k = 0; + points[k++] = shepard->domain->points[i]; + while (stencil_next(shepard->neighborhoods, i, &pos, &j, NULL)) + points[k++] = shepard->domain->points[j]; +} + +static void shepard_set_neighborhood(void* context, int i) +{ + shepard_t* shepard = context; + ASSERT(i < shepard->domain->num_points); + + // Extract the points. + shepard->N = stencil_size(shepard->neighborhoods, i); + int pos = 0, j, k = 0; + while (stencil_next(shepard->neighborhoods, i, &pos, &j, NULL)) + { + shepard->xj[k] = shepard->domain->points[j]; + shepard->hj[k] = shepard->smoothing_lengths[j]; + ++k; + } +} + +static void shepard_compute(void* context, + int i, + point_t* x, + real_t* values, + vector_t* gradients) +{ + shepard_t* shepard = context; + int N = shepard->N; + + // Compute the kernels and their gradients at x. + real_t W[N]; + vector_t grad_W[N]; + shape_function_kernel_compute(shepard->W, shepard->xj, shepard->hj, N, x, W, grad_W); + + // Compute the values of the Shepard function. + real_t sum_Wi = 0.0; + for (i = 0; i < N; ++i) + sum_Wi += W[i]; + if (sum_Wi == 0.0) + memset(values, 0, sizeof(real_t) * N); + else + { + for (i = 0; i < N; ++i) + values[i] = W[i] / sum_Wi; + } + + // Compute the gradients if needed. + if (gradients != NULL) + { + if (sum_Wi == 0.0) + memset(gradients, 0, sizeof(vector_t) * N); + else + { + vector_t sum_grad_Wi = {.x = 0.0, .y = 0.0, .z = 0.0}; + for (i = 0; i < N; ++i) + { + sum_grad_Wi.x += grad_W[i].x; + sum_grad_Wi.y += grad_W[i].y; + sum_grad_Wi.z += grad_W[i].z; + } + + // Use the quotient rule! + for (i = 0; i < N; ++i) + { + gradients[i].x = (sum_Wi * grad_W[i].x - sum_grad_Wi.x * W[i]) / (sum_grad_Wi.x * sum_grad_Wi.x); + gradients[i].y = (sum_Wi * grad_W[i].y - sum_grad_Wi.y * W[i]) / (sum_grad_Wi.y * sum_grad_Wi.y); + gradients[i].z = (sum_Wi * grad_W[i].z - sum_grad_Wi.z * W[i]) / (sum_grad_Wi.z * sum_grad_Wi.z); + } + } + } +} + +static void shepard_dtor(void* context) +{ + shepard_t* shepard = context; + polymec_free(shepard->xj); + polymec_free(shepard->hj); + polymec_free(shepard); +} + +shape_function_t* shepard_shape_function_new(shape_function_kernel_t* kernel, + point_cloud_t* domain, + stencil_t* neighborhoods, + real_t* smoothing_lengths) +{ + shepard_t* shepard = polymec_malloc(sizeof(shepard_t)); + shepard->W = kernel; + shepard->domain = domain; + shepard->neighborhoods = neighborhoods; + shepard->smoothing_lengths = smoothing_lengths; + + // Count up the maximum neighborhood size and allocate storage. + int max_neighborhood_size = -1; + for (int i = 0; i < shepard->domain->num_points; ++i) + max_neighborhood_size = MAX(max_neighborhood_size, stencil_size(shepard->neighborhoods, i)); + shepard->xj = polymec_malloc(sizeof(point_t) * max_neighborhood_size); + shepard->hj = polymec_malloc(sizeof(real_t) * max_neighborhood_size); + + // Make sure our ghost points are consistent a representation of ghost points. + stencil_exchange(shepard->neighborhoods, shepard->domain->points, 3, 0, MPI_REAL_T); + stencil_exchange(shepard->neighborhoods, shepard->smoothing_lengths, 1, 0, MPI_REAL_T); + + shape_function_vtable vtable = {.neighborhood_size = shepard_neighborhood_size, + .get_neighborhood_points = shepard_get_neighborhood_points, + .set_neighborhood = shepard_set_neighborhood, + .compute = shepard_compute, + .dtor = shepard_dtor}; + return shape_function_new("Shepard", shepard, vtable); +} + diff --git a/code/validation/C/0090000_jni.c b/code/validation/C/0090000_jni.c new file mode 100644 index 0000000000000000000000000000000000000000..0286c6374c827cdcb15e094a06f729d6d2ea639f --- /dev/null +++ b/code/validation/C/0090000_jni.c @@ -0,0 +1,104 @@ +#include +#include +#include +#include +#include +#include +#include "aes/aes.h" +#include "utils.h" +#include "gif.h" + +jint JNI_OnLoad(JavaVM *vm, void *reserved) { + JNIEnv *env = 0; + srand(time(NULL)); + + if ((*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_4) != JNI_OK) { + return -1; + } + + + gifOnJNILoad(vm, reserved, env); + + return JNI_VERSION_1_4; +} + +void JNI_OnUnload(JavaVM *vm, void *reserved) { + gifOnJNIUnload(vm, reserved); +} + +JNIEXPORT void Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *env, jclass class, + jobject buffer, + jbyteArray key, jbyteArray iv, + jboolean encrypt, int offset, + int length) { + jbyte *what = (*env)->GetDirectBufferAddress(env, buffer) + offset; + unsigned char *keyBuff = (unsigned char *) (*env)->GetByteArrayElements(env, key, NULL); + unsigned char *ivBuff = (unsigned char *) (*env)->GetByteArrayElements(env, iv, NULL); + + AES_KEY akey; + if (!encrypt) { + AES_set_decrypt_key(keyBuff, 32 * 8, &akey); + AES_ige_encrypt(what, what, length, &akey, ivBuff, AES_DECRYPT); + } else { + AES_set_encrypt_key(keyBuff, 32 * 8, &akey); + AES_ige_encrypt(what, what, length, &akey, ivBuff, AES_ENCRYPT); + } + (*env)->ReleaseByteArrayElements(env, key, keyBuff, JNI_ABORT); + (*env)->ReleaseByteArrayElements(env, iv, ivBuff, 0); +} + +uint64_t gcd(uint64_t a, uint64_t b) { + while (a != 0 && b != 0) { + while ((b & 1) == 0) b >>= 1; + while ((a & 1) == 0) a >>= 1; + if (a > b) a -= b; else b -= a; + } + return b == 0 ? a : b; +} + +JNIEXPORT jlong +Java_org_telegram_messenger_Utilities_doPQNative(JNIEnv +* env, +jclass class, jlong +_what) { +uint64_t what = _what; +int it = 0, i, j; +uint64_t g = 0; +for ( +i = 0; +i < 3 || it < 1000; i++){ +int q = ((lrand48() & 15) + 17) % what; +uint64_t x = (long long) lrand48() % (what - 1) + 1, y = x; +int lim = 1 << (i + 18), j; +for( +j = 1; +j= what) c -= +what; +} +a += +a; +if(a >= what) a -= +what; +b >>= 1; +} +x = c; +uint64_t z = x < y ? what + x - y : x - y; +g = gcd(z, what); +if(g != 1) break; +if(!(j & (j - 1))) +y = x; +} +if(g > 1 && g < what) break; +} +return +g; +} diff --git a/code/validation/C/0093445_pk-bitfield.c b/code/validation/C/0093445_pk-bitfield.c new file mode 100644 index 0000000000000000000000000000000000000000..69535ac725ba74537109fb44dca93745bcde831c --- /dev/null +++ b/code/validation/C/0093445_pk-bitfield.c @@ -0,0 +1,326 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- + * + * Copyright (C) 2007-2008 Richard Hughes + * + * Licensed under the GNU Lesser General Public License Version 2.1 + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * SECTION:pk-enum + * @short_description: Functions for converting strings to enum and vice-versa + * + * This file contains functions to convert to and from enumerated types. + */ + +#include "config.h" + +#include +#include +#include + +/** + * pk_bitfield_contain_priority: + * @values: a valid bitfield instance + * @value: the values we are searching for + * + * Finds elements in a list, but with priority going to the preceeding entry + * + * Return value: The return enumerated type, or -1 if none are found + * + * Since: 0.5.2 + **/ +gint +pk_bitfield_contain_priority (PkBitfield values, gint value, ...) +{ + va_list args; + guint i; + gint value_temp; + gint retval = -1; + + /* we must query at least one thing */ + if (pk_bitfield_contain (values, value)) + return value; + + /* process the valist */ + va_start (args, value); + for (i=0;; i++) { + value_temp = va_arg (args, gint); + /* do we have this one? */ + if (pk_bitfield_contain (values, value_temp)) { + retval = value_temp; + break; + } + /* end of the list */ + if (value_temp == -1) + break; + } + va_end (args); + + return retval; +} + +/** + * pk_bitfield_from_enums: + * @value: the values we want to add to the bitfield + * + * Return value: The return bitfield, or 0 if invalid + * + * Since: 0.5.2 + **/ +PkBitfield +pk_bitfield_from_enums (gint value, ...) +{ + va_list args; + guint i; + gint value_temp; + PkBitfield values; + + /* we must query at least one thing */ + values = pk_bitfield_value (value); + + /* process the valist */ + va_start (args, value); + for (i=0;; i++) { + value_temp = va_arg (args, gint); + if (value_temp == -1) + break; + values += pk_bitfield_value (value_temp); + } + va_end (args); + + return values; +} + +/** + * pk_role_bitfield_to_string: + * @roles: The enumerated type values + * + * Converts a enumerated type bitfield to its text representation + * + * Return value: the enumerated constant value, e.g. "install-file;update-system" + * + * Since: 0.5.2 + **/ +gchar * +pk_role_bitfield_to_string (PkBitfield roles) +{ + GString *string; + guint i; + + string = g_string_new (""); + for (i=0; ilen == 0) { + g_warning ("not valid!"); + g_string_append (string, pk_role_enum_to_string (PK_ROLE_ENUM_UNKNOWN)); + } else { + /* remove last \n */ + g_string_set_size (string, string->len - 1); + } + return g_string_free (string, FALSE); +} + +/** + * pk_role_bitfield_from_string: + * @roles: the enumerated constant value, e.g. "available;~gui" + * + * Converts text representation to its enumerated type bitfield + * + * Return value: The enumerated type values, or 0 for invalid + * + * Since: 0.5.2 + **/ +PkBitfield +pk_role_bitfield_from_string (const gchar *roles) +{ + PkBitfield roles_enum = 0; + gchar **split; + guint length; + guint i; + PkRoleEnum role; + + split = g_strsplit (roles, ";", 0); + if (split == NULL) { + g_warning ("unable to split"); + goto out; + } + + length = g_strv_length (split); + for (i=0; ilen == 0) { + g_warning ("not valid!"); + g_string_append (string, pk_group_enum_to_string (PK_GROUP_ENUM_UNKNOWN)); + } else { + /* remove last \n */ + g_string_set_size (string, string->len - 1); + } + return g_string_free (string, FALSE); +} + +/** + * pk_group_bitfield_from_string: + * @groups: the enumerated constant value, e.g. "available;~gui" + * + * Converts text representation to its enumerated type bitfield + * + * Return value: The enumerated type values, or 0 for invalid + * + * Since: 0.5.2 + **/ +PkBitfield +pk_group_bitfield_from_string (const gchar *groups) +{ + PkBitfield groups_enum = 0; + gchar **split; + guint length; + guint i; + PkGroupEnum group; + + split = g_strsplit (groups, ";", 0); + if (split == NULL) { + g_warning ("unable to split"); + goto out; + } + + length = g_strv_length (split); + for (i=0; ilen == 0) { + g_warning ("not valid!"); + g_string_append (string, pk_filter_enum_to_string (PK_FILTER_ENUM_NONE)); + } else { + /* remove last \n */ + g_string_set_size (string, string->len - 1); + } + return g_string_free (string, FALSE); +} + +/** + * pk_filter_bitfield_from_string: + * @filters: the enumerated constant value, e.g. "available;~gui" + * + * Converts text representation to its enumerated type bitfield, or 0 for invalid + * + * Return value: The enumerated type values + * + * Since: 0.5.2 + **/ +PkBitfield +pk_filter_bitfield_from_string (const gchar *filters) +{ + PkBitfield filters_enum = 0; + gchar **split; + guint length; + guint i; + PkFilterEnum filter; + + split = g_strsplit (filters, ";", 0); + if (split == NULL) { + g_warning ("unable to split"); + goto out; + } + + length = g_strv_length (split); + for (i=0; i +#include +#include +#include +#include +#include + +#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) +/** + * container_of - cast a member of a structure out to the containing structure + * @ptr: the pointer to the member. + * @type: the type of the container struct this is embedded in. + * @member: the name of the member within the struct. + * + */ +#define container_of(ptr, type, member) ({ \ + const typeof(((type *)0)->member)*__mptr = (ptr); \ + (type *)((char *)__mptr - offsetof(type, member)); }) + +/* + * Simple doubly linked list implementation. + * + * Some of the internal functions ("__xxx") are useful when + * manipulating whole lists rather than single entries, as + * sometimes we already know the next/prev entries and we can + * generate better code by using them directly rather than + * using the generic single-entry routines. + */ + +struct list_head { + struct list_head *next, *prev; +}; + + +static inline void INIT_LIST_HEAD(struct list_head *list) +{ + list->next = list; + list->prev = list; +} + +/* + * Insert a new entry between two known consecutive entries. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +#ifndef CONFIG_DEBUG_LIST +static inline void __list_add(struct list_head *new, + struct list_head *prev, struct list_head *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} +#else +extern void __list_add(struct list_head *new, + struct list_head *prev, struct list_head *next); +#endif + +/** + * list_add_tail - add a new entry + * @new: new entry to be added + * @head: list head to add it before + * + * Insert a new entry before the specified head. + * This is useful for implementing queues. + */ +static inline void list_add_tail(struct list_head *new, struct list_head *head) +{ + __list_add(new, head->prev, head); +} + +/** + * list_entry - get the struct for this entry + * @ptr: the &struct list_head pointer. + * @type: the type of the struct this is embedded in. + * @member: the name of the list_head within the struct. + */ +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +/** + * list_for_each_entry - iterate over list of given type + * @pos: the type * to use as a loop cursor. + * @head: the head for your list. + * @member: the name of the list_head within the struct. + */ +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member)) + +struct offset { + struct list_head list; + unsigned offset; +}; + +struct table { + struct list_head offsets; + unsigned offset_max; + unsigned nentry; + unsigned *table; + char *gpu_prefix; +}; + +static struct offset *offset_new(unsigned o) +{ + struct offset *offset; + + offset = (struct offset *)malloc(sizeof(struct offset)); + if (offset) { + INIT_LIST_HEAD(&offset->list); + offset->offset = o; + } + return offset; +} + +static void table_offset_add(struct table *t, struct offset *offset) +{ + list_add_tail(&offset->list, &t->offsets); +} + +static void table_init(struct table *t) +{ + INIT_LIST_HEAD(&t->offsets); + t->offset_max = 0; + t->nentry = 0; + t->table = NULL; +} + +static void table_print(struct table *t) +{ + unsigned nlloop, i, j, n, c, id; + + nlloop = (t->nentry + 3) / 4; + c = t->nentry; + printf("static const unsigned %s_reg_safe_bm[%d] = {\n", t->gpu_prefix, + t->nentry); + for (i = 0, id = 0; i < nlloop; i++) { + n = 4; + if (n > c) + n = c; + c -= n; + for (j = 0; j < n; j++) { + if (j == 0) + printf("\t"); + else + printf(" "); + printf("0x%08X,", t->table[id++]); + } + printf("\n"); + } + printf("};\n"); +} + +static int table_build(struct table *t) +{ + struct offset *offset; + unsigned i, m; + + t->nentry = ((t->offset_max >> 2) + 31) / 32; + t->table = (unsigned *)malloc(sizeof(unsigned) * t->nentry); + if (t->table == NULL) + return -1; + memset(t->table, 0xff, sizeof(unsigned) * t->nentry); + list_for_each_entry(offset, &t->offsets, list) { + i = (offset->offset >> 2) / 32; + m = (offset->offset >> 2) & 31; + m = 1 << m; + t->table[i] ^= m; + } + return 0; +} + +static char gpu_name[10]; +static int parser_auth(struct table *t, const char *filename) +{ + FILE *file; + regex_t mask_rex; + regmatch_t match[4]; + char buf[1024]; + size_t end; + int len; + int done = 0; + int r; + unsigned o; + struct offset *offset; + char last_reg_s[10]; + int last_reg; + + if (regcomp + (&mask_rex, "(0x[0-9a-fA-F]*) *([_a-zA-Z0-9]*)", REG_EXTENDED)) { + fprintf(stderr, "Failed to compile regular expression\n"); + return -1; + } + file = fopen(filename, "r"); + if (file == NULL) { + fprintf(stderr, "Failed to open: %s\n", filename); + return -1; + } + fseek(file, 0, SEEK_END); + end = ftell(file); + fseek(file, 0, SEEK_SET); + + /* get header */ + if (fgets(buf, 1024, file) == NULL) { + fclose(file); + return -1; + } + + /* first line will contain the last register + * and gpu name */ + sscanf(buf, "%9s %9s", gpu_name, last_reg_s); + t->gpu_prefix = gpu_name; + last_reg = strtol(last_reg_s, NULL, 16); + + do { + if (fgets(buf, 1024, file) == NULL) { + fclose(file); + return -1; + } + len = strlen(buf); + if (ftell(file) == end) + done = 1; + if (len) { + r = regexec(&mask_rex, buf, 4, match, 0); + if (r == REG_NOMATCH) { + } else if (r) { + fprintf(stderr, + "Error matching regular expression %d in %s\n", + r, filename); + fclose(file); + return -1; + } else { + buf[match[0].rm_eo] = 0; + buf[match[1].rm_eo] = 0; + buf[match[2].rm_eo] = 0; + o = strtol(&buf[match[1].rm_so], NULL, 16); + offset = offset_new(o); + table_offset_add(t, offset); + if (o > t->offset_max) + t->offset_max = o; + } + } + } while (!done); + fclose(file); + if (t->offset_max < last_reg) + t->offset_max = last_reg; + return table_build(t); +} + +int main(int argc, char *argv[]) +{ + struct table t; + + if (argc != 2) { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(1); + } + table_init(&t); + if (parser_auth(&t, argv[1])) { + fprintf(stderr, "Failed to parse file %s\n", argv[1]); + return -1; + } + table_print(&t); + return 0; +} diff --git a/code/validation/C/0094425_packet-osi.c b/code/validation/C/0094425_packet-osi.c new file mode 100644 index 0000000000000000000000000000000000000000..bbe763cff41660c29e352ca1965a7fc937dc4eef --- /dev/null +++ b/code/validation/C/0094425_packet-osi.c @@ -0,0 +1,354 @@ +/* packet-osi.c + * Routines for ISO/OSI network and transport protocol packet disassembly + * Main entrance point and common functions + * + * $Id$ + * Laurent Deniel + * Ralf Schneider + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "packet-osi.h" +#include "packet-isis.h" +#include "packet-esis.h" +#include "packet-tpkt.h" + +static int proto_osi = -1; +static dissector_handle_t osi_handle; + + +/* Preferences for OSI over TPKT over TCP */ +static gboolean tpkt_desegment = FALSE; +static guint global_tcp_port_osi_over_tpkt = 0; + +cksum_status_t +calc_checksum( tvbuff_t *tvb, int offset, guint len, guint checksum) { + const gchar *buffer; + guint available_len; + const guint8 *p; + guint32 c0, c1; + guint seglen; + guint i; + + if ( 0 == checksum ) + return( NO_CKSUM ); + + available_len = tvb_length_remaining( tvb, offset ); + if ( available_len < len ) + return( DATA_MISSING ); + + buffer = tvb_get_ptr( tvb, offset, len ); + + /* + * The maximum values of c0 and c1 will occur if all bytes have the + * value 255; if so, then c0 will be len*255 and c1 will be + * (len*255 + (len-1)*255 + ... + 255), which is + * (len + (len - 1) + ... + 1)*255, or 255*(len*(len + 1))/2. + * This means it can overflow if "len" is 5804 or greater. + * + * (A+B) mod 255 = ((A mod 255) + (B mod 255) mod 255, so + * we can solve this by taking c0 and c1 mod 255 every + * 5803 bytes. + */ + p = buffer; + c0 = 0; + c1 = 0; + while (len != 0) { + seglen = len; + if (seglen > 5803) + seglen = 5803; + for (i = 0; i < seglen; i++) { + c0 = c0 + *(p++); + c1 += c0; + } + + c0 = c0 % 255; + c1 = c1 % 255; + + len -= seglen; + } + if (c0 != 0 || c1 != 0) + return( CKSUM_NOT_OK ); /* XXX - what should the checksum field be? */ + else + return( CKSUM_OK ); +} + + +cksum_status_t +check_and_get_checksum( tvbuff_t *tvb, int offset, guint len, guint checksum, int offset_check, guint16* result) { + const gchar *buffer; + guint available_len; + const guint8 *p; + guint8 discard = 0; + guint32 c0, c1, factor; + guint seglen, initlen = len; + guint i; + int block, x, y; + + if ( 0 == checksum ) + return( NO_CKSUM ); + + available_len = tvb_length_remaining( tvb, offset ); + offset_check -= offset; + if ( ( available_len < len ) || ( offset_check < 0 ) || ( (guint)(offset_check+2) > len ) ) + return( DATA_MISSING ); + + buffer = tvb_get_ptr( tvb, offset, len ); + block = offset_check / 5803; + + /* + * The maximum values of c0 and c1 will occur if all bytes have the + * value 255; if so, then c0 will be len*255 and c1 will be + * (len*255 + (len-1)*255 + ... + 255), which is + * (len + (len - 1) + ... + 1)*255, or 255*(len*(len + 1))/2. + * This means it can overflow if "len" is 5804 or greater. + * + * (A+B) mod 255 = ((A mod 255) + (B mod 255) mod 255, so + * we can solve this by taking c0 and c1 mod 255 every + * 5803 bytes. + */ + p = buffer; + c0 = 0; + c1 = 0; + + while (len != 0) { + seglen = len; + if ( block-- == 0 ) { + seglen = offset_check % 5803; + discard = 1; + } else if ( seglen > 5803 ) + seglen = 5803; + for (i = 0; i < seglen; i++) { + c0 = c0 + *(p++); + c1 += c0; + } + if ( discard ) { + /* + * This works even if (offset_check % 5803) == 5802 + */ + p += 2; + c1 += 2*c0; + len -= 2; + discard = 0; + } + + c0 = c0 % 255; + c1 = c1 % 255; + + len -= seglen; + } + + factor = ( initlen - offset_check ) * c0; + x = factor - c0 - c1; + y = c1 - factor - 1; + + /* + * This algorithm uses the 8 bits one's complement arithmetic. + * Therefore, we must correct an effect produced + * by the "standard" arithmetic (two's complement) + */ + + if (x < 0 ) x--; + if (y > 0 ) y++; + + x %= 255; + y %= 255; + + if (x == 0) x = 0xFF; + if (y == 0) y = 0x01; + + *result = ( x << 8 ) | ( y & 0xFF ); + + if (*result != checksum) + return( CKSUM_NOT_OK ); /* XXX - what should the checksum field be? */ + else + return( CKSUM_OK ); +} + + + +/* main entry point */ + +/* + * These assume the NLPID is a secondary protocol identifier, not an + * initial protocol identifier. + * + * This is an issue only if, in any packet where an NLPID appears, it's + * an initial protocol identifier *AND* it can have the value 1, which + * means T.70 for an IPI and X.29 for an SPI. + */ +const value_string nlpid_vals[] = { + { NLPID_NULL, "NULL" }, + { NLPID_SPI_X_29, "X.29" }, + { NLPID_X_633, "X.633" }, + { NLPID_Q_931, "Q.931" }, + { NLPID_Q_2931, "Q.2931" }, + { NLPID_Q_2119, "Q.2119" }, + { NLPID_SNAP, "SNAP" }, + { NLPID_ISO8473_CLNP, "CLNP" }, + { NLPID_ISO9542_ESIS, "ESIS" }, + { NLPID_ISO10589_ISIS, "ISIS" }, + { NLPID_ISO10747_IDRP, "IDRP" }, + { NLPID_ISO9542X25_ESIS, "ESIS (X.25)" }, + { NLPID_ISO10030, "ISO 10030" }, + { NLPID_ISO11577, "ISO 11577" }, + { NLPID_COMPRESSED, "Data compression protocol" }, + { NLPID_IP, "IP" }, + { NLPID_SNDCF, "SubNetwork Dependent Convergence Function"}, + { NLPID_IP6, "IPv6" }, + { NLPID_PPP, "PPP" }, + { 0, NULL }, +}; + +static dissector_table_t osinl_subdissector_table; +static dissector_table_t osinl_excl_subdissector_table; +static dissector_handle_t data_handle, ppp_handle; + +/* Dissect OSI over TCP over TPKT */ +static void +dissect_osi_tpkt(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) +{ + dissect_tpkt_encap(tvb, pinfo, tree, tpkt_desegment, osi_handle); +} + +static void dissect_osi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) +{ + guint8 nlpid; + tvbuff_t *new_tvb; + + pinfo->current_proto = "OSI"; + + nlpid = tvb_get_guint8(tvb, 0); + + /* try lookup with the subdissector tables that includes the nlpid */ + if (dissector_try_uint(osinl_subdissector_table, nlpid, tvb, pinfo, tree)) + return; + /* try lookup with the subdissector tables that excludes the nlpid */ + new_tvb = tvb_new_subset_remaining(tvb, 1); + if (dissector_try_uint(osinl_excl_subdissector_table, nlpid, new_tvb, pinfo, tree)) + return; + + switch (nlpid) { + + /* ESIS (X.25) is not currently decoded */ + + case NLPID_ISO9542X25_ESIS: + col_set_str(pinfo->cinfo, COL_PROTOCOL, "ESIS (X.25)"); + call_dissector(data_handle,tvb, pinfo, tree); + break; + case NLPID_ISO10747_IDRP: + col_set_str(pinfo->cinfo, COL_PROTOCOL, "IDRP"); + call_dissector(data_handle,tvb, pinfo, tree); + break; + default: + col_set_str(pinfo->cinfo, COL_PROTOCOL, "ISO"); + if (check_col(pinfo->cinfo, COL_INFO)) { + col_add_fstr(pinfo->cinfo, COL_INFO, "Unknown ISO protocol (%02x)", nlpid); + } + call_dissector(data_handle,tvb, pinfo, tree); + break; + } +} /* dissect_osi */ + +void +proto_reg_handoff_osi(void) +{ + static gboolean osi_prefs_initialized = FALSE; + static dissector_handle_t osi_tpkt_handle; + static guint tcp_port_osi_over_tpkt; + + if (!osi_prefs_initialized) { + osi_handle = create_dissector_handle(dissect_osi, proto_osi); + dissector_add_uint("llc.dsap", SAP_OSINL1, osi_handle); + dissector_add_uint("llc.dsap", SAP_OSINL2, osi_handle); + dissector_add_uint("llc.dsap", SAP_OSINL3, osi_handle); + dissector_add_uint("llc.dsap", SAP_OSINL4, osi_handle); + dissector_add_uint("llc.dsap", SAP_OSINL5, osi_handle); + dissector_add_uint("ppp.protocol", PPP_OSI, osi_handle); + dissector_add_uint("chdlctype", CHDLCTYPE_OSI, osi_handle); + dissector_add_uint("null.type", BSD_AF_ISO, osi_handle); + dissector_add_uint("gre.proto", SAP_OSINL5, osi_handle); + dissector_add_uint("ip.proto", IP_PROTO_ISOIP, osi_handle); /* ISO-TP4 ISO Transport Protocol Class 4 [RFC905,RC77] */ + data_handle = find_dissector("data"); + ppp_handle = find_dissector("ppp"); + + + osi_tpkt_handle = create_dissector_handle(dissect_osi_tpkt, proto_osi); + dissector_add_handle("tcp.port", osi_tpkt_handle); /* for 'decode-as' */ + osi_prefs_initialized = TRUE; + } else { + if (tcp_port_osi_over_tpkt != 0) { + dissector_delete_uint("tcp.port", tcp_port_osi_over_tpkt, osi_tpkt_handle); + } + } + + if (global_tcp_port_osi_over_tpkt != 0) { + dissector_add_uint("tcp.port", global_tcp_port_osi_over_tpkt, osi_tpkt_handle); + } + tcp_port_osi_over_tpkt = global_tcp_port_osi_over_tpkt; +} + +void +proto_register_osi(void) +{ + module_t *osi_module; + + /* There's no "OSI" protocol *per se*, but we do register a + dissector table so various protocols running at the + network layer can register themselves. + all protocols that require inclusion of the NLPID + should register here + */ + osinl_subdissector_table = register_dissector_table("osinl", + "OSI incl NLPID", FT_UINT8, BASE_HEX); + + /* This dissector table is for those protocols whose PDUs + * aren't* defined to begin with an NLPID. + * (typically non OSI protocols like IP,IPv6,PPP */ + osinl_excl_subdissector_table = register_dissector_table("osinl.excl", + "OSI excl NLPID", FT_UINT8, BASE_HEX); + + proto_osi = proto_register_protocol("OSI", "OSI", "osi"); + /* Preferences how OSI protocols should be dissected */ + osi_module = prefs_register_protocol(proto_osi, proto_reg_handoff_osi); + + prefs_register_uint_preference(osi_module, "tpkt_port", + "TCP port for OSI over TPKT", + "TCP port for OSI over TPKT", + 10, &global_tcp_port_osi_over_tpkt); + prefs_register_bool_preference(osi_module, "tpkt_reassemble", + "Reassemble segmented TPKT datagrams", + "Whether segmented TPKT datagrams should be reassembled", + &tpkt_desegment); + +} + diff --git a/code/validation/C/0096232_5ex7.19.c b/code/validation/C/0096232_5ex7.19.c new file mode 100644 index 0000000000000000000000000000000000000000..be5690f6541104d816b5dcec06972906e2db3821 --- /dev/null +++ b/code/validation/C/0096232_5ex7.19.c @@ -0,0 +1,164 @@ +#include + +#define READ 10 +#define WRITE 11 + +#define LOAD 20 +#define STORE 21 + +#define ADD 30 +#define SUBTRACT 31 +#define DIVIDE 32 +#define MULTIPLY 33 + +#define BRANCH 40 +#define BRANCHNEG 41 +#define BRANCHZERO 42 +#define HALT 43 + + +void error(int opt); +void introduce(void); +void init(void); +void run(void); +void dump(void); +void initProgram(void); + +int main(int argc, char const *argv[]) +{ + introduce(); + initProgram(); + init(); + run(); +} + + +void introduce(void) +{ + printf("*** %s ***\n","Welcome to Simpletron" ); + printf("*** %s ***\n","Please enter your program one instruction" ); + printf("*** %s ***\n","(or data word) at a time,I will type the" ); + printf("*** %s ***\n","location number and a question mark (?)." ); + printf("*** %s ***\n","You then type the word for that location." ); + printf("*** %s ***\n","Type the sentinel -99999 to stop entering" ); + printf("*** %s ***\n","your program." ); +} + +int memory[100]={0}; +int accumulator; +int instructionCounter; +int instructionRegister; +int operationCode; +int operand; + +void init(void) +{ + accumulator = +0000; + instructionCounter = 00; + instructionRegister = +0000; + operationCode = 00; + operand = 00; +} + +void dump(void) +{ + int i,j; + printf("%s\n","REGISTERS:" ); + printf("%-20s\t%+05d\n","accumulator",accumulator ); + printf("%-20s\t %02d\n","instructionCounter",instructionCounter ); + printf("%-20s\t%+05d\n","instructionRegister",instructionRegister ); + printf("%-20s\t %02d\n","operationCode",operationCode ); + printf("%-20s\t %02d\n","operand",operand ); + printf("\n%s\n","MEMORY:" ); + printf("%8d",0 ); + for(i=1;i<10;i++) + { + printf("%6d",i ); + } + printf("\n" ); + for(i=0;i<10;i++) + { + printf("%2d",i*10 ); + for(j=0;j<10;j++) + { + printf(" %+05d",memory[i*10+j] ); + } + printf("\n" ); + } +} +void initProgram(void) +{ + int i; + for(i=0;i<100;i++) + { + printf("%02d%s",i," ? " ); + scanf("%d",&memory[i] ); + while(memory[i] > +9999 || memory[i] < -9999 ) + { + if(-99999==memory[i]) break; + printf("*** %s ***\n","please enter a number between -9999 and +9999" ); + printf("%02d%s",i," ? " ); + scanf("%d",&memory[i] ); + } + if(-99999 == memory[i]) + { + memory[i]=0000; + printf("*** %s ***\n","Program. loading completed" ); + printf("*** %s ***\n","Program. execution begins" ); + break; + } + } +} +void run(void) +{ + int err=0; + while(!err) + { + instructionRegister = memory[instructionCounter]; + operationCode = instructionRegister / 100; + operand = instructionRegister % 100; + // printf("--- %d %d ---\n",operationCode,operand ); + switch (operationCode) + { + case READ:printf("(?)" );scanf("%d",&memory[operand]);break; + case WRITE:printf("%d\n",memory[operand]);break; + + case LOAD:accumulator = memory[operand];break; + case STORE:memory[operand] = accumulator;break; + + case ADD:accumulator += memory[operand];break; + case SUBTRACT:accumulator -= memory[operand];break; + case DIVIDE:if(0 == memory[operand]) + { + error(0); + err=1; + break; + } + accumulator /= memory[operand];break; + case MULTIPLY:accumulator *= memory[operand];break; + + case BRANCH:instructionCounter = operand;break; + case BRANCHNEG:if(accumulator < 0) instructionCounter = operand-1;break; + case BRANCHZERO:if(accumulator == 0) instructionCounter = operand-1;break; + case HALT:printf("*** %s ***\n","Simpletron execution terminated" );instructionCounter--;err=1;break; + } + ++ instructionCounter; + if(instructionCounter>99) + { + error(2); + err=1; + instructionCounter--; + } + } + dump(); +} +void error(int opt) +{ + switch (opt) + { + case 0:printf("*** %s ***\n","Attempt to divide by zero" );break; + case 1:printf("*** %s ***\n","Accumulator overflow" );break; + case 2:printf("*** %s ***\n","Memory overflow" );break; + } + printf("*** %s ***\n","Simpletron execution abnormally terminated" ); +} diff --git a/code/validation/C/0097010_clutter-fixed-layout.c b/code/validation/C/0097010_clutter-fixed-layout.c new file mode 100644 index 0000000000000000000000000000000000000000..919a856cc5dbe29906a97429243f63de7269f143 --- /dev/null +++ b/code/validation/C/0097010_clutter-fixed-layout.c @@ -0,0 +1,218 @@ +/* + * Clutter. + * + * An OpenGL based 'interactive canvas' library. + * + * Copyright (C) 2009 Intel Corporation. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + * + * Author: + * Emmanuele Bassi + * + * Based on the fixed layout code inside clutter-group.c + */ + +/** + * SECTION:clutter-fixed-layout + * @short_description: A fixed layout manager + * + * #ClutterFixedLayout is a layout manager implementing the same + * layout policies as #ClutterGroup. + * + * #ClutterFixedLayout is available since Clutter 1.2 + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "clutter-debug.h" +#include "clutter-fixed-layout.h" +#include "clutter-private.h" + +G_DEFINE_TYPE (ClutterFixedLayout, + clutter_fixed_layout, + CLUTTER_TYPE_LAYOUT_MANAGER); + +static void +clutter_fixed_layout_get_preferred_width (ClutterLayoutManager *manager, + ClutterContainer *container, + gfloat for_height, + gfloat *min_width_p, + gfloat *nat_width_p) +{ + GList *children, *l; + gdouble min_right; + gdouble natural_right; + + min_right = 0; + natural_right = 0; + + children = clutter_container_get_children (container); + + for (l = children; l != NULL; l = l->next) + { + ClutterActor *child = l->data; + gfloat child_x, child_min, child_natural; + + child_x = clutter_actor_get_x (child); + + clutter_actor_get_preferred_size (child, + &child_min, NULL, + &child_natural, NULL); + + if (child_x + child_min > min_right) + min_right = child_x + child_min; + + if (child_x + child_natural > natural_right) + natural_right = child_x + child_natural; + } + + g_list_free (children); + + if (min_width_p) + *min_width_p = min_right; + + if (nat_width_p) + *nat_width_p = natural_right; +} + +static void +clutter_fixed_layout_get_preferred_height (ClutterLayoutManager *manager, + ClutterContainer *container, + gfloat for_width, + gfloat *min_height_p, + gfloat *nat_height_p) +{ + GList *children, *l; + gdouble min_bottom; + gdouble natural_bottom; + + min_bottom = 0; + natural_bottom = 0; + + children = clutter_container_get_children (container); + + for (l = children; l != NULL; l = l->next) + { + ClutterActor *child = l->data; + gfloat child_y, child_min, child_natural; + + child_y = clutter_actor_get_y (child); + + clutter_actor_get_preferred_size (child, + NULL, &child_min, + NULL, &child_natural); + + if (child_y + child_min > min_bottom) + min_bottom = child_y + child_min; + + if (child_y + child_natural > natural_bottom) + natural_bottom = child_y + child_natural; + } + + g_list_free (children); + + if (min_height_p) + *min_height_p = min_bottom; + + if (nat_height_p) + *nat_height_p = natural_bottom; +} + +static void +clutter_fixed_layout_allocate (ClutterLayoutManager *manager, + ClutterContainer *container, + const ClutterActorBox *allocation, + ClutterAllocationFlags flags) +{ + GList *children, *l; + + children = clutter_container_get_children (container); + + for (l = children; l != NULL; l = l->next) + { + ClutterActor *child = l->data; + + clutter_actor_allocate_preferred_size (child, flags); + } + + g_list_free (children); +} + +void +clutter_fixed_layout_set_container (ClutterLayoutManager *manager, + ClutterContainer *container) +{ + ClutterLayoutManagerClass *parent_class; + + if (container != NULL) + { + g_object_set_data (G_OBJECT (manager), "fixed-container", container); + + /* signal Clutter that we don't impose any layout on + * our children, so we can shave off some relayout + * operations + */ + CLUTTER_ACTOR_SET_FLAGS (container, CLUTTER_ACTOR_NO_LAYOUT); + } + else + { + gpointer old_container; + + old_container = g_object_get_data (G_OBJECT (manager), "fixed-container"); + if (old_container != NULL) + CLUTTER_ACTOR_UNSET_FLAGS (old_container, CLUTTER_ACTOR_NO_LAYOUT); + + g_object_set_data (G_OBJECT (manager), "fixed-container", NULL); + } + + parent_class = CLUTTER_LAYOUT_MANAGER_CLASS (clutter_fixed_layout_parent_class); + parent_class->set_container (manager, container); +} + +static void +clutter_fixed_layout_class_init (ClutterFixedLayoutClass *klass) +{ + ClutterLayoutManagerClass *manager_class = + CLUTTER_LAYOUT_MANAGER_CLASS (klass); + + manager_class->get_preferred_width = + clutter_fixed_layout_get_preferred_width; + manager_class->get_preferred_height = + clutter_fixed_layout_get_preferred_height; + manager_class->allocate = clutter_fixed_layout_allocate; + manager_class->set_container = clutter_fixed_layout_set_container; +} + +static void +clutter_fixed_layout_init (ClutterFixedLayout *self) +{ +} + +/** + * clutter_fixed_layout_new: + * + * Creates a new #ClutterFixedLayout + * + * Return value: the newly created #ClutterFixedLayout + * + * Since: 1.2 + */ +ClutterLayoutManager * +clutter_fixed_layout_new (void) +{ + return g_object_new (CLUTTER_TYPE_FIXED_LAYOUT, NULL); +} diff --git a/code/validation/C/0097559_joystick.c b/code/validation/C/0097559_joystick.c new file mode 100644 index 0000000000000000000000000000000000000000..df5f3d8c723d6aeafe85bd23451cb1563ceb104d --- /dev/null +++ b/code/validation/C/0097559_joystick.c @@ -0,0 +1,192 @@ +/** + ****************************************************************************** + * @file BSP/Src/joystick.c + * @author MCD Application Team + * @version V1.3.0 + * @date 17-February-2017 + * @brief This example code shows how to use the joystick feature in the + * stm324xg_eval driver + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2017 STMicroelectronics

> + * + * 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 STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "main.h" + +/** @addtogroup STM32F4xx_HAL_Examples + * @{ + */ + +/** @addtogroup BSP + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +static JOYState_TypeDef JoyState = JOY_NONE; + +/* Private function prototypes -----------------------------------------------*/ +static void Joystick_SetHint(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Joystick demo + * @param None + * @retval None + */ +void Joystick_demo(void) +{ + static uint16_t xPtr = 12; + static uint16_t yPtr = 92; + static uint16_t old_xPtr = 12; + static uint16_t old_yPtr = 92; + uint8_t status = 0; + + Joystick_SetHint(); + + status = BSP_JOY_Init(JOY_MODE_GPIO); + + if (status != IO_OK) + { + BSP_LCD_SetBackColor(LCD_COLOR_WHITE); + BSP_LCD_SetTextColor(LCD_COLOR_RED); + BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize()- 95, (uint8_t *)"ERROR", CENTER_MODE); + BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize()- 80, (uint8_t *)"Joystick cannot be initialized", CENTER_MODE); + } + + while (1) + { + if (status == IO_OK) + { + /* Get the Joystick State */ + JoyState = BSP_JOY_GetState(); + + switch(JoyState) + { + case JOY_UP: + if(yPtr > 92) + { + yPtr--; + } + break; + case JOY_DOWN: + if(yPtr < (BSP_LCD_GetYSize() - 12 - 11)) + { + yPtr++; + } + break; + case JOY_LEFT: + if(xPtr > 12) + { + xPtr--; + } + break; + case JOY_RIGHT: + if(xPtr < (BSP_LCD_GetXSize() - 8 - 11)) + { + xPtr++; + } + break; + default: + break; + } + + BSP_LCD_SetBackColor(LCD_COLOR_WHITE); + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + + if(JoyState == JOY_SEL) + { + BSP_LCD_SetTextColor(LCD_COLOR_RED); + BSP_LCD_DisplayChar(xPtr, yPtr, 'X'); + + } + else if(JoyState == JOY_NONE) + { + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + BSP_LCD_DisplayChar(xPtr, yPtr, 'X'); + } + else + { + BSP_LCD_SetTextColor(LCD_COLOR_WHITE); + BSP_LCD_DisplayChar(old_xPtr, old_yPtr, 'X'); + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + BSP_LCD_DisplayChar(xPtr, yPtr, 'X'); + + old_xPtr = xPtr; + old_yPtr = yPtr; + } + } + if(CheckForUserInput() > 0) + { + return; + } + HAL_Delay(5); + } +} + +/** + * @brief Display joystick demo hint + * @param None + * @retval None + */ +static void Joystick_SetHint(void) +{ + /* Clear the LCD */ + BSP_LCD_Clear(LCD_COLOR_WHITE); + + /* Set Joystick Demo description */ + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + BSP_LCD_FillRect(0, 0, BSP_LCD_GetXSize(), 80); + BSP_LCD_SetTextColor(LCD_COLOR_WHITE); + BSP_LCD_SetBackColor(LCD_COLOR_BLUE); + BSP_LCD_SetFont(&Font24); + BSP_LCD_DisplayStringAt(0, 0, (uint8_t *)"Joystick", CENTER_MODE); + BSP_LCD_SetFont(&Font12); + BSP_LCD_DisplayStringAt(0, 30, (uint8_t *)"Please use the joystick to", CENTER_MODE); + BSP_LCD_DisplayStringAt(0, 45, (uint8_t *)"move the pointer inside the", CENTER_MODE); + BSP_LCD_DisplayStringAt(0, 60, (uint8_t *)"rectangle", CENTER_MODE); + + /* Set the LCD Text Color */ + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + BSP_LCD_DrawRect(10, 90, BSP_LCD_GetXSize() - 20, BSP_LCD_GetYSize()- 100); + BSP_LCD_DrawRect(11, 91, BSP_LCD_GetXSize() - 22, BSP_LCD_GetYSize()- 102); +} + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/code/validation/C/0097861_sdtest.c b/code/validation/C/0097861_sdtest.c new file mode 100644 index 0000000000000000000000000000000000000000..cd10d0c3d7f021c20a24600ee1cfea38f304215d --- /dev/null +++ b/code/validation/C/0097861_sdtest.c @@ -0,0 +1,239 @@ +/* +vi:noexpandtab:ts=2:sw=2 +*/ + +#define _LARGEFILE64_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "util.h" + +u64 global_error_count = 0; + +unsigned int BLOCK_SIZE = 0; +u8 *buf_g; /* Generated */ +u8 *buf_f; /* File */ +#define RAND_BLOCK_SIZE 4*1024 /* Data is seeded every 4K to be block size agnostic */ + +void _genranddata(u64 pos, u64 off, unsigned int seed) +{ + unsigned int seed_short = (pos >> 32) ^ (pos & 0xffffffff) ^ seed; + unsigned int i,j; + u32 tmp1, tmp2; + + assert(RAND_MAX >= 31); /* Assert that rand() still gives us the amount + of random bits we rely on below. */ + assert(RAND_BLOCK_SIZE % 4 == 0); + + srand(seed_short); rand(); rand(); + + for (i=0; i < RAND_BLOCK_SIZE;) { + tmp2 = rand(); + for (j=1; i < RAND_BLOCK_SIZE && j < 32; j++) { + tmp1 = rand(); + buf_g[off + i++] = (tmp1 & 0x000000ff) ; + buf_g[off + i++] = (tmp1 & 0x0000ff00) >> 8; + buf_g[off + i++] = (tmp1 & 0x00ff0000) >> 16; + /* We don't quite have 4 bytes of random data in tmp1, + * so get the high bit from tmp2: */ + buf_g[off + i++] = ((tmp1 & 0x7f000000) | ((tmp2 << j) & 0x80000000)) >> 24; + } + } +} + +void genranddata(u64 pos, unsigned int seed) +{ + u64 off; + + assert(pos % RAND_BLOCK_SIZE == 0); + assert(BLOCK_SIZE % RAND_BLOCK_SIZE == 0); + + for (off=0; off < BLOCK_SIZE; off += RAND_BLOCK_SIZE) + _genranddata(pos+off, off, seed); +} + +static void verifyblock(u64 pos, unsigned int seed, unsigned int size) +{ + unsigned int i; + + genranddata(pos, seed); + + for (i=0;i 4) { + printf("Usage: %s device [ start [ readonly ]]\nWARNING - all data on device will be destroyed!\n", argv[0]); + return 1; + } + filename = argv[1]; + alloc_bufs(sd_erase_size(filename)); /* BLOCK_SIZE set here */ + + if (argc > 2) { + start = interpret_number(argv[2]); + start = start - start % BLOCK_SIZE; + } + start_human = human_size(start, &start_units); + printf("Starting at %#llx (%.2f %s)\n", start, start_human, start_units); + readonly = argc > 3; + + size = dev_size(filename); + if (size) + expected_len = size - start; + + if (!readonly) { + written = writedata(argv[1], start, size, seed); + printf("\x1b[36m%llu bytes written to %s, verifying...\x1b[0m\n", written, filename); + if (expected_len && written != expected_len) { + printf("\x1b[1;31mSIZE MISMATCH: wrote %llu bytes, but expected to write %llu bytes!\x1b[0m\n", + written, expected_len); + global_error_count++; + } + } + + sync(); + + read = verifydata(argv[1], start, size, seed); + printf("\x1b[36m%llu bytes read from %s.\x1b[0m\n", read, filename); + + if (!readonly && written != read) { + printf("\x1b[1;31mSIZE MISMATCH: wrote %llu bytes, but read back %llu bytes!\x1b[0m\n", written, read); + global_error_count++; + } else if (expected_len && read != expected_len) { + printf("\x1b[1;31mSIZE MISMATCH: read %llu bytes, but expected to read %llu bytes!\x1b[0m\n", read, expected_len); + global_error_count++; + } + + if (global_error_count) { + printf("\x1b[1;31m\n%llu Errors detected :-(\x1b[0m\n", global_error_count); + return 1; + } + + if (read) + printf("\x1b[1;32m\nNo Errors Detected :-)\x1b[0m\n"); + return 0; +} diff --git a/code/validation/C/0104147_sonar_bebop.c b/code/validation/C/0104147_sonar_bebop.c new file mode 100644 index 0000000000000000000000000000000000000000..717122e292c57e8428c3b17b8ccac347266ab730 --- /dev/null +++ b/code/validation/C/0104147_sonar_bebop.c @@ -0,0 +1,207 @@ +/* + * Copyright (C) 2015 Freek van Tienen + * + * This file is part of paparazzi. + * + * paparazzi is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * paparazzi is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with paparazzi; see the file COPYING. If not, write to + * the Free Software Foundation, 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + * + */ + +/** @file modules/sonar/sonar_bebop.c + * @brief Parrot Bebop Sonar driver + * + * This file contains the ADC driver for the sonar on the Parrot Bebop + * and Bebop 2 quadrotors. The sonar is both transmitter and receiver. + * An SPI interface is used to communicate with the 12 bit ADC which + * operates at 160kHz. The required waveform of the sonar is sent during + * the SPI transaction, with the returned data the recorded signal from + * the sonar. Two waveforms have been implemented dependent on the + * operating altitude of the Bebop. + */ + +#include "sonar_bebop.h" +#include "generated/airframe.h" +#include "mcu_periph/adc.h" +#include "mcu_periph/spi.h" +#include "subsystems/abi.h" +#include +#include "subsystems/datalink/downlink.h" + +#include "filters/median_filter.h" + +struct MedianFilterFloat sonar_filt; + +#ifdef SITL +#include "state.h" +#endif + +/** SONAR_BEBOP_INX_DIFF_TO_DIST conversion from index difference to distance based on time of flight + * ADC speed = 160kHz + * speed of sound = 340m/s */ +#define SONAR_BEBOP_INX_DIFF_TO_DIST 340./(2.*160000.) + +/** SONAR_BEBOP_ADC_MAX_VALUE maximum ADC output (12 bit ADC) */ +#define SONAR_BEBOP_ADC_MAX_VALUE 4095 + +/** SONAR_BEBOP_ADC_BUFFER_SIZE ADC buffer size */ +#define SONAR_BEBOP_ADC_BUFFER_SIZE 8192 + +/** mode holds the current sonar mode + * mode = 0 used at high altitude, uses 16 wave patterns + * mode = 1 used at low altitude, uses 4 wave patterns + */ +static uint8_t mode; + +/** SONAR_BEBOP_TRANSITION_HIGH_TO_LOW below this altitude we should use mode 0 */ +#define SONAR_BEBOP_TRANSITION_HIGH_TO_LOW 0.8 + +/** SONAR_BEBOP_TRANSITION_LOW_TO_HIGH above this altitude we should use mode 1 */ +#define SONAR_BEBOP_TRANSITION_LOW_TO_HIGH 1.2 + +/** SONAR_BEBOP_TRANSITION_COUNT number of samples before switching mode */ +#define SONAR_BEBOP_TRANSITION_COUNT 7 + +static uint8_t pulse_transition_counter; + +/** SONAR_BEBOP_PEAK_THRESHOLD minimum samples from broadcast stop */ +#define SONAR_BEBOP_PEAK_THRESHOLD 250 + +/** sonar_bebop_spi_d the waveforms emitted by the sonar + * waveform 0 is long pulse used at high altitude + * waveform 1 is shorter pulse used at low altitude + */ +static uint8_t sonar_bebop_spi_d[2][16] = {{ 0xF0, 0xF0, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, + { 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x00, 0x00, 0x00, 0x00 }}; + +struct SonarBebop sonar_bebop; + +static struct spi_transaction sonar_bebop_spi_t; +void *sonar_bebop_read(void *data); +#ifdef USE_SONAR +static pthread_t sonar_bebop_thread; +#endif + +void sonar_bebop_init(void) +{ + mode = 0; // default mode is low altitude + pulse_transition_counter = 0; + + sonar_bebop.meas = 0; + sonar_bebop.offset = 0; + + sonar_bebop_spi_t.status = SPITransDone; + sonar_bebop_spi_t.select = SPISelectUnselect; + sonar_bebop_spi_t.dss = SPIDss8bit; + sonar_bebop_spi_t.output_buf = sonar_bebop_spi_d[mode]; + sonar_bebop_spi_t.output_length = 16; + sonar_bebop_spi_t.input_buf = NULL; + sonar_bebop_spi_t.input_length = 0; + +#if USE_SONAR + pthread_create(&sonar_bebop_thread, NULL, sonar_bebop_read, NULL); +#endif + + init_median_filter_f(&sonar_filt, 3); +} + +uint16_t adc_buffer[SONAR_BEBOP_ADC_BUFFER_SIZE]; +/** sonar_bebop_read + * Read ADC value to update sonar measurement + */ +void *sonar_bebop_read(void *data __attribute__((unused))) +{ + while (true) { +#ifndef SITL + uint16_t i; + + /* Start ADC and send sonar output */ + adc_enable(&adc0, 1); + sonar_bebop_spi_t.status = SPITransDone; + sonar_bebop_spi_t.output_buf = sonar_bebop_spi_d[mode]; + spi_submit(&spi0, &sonar_bebop_spi_t); + while (sonar_bebop_spi_t.status != SPITransSuccess); + adc_read(&adc0, adc_buffer, SONAR_BEBOP_ADC_BUFFER_SIZE); + adc_enable(&adc0, 0); + + /* Find the peaks */ + uint16_t start_send = 0; + uint16_t stop_send = 0; + uint16_t first_peak = 0; + uint16_t lowest_value = SONAR_BEBOP_ADC_MAX_VALUE; + uint16_t peak_value = 0; + + for (i = 0; i < SONAR_BEBOP_ADC_BUFFER_SIZE; i++) { + uint16_t adc_val = adc_buffer[i] >> 4; + if (start_send == 0 && adc_val == SONAR_BEBOP_ADC_MAX_VALUE) { + start_send = i; + } else if (start_send != 0 && stop_send == 0 && adc_val != SONAR_BEBOP_ADC_MAX_VALUE) { + stop_send = i - 1; + i += SONAR_BEBOP_PEAK_THRESHOLD; + continue; + } + + if (start_send != 0 && stop_send != 0 && first_peak == 0 && adc_val < lowest_value) { + lowest_value = adc_val; // find trough from initial broadcast signal + } else if (start_send != 0 && stop_send != 0 && adc_val > lowest_value + 100 && adc_val > peak_value) { + first_peak = i; + peak_value = adc_val; + } + } + + /* Calculate the distance from the peeks */ + uint16_t diff = stop_send - start_send; + float peak_distance; + if (diff > 250) { + peak_distance = 0; + } else { + peak_distance = first_peak - (stop_send - diff / 2); + } + + sonar_bebop.distance = update_median_filter_f(&sonar_filt, peak_distance * SONAR_BEBOP_INX_DIFF_TO_DIST); + + // set sonar pulse mode for next pulse based on altitude + if (mode == 0 && sonar_bebop.distance > SONAR_BEBOP_TRANSITION_LOW_TO_HIGH) { + if (++pulse_transition_counter > SONAR_BEBOP_TRANSITION_COUNT) { + mode = 1; + pulse_transition_counter = 0; + } + } else if (mode == 1 && sonar_bebop.distance < SONAR_BEBOP_TRANSITION_HIGH_TO_LOW) { + if (++pulse_transition_counter > SONAR_BEBOP_TRANSITION_COUNT) { + mode = 0; + pulse_transition_counter = 0; + } + } else { + pulse_transition_counter = 0; + } + +#else // SITL + sonar_bebop.distance = stateGetPositionEnu_f()->z; + Bound(sonar_bebop.distance, 0.1f, 7.0f); + uint16_t peak_distance = 1; +#endif // SITL + + if (peak_distance > 0) { + // Send ABI message + AbiSendMsgAGL(AGL_SONAR_ADC_ID, sonar_bebop.distance); +#ifdef SENSOR_SYNC_SEND_SONAR + // Send Telemetry report + DOWNLINK_SEND_SONAR(DefaultChannel, DefaultDevice, &sonar_bebop.meas, &sonar_bebop.distance); +#endif + } + } + usleep(10000); //100Hz + return NULL; +} diff --git a/code/validation/C/0104214_eventq.c b/code/validation/C/0104214_eventq.c new file mode 100644 index 0000000000000000000000000000000000000000..2a78d9c368b34fcb03b6bede1331419a07476c9b --- /dev/null +++ b/code/validation/C/0104214_eventq.c @@ -0,0 +1,332 @@ +/* + * eventq.c - event queue manager routines + * + * This file is a part of the SimpleScalar tool suite written by + * Todd M. Austin as a part of the Multiscalar Research Project. + * + * The tool suite is currently maintained by Doug Burger and Todd M. Austin. + * + * Copyright (C) 1994, 1995, 1996, 1997, 1998 by Todd M. Austin + * + * This source file is distributed "as is" in the hope that it will be + * useful. The tool set comes with no warranty, and no author or + * distributor accepts any responsibility for the consequences of its + * use. + * + * Everyone is granted permission to copy, modify and redistribute + * this tool set under the following conditions: + * + * This source code is distributed for non-commercial use only. + * Please contact the maintainer for restrictions applying to + * commercial use. + * + * Permission is granted to anyone to make or distribute copies + * of this source code, either as received or modified, in any + * medium, provided that all copyright notices, permission and + * nonwarranty notices are preserved, and that the distributor + * grants the recipient permission for further redistribution as + * permitted by this document. + * + * Permission is granted to distribute this file in compiled + * or executable form under the same conditions that apply for + * source code, provided that either: + * + * A. it is accompanied by the corresponding machine-readable + * source code, + * B. it is accompanied by a written offer, with no time limit, + * to give anyone a machine-readable copy of the corresponding + * source code in return for reimbursement of the cost of + * distribution. This written offer must permit verbatim + * duplication by anyone, or + * C. it is distributed by someone who received only the + * executable form, and is accompanied by a copy of the + * written offer of source code that they received concurrently. + * + * In other words, you are welcome to use, share and improve this + * source file. You are forbidden to forbid anyone else to use, share + * and improve what you give them. + * + * INTERNET: dburger@cs.wisc.edu + * US Mail: 1210 W. Dayton Street, Madison, WI 53706 + * + * $Id: eventq.c,v 1.1.1.1 2000/05/26 15:18:57 taustin Exp $ + * + * $Log: eventq.c,v $ + * Revision 1.1.1.1 2000/05/26 15:18:57 taustin + * SimpleScalar Tool Set + * + * + * Revision 1.4 1998/08/27 08:28:03 taustin + * implemented host interface description in host.h + * added target interface support + * + * Revision 1.3 1997/03/11 01:12:18 taustin + * updated copyright + * + * Revision 1.1 1996/12/05 18:52:32 taustin + * Initial revision + * + * + */ + +#include +#include + +#include "host.h" +#include "misc.h" +#include "machine.h" +#include "eventq.h" + +int eventq_max_events; +int eventq_event_count; +struct eventq_desc *eventq_pending; +struct eventq_desc *eventq_free; + +static EVENTQ_ID_TYPE next_ID = 1; + +void +eventq_init(int max_events) +{ + eventq_max_events = max_events; + eventq_event_count = 0; + eventq_pending = NULL; + eventq_free = NULL; +} + +#define __QUEUE_EVENT(WHEN, ID, ACTION) \ + struct eventq_desc *prev, *ev, *new; \ + /* get a free event descriptor */ \ + if (!eventq_free) \ + { \ + if (eventq_max_events && eventq_event_count >= eventq_max_events) \ + panic("too many events"); \ + eventq_free = calloc(1, sizeof(struct eventq_desc)); \ + } \ + new = eventq_free; \ + eventq_free = eventq_free->next; \ + /* plug in event data */ \ + new->when = (WHEN); (ID) = new->id = next_ID++; ACTION; \ + /* locate insertion point */ \ + for (prev=NULL,ev=eventq_pending; \ + ev && ev->when < when; \ + prev=ev, ev=ev->next); \ + /* insert new record */ \ + if (prev) \ + { \ + /* insert middle or end */ \ + new->next = prev->next; \ + prev->next = new; \ + } \ + else \ + { \ + /* insert beginning */ \ + new->next = eventq_pending; \ + eventq_pending = new; \ + } + +EVENTQ_ID_TYPE +eventq_queue_setbit(SS_TIME_TYPE when, + BITMAP_ENT_TYPE *bmap, int sz, int bitnum) +{ + EVENTQ_ID_TYPE id; + __QUEUE_EVENT(when, id, \ + new->action = EventSetBit; new->data.bit.bmap = bmap; \ + new->data.bit.sz = sz; new->data.bit.bitnum = bitnum); + return id; +} + +EVENTQ_ID_TYPE +eventq_queue_clearbit(SS_TIME_TYPE when, + BITMAP_ENT_TYPE *bmap, int sz, int bitnum) +{ + EVENTQ_ID_TYPE id; + __QUEUE_EVENT(when, id, \ + new->action = EventClearBit; new->data.bit.bmap = bmap; \ + new->data.bit.sz = sz; new->data.bit.bitnum = bitnum); + return id; +} + +EVENTQ_ID_TYPE +eventq_queue_setflag(SS_TIME_TYPE when, int *pflag, int value) +{ + EVENTQ_ID_TYPE id; + __QUEUE_EVENT(when, id, \ + new->action = EventSetFlag; \ + new->data.flag.pflag = pflag; new->data.flag.value = value); + return id; +} + +EVENTQ_ID_TYPE +eventq_queue_addop(SS_TIME_TYPE when, int *summand, int addend) +{ + EVENTQ_ID_TYPE id; + __QUEUE_EVENT(when, id, \ + new->action = EventAddOp; \ + new->data.addop.summand = summand; \ + new->data.addop.addend = addend); + return id; +} + +EVENTQ_ID_TYPE +eventq_queue_callback(SS_TIME_TYPE when, + void (*fn)(SS_TIME_TYPE time, int arg), int arg) +{ + EVENTQ_ID_TYPE id; + __QUEUE_EVENT(when, id, \ + new->action = EventCallback; new->data.callback.fn = fn;\ + new->data.callback.arg = arg); + return id; +} + +#define EXECUTE_ACTION(ev, now) \ + /* execute action */ \ + switch (ev->action) { \ + case EventSetBit: \ + BITMAP_SET(ev->data.bit.bmap, ev->data.bit.sz, ev->data.bit.bitnum);\ + break; \ + case EventClearBit: \ + BITMAP_CLEAR(ev->data.bit.bmap, ev->data.bit.sz, ev->data.bit.bitnum);\ + break; \ + case EventSetFlag: \ + *ev->data.flag.pflag = ev->data.flag.value; \ + break; \ + case EventAddOp: \ + *ev->data.addop.summand += ev->data.addop.addend; \ + break; \ + case EventCallback: \ + (*ev->data.callback.fn)(now, ev->data.callback.arg); \ + break; \ + default: \ + panic("bogus event action"); \ + } + +/* execute an event immediately, returns non-zero if the event was + located an deleted */ +int +eventq_execute(EVENTQ_ID_TYPE id) +{ + struct eventq_desc *prev, *ev; + + for (prev=NULL,ev=eventq_pending; ev; prev=ev,ev=ev->next) + { + if (ev->id == id) + { + if (prev) + { + /* middle of end of list */ + prev->next = ev->next; + } + else /* !prev */ + { + /* beginning of list */ + eventq_pending = ev->next; + } + + /* handle action, now is munged */ + EXECUTE_ACTION(ev, 0); + + /* put event on free list */ + ev->next = eventq_free; + eventq_free = ev; + + /* return success */ + return TRUE; + } + } + /* not found */ + return FALSE; +} + +/* remove an event from the eventq, action is never performed, returns + non-zero if the event was located an deleted */ +int +eventq_remove(EVENTQ_ID_TYPE id) +{ + struct eventq_desc *prev, *ev; + + for (prev=NULL,ev=eventq_pending; ev; prev=ev,ev=ev->next) + { + if (ev->id == id) + { + if (prev) + { + /* middle of end of list */ + prev->next = ev->next; + } + else /* !prev */ + { + /* beginning of list */ + eventq_pending = ev->next; + } + + /* put event on free list */ + ev->next = eventq_free; + eventq_free = ev; + + /* return success */ + return TRUE; + } + } + /* not found */ + return FALSE; +} + +void +eventq_service_events(SS_TIME_TYPE now) +{ + while (eventq_pending && eventq_pending->when <= now) + { + struct eventq_desc *ev = eventq_pending; + + /* handle action */ + EXECUTE_ACTION(ev, now); + + /* return the event record to the free list */ + eventq_pending = ev->next; + ev->next = eventq_free; + eventq_free = ev; + } +} + +void +eventq_dump(FILE *stream) +{ + struct eventq_desc *ev; + + if (!stream) + stream = stderr; + + fprintf(stream, "Pending Events: "); + for (ev=eventq_pending; ev; ev=ev->next) + { + fprintf(stream, "@ %.0f:%s:", + (double)ev->when, + ev->action == EventSetBit ? "set bit" + : ev->action == EventClearBit ? "clear bit" + : ev->action == EventSetFlag ? "set flag" + : ev->action == EventAddOp ? "add operation" + : ev->action == EventCallback ? "call back" + : (abort(), "")); + switch (ev->action) { + case EventSetBit: + case EventClearBit: + fprintf(stream, "0x%p, %d, %d", + ev->data.bit.bmap, ev->data.bit.sz, ev->data.bit.bitnum); + break; + case EventSetFlag: + fprintf(stream, "0x%p, %d", ev->data.flag.pflag, ev->data.flag.value); + break; + case EventAddOp: + fprintf(stream, "0x%p, %d", + ev->data.addop.summand, ev->data.addop.addend); + break; + case EventCallback: + fprintf(stream, "0x%p, %d", + ev->data.callback.fn, ev->data.callback.arg); + break; + default: + panic("bogus event action"); + } + fprintf(stream, " "); + } +} diff --git a/code/validation/C/0104560_jsonr.c b/code/validation/C/0104560_jsonr.c new file mode 100644 index 0000000000000000000000000000000000000000..aaca28d2372ce0c6f06a4821b1b3960d06c6119e --- /dev/null +++ b/code/validation/C/0104560_jsonr.c @@ -0,0 +1,146 @@ +#include "json.h" +#include "adaboost.h" + +char* readJson() +{ + FILE* file = NULL; + file = fopen("training.json", "r"); + + if (file == NULL) + { + return NULL; + } + else + { + fseek(file, 0, SEEK_END); + long fsize = ftell(file); + fseek(file, 0, SEEK_SET); + + char *string = malloc(fsize + 1); + fread(string, fsize, 1, file); + fclose(file); + + string[fsize] = 0; + + return string; + } +} + + +SCList* dbExtract() +{ + char* str = readJson(); + + if (str == NULL) + { + printf("error: can not read training database\n"); + // HERE IS A EXIT(0) JUST HERE !!! IN CASE OF BUG, REMOVE IT !!! + exit(0); + } + else + { + json_object *jobj = json_tokener_parse(str); + return jsonToStrongClassifierList(jobj); + } +} + + +SCList* jsonToStrongClassifierList(json_object* jStrongList) +{ + int len = json_object_array_length(jStrongList); + + SCList *old = NULL; + + for (int i = len - 1; i >= 0; i--) + { + json_object *jStrongElt; + jStrongElt = json_object_array_get_idx(jStrongList, i); + + SCList *strongList = malloc(sizeof(SCList));; + + strongList->sc = jsonToStrongClassifier(jStrongElt); + strongList->next = old; + + old = strongList; + } + + return old; + +} + + +StrongClassifier jsonToStrongClassifier(json_object *jStrongClass) +{ + StrongClassifier strongClass; + + json_object *jWeakL, *jTotalT, *jFalseNegative, *jWeakNumber; + json_object_object_get_ex(jStrongClass, "weak_classifier_list", &jWeakL); + json_object_object_get_ex(jStrongClass, "total_threshold", &jTotalT); + json_object_object_get_ex(jStrongClass, "false_negative", &jFalseNegative); + json_object_object_get_ex(jStrongClass, "weak_number", &jWeakNumber); + + strongClass.weak = jsonToWeakClassifierList(jWeakL); + strongClass.totalThreshold = json_object_get_double(jTotalT); + strongClass.falseNegative = json_object_get_double(jFalseNegative); + strongClass.weakNumber = json_object_get_int(jWeakNumber); + + return strongClass; +} + + +ClassifierList* jsonToWeakClassifierList(json_object *jWeakList) +{ + int len = json_object_array_length(jWeakList); + + ClassifierList *old = NULL; + + for (int i = len - 1; i >= 0; i--) + { + json_object *jWeakElt, *jWeight, *jWeakClass; + jWeakElt = json_object_array_get_idx(jWeakList, i); + + json_object_object_get_ex(jWeakElt, "weight", &jWeight); + json_object_object_get_ex(jWeakElt, "weak_classifier", &jWeakClass); + + + + ClassifierList *weakList = malloc(sizeof(ClassifierList));; + weakList->weight = json_object_get_double(jWeight); + + weakList->class = jsonToWeakClassifier(jWeakClass); + weakList->next = old; + + old = weakList; + } + + return old; +} + + +WeakClassifier jsonToWeakClassifier(json_object *jWeakClass) +{ + WeakClassifier weakClass; + + json_object *jXmin, *jYmin, *jXmax, *jYmax, *jType, *jParity, *jThreshold; + json_object_object_get_ex(jWeakClass, "xmin", &jXmin); + json_object_object_get_ex(jWeakClass, "ymin", &jYmin); + json_object_object_get_ex(jWeakClass, "xmax", &jXmax); + json_object_object_get_ex(jWeakClass, "ymax", &jYmax); + + json_object_object_get_ex(jWeakClass, "type", &jType); + json_object_object_get_ex(jWeakClass, "parity", &jParity); + json_object_object_get_ex(jWeakClass, "threshold", &jThreshold); + + + weakClass.xmin = json_object_get_int(jXmin); + weakClass.ymin = json_object_get_int(jYmin); + weakClass.xmax = json_object_get_int(jXmax); + weakClass.ymax = json_object_get_int(jYmax); + + weakClass.type = json_object_get_int(jType); + weakClass.parity = json_object_get_int(jParity); + weakClass.threshold = json_object_get_double(jThreshold); + + return weakClass; +} + diff --git a/code/validation/C/0104769_stable_plot.c b/code/validation/C/0104769_stable_plot.c new file mode 100644 index 0000000000000000000000000000000000000000..0bd629f2fddd8a88e1b7315a60c830d86bd5a817 --- /dev/null +++ b/code/validation/C/0104769_stable_plot.c @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2015 - Naudit High Performance Computing and Networking + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or (at + * your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; If not, see . + */ + +#include +#include +#include +#include "stable_api.h" +#include "benchmarking.h" +#include "opencl_integ.h" + +#define XI_TH 0.01 +// #define AROUND_XI + +int main(int argc, char **argv) +{ + double alfa = 1.2; + double beta = 0.1; + int param = 0; + double sigma = 1.0, mu = 0.0; + double min_x_range; + double max_x_range; + double xi; + int num_samples = 8000; + double *x; + double *pdf, *cpu_pdf; + double *errs, *cpu_errs; + double x_step_size; + StableDist* dist; + double abserr = 0, relerr = 0, cpu_err = 0, gpu_err = 0; + double abserr_v = 0, relerr_v = 0, cpu_err_v = 0, gpu_err_v = 0; + int i; + + if (argc == 3) { + alfa = strtod(argv[1], NULL); + beta = strtod(argv[2], NULL); + } + + xi = - beta * tan(alfa * M_PI_2); + + stable_set_XXI_TH(1.0 * XI_TH); +#ifdef AROUND_XI + min_x_range = xi - XI_TH; + max_x_range = xi + XI_TH; +#else + min_x_range = -3; + max_x_range = 3; +#endif + + x_step_size = ((double)(max_x_range - min_x_range)) / (double) num_samples; + + dist = stable_create(alfa, beta, sigma, mu, param); + x = calloc(num_samples, sizeof(double)); + pdf = calloc(num_samples, sizeof(double)); + cpu_pdf = calloc(num_samples, sizeof(double)); + errs = calloc(num_samples, sizeof(double)); + cpu_errs = calloc(num_samples, sizeof(double)); + + if (!dist) { + fprintf(stderr, "StableDist creation failure. Aborting.\n"); + return 1; + } + + for (i = 0; i < num_samples; i++) + x[i] = min_x_range + x_step_size * i; + + if (stable_activate_gpu(dist)) { + fprintf(stderr, "Couldn't initialize GPU.\n"); + return 1; + } + + + stable_pdf(dist, x, num_samples, cpu_pdf, cpu_errs); + stable_pdf_gpu(dist, x, num_samples, pdf, errs); + + for (i = 0; i < num_samples; i++) { + abserr += fabs(pdf[i] - cpu_pdf[i]); + abserr_v += (fabs(pdf[i] - cpu_pdf[i])) * (fabs(pdf[i] - cpu_pdf[i])); + relerr += fabs(pdf[i] - cpu_pdf[i]) / cpu_pdf[i]; + relerr_v += (fabs(pdf[i] - cpu_pdf[i]) / cpu_pdf[i]) * (fabs(pdf[i] - cpu_pdf[i]) / cpu_pdf[i]); + cpu_err += cpu_errs[i]; + cpu_err_v += (cpu_errs[i]) * (cpu_errs[i]); + gpu_err += errs[i]; + gpu_err_v += (errs[i]) * (errs[i]); + printf("%lf %lf %lf %lf %lf\n", x[i], pdf[i], cpu_pdf[i], errs[i], cpu_errs[i]); + } + + abserr /= num_samples; + abserr_v = sqrt((abserr_v / num_samples - abserr * abserr) * num_samples / (num_samples - 1)); + relerr /= num_samples; + relerr_v = sqrt((relerr_v / num_samples - relerr * relerr) * num_samples / (num_samples - 1)); + cpu_err /= num_samples; + cpu_err_v = sqrt((cpu_err_v / num_samples - cpu_err * cpu_err) * num_samples / (num_samples - 1)); + gpu_err /= num_samples; + gpu_err_v = sqrt((gpu_err_v / num_samples - gpu_err * gpu_err) * num_samples / (num_samples - 1)); + + fprintf(stderr, "Average absolute error: %g ± %g\n", abserr, abserr_v); + fprintf(stderr, "Average relative error: %g ± %g\n", relerr, relerr_v); + fprintf(stderr, "Average cpu error: %g ± %g\n", cpu_err, cpu_err_v); + fprintf(stderr, "Average gpu error: %g ± %g\n", gpu_err, gpu_err_v); + fprintf(stderr, "ξ is %g\n", xi); + + stable_free(dist); + return 0; +} diff --git a/code/validation/C/0109746_freeaddrinfo.c b/code/validation/C/0109746_freeaddrinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..3e64a9ae733feb36bd1a3215889c950e4b2002d6 --- /dev/null +++ b/code/validation/C/0109746_freeaddrinfo.c @@ -0,0 +1,56 @@ +/* $NetBSD: freeaddrinfo.c,v 1.1.1.1 2011/04/13 18:15:41 elric Exp $ */ + +/* + * Copyright (c) 1999 - 2001 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE 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 + +#include + +/* + * free the list of `struct addrinfo' starting at `ai' + */ + +ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL +freeaddrinfo(struct addrinfo *ai) +{ + struct addrinfo *tofree; + + while(ai != NULL) { + free (ai->ai_canonname); + free (ai->ai_addr); + tofree = ai; + ai = ai->ai_next; + free (tofree); + } +} diff --git a/code/validation/C/0109750_main.c b/code/validation/C/0109750_main.c new file mode 100644 index 0000000000000000000000000000000000000000..da34dc74db88c3707854469aa7deb2730b2de3b8 --- /dev/null +++ b/code/validation/C/0109750_main.c @@ -0,0 +1,164 @@ +/** + ****************************************************************************** + * @file FSMC/SRAM/main.c + * @author MCD Application Team + * @version V1.1.1 + * @date 13-April-2012 + * @brief Main program body + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2012 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 + * + * 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l152d_eval_fsmc_sram.h" +#include "stm32l152d_eval.h" + +/** @addtogroup STM32L1xx_StdPeriph_Examples + * @{ + */ + +/** @addtogroup FSMC_SRAM + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define BUFFER_SIZE 0x400 +#define WRITE_READ_ADDR 0x8000 + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +uint16_t TxBuffer[BUFFER_SIZE]; +uint16_t RxBuffer[BUFFER_SIZE]; +uint32_t WriteReadStatus = 0, Index = 0; + +/* Private function prototypes -----------------------------------------------*/ +void Fill_Buffer(uint16_t *pBuffer, uint16_t BufferLenght, uint32_t Offset); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Main program. + * @param None + * @retval None + */ +int main(void) +{ + /*!< At this stage the microcontroller clock setting is already configured, + this is done through SystemInit() function which is called from startup + file (startup_stm32l1xx_xx.s) before to branch to application main. + To reconfigure the default setting of SystemInit() function, refer to + system_stm32l1xx.c file + */ + + /* Initialize Leds mounted on STM32LXX-EVAL board */ + STM_EVAL_LEDInit(LED1); + STM_EVAL_LEDInit(LED2); + + /* Write/read to/from FSMC SRAM memory *************************************/ + /* Enable the FSMC Clock */ + RCC_AHBPeriphClockCmd(RCC_AHBPeriph_FSMC, ENABLE); + + /* Configure FSMC Bank1 NOR/SRAM3 */ + SRAM_Init(); + + /* Write data to FSMC SRAM memory */ + /* Fill the buffer to send */ + Fill_Buffer(TxBuffer, BUFFER_SIZE, 0x3212); + SRAM_WriteBuffer(TxBuffer, WRITE_READ_ADDR, BUFFER_SIZE); + + + /* Read data from FSMC SRAM memory */ + SRAM_ReadBuffer(RxBuffer, WRITE_READ_ADDR, BUFFER_SIZE); + + /* Read back SRAM memory and check content correctness */ + for (Index = 0x00; (Index < BUFFER_SIZE) && (WriteReadStatus == 0); Index++) + { + if (RxBuffer[Index] != TxBuffer[Index]) + { + WriteReadStatus = Index + 1; + } + } + + if (WriteReadStatus == 0) + { + /* OK */ + /* Turn on LED1 */ + STM_EVAL_LEDOn(LED1); + } + else + { + /* KO */ + /* Turn on LED2 */ + STM_EVAL_LEDOn(LED2); + } + + while (1) + { + } +} + +/** + * @brief Fill the global buffer + * @param pBuffer: pointer on the Buffer to fill + * @param BufferSize: size of the buffer to fill + * @param Offset: first value to fill on the Buffer + */ +void Fill_Buffer(uint16_t *pBuffer, uint16_t BufferLenght, uint32_t Offset) +{ + uint16_t IndexTmp = 0; + + /* Put in global buffer same values */ + for (IndexTmp = 0; IndexTmp < BufferLenght; IndexTmp++ ) + { + pBuffer[IndexTmp] = IndexTmp + Offset; + } +} + +#ifdef USE_FULL_ASSERT + +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t* file, uint32_t line) +{ + /* User can add his own implementation to report the file name and line number, + ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + + /* Infinite loop */ + while (1) + { + } +} + +#endif + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/code/validation/C/0109878_pwdfile.c b/code/validation/C/0109878_pwdfile.c new file mode 100644 index 0000000000000000000000000000000000000000..36ba8da75bc0ae01f2b4ba595e4b1fb740d80435 --- /dev/null +++ b/code/validation/C/0109878_pwdfile.c @@ -0,0 +1,208 @@ +/* + * foo-tools, a collection of utilities for glftpd users. + * Copyright (C) 2003 Tanesha FTPD Project, www.tanesha.net + * + * This file is part of foo-tools. + * + * foo-tools is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * foo-tools is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with foo-tools; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + + +#include +#include +#include +#include +#include +#include "stringtokenizer.h" +#include "pwdfile.h" + +long pwd_lastupdate = 0; +pwdfile *pwd_userlist = 0; +grpfile_t *pwd_grouplist = 0; +char *_etcdir = 0; + +void _pwd_finalize(pwdfile *l) { + pwdfile *t; + + while (l) { + t = l; + l = l->next; + free(t); + } +} + +void pwd_set_etcdir(char *etcdir) { + if (_etcdir != 0) + free(_etcdir); + + _etcdir = strdup(etcdir); +} + +char *_pwd_get_etcdir() { + if (_etcdir == 0) + _etcdir = strdup(DEFAULT_ETCDIR); + + return _etcdir; +} + +pwdfile *_pwd_reload() { + struct stat stt; + char buf[500], *t, idbuf[10]; + pwdfile *tmp; + linefilereader_t lfr; + stringtokenizer st; + int i; + + sprintf(buf, "%s/%s", _pwd_get_etcdir(), DEFAULT_PASSWD); + + if (stat(buf, &stt) == -1) + return pwd_userlist; + + if (stt.st_mtime == pwd_lastupdate) + return pwd_userlist; + +#ifdef DEBUG + printf("Debug -> passwd file loading ..\n"); +#endif + + _pwd_finalize(pwd_userlist); + + if (lfr_open(&lfr, buf) < 0) + return pwd_userlist; + + while (lfr_getline(&lfr, buf, 300) > -1) { + + st_initialize(&st, buf, ":"); + + if (st_count(&st) != 7) { + st_finalize(&st); + continue; + } + + tmp = (pwdfile*)malloc(sizeof(pwdfile)); + + strcpy(tmp->name, st_next(&st)); + strcpy(tmp->pass, st_next(&st)); + + strcpy(idbuf, st_next(&st)); + tmp->uid = atoi(idbuf); + + strcpy(idbuf, st_next(&st)); + tmp->gid = atoi(idbuf); + + strcpy(tmp->longname, st_next(&st)); + strcpy(tmp->homedir, st_next(&st)); + strcpy(tmp->shell, st_next(&st)); + + tmp->next = pwd_userlist; + pwd_userlist = tmp; + } + + lfr_close(&lfr); + + pwd_lastupdate = stt.st_mtime; + + return pwd_userlist; +} + +pwdfile *pwd_getpwnam(char *u) { + pwdfile *tmp = 0; + + pwd_userlist = _pwd_reload(); + + for (tmp = pwd_userlist; tmp; tmp = tmp->next) + if (!strcmp(tmp->name, u)) + break; + + return tmp; +} + +pwdfile *pwd_getpwuid(int uid) { + pwdfile *tmp = 0; + + pwd_userlist = _pwd_reload(); + + for (tmp = pwd_userlist; tmp; tmp = tmp->next) + if (tmp->uid == uid) + break; + + return tmp; +} + +grpfile_t *_pwd_grpreload() { + linefilereader_t lfr; + char buf[300], gidbuf[30]; + stringtokenizer st; + grpfile_t *tmp = 0; + + if (pwd_grouplist) + return pwd_grouplist; + + sprintf(buf, "%s/%s", _pwd_get_etcdir(), DEFAULT_GROUP); + + if (lfr_open(&lfr, buf) < 0) + return 0; + + while (lfr_getline(&lfr, buf, 300) > 0) { + st_initialize(&st, buf, ":"); + + if (st_count(&st) < 3) { + st_finalize(&st); + continue; + } + + tmp = (grpfile_t*)malloc(sizeof(grpfile_t)); + + strcpy(tmp->group, st_next(&st)); + strcpy(tmp->pass, st_next(&st)); + strcpy(gidbuf, st_next(&st)); + + if (st_hasnext(&st)) + tmp->users = strdup(st_next(&st)); + else + tmp->users = 0; + + tmp->gid = atoi(gidbuf); + + tmp->next = pwd_grouplist; + + pwd_grouplist = tmp; + + st_finalize(&st); + } + lfr_close(&lfr); + + return pwd_grouplist; +} + +grpfile_t *pwd_getgpnam(char *g) { + grpfile_t *t = 0; + + for (t = _pwd_grpreload(); t; t = t->next) + if (!strcmp(t->group, g)) + break; + + return t; +} + +grpfile_t *pwd_getgpgid(int gid) { + grpfile_t *t; + + for (t = _pwd_grpreload(); t; t = t->next) + if (t->gid == gid) + break; + + return t; +} diff --git a/code/validation/C/0111228_rwsem.c b/code/validation/C/0111228_rwsem.c new file mode 100644 index 0000000000000000000000000000000000000000..b080b2d3fde9c17323b741beb6ffd09512072b02 --- /dev/null +++ b/code/validation/C/0111228_rwsem.c @@ -0,0 +1,292 @@ +/* rwsem.c: R/W semaphores: contention handling functions + * + * Written by David Howells (dhowells@redhat.com). + * Derived from arch/i386/kernel/semaphore.c + * + * Writer lock-stealing by Alex Shi + * and Michel Lespinasse + */ +#include +#include +#include +#include +#include + +/* + * Initialize an rwsem: + */ +void __init_rwsem(struct rw_semaphore *sem, const char *name, + struct lock_class_key *key) +{ +#ifdef CONFIG_DEBUG_LOCK_ALLOC + /* + * Make sure we are not reinitializing a held semaphore: + */ + debug_check_no_locks_freed((void *)sem, sizeof(*sem)); + lockdep_init_map(&sem->dep_map, name, key, 0); +#endif + sem->count = RWSEM_UNLOCKED_VALUE; + spin_lock_init(&sem->wait_lock); + INIT_LIST_HEAD(&sem->wait_list); +} + +EXPORT_SYMBOL(__init_rwsem); + +enum rwsem_waiter_type { + RWSEM_WAITING_FOR_WRITE, + RWSEM_WAITING_FOR_READ +}; + +struct rwsem_waiter { + struct list_head list; + struct task_struct *task; + enum rwsem_waiter_type type; +}; + +enum rwsem_wake_type { + RWSEM_WAKE_ANY, /* Wake whatever's at head of wait list */ + RWSEM_WAKE_READERS, /* Wake readers only */ + RWSEM_WAKE_READ_OWNED /* Waker thread holds the read lock */ +}; + +/* + * handle the lock release when processes blocked on it that can now run + * - if we come here from up_xxxx(), then: + * - the 'active part' of count (&0x0000ffff) reached 0 (but may have changed) + * - the 'waiting part' of count (&0xffff0000) is -ve (and will still be so) + * - there must be someone on the queue + * - the spinlock must be held by the caller + * - woken process blocks are discarded from the list after having task zeroed + * - writers are only woken if downgrading is false + */ +static struct rw_semaphore * +__rwsem_do_wake(struct rw_semaphore *sem, enum rwsem_wake_type wake_type) +{ + struct rwsem_waiter *waiter; + struct task_struct *tsk; + struct list_head *next; + long oldcount, woken, loop, adjustment; + + waiter = list_entry(sem->wait_list.next, struct rwsem_waiter, list); + if (waiter->type == RWSEM_WAITING_FOR_WRITE) { + if (wake_type == RWSEM_WAKE_ANY) + /* Wake writer at the front of the queue, but do not + * grant it the lock yet as we want other writers + * to be able to steal it. Readers, on the other hand, + * will block as they will notice the queued writer. + */ + wake_up_process(waiter->task); + goto out; + } + + /* Writers might steal the lock before we grant it to the next reader. + * We prefer to do the first reader grant before counting readers + * so we can bail out early if a writer stole the lock. + */ + adjustment = 0; + if (wake_type != RWSEM_WAKE_READ_OWNED) { + adjustment = RWSEM_ACTIVE_READ_BIAS; + try_reader_grant: + oldcount = rwsem_atomic_update(adjustment, sem) - adjustment; + if (unlikely(oldcount < RWSEM_WAITING_BIAS)) { + /* A writer stole the lock. Undo our reader grant. */ + if (rwsem_atomic_update(-adjustment, sem) & + RWSEM_ACTIVE_MASK) + goto out; + /* Last active locker left. Retry waking readers. */ + goto try_reader_grant; + } + } + + /* Grant an infinite number of read locks to the readers at the front + * of the queue. Note we increment the 'active part' of the count by + * the number of readers before waking any processes up. + */ + woken = 0; + do { + woken++; + + if (waiter->list.next == &sem->wait_list) + break; + + waiter = list_entry(waiter->list.next, + struct rwsem_waiter, list); + + } while (waiter->type != RWSEM_WAITING_FOR_WRITE); + + adjustment = woken * RWSEM_ACTIVE_READ_BIAS - adjustment; + if (waiter->type != RWSEM_WAITING_FOR_WRITE) + /* hit end of list above */ + adjustment -= RWSEM_WAITING_BIAS; + + if (adjustment) + rwsem_atomic_add(adjustment, sem); + + next = sem->wait_list.next; + loop = woken; + do { + waiter = list_entry(next, struct rwsem_waiter, list); + next = waiter->list.next; + tsk = waiter->task; + smp_mb(); + waiter->task = NULL; + wake_up_process(tsk); + put_task_struct(tsk); + } while (--loop); + + sem->wait_list.next = next; + next->prev = &sem->wait_list; + + out: + return sem; +} + +/* + * wait for the read lock to be granted + */ +struct rw_semaphore __sched *rwsem_down_read_failed(struct rw_semaphore *sem) +{ + long count, adjustment = -RWSEM_ACTIVE_READ_BIAS; + struct rwsem_waiter waiter; + struct task_struct *tsk = current; + + /* set up my own style of waitqueue */ + waiter.task = tsk; + waiter.type = RWSEM_WAITING_FOR_READ; + get_task_struct(tsk); + + spin_lock_irq(&sem->wait_lock); + if (list_empty(&sem->wait_list)) + adjustment += RWSEM_WAITING_BIAS; + list_add_tail(&waiter.list, &sem->wait_list); + + /* we're now waiting on the lock, but no longer actively locking */ + count = rwsem_atomic_update(adjustment, sem); + + /* If there are no active locks, wake the front queued process(es). + * + * If there are no writers and we are first in the queue, + * wake our own waiter to join the existing active readers ! + */ + if (count == RWSEM_WAITING_BIAS || + (count > RWSEM_WAITING_BIAS && + adjustment != -RWSEM_ACTIVE_READ_BIAS)) + sem = __rwsem_do_wake(sem, RWSEM_WAKE_ANY); + + spin_unlock_irq(&sem->wait_lock); + + /* wait to be given the lock */ + while (true) { + set_task_state(tsk, TASK_UNINTERRUPTIBLE); + if (!waiter.task) + break; + schedule(); + } + + tsk->state = TASK_RUNNING; + + return sem; +} + +/* + * wait until we successfully acquire the write lock + */ +struct rw_semaphore __sched *rwsem_down_write_failed(struct rw_semaphore *sem) +{ + long count, adjustment = -RWSEM_ACTIVE_WRITE_BIAS; + struct rwsem_waiter waiter; + struct task_struct *tsk = current; + + /* set up my own style of waitqueue */ + waiter.task = tsk; + waiter.type = RWSEM_WAITING_FOR_WRITE; + + spin_lock_irq(&sem->wait_lock); + if (list_empty(&sem->wait_list)) + adjustment += RWSEM_WAITING_BIAS; + list_add_tail(&waiter.list, &sem->wait_list); + + /* we're now waiting on the lock, but no longer actively locking */ + count = rwsem_atomic_update(adjustment, sem); + + /* If there were already threads queued before us and there are no + * active writers, the lock must be read owned; so we try to wake + * any read locks that were queued ahead of us. */ + if (count > RWSEM_WAITING_BIAS && + adjustment == -RWSEM_ACTIVE_WRITE_BIAS) + sem = __rwsem_do_wake(sem, RWSEM_WAKE_READERS); + + /* wait until we successfully acquire the lock */ + set_task_state(tsk, TASK_UNINTERRUPTIBLE); + while (true) { + if (!(count & RWSEM_ACTIVE_MASK)) { + /* Try acquiring the write lock. */ + count = RWSEM_ACTIVE_WRITE_BIAS; + if (!list_is_singular(&sem->wait_list)) + count += RWSEM_WAITING_BIAS; + if (cmpxchg(&sem->count, RWSEM_WAITING_BIAS, count) == + RWSEM_WAITING_BIAS) + break; + } + + spin_unlock_irq(&sem->wait_lock); + + /* Block until there are no active lockers. */ + do { + schedule(); + set_task_state(tsk, TASK_UNINTERRUPTIBLE); + } while ((count = sem->count) & RWSEM_ACTIVE_MASK); + + spin_lock_irq(&sem->wait_lock); + } + + list_del(&waiter.list); + spin_unlock_irq(&sem->wait_lock); + tsk->state = TASK_RUNNING; + + return sem; +} + +/* + * handle waking up a waiter on the semaphore + * - up_read/up_write has decremented the active part of count if we come here + */ +struct rw_semaphore *rwsem_wake(struct rw_semaphore *sem) +{ + unsigned long flags; + + spin_lock_irqsave(&sem->wait_lock, flags); + + /* do nothing if list empty */ + if (!list_empty(&sem->wait_list)) + sem = __rwsem_do_wake(sem, RWSEM_WAKE_ANY); + + spin_unlock_irqrestore(&sem->wait_lock, flags); + + return sem; +} + +/* + * downgrade a write lock into a read lock + * - caller incremented waiting part of count and discovered it still negative + * - just wake up any readers at the front of the queue + */ +struct rw_semaphore *rwsem_downgrade_wake(struct rw_semaphore *sem) +{ + unsigned long flags; + + spin_lock_irqsave(&sem->wait_lock, flags); + + /* do nothing if list empty */ + if (!list_empty(&sem->wait_list)) + sem = __rwsem_do_wake(sem, RWSEM_WAKE_READ_OWNED); + + spin_unlock_irqrestore(&sem->wait_lock, flags); + + return sem; +} + +EXPORT_SYMBOL(rwsem_down_read_failed); +EXPORT_SYMBOL(rwsem_down_write_failed); +EXPORT_SYMBOL(rwsem_wake); +EXPORT_SYMBOL(rwsem_downgrade_wake); diff --git a/code/validation/C/0113435_s3c24xx_uda134x.c b/code/validation/C/0113435_s3c24xx_uda134x.c new file mode 100644 index 0000000000000000000000000000000000000000..7853fbe6ccc92b6785bef74a913add08655b22ec --- /dev/null +++ b/code/validation/C/0113435_s3c24xx_uda134x.c @@ -0,0 +1,253 @@ +/* + * Modifications by Christian Pellegrin + * + * s3c24xx_uda134x.c -- S3C24XX_UDA134X ALSA SoC Audio board driver + * + * Copyright 2007 Dension Audio Systems Ltd. + * Author: Zoltan Devai + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include + +#include +#include + +#include "regs-iis.h" + +#include "s3c24xx-i2s.h" + +/* #define ENFORCE_RATES 1 */ +/* + Unfortunately the S3C24XX in master mode has a limited capacity of + generating the clock for the codec. If you define this only rates + that are really available will be enforced. But be careful, most + user level application just want the usual sampling frequencies (8, + 11.025, 22.050, 44.1 kHz) and anyway resampling is a costly + operation for embedded systems. So if you aren't very lucky or your + hardware engineer wasn't very forward-looking it's better to leave + this undefined. If you do so an approximate value for the requested + sampling rate in the range -/+ 5% will be chosen. If this in not + possible an error will be returned. +*/ + +static struct clk *xtal; +static struct clk *pclk; +/* this is need because we don't have a place where to keep the + * pointers to the clocks in each substream. We get the clocks only + * when we are actually using them so we don't block stuff like + * frequency change or oscillator power-off */ +static int clk_users; +static DEFINE_MUTEX(clk_lock); + +static unsigned int rates[33 * 2]; +#ifdef ENFORCE_RATES +static struct snd_pcm_hw_constraint_list hw_constraints_rates = { + .count = ARRAY_SIZE(rates), + .list = rates, + .mask = 0, +}; +#endif + +static int s3c24xx_uda134x_startup(struct snd_pcm_substream *substream) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *cpu_dai = rtd->cpu_dai; +#ifdef ENFORCE_RATES + struct snd_pcm_runtime *runtime = substream->runtime; +#endif + int ret = 0; + + mutex_lock(&clk_lock); + + if (clk_users == 0) { + xtal = clk_get(rtd->dev, "xtal"); + if (IS_ERR(xtal)) { + dev_err(rtd->dev, "%s cannot get xtal\n", __func__); + ret = PTR_ERR(xtal); + } else { + pclk = clk_get(cpu_dai->dev, "iis"); + if (IS_ERR(pclk)) { + dev_err(rtd->dev, "%s cannot get pclk\n", + __func__); + clk_put(xtal); + ret = PTR_ERR(pclk); + } + } + if (!ret) { + int i, j; + + for (i = 0; i < 2; i++) { + int fs = i ? 256 : 384; + + rates[i*33] = clk_get_rate(xtal) / fs; + for (j = 1; j < 33; j++) + rates[i*33 + j] = clk_get_rate(pclk) / + (j * fs); + } + } + } + clk_users += 1; + mutex_unlock(&clk_lock); + if (!ret) { +#ifdef ENFORCE_RATES + ret = snd_pcm_hw_constraint_list(runtime, 0, + SNDRV_PCM_HW_PARAM_RATE, + &hw_constraints_rates); + if (ret < 0) + dev_err(rtd->dev, "%s cannot set constraints\n", + __func__); +#endif + } + return ret; +} + +static void s3c24xx_uda134x_shutdown(struct snd_pcm_substream *substream) +{ + mutex_lock(&clk_lock); + clk_users -= 1; + if (clk_users == 0) { + clk_put(xtal); + xtal = NULL; + clk_put(pclk); + pclk = NULL; + } + mutex_unlock(&clk_lock); +} + +static int s3c24xx_uda134x_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *codec_dai = rtd->codec_dai; + struct snd_soc_dai *cpu_dai = rtd->cpu_dai; + unsigned int clk = 0; + int ret = 0; + int clk_source, fs_mode; + unsigned long rate = params_rate(params); + long err, cerr; + unsigned int div; + int i, bi; + + err = 999999; + bi = 0; + for (i = 0; i < 2*33; i++) { + cerr = rates[i] - rate; + if (cerr < 0) + cerr = -cerr; + if (cerr < err) { + err = cerr; + bi = i; + } + } + if (bi / 33 == 1) + fs_mode = S3C2410_IISMOD_256FS; + else + fs_mode = S3C2410_IISMOD_384FS; + if (bi % 33 == 0) { + clk_source = S3C24XX_CLKSRC_MPLL; + div = 1; + } else { + clk_source = S3C24XX_CLKSRC_PCLK; + div = bi % 33; + } + + dev_dbg(rtd->dev, "%s desired rate %lu, %d\n", __func__, rate, bi); + + clk = (fs_mode == S3C2410_IISMOD_384FS ? 384 : 256) * rate; + + dev_dbg(rtd->dev, "%s will use: %s %s %d sysclk %d err %ld\n", __func__, + fs_mode == S3C2410_IISMOD_384FS ? "384FS" : "256FS", + clk_source == S3C24XX_CLKSRC_MPLL ? "MPLLin" : "PCLK", + div, clk, err); + + if ((err * 100 / rate) > 5) { + dev_err(rtd->dev, "effective frequency too different " + "from desired (%ld%%)\n", err * 100 / rate); + return -EINVAL; + } + + ret = snd_soc_dai_set_sysclk(cpu_dai, clk_source , clk, + SND_SOC_CLOCK_IN); + if (ret < 0) + return ret; + + ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_MCLK, fs_mode); + if (ret < 0) + return ret; + + ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_BCLK, + S3C2410_IISMOD_32FS); + if (ret < 0) + return ret; + + ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_PRESCALER, + S3C24XX_PRESCALE(div, div)); + if (ret < 0) + return ret; + + /* set the codec system clock for DAC and ADC */ + ret = snd_soc_dai_set_sysclk(codec_dai, 0, clk, + SND_SOC_CLOCK_OUT); + if (ret < 0) + return ret; + + return 0; +} + +static struct snd_soc_ops s3c24xx_uda134x_ops = { + .startup = s3c24xx_uda134x_startup, + .shutdown = s3c24xx_uda134x_shutdown, + .hw_params = s3c24xx_uda134x_hw_params, +}; + +static struct snd_soc_dai_link s3c24xx_uda134x_dai_link = { + .name = "UDA134X", + .stream_name = "UDA134X", + .codec_name = "uda134x-codec", + .codec_dai_name = "uda134x-hifi", + .cpu_dai_name = "s3c24xx-iis", + .dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBS_CFS, + .ops = &s3c24xx_uda134x_ops, + .platform_name = "s3c24xx-iis", +}; + +static struct snd_soc_card snd_soc_s3c24xx_uda134x = { + .name = "S3C24XX_UDA134X", + .owner = THIS_MODULE, + .dai_link = &s3c24xx_uda134x_dai_link, + .num_links = 1, +}; + +static int s3c24xx_uda134x_probe(struct platform_device *pdev) +{ + struct snd_soc_card *card = &snd_soc_s3c24xx_uda134x; + int ret; + + platform_set_drvdata(pdev, card); + card->dev = &pdev->dev; + + ret = devm_snd_soc_register_card(&pdev->dev, card); + if (ret) + dev_err(&pdev->dev, "failed to register card: %d\n", ret); + + return ret; +} + +static struct platform_driver s3c24xx_uda134x_driver = { + .probe = s3c24xx_uda134x_probe, + .driver = { + .name = "s3c24xx_uda134x", + }, +}; +module_platform_driver(s3c24xx_uda134x_driver); + +MODULE_AUTHOR("Zoltan Devai, Christian Pellegrin "); +MODULE_DESCRIPTION("S3C24XX_UDA134X ALSA SoC audio driver"); +MODULE_LICENSE("GPL"); diff --git a/code/validation/C/0115294_calls.c b/code/validation/C/0115294_calls.c new file mode 100644 index 0000000000000000000000000000000000000000..adefce197ae52d4b6631e49640a120aa6450e35f --- /dev/null +++ b/code/validation/C/0115294_calls.c @@ -0,0 +1,88 @@ +/* + * calls.c - implements a call to lots of procedures. + * + * Copyright (c) 1997 Phil Maker + * 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. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * Id: calls.c,v 1.1.1.1 1997/11/23 11:45:50 pjm Exp + */ + +#include +#include + +#include + +void calls_add(CALL **head, FUNC fp, void *arg) { + CALL *p; + + if((p = ((CALL *)malloc(sizeof(CALL)))) != 0) { + p->func = fp; + p->arg = arg; + p->next = *head; + *head = p; + } else { /* malloc failed - uhm */ + nana_error("calls_add: out of memory"); + } +} + +void calls_exec(CALL **head, FUNC fp, void *arg) { + CALL *p; + + for(p = *head; p != 0; p = p->next) { + if(((fp == 0) || (fp == p->func)) && + ((arg == 0) || (arg == p->arg))) { + (*(p->func))(p->arg); + } + } +} + +void calls_delete(CALL **head, FUNC fp, void *arg) { + CALL *p, *q, *prev; + + p = *head; + prev = 0; + while(p != 0) { + if(((fp == 0) || (fp == p->func)) && + ((arg == 0) || (arg == p->arg))) { /* p should be deleted */ + if(prev != 0) { /* we have a defined predecessor (not the first node) */ + prev->next = p->next; /* relink over p */ + q = p; /* save p away so we can free it later */ + p = p->next; + /* prev = prev; */ + free(q); + } else { /* first item in the list */ + q = p; + *head = p->next; + p = p->next; + /* prev = prev; */ + free(q); + } + } else { /* p should NOT be deleted */ + prev = p; + p = p->next; + } + } +} + + diff --git a/code/validation/C/0117669_encseq2offset.c b/code/validation/C/0117669_encseq2offset.c new file mode 100644 index 0000000000000000000000000000000000000000..d8b3ac799e720dd58a9afc847abbcad84ae007b6 --- /dev/null +++ b/code/validation/C/0117669_encseq2offset.c @@ -0,0 +1,134 @@ +/* + Copyright (c) 2007 Stefan Kurtz + Copyright (c) 2007 Center for Bioinformatics, University of Hamburg + + Permission to use, copy, modify, and distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#include "core/chardef.h" +#include "spacedef.h" +#include "sarr-def.h" +#include "core/safecast-gen.h" + +unsigned long *gt_encseqtable2sequenceoffsets( + unsigned long *totallength, + GtSpecialcharinfo *specialcharinfo, + const Suffixarray *suffixarraytable, + unsigned int numofindexes) +{ + unsigned int idx; + GtUchar lastofprevious, firstofcurrent; + unsigned long tmplength, numofsequences = 0, *sequenceoffsettable; + uint64_t tmpspecialcharacters, + tmpwildcards, + tmpspecialranges, + tmpwildcardranges, + tmprealspecialranges, + tmprealwildcardranges, + tmpoffset; + + gt_assert(numofindexes > 0); + ALLOCASSIGNSPACE(sequenceoffsettable,NULL,unsigned long,numofindexes); + tmpspecialcharacters = (uint64_t) (numofindexes-1); + tmpwildcards = 0; + tmpspecialranges = 0; + tmpwildcardranges = 0; + tmprealspecialranges = 0; + tmprealwildcardranges = 0; + for (idx=0; idx 0) + { + /* Random access */ + lastofprevious + = gt_encseq_get_encoded_char(suffixarraytable[idx-1].encseq, + tmplength-1, + suffixarraytable[idx - 1].readmode); + /* Random access */ + firstofcurrent + = gt_encseq_get_encoded_char(suffixarraytable[idx].encseq, + 0, + suffixarraytable[idx].readmode); + if (ISSPECIAL(lastofprevious)) + { + if (ISSPECIAL(firstofcurrent)) + { + tmpspecialranges--; + tmprealspecialranges--; + } + } else + { + if (ISNOTSPECIAL(firstofcurrent)) + { + tmpspecialranges++; + tmprealspecialranges++; + } + } + } + tmpoffset = (uint64_t) sequenceoffsettable[idx] + + (uint64_t) gt_encseq_total_length(suffixarraytable[idx].encseq); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmpoffset); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmpspecialcharacters); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmpwildcards); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmpspecialranges); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmpwildcardranges); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmprealspecialranges); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmprealwildcardranges); + printf("# seqlen[%u] = %lu\n", + idx, + gt_encseq_total_length(suffixarraytable[idx].encseq)); + } + tmplength = gt_encseq_total_length(suffixarraytable[numofindexes -1].encseq); + *totallength = sequenceoffsettable[numofindexes-1] + tmplength; + specialcharinfo->specialcharacters = (unsigned long) tmpspecialcharacters; + specialcharinfo->wildcards = (unsigned long) tmpwildcards; + specialcharinfo->specialranges = (unsigned long) tmpspecialranges; + specialcharinfo->wildcardranges = (unsigned long) tmpwildcardranges; + specialcharinfo->realspecialranges = (unsigned long) tmprealspecialranges; + specialcharinfo->realwildcardranges = (unsigned long) tmprealwildcardranges; + specialcharinfo->lengthofspecialprefix + = gt_encseq_lengthofspecialprefix(suffixarraytable[0].encseq); + specialcharinfo->lengthofwildcardprefix + = gt_encseq_lengthofwildcardprefix(suffixarraytable[0].encseq); + specialcharinfo->lengthofspecialsuffix + = gt_encseq_lengthofspecialsuffix(suffixarraytable[idx-1].encseq); + specialcharinfo->lengthofwildcardsuffix + = gt_encseq_lengthofwildcardsuffix(suffixarraytable[idx-1].encseq); + gt_assert(numofsequences > 0); +#ifndef NDEBUG + gt_GtSpecialcharinfo_check(specialcharinfo,numofsequences - 1); +#endif + return sequenceoffsettable; +} diff --git a/code/validation/C/0119403_xps-outline.c b/code/validation/C/0119403_xps-outline.c new file mode 100644 index 0000000000000000000000000000000000000000..c4dda2a1dff36086a64cdca22161725799728dc7 --- /dev/null +++ b/code/validation/C/0119403_xps-outline.c @@ -0,0 +1,145 @@ +#include "mupdf/fitz.h" +#include "xps-imp.h" + +#include +#include + +/* + * Parse the document structure / outline parts referenced from fixdoc relationships. + */ + +static fz_outline * +xps_lookup_last_outline_at_level(fz_context *ctx, xps_document *doc, fz_outline *node, int level, int target_level) +{ + while (node->next) + node = node->next; + if (level == target_level || !node->down) + return node; + return xps_lookup_last_outline_at_level(ctx, doc, node->down, level + 1, target_level); +} + +static fz_outline * +xps_parse_document_outline(fz_context *ctx, xps_document *doc, fz_xml *root) +{ + fz_xml *node; + fz_outline *head = NULL, *entry, *tail; + int last_level = 1, this_level; + for (node = fz_xml_down(root); node; node = fz_xml_next(node)) + { + if (fz_xml_is_tag(node, "OutlineEntry")) + { + char *level = fz_xml_att(node, "OutlineLevel"); + char *target = fz_xml_att(node, "OutlineTarget"); + char *description = fz_xml_att(node, "Description"); + if (!target || !description) + continue; + + entry = fz_new_outline(ctx); + entry->title = Memento_label(fz_strdup(ctx, description), "outline_title"); + entry->uri = Memento_label(fz_strdup(ctx, target), "outline_uri"); + entry->page = xps_lookup_link_target(ctx, (fz_document*)doc, target, NULL, NULL).page; + entry->down = NULL; + entry->next = NULL; + + this_level = level ? atoi(level) : 1; + + if (!head) + { + head = entry; + } + else + { + tail = xps_lookup_last_outline_at_level(ctx, doc, head, 1, this_level); + if (this_level > last_level) + tail->down = entry; + else + tail->next = entry; + } + + last_level = this_level; + } + } + return head; +} + +static fz_outline * +xps_parse_document_structure(fz_context *ctx, xps_document *doc, fz_xml *root) +{ + fz_xml *node; + if (fz_xml_is_tag(root, "DocumentStructure")) + { + node = fz_xml_down(root); + if (node && fz_xml_is_tag(node, "DocumentStructure.Outline")) + { + node = fz_xml_down(node); + if (node && fz_xml_is_tag(node, "DocumentOutline")) + return xps_parse_document_outline(ctx, doc, node); + } + } + return NULL; +} + +static fz_outline * +xps_load_document_structure(fz_context *ctx, xps_document *doc, xps_fixdoc *fixdoc) +{ + xps_part *part; + fz_xml_doc *xml = NULL; + fz_outline *outline = NULL; + + fz_var(xml); + + part = xps_read_part(ctx, doc, fixdoc->outline); + fz_try(ctx) + { + xml = fz_parse_xml(ctx, part->data, 0, 0); + outline = xps_parse_document_structure(ctx, doc, fz_xml_root(xml)); + } + fz_always(ctx) + { + fz_drop_xml(ctx, xml); + xps_drop_part(ctx, doc, part); + } + fz_catch(ctx) + { + fz_rethrow(ctx); + } + + return outline; +} + +fz_outline * +xps_load_outline(fz_context *ctx, fz_document *doc_) +{ + xps_document *doc = (xps_document*)doc_; + xps_fixdoc *fixdoc; + fz_outline *head = NULL, *tail, *outline = NULL; + + for (fixdoc = doc->first_fixdoc; fixdoc; fixdoc = fixdoc->next) + { + if (fixdoc->outline) + { + fz_try(ctx) + { + outline = xps_load_document_structure(ctx, doc, fixdoc); + } + fz_catch(ctx) + { + fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); + outline = NULL; + } + if (!outline) + continue; + + if (!head) + head = outline; + else + { + while (tail->next) + tail = tail->next; + tail->next = outline; + } + tail = outline; + } + } + return head; +} diff --git a/code/validation/C/0119769_LoaderLibrary.c b/code/validation/C/0119769_LoaderLibrary.c new file mode 100644 index 0000000000000000000000000000000000000000..531e0bae3ffbaa6115c80aa1f5972f5ecd4922c4 --- /dev/null +++ b/code/validation/C/0119769_LoaderLibrary.c @@ -0,0 +1,300 @@ +/****************************************************************\ +* * +* Copyright (C) 2007 by Markus Duft * +* * +* This file is part of parity. * +* * +* parity is free software: you can redistribute it and/or modify * +* it under the terms of the GNU Lesser General Public License as * +* published by the Free Software Foundation, either version 3 of * +* the License, or (at your option) any later version. * +* * +* parity is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU Lesser General Public License for more details. * +* * +* You should have received a copy of the GNU Lesser General * +* Public License along with parity. If not, * +* see . * +* * +\****************************************************************/ + +#include "LoaderLibrary.h" +#include "LoaderInit.h" +#include "LoaderLog.h" +#include "LoaderHelper.h" + +#include + +#define LOADER_MAX_ERRORS 64 +#define LOADER_PATHFIELD_LEN 50 + +typedef struct { + const char* path; +} LoaderPathCacheNode; + +typedef struct { + const char* path; + unsigned long error; +} LoaderErrorList; + +static LoaderPathCacheNode* gPathCache = 0; + +static unsigned int gPathCacheCount = 0; + +static void* LibLoad(const char* name, unsigned int strict) +{ + HMODULE handle = 0; + unsigned int i; + LoaderErrorList lst[LOADER_MAX_ERRORS+1]; + unsigned int longest = 0; + + if(!name) { + if (!GetModuleHandleEx(0, NULL, &handle) && LogGetLevel() > LevelWarning) { + unsigned long lastError = GetLastError(); + char* tmp = LoaderFormatErrorMessage(lastError); + LogDebug("error %d querying main module handle (%s)\n", lastError, tmp); + LocalFree(tmp); + SetLastError(lastError); + } + return handle; + } + + for(i = 0; i < gPathCacheCount; ++i) + { + char * ptrTry = HeapAlloc(GetProcessHeap(), 0, lstrlen(name) + lstrlen(gPathCache[i].path) + 2); + + lstrcpyn(ptrTry, gPathCache[i].path, lstrlen(gPathCache[i].path) + 1); + ptrTry[lstrlen(gPathCache[i].path)] = '\\'; + lstrcpyn(&ptrTry[lstrlen(gPathCache[i].path)+1], name, lstrlen(name) + 1); + + handle = LoadLibrary(ptrTry); + + if(!handle && LogGetLevel() > LevelWarning) { + unsigned long lastError = GetLastError(); + char* tmp = LoaderFormatErrorMessage(lastError); + LogDebug("error %d loading '%s' (%s)\n", lastError, ptrTry, tmp); + LocalFree(tmp); + } else + if(!handle && i < LOADER_MAX_ERRORS) { + register int len; + + lst[i].error = GetLastError(); + lst[i].path = gPathCache[i].path; + + len = strlen(lst[i].path); + if(len > longest) + longest = len; + } + + HeapFree(GetProcessHeap(), 0, ptrTry); + + if(handle) { + LogDebug("loaded %s through path cache.\n", name); + return handle; + } + } + + // + // try default lookup + // + handle = LoadLibrary(name); + + if(!handle && LogGetLevel() > LevelWarning) { + unsigned long lastError = GetLastError(); + char* tmp = LoaderFormatErrorMessage(lastError); + LogDebug("error %d loading '%s' (%s)\n", lastError, name, tmp); + LocalFree(tmp); + } else + if(!handle && i < LOADER_MAX_ERRORS) { + lst[i].error = GetLastError(); + lst[i].path = name; + } + + if(handle) + { + LogDebug("loaded %s through windows default lookup or absolute name\n", name); + return handle; + } + + if(strict && LogGetLevel() <= LevelWarning) { + unsigned int y = 0; + char spaces[MAX_PATH]; + + FillMemory(spaces, sizeof(spaces), ' '); + + LogWarning("failed to load %s from following paths (%d in cache):\n", name, gPathCacheCount); + + lst[LOADER_MAX_ERRORS].error = ERROR_MORE_DATA; + lst[LOADER_MAX_ERRORS].path = "..."; + + for(y = 0; y <= i && y <= LOADER_MAX_ERRORS; ++y) { + char* tmp = LoaderFormatErrorMessage(lst[y].error); + register int index = longest - strlen(lst[y].path); + + spaces[index] = 0; + + LogWarning(" * [%s%d] %s%s (%s)\n", + ( lst[y].error < 10000 ? ( lst[y].error < 1000 ? ( lst[y].error < 100 ? ( lst[y].error < 10 ? " " : " " ) : " ") : " ") : ""), + lst[y].error, lst[y].path, spaces, tmp); + + spaces[index] = ' '; + + LocalFree(tmp); + } + } + + return 0; +} + +static const char* LibStrChr(const char* ptr, char c) +{ + while(*ptr != '\0' && *ptr != c) ++ptr; + + if(*ptr == c) + return ptr; + + return 0; +} + +static void LibCreatePathCache() +{ + unsigned int szLdLib = 0; + const char* ptrRPath = ParityLoaderGetGeneratedRunPath(); + + // + // first lookup from LD_LIBRARY_PATH! + // this has the effect, that LD_LIBRARY_PATH + // is searched before the runpaths. (for libtool: + // shlibpath_overrides_runpath = yes!). This saves + // us from relinking all the time. + // + szLdLib = GetEnvironmentVariable("LD_LIBRARY_PATH", 0, 0); + + if(szLdLib > 1) + { + char* ptrLdLib = HeapAlloc(GetProcessHeap(), 0, szLdLib); + char* start = 0; + char* end = 0; + + if(!GetEnvironmentVariable("LD_LIBRARY_PATH", ptrLdLib, szLdLib)) + { + LogWarning("cannot get environment variable LD_LIBRARY_PATH!\n"); + } else { + char pSep = ':'; + start = ptrLdLib; + end = ptrLdLib; + + if(LibStrChr(ptrLdLib, ';') || LibStrChr(ptrLdLib, '\\')) + pSep = ';'; + + LogDebug("adding LD_LIBRARY_PATH to path cache (sep: %c)\n", pSep); + + while(end && *end != '\0') + { + int isSep = 0; + + while(*end != pSep && *end != '\0') + ++end; + + if(*end == pSep) { + *end = '\0'; + isSep = 1; + ++end; + } + + if(gPathCache == 0) + gPathCache = HeapAlloc(GetProcessHeap(), 0, sizeof(LoaderPathCacheNode)); + else + gPathCache = HeapReAlloc(GetProcessHeap(), 0, gPathCache, sizeof(LoaderPathCacheNode) * (gPathCacheCount + 1)); + + if(!gPathCache) + { + LogWarning("cannot allocate %d bytes for the path cache, this will break library loading!\n", sizeof(LoaderPathCacheNode) * (gPathCacheCount + 1)); + LoaderWriteLastWindowsError(); + gPathCacheCount = 0; + } else { + // + // buffer2 is never freed, this is intentionally! + // + const char * buffer1 = LoaderConvertPathToNative(start); + char * buffer2 = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * (lstrlen(buffer1) + 1)); + lstrcpy(buffer2, buffer1); + gPathCache[gPathCacheCount].path = buffer2; + + LogDebug(" * %s\n", gPathCache[gPathCacheCount].path); + + ++gPathCacheCount; + } + + if(!isSep) + break; + + start = end; + } + } + } + + // + // second lookup runpaths, pointers can be stored directly. + // + LogDebug("adding runpaths to path cache\n"); + + while(ptrRPath && *ptrRPath != '\0') + { + if(gPathCache == 0) + gPathCache = HeapAlloc(GetProcessHeap(), 0, sizeof(LoaderPathCacheNode)); + else + gPathCache = HeapReAlloc(GetProcessHeap(), 0, gPathCache, sizeof(LoaderPathCacheNode) * (gPathCacheCount + 1)); + + if(!gPathCache) + { + LogWarning("cannot allocate %d bytes for the path cache, this will break library loading!\n", sizeof(LoaderPathCacheNode) * (gPathCacheCount + 1)); + LoaderWriteLastWindowsError(); + gPathCacheCount = 0; + } else { + gPathCache[gPathCacheCount].path = ptrRPath; + ++gPathCacheCount; + + LogDebug(" * %s\n", ptrRPath); + } + + while(*ptrRPath != '\0') + ++ptrRPath; + + ++ptrRPath; + } +} + +void* LoaderLibraryGetHandle(const char* name, int strict) +{ + void* handle = 0; + unsigned int errormode = 0; + + if(gPathCache == 0) + LibCreatePathCache(); + + errormode = SetErrorMode(SEM_FAILCRITICALERRORS); + SetErrorMode(errormode | SEM_FAILCRITICALERRORS); + + handle = LibLoad(name, strict); + + SetErrorMode(errormode); + + if(handle) { + return handle; + } else if(strict) { + /* + * Don't issue a warning here, since LibLoad does this already. + */ + ExitProcess(1); + } + + return 0; +} + +int LoaderLibraryReleaseHandle(void *handle) +{ + return FreeLibrary(handle); +} diff --git a/code/validation/C/0123047_func.c b/code/validation/C/0123047_func.c new file mode 100644 index 0000000000000000000000000000000000000000..11b614279c7afa18e72085a1f8baba45ae8a998e --- /dev/null +++ b/code/validation/C/0123047_func.c @@ -0,0 +1,182 @@ + +#include + +#include "psede_func.h" +#include "psede_util.h" + + + + +typedef struct { + psede_func_t *func; + void *params; + + int size; + psede_transf_t nodes; + double *xs; +} psede_functransf_params_t; + +int +psede_func_transform(double *target, int size, int stride, + int howmany, int dist, psede_functransf_params_t *params) +{ + int status; + int i, j; + + if (params->size != size) + { + double *ptr; + ptr = realloc(params->xs, size*sizeof(*params->xs)); + if (ptr == NULL) return 1; + + params->xs = ptr; + params->size = size; + + status = psede_transf_apply(¶ms->nodes, params->xs, size, 1, 1, 0); + if (status) return status; + + for (j = 0; j < size; ++j) + { + double y; + status = params->func(params->xs[j], &y, params->params); + if (status) return status; + params->xs[j] = y; + } + } + + /* todo: delegate this to blas. */ + for (i = 0; i < howmany; ++i) + { + double *ptr = target + i*dist; + for (j = 0; j < size; ++j) ptr[j*stride] *= params->xs[j]; + } + + return 0; +} + +void +psede_functransf_params_free(psede_functransf_params_t *params) +{ + if (params == NULL) return; + + psede_transf_destroy(¶ms->nodes); + + free(params); +} + +psede_functransf_params_t * +psede_functransf_params_alloc(psede_func_t *func, + void *func_params, + const psede_colloc_t *colloc) +{ + psede_functransf_params_t *params = NULL; + + params = malloc(sizeof(*params)); + if (params == NULL) return NULL; + + params->func = func; + params->params = func_params; + params->size = 0; + params->nodes = psede_tnil; + params->xs = NULL; + + int status; + status = psede_init_nodes(colloc, ¶ms->nodes); + if (status) goto fail; + + return params; + + fail: + psede_functransf_params_free(params); + + return NULL; +} + +int +psede_init_func(const psede_colloc_t *colloc, + psede_transf_t *t, + psede_func_t *func, + void *func_params) +{ + psede_functransf_params_t *params = NULL; + + params = psede_functransf_params_alloc(func, func_params, colloc); + if (params == NULL) return 1; + + t->transform = (psede_transf_call_t*) psede_func_transform; + t->finalize = (psede_transf_finalize_t*) psede_functransf_params_free; + t->params = params; + + return 0; +} + +int +psede_function_multiply_multi_0(double *mat, + double (*func)(const double *x, void *params), + void *params, + double **nodes, + int dims, const int *sizes, + int init) +{ + int status = 0; + int *i = NULL, j, k, m = 1; + double *x = NULL; + + i = malloc(dims*sizeof(*i)); + if (i == NULL) { status = 1; goto exit; } + + x = malloc(dims*sizeof(*x)); + if (x == NULL) { status = 1; goto exit; } + + for (j = 0; j < dims; ++j) i[j] = 0; + for (j = 0; j < dims; ++j) x[j] = nodes[j][0]; + for (j = 0; j < dims; ++j) m *= sizes[j]; + + if (init) psede_identity(mat, m, 1, m, m); + + k = 0; + int loop = 1; + while (loop) + { + const double f = func(x, params); + + if (init) + { + mat[k*m + k] = f; + } + else + { + for (j = 0; j < m; ++j) mat[k*m + j] *= f; + } + + /* Increment all indices (last is fastest varying), and if all + roll back to zero, exit the main loop */ + loop = 0; + for (j = dims - 1; j >= 0 && !loop; --j) + { + i[j]++; + if (i[j] == sizes[j]) i[j] = 0; + else loop = 1; + + x[j] = nodes[j][i[j]]; + } + + k++; + } + + /* Internal consistency check: Should have processed all m rows of + the input matrix. */ + if (k != m) { status = 1; goto exit; } + + exit: + if (i) free(i); + if (x) free(x); + + return status; +} + + + + + + diff --git a/code/validation/C/0124005_kabsch.c b/code/validation/C/0124005_kabsch.c new file mode 100644 index 0000000000000000000000000000000000000000..bbf58c0e6703763fef08e7d4c64b0cac149f2653 --- /dev/null +++ b/code/validation/C/0124005_kabsch.c @@ -0,0 +1,211 @@ +/* + * Kabsch's algorithm: compute least-square-best-fit transformation + * Copyright (C) 2003, Arno Formella (formella@ei.uvigo.es) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at + * your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * This is a gsl-based implementation of Kabsch's algorithm presented in: + * + * W. Kabsch, A solution for the best rotation to relate two sets of vectors, + * Acta Cryst. (1976), A32, 922-923 + * + * W. Kabsch, A discussion of the solution for the best rotation to relate + * two sets of vectors, Acta Cryst. (1978), A34, 827-828 + * + * The code is C and C++ compilable. + * + * More information about GSL: + * + * The project homepage is http://www.gnu.org/software/gsl/ + * The development site is http://sources.redhat.com/gsl/ + */ + +#include +#include +#include + +#include "kabsch.h" + +/* gsl does not provide it */ +__inline__ static void gsl_vector_cross( + const gsl_vector *a, + const gsl_vector *b, + gsl_vector *c +) { + double a0=gsl_vector_get(a,0); + double a1=gsl_vector_get(a,1); + double a2=gsl_vector_get(a,2); + double b0=gsl_vector_get(b,0); + double b1=gsl_vector_get(b,1); + double b2=gsl_vector_get(b,2); + gsl_vector_set(c,0,a1*b2-b1*a2); + gsl_vector_set(c,1,a2*b0-b2*a0); + gsl_vector_set(c,2,a0*b1-b0*a1); +} + +#define NORM_EPS 0.00000001 + +int kabsch( + unsigned int size, /* the number of points */ + gsl_matrix *X, /* the points to be moved */ + gsl_matrix *Y, /* the points to move to */ + gsl_matrix *U, /* the rotation matrix */ + gsl_vector *t, /* the translation vector */ + double *s /* the optimal scaling, if != 0 */ +) { + unsigned int i,j,k; + int U_ok=1; + double n=1.0/size; + gsl_vector *cx=gsl_vector_alloc(3); /* centroid of X */ + gsl_vector *cy=gsl_vector_alloc(3); /* centroid of Y */ + gsl_matrix *R=gsl_matrix_alloc(3,3); /* Kabsch's R */ + gsl_matrix *RTR=gsl_matrix_alloc(3,3); /* R_trans * R (and Kabsch's bk) */ + gsl_eigen_symmv_workspace *espace=gsl_eigen_symmv_alloc(3); + gsl_matrix *evec=gsl_matrix_alloc(3,3); /* eigenvectors (and Kabsch's ak) */ + gsl_vector *eval=gsl_vector_alloc(3); /* vector of eigenvalues */ + + /** compute centroid of X */ + gsl_vector_set_zero(cx); + for(i=size;i>0;) { + gsl_vector_const_view row=gsl_matrix_const_row(X,--i); + gsl_vector_add(cx,&row.vector); + } + gsl_vector_scale(cx,n); + + /** compute centroid of Y */ + gsl_vector_set_zero(cy); + for(i=size;i>0;) { + gsl_vector_const_view row=gsl_matrix_const_row(Y,--i); + gsl_vector_add(cy,&row.vector); + } + gsl_vector_scale(cy,n); + + /** move X to origin */ + for(i=size;i>0;) { + gsl_vector_view row=gsl_matrix_row(X,--i); + gsl_vector_sub(&row.vector,cx); + } + /** move Y to origin */ + for(i=size;i>0;) { + gsl_vector_view row=gsl_matrix_row(Y,--i); + gsl_vector_sub(&row.vector,cy); + } + + if(size==1) { + /* just one point, so U is trival */ + gsl_matrix_set_identity(U); + } + else { + /** compute R */ + gsl_matrix_set_zero(R); + for(k=size;k>0;) { + --k; + for(i=3;i>0;) { + --i; + for(j=3;j>0;) { + --j; + gsl_matrix_set(R,i,j, + gsl_matrix_get(R,i,j)+ + gsl_matrix_get(Y,k,i)*gsl_matrix_get(X,k,j) + ); + } + } + } + + /** compute RTR = R_trans * R */ + gsl_matrix_set_zero(RTR); + gsl_blas_dgemm(CblasTrans,CblasNoTrans,1.0,R,R,0.0,RTR); + + /** compute orthonormal eigenvectors */ + gsl_eigen_symmv(RTR,eval,evec,espace); /* RTR will be modified! */ + gsl_eigen_symmv_sort(eval,evec,GSL_EIGEN_SORT_VAL_DESC); + if(gsl_vector_get(eval,1)>NORM_EPS) { + /** compute ak's (as columns of evec) and bk's (as columns of RTR) */ + double norm_b0,norm_b1,norm_b2; + gsl_vector_const_view a0=gsl_matrix_const_column(evec,0); + gsl_vector_const_view a1=gsl_matrix_const_column(evec,1); + gsl_vector_view a2=gsl_matrix_column(evec,2); + gsl_vector_view b0=gsl_matrix_column(RTR,0); + gsl_vector_view b1=gsl_matrix_column(RTR,1); + gsl_vector_view b2=gsl_matrix_column(RTR,2); + gsl_vector_cross(&a0.vector,&a1.vector,&a2.vector); /* a2 = a0 x a1 */ + gsl_blas_dgemv(CblasNoTrans,1.0,R,&a0.vector,0.0,&b0.vector); + norm_b0=gsl_blas_dnrm2(&b0.vector); + gsl_blas_dgemv(CblasNoTrans,1.0,R,&a1.vector,0.0,&b1.vector); + norm_b1=gsl_blas_dnrm2(&b1.vector); + if(norm_b0>NORM_EPS&&norm_b1>NORM_EPS) { + gsl_vector_scale(&b0.vector,1.0/norm_b0); /* b0 = ||R * a0|| */ + gsl_vector_scale(&b1.vector,1.0/norm_b1); /* b1 = ||R * a1|| */ + gsl_vector_cross(&b0.vector,&b1.vector,&b2.vector); /* b2 = b0 x b1 */ + + norm_b2=gsl_blas_dnrm2(&b2.vector); + if(norm_b2>NORM_EPS) { + /** we reach this point only if all bk different from 0 */ + /** compute U = B * A_trans (use RTR as B and evec as A) */ + gsl_matrix_set_zero(U); /* to avoid nan */ + gsl_blas_dgemm(CblasNoTrans,CblasTrans,1.0,RTR,evec,0.0,U); + } + else { + U_ok=0; + gsl_matrix_set_identity(U); + } + } + else { + U_ok=0; + gsl_matrix_set_identity(U); + } + } + else { + U_ok=0; + gsl_matrix_set_identity(U); + } + } + + /** compute t = cy - U * cx */ + gsl_vector_memcpy(t,cy); + gsl_blas_dgemv(CblasNoTrans,-1.0,U,cx,1.0,t); + + if(s) { + /** let us compute the optimal scaling as well */ + /** s = / */ + *s=1.0; + if(U_ok&&size>1) { + double dom=0.0; + double nom=0.0; + double dom_i,nom_i; + gsl_vector *Uxi=gsl_vector_alloc(3); + for(i=size;i>0;) { + gsl_vector_const_view row_x=gsl_matrix_const_row(X,--i); + gsl_vector_const_view row_y=gsl_matrix_const_row(Y,i); + gsl_vector_set_zero(Uxi); + gsl_blas_dgemv(CblasNoTrans,1.0,U,&row_x.vector,1.0,Uxi); + gsl_blas_ddot(&row_y.vector,Uxi,&nom_i); + nom+=nom_i; + gsl_blas_ddot(Uxi,Uxi,&dom_i); + dom+=dom_i; + } + *s=nom/dom; + gsl_vector_free(Uxi); + } + } + + gsl_vector_free(eval); + gsl_matrix_free(evec); + gsl_eigen_symmv_free(espace); + gsl_matrix_free(RTR); + gsl_matrix_free(R); + gsl_vector_free(cy); + gsl_vector_free(cx); + + /* return U_ok; */ + return 0; +} + diff --git a/code/validation/C/0124512_pwm.c b/code/validation/C/0124512_pwm.c new file mode 100644 index 0000000000000000000000000000000000000000..c68d80ae9a1d1fe97d300c14643376fa06017ba3 --- /dev/null +++ b/code/validation/C/0124512_pwm.c @@ -0,0 +1,346 @@ +/* + * (C) Copyright 2010 + * jung hyun kim, Nexell Co, + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include +#include +#include +#include +#include +#include + +/* nexell soc headers */ +#include +#include + +#if (0) +#define DBGOUT(msg...) { printk("pwm: " msg); } +#else +#define DBGOUT(msg...) do {} while (0) +#endif + +/*-----------------------------------------------------------------------------*/ +struct pwm_device{ + u_int ch; /* 0 ~ 1, 2 channels */ + u_int duty; /* unit % 0% ~ 100% */ + u_int freq; /* unit Hz 237Hz ~ 30KHz, default = 1000 */ + u_int enable; + u_int suspend_ch; + u_int io; + u_int iofunc; +}; + +static struct pwm_device gpwm[] = { + { 0, 0, 0, 0, 0, (PAD_GPIO_B + 2), NX_GPIO_PADFUNC_1 }, + { 1, 0, 0, 0, 0, (PAD_GPIO_B + 3), NX_GPIO_PADFUNC_1 }, + { 2, 0, 0, 0, 0, (PAD_GPIO_C + 18), NX_GPIO_PADFUNC_3 }, +}; +#define PWM_CHANNEL_NUM (sizeof(gpwm)/sizeof(gpwm[0])) + +/*----------------------------------------------------------------------------- + * |-----------------------------------------------| + * MIN Frequency | + * | | MAX Frequency + * scale max (128) ~~~ scale min (1) scale min (1) + * period max(1000 period max(1000) ~~~~~~~~~ period min(2) + */ +#define PWM_PERIOD_MIN 2 +#define PWM_PERIOD_MAX 1000 +#define PWM_PRESCL_MIN 1 +#define PWM_PRESCL_MAX 128 + +#define PWM_CLOCK_SOURCE (CFG_PWM_CLK_SOURCE) + +#define TMP_DIVISOR ((CFG_PWM_CLK_FREQ + 80000000 - 1)/80000000) /* peri max clock is 80Mhz */ +#if (TMP_DIVISOR & 0x1) /* support only even value */ +#define PWM_CLOCK_DIVISOR (TMP_DIVISOR + 1) +#else +#define PWM_CLOCK_DIVISOR (TMP_DIVISOR) +#endif + +#define PWM_FREQUENCY_MAX (CFG_PWM_CLK_FREQ/PWM_CLOCK_DIVISOR) +#define PWM_FREQUENCY_MIN (CFG_PWM_CLK_FREQ/PWM_PRESCL_MAX/PWM_PERIOD_MAX) +/*-----------------------------------------------------------------------------*/ + +static DEFINE_MUTEX(mutex); +static u_int g_clk_enb = 0; + +#define PWM_LOCK(id) { if (! preempt_count() && ! in_interrupt()) mutex_lock(&mutex); } +#define PWM_UNLOCK(id) { if (mutex_is_locked(&mutex)) mutex_unlock(&mutex); } + +/*-----------------------------------------------------------------------------*/ +void soc_pwm_init(void) +{ +#if !defined (CFG_PWM_NO_INIT) + int i = 0, io = 0; +#endif + DBGOUT("%s (total ch:%d)\n", __func__, PWM_CHANNEL_NUM); + NX_PWM_SetBaseAddress((U32)IO_ADDRESS(NX_PWM_GetPhysicalAddress())); + NX_PWM_OpenModule(); + + /* check bootloader pwm config */ + if (NX_PWM_GetClockDivisorEnable() && + PWM_CLOCK_DIVISOR != NX_PWM_GetClockDivisor(0)) + { + NX_PWM_SetClockDivisorEnable(CFALSE); + NX_PWM_SetClockSource (0, PWM_CLOCK_SOURCE); + NX_PWM_SetClockDivisor (0, PWM_CLOCK_DIVISOR); + NX_PWM_SetClockPClkMode (NX_PCLKMODE_DYNAMIC); + NX_PWM_SetClockDivisorEnable(CTRUE); + } + +#if !defined (CFG_PWM_NO_INIT) + NX_PWM_SetClockPClkMode (NX_PCLKMODE_DYNAMIC); + NX_PWM_SetClockDivisorEnable(CFALSE); + + for (i = 0; PWM_CHANNEL_NUM > i; i++) { + io = gpwm[i].io; + soc_gpio_set_out_value(io, 0); + soc_gpio_set_io_dir(io, 1); + soc_gpio_set_io_pullup(io, 0); + soc_gpio_set_io_func(io, NX_GPIO_PADFUNC_GPIO); + } +#endif + printk(KERN_INFO "pwm : %lu hz ~ %lu hz, pll:%lu, div:%lu\n", + PWM_FREQUENCY_MIN, PWM_FREQUENCY_MAX, CFG_PWM_CLK_FREQ, PWM_CLOCK_DIVISOR); +} + +static int set_pwm_freq(int ch, u_int freq, u_int duty) +{ + struct pwm_device * pwm = &gpwm[ch]; + u_int io = pwm->io; + u_int fn = pwm->iofunc; + int clkenb = 0, i = 0; + int r_scale = 0, r_period = 0, r_duty = 0; + + DBGOUT("%s (ch:%d, freq:%d, duty:%d)\n", __func__, ch, freq, duty); + + if (freq > PWM_FREQUENCY_MAX || PWM_FREQUENCY_MIN > freq) { + printk("Invalid pwm[%d], freq:%d hz (%lu ~ %lu) \n", + ch, freq, PWM_FREQUENCY_MIN, PWM_FREQUENCY_MAX); + return (-1); + } + + if (duty > 100 || 0 > duty) { + printk("Invalid pwm[%d], duty:%d percent (0 ~ 100)\n", ch, duty); + return (-1); + } + + /* lock */ + PWM_LOCK(0); + + if (freq > PWM_FREQUENCY_MAX/PWM_PERIOD_MAX) { + r_scale = PWM_PRESCL_MIN; + r_period = (PWM_FREQUENCY_MAX/r_scale)/freq; + } else { + r_period = PWM_PERIOD_MAX; + r_scale = (PWM_FREQUENCY_MAX/r_period)/freq; + } + r_duty = (r_period * duty) / 100; + + NX_PWM_SetPreScale (ch, r_scale); + NX_PWM_SetPeriod (ch, r_period); + NX_PWM_SetDutyCycle (ch, r_duty); + + printk("pwm ch[%d]: freq:%lu hz, duty:%2d%% (reg: scale=%2d, period=%4d, duty=%3d) \n", + ch, (PWM_FREQUENCY_MAX/r_period)/r_scale, duty, r_scale, r_period, r_duty); + + if (r_period >= r_duty && r_duty > 0) + pwm->enable = 1; + else + pwm->enable = 0; + + /* check pwm status */ + for (i = 0; PWM_CHANNEL_NUM > i; i++) { + DBGOUT("pwm ch[%d] - on:%d\n", i, gpwm[i].enable); + if (gpwm[i].enable) + clkenb = 1; + } + DBGOUT("clock %d, current clock:%d \n", clkenb, g_clk_enb); + + /* pwm clock */ + if (clkenb && ! g_clk_enb) { + NX_PWM_SetClockSource (0, PWM_CLOCK_SOURCE); + NX_PWM_SetClockDivisor (0, PWM_CLOCK_DIVISOR); + NX_PWM_SetClockPClkMode (NX_PCLKMODE_ALWAYS); + NX_PWM_SetClockDivisorEnable(CTRUE); + } + + if (!clkenb) { + DBGOUT("disable pwm clock ...\n"); + NX_PWM_SetClockPClkMode(NX_PCLKMODE_DYNAMIC); + NX_PWM_SetClockDivisorEnable(CFALSE); + } + + /* pwm pad */ + if (pwm->enable) { + soc_gpio_set_io_func(io, fn); + } else { + soc_gpio_set_out_value(io, 0); + soc_gpio_set_io_dir(io, 1); + soc_gpio_set_io_pullup(io, 0); + soc_gpio_set_io_func(io, NX_GPIO_PADFUNC_GPIO); + } + + /* clock status */ + g_clk_enb = clkenb; + + /* unlock */ + PWM_UNLOCK(0); + return 0; +} + +/*------------------------------------------------------------------------------ + * Description : set pwm frequncy, and save frequency info + * In[ch] : pwm channel, 0 ~ 3 + * In[freq] : pwm frequency, unit (Hz), : 30Hz ~ 237KHz + * In[duty] : pwm pulse width, unit (%), 0 % ~ 100 % + * : if 0, pulse is low out. + * Return : none. + */ +void soc_pwm_set_frequency(int ch, u_int freq, u_int duty) +{ + struct pwm_device * pwm = NULL; + u_int org_freq, org_duty; + + DBGOUT("%s\n", __func__); + + NX_ASSERT(PWM_CHANNEL_NUM > ch && ch >= 0); + + pwm = &gpwm[ch]; + + org_freq = pwm->freq; + org_duty = pwm->duty; + pwm->freq = freq; + pwm->duty = duty; + + if (0 > set_pwm_freq(ch, freq, duty)) { + pwm->freq = org_freq; + pwm->duty = org_duty; + return; + } +} +EXPORT_SYMBOL_GPL(soc_pwm_set_frequency); + +/*------------------------------------------------------------------------------ + * Description : get pwm frequncy info + * In[ch] : pwm channel, 0 ~ 3 + * out[freq] : pwm frequency, unit (Hz), : 30Hz ~ 237KHz + * out[duty] : pwm pulse width, unit (%), 0 % ~ 100 % + * Return : none. + */ +void soc_pwm_get_frequency(int ch, uint *freq, uint *duty) +{ + struct pwm_device * pwm = NULL; + + DBGOUT("%s\n", __func__); + + NX_ASSERT(PWM_CHANNEL_NUM > ch && ch >= 0); + + pwm = &gpwm[ch]; + *freq = pwm->freq; + *duty = pwm->duty; + + DBGOUT("%s (ch:%d, freq:%d, duty:%d)\n", __func__, ch, *freq, *duty); +} +EXPORT_SYMBOL_GPL(soc_pwm_get_frequency); + +/*------------------------------------------------------------------------------ + * Description : set suspend mode, + * Return : none. + */ +void soc_pwm_set_suspend(void) +{ + PM_DBGOUT("+%s\n", __func__); + /* clock status */ + g_clk_enb = 0; + + PM_DBGOUT("-%s\n", __func__); +} +EXPORT_SYMBOL_GPL(soc_pwm_set_suspend); + +/*------------------------------------------------------------------------------ + * Description : resume mode, restore saved pwm frequency. + * In[ch] : pwm channel, 0 ~ 3 + * Return : none. + */ +void soc_pwm_set_resume(void) +{ + struct pwm_device * pwm = NULL; + int ch = 0; + + PM_DBGOUT("+%s\n", __func__); + + for (; PWM_CHANNEL_NUM > ch; ch++) { + pwm = &gpwm[ch]; + if (! pwm->suspend_ch) + set_pwm_freq(ch, pwm->freq, pwm->duty); + } + PM_DBGOUT("-%s\n", __func__); +} +EXPORT_SYMBOL_GPL(soc_pwm_set_resume); + +/*------------------------------------------------------------------------------ + * Description : ch suspend mode, it's not save frequency info + * In[ch] : pwm channel, 0 ~ 3 + * In[freq] : pwm frequency, unit (Hz), : 30Hz ~ 237KHz + * In[duty] : pwm pulse width, unit (%), 0 % ~ 100 % + * : if 0, pulse is low out. + * Return : none. + */ +void soc_pwm_set_suspend_ch(int ch, u_int freq, u_int duty) +{ + struct pwm_device * pwm = NULL; + + PM_DBGOUT("+%s\n", __func__); + + NX_ASSERT(PWM_CHANNEL_NUM > ch && ch >= 0); + + pwm = &gpwm[ch]; + pwm->suspend_ch = 1; + + set_pwm_freq(ch, freq, duty); + + /* clock status */ + g_clk_enb = 0; + + PM_DBGOUT("-%s\n", __func__); +} +EXPORT_SYMBOL_GPL(soc_pwm_set_suspend_ch); + +/*------------------------------------------------------------------------------ + * Description : ch resume mode, restore saved pwm frequency. + * In[ch] : pwm channel, 0 ~ 3 + * Return : none. + */ +void soc_pwm_set_resume_ch(int ch) +{ + struct pwm_device * pwm = NULL; + + PM_DBGOUT("+%s\n", __func__); + + NX_ASSERT(PWM_CHANNEL_NUM > ch && ch >= 0); + + pwm = &gpwm[ch]; + pwm->suspend_ch = 0; + + set_pwm_freq(ch, pwm->freq, pwm->duty); + + PM_DBGOUT("-%s\n", __func__); +} +EXPORT_SYMBOL_GPL(soc_pwm_set_resume_ch); + diff --git a/code/validation/C/0125293_datum.c b/code/validation/C/0125293_datum.c new file mode 100644 index 0000000000000000000000000000000000000000..e5c21b79ca25b08ee718d52903b90735609216e9 --- /dev/null +++ b/code/validation/C/0125293_datum.c @@ -0,0 +1,169 @@ +// Copyright (c) 2012-2014 Bartosz Szczesny +// This program is free software under the MIT license. + +#include "datum.h" + +void* datum_free(struct datum* dat) { + if (dat == NULL) { + fprintf(stderr, "datum error: datum pointer = NULL\n"); + } else { + free(dat->lens); + free(dat->data); + free(dat); + } + return NULL; +} + +static void* datum_alloc_err(struct datum* dat) { + fprintf(stderr, "datum error: cannot allocate memory\n"); + datum_free(dat); + return NULL; +} + +struct datum* datum_alloc(const int ndim, const int* lens) { + if (ndim < 1) { + fprintf(stderr, "datum error: number of dimensions = %d < 1\n", ndim); + return NULL; + } + for (int d = 0; d < ndim; d++) { + if (lens[d] < 1) { + fprintf(stderr, "datum error: dimension[%d] = %d < 1\n", d, lens[d]); + return NULL; + } + } + + struct datum* dat = calloc(1, sizeof(struct datum)); + if (dat == NULL) { + return datum_alloc_err(dat); + } + dat->ndim = ndim; + dat->data = NULL; // for clean freeing + + dat->lens = calloc(ndim, sizeof(int)); + if (dat->lens == NULL) { + return datum_alloc_err(dat); + } + dat->len = 1; + for (int d = 0; d < ndim; d++) { + dat->lens[d] = lens[d]; + dat->len *= lens[d]; + } + + dat->data = calloc(dat->len, sizeof(double)); + if (dat->data == NULL) { + return datum_alloc_err(dat); + } + + return dat; +} // datum_alloc() + +struct datum* datum_read(const char* filename) { + struct datum* dat = NULL; + + FILE* file = fopen(filename, "rb"); + if (file == NULL) { + fprintf(stderr, "datum error: cannot open file '%s'\n", filename); + return NULL; + } + int ndim; + if (fscanf(file, "%d", &ndim) < 0) { + fprintf(stderr, "datum error: cannot read dimension number\n"); + goto fclose_file; + } + int* lens = calloc(ndim, sizeof(int)); + if (lens == NULL) { + fprintf(stderr, "datum error: cannot allocate memory\n"); + goto fclose_file; + } + for (int d = 0; d < ndim; d++) { + if (fscanf(file, "%d", &lens[d]) < 1) { + fprintf(stderr, "datum error: cannot read dimension %d size\n", d); + goto free_lens; + } + } + + dat = datum_alloc(ndim, lens); + if (dat == NULL) { + goto free_lens; + } + for (int d = 0; d < dat->len; d++) { + if (fscanf(file, "%lf", &dat->data[d]) < 1) { + fprintf(stderr, "datum error: cannot read data point %d\n", d); + dat = datum_free(dat); + goto free_lens; + } + } + +free_lens: + free(lens); +fclose_file: + if (fclose(file) != 0) { + fprintf(stderr, "datum error: cannot close file '%s'\n", filename); + return NULL; + } + return dat; +} // datum_read() + +int datum_write(const struct datum* dat, const char* filename) { + int err = 0; + + FILE* file = fopen(filename, "wb"); + if (file == NULL) { + fprintf(stderr, "datum error: cannot open file '%s'\n", filename); + return 1; + } + if (fprintf(file, "%d\n", dat->ndim) < 1) { + fprintf(stderr, "datum error: cannot write to file '%s'\n", filename); + err = 1; + goto fclose_file; + } + for (int d = 0; d < dat->ndim; d++) { + if (fprintf(file, "%d\n", dat->lens[d]) < 1) { + fprintf(stderr, "datum error: cannot write to file '%s'\n", filename); + err = 1; + goto fclose_file; + } + } + for (int d = 0; d < dat->len; d++) { + if (fprintf(file, "%.17lg\n", dat->data[d]) < 1) { + fprintf(stderr, "datum error: cannot write to file '%s'\n", filename); + err = 1; + goto fclose_file; + } + } + +fclose_file: + if (fclose(file) != 0) { + fprintf(stderr, "datum error: cannot close file '%s'\n", filename); + err = 1; + } + return err; +} // datum_write() + +inline +int datum_index(const struct datum* dat, ...) { + va_list indexes; + va_start(indexes, dat); + int index = 0; + int flat_index = 0; + for (int i = 1; i < dat->ndim; i++) { + index = va_arg(indexes, int); + flat_index += index; + flat_index *= dat->lens[i]; + } + index = va_arg(indexes, int); + flat_index += index; + va_end(indexes); + return flat_index; +} + +inline +int datum_index_array(const struct datum* dat, const int* indexes) { + int flat_index = 0; + for (int i = 0; i < dat->ndim - 1; i++) { + flat_index += indexes[i]; + flat_index *= dat->lens[i + 1]; + } + flat_index += indexes[dat->ndim - 1]; + return flat_index; +} diff --git a/code/validation/C/0127010_lib_io_gaussconv.c b/code/validation/C/0127010_lib_io_gaussconv.c new file mode 100644 index 0000000000000000000000000000000000000000..7aa916190ddbc2d7b969ffad198768640db43f64 --- /dev/null +++ b/code/validation/C/0127010_lib_io_gaussconv.c @@ -0,0 +1,109 @@ + +// Copyright (C) 2014, Ives Rey-Otero, CMLA ENS Cachan +// // +// // +// // Version 20140515 (May 15th, 2014) +// // +// // +// // This program is free software: you can use, modify and/or +// // redistribute it under the terms of the GNU General Public +// // License as published by the Free Software Foundation, either +// // version 3 of the License, or (at your option) any later +// // version. You should have received a copy of this license along +// // this program. If not, see . +// +// +// + + +#include +#include +#include + +#include "io_png.h" + +#include "lib_io_gaussconv.h" +#define MAX(i,j) ( (i)<(j) ? (j):(i) ) +#define MIN(i,j) ( (i)<(j) ? (i):(j) ) + + +double* read_image_to_gray(char* fname, int *pw, int *ph) +{ + size_t w, h; + float* imf32 = io_png_read_f32_rgb(fname, &w, &h); + double* x = (double*)malloc(w*h*sizeof(double)); + for(int i = 0; i < w*h; i++) + x[i] = (double)((0.299*imf32[i] + 0.587*imf32[w*h+i] + 0.1140*imf32[2*w*h+i])); //RGB2GRAY + free(imf32); + *pw = w; + *ph = h; + return x; +} + + + + +void printImage(double *imageIn, int w, int h, char *name) +{ + float *imf32 = (float *) malloc(w * h * sizeof(float)); + for (int i = 0; i < w * h; i++) { + imf32[i] = (float) imageIn[i]; + } + io_png_write_f32(name, imf32, w, h, 1); + free(imf32); +} + + + + + +void capped_linear_conversion(double *in, double *out, int l, double mindiff) +{ + double a, b; + double minV = DBL_MAX; + double maxV = DBL_MIN; + for (int i = 0; i < l; i++) { + if (in[i] >= maxV){ + maxV = in[i]; + } + if (in[i] <= minV){ + minV = in[i]; + } + } + double div = MAX( maxV - minV, mindiff ); + a = (250.0 - 0.0) / div ; + b = -a * minV; + for (int i = 0; i < l; i++) + out[i] = a * in[i] + b; +} + + + +void linear_conversion(double *imIn, double *imOut, int length){ + double a, b; + double minVal = DBL_MAX; + double maxVal = DBL_MIN; + for (int i = 0; i < length; i++) { + if (imIn[i] >= maxVal){ + maxVal = imIn[i]; + } + if (imIn[i] <= minVal){ + minVal = imIn[i]; + } + } + a = (250.0 - 0.0) / (maxVal - minVal); + b = -a * minVal; + for (int i = 0; i < length; i++) + imOut[i] = a * imIn[i] + b; +} + +void printImage_LinearConversion(double *imageIn, int w, int h, char *name){ + double *imTemp = (double*)malloc(w*h*sizeof(double)); + linear_conversion(imageIn, imTemp, w * h); + //capped_linear_conversion(imageIn, imTemp, w * h, 0.00000001); + linear_conversion(imageIn, imTemp, w * h); + printImage(imTemp, w, h, name); + free(imTemp); +} + + diff --git a/code/validation/C/0127400_writevtk.c b/code/validation/C/0127400_writevtk.c new file mode 100644 index 0000000000000000000000000000000000000000..4fefd534a281e1d3d99732ee5ffa50c4c96c213e --- /dev/null +++ b/code/validation/C/0127400_writevtk.c @@ -0,0 +1,226 @@ +/************************************************************* +* export vectors and tensors in big-endian mixed ascii/binary +* vtk format for Paraview. +* +* sylvain barbot 10/27/11 - original form +*************************************************************/ + +#include +#include +#include +#include "config.h" + +// check data alignment +#ifdef FFTW3 +#define ALIGN_DATA 1 +#else +#ifdef SGI_FFT +#define ALIGN_DATA 1 +#else +#ifdef IMKL_FFT +#define ALIGN_DATA 1 +#endif +#endif +#endif + +int fix(int n){ + if(n<0) return n-1;return n+1; +} + +float swap(float d){ + float a; + unsigned char *dst = (unsigned char *)&a; + unsigned char *src = (unsigned char *)&d; + dst[0] = src[3]; + dst[1] = src[2]; + dst[2] = src[1]; + dst[3] = src[0]; + return a; +} + +// test endianness of the machine +unsigned char isbigendian(){ + + typedef union{ + int i; + char c[4]; + } u; + u temp; + + temp.i = 0x12345678; + + switch(temp.c[0]) { + case 0x12: + return 1u; // big endian + case 0x78: + return 0u; // little endian + default: + fprintf(stderr,"invalid result for endianness test.\n"); + fprintf(stderr,"temp %x %x %x %x.\n",temp.c[0],temp.c[1],temp.c[2],temp.c[3]); + fprintf(stderr,"temp %x \n",temp.c[0]); + return 2u; + } +} + +/************************************************************* +* subroutine ExportVTK_Vectors_Legacy +* creates a .vtk file in the VTK Legacy binary format with +* structured points containing a vector field. +* +* sylvain barbot 10/27/11 - original form +*************************************************************/ +void exportvtk_vectors_legacy_(u1,u2,u3,sx1,sx2,sx3,dx1,dx2,dx3,j1,j2,j3,filename,title,name) + float *u1, *u2, *u3; /* data array for output */ + int *sx1, *sx2, *sx3; /* number of points */ + double*dx1, *dx2, *dx3; /* sampling distance */ + int *j1, *j2, *j3; /* subsampling rate */ + char *filename; /* output file name */ + char *title; /* output file name */ + char *name; /* output file name */ +{ + + FILE * funit; + float buffer[3]; + int i1,i2,k1,k2,k3,index; + unsigned char endian; + + funit=fopen(filename,"wb"); + if (NULL==funit){ + fprintf(stderr,"could not open file %s for vtk output\n",filename); + fprintf(stderr,"exiting.\n"); + return; + } + + // find endianness + endian=isbigendian(); + + // writing header of file + fprintf(funit,"# vtk DataFile Version 3.0\n"); + fprintf(funit,"%s\n",title); + fprintf(funit,"BINARY\n"); + fprintf(funit,"DATASET STRUCTURED_POINTS\n"); + + // structured points grid + fprintf(funit,"DIMENSIONS %i %i %i\n",(*sx1)/(*j1),(*sx2)/(*j2),(*sx3)/(*j3)); + fprintf(funit,"ORIGIN %f %f %f\n",-(*dx1)*((*sx1)/2),-(*dx2)*((*sx2)/2),0.0); + fprintf(funit,"SPACING %f %f %f\n",(*dx1)*(*j1),(*dx2)*(*j2),(*dx3)*(*j3)); + + // data header for this grid + fprintf(funit,"POINT_DATA %i\n",((*sx1)/(*j1))*((*sx2)/(*j2))*((*sx3)/(*j3))); + + // data array + fprintf(funit,"VECTORS %s float\n",name); + + // data values + for (k3=0; k3<(*sx3); k3=k3+(*j3)){ + for (k2=-(*sx2)/2; k2<(*sx2)/2; k2=k2+(*j2)){ + i2=((*sx2)+fix(k2)) % (*sx2); + + for (k1=-(*sx1)/2; k1<(*sx1)/2; k1+=(*j1)){ + i1=((*sx1)+fix(k1)) % (*sx1); + +#ifdef ALIGN_DATA + index=i1+(i2+k3*(*sx2))*((*sx1)+2); +#else + index=i1+(i2+k3*(*sx2))*(*sx1); +#endif + + // convert to big endian if necessary + buffer[0]=(1u==endian)?u1[index]:swap(u1[index]); + buffer[1]=(1u==endian)?u2[index]:swap(u2[index]); + buffer[2]=(1u==endian)?u3[index]:swap(u3[index]); + + fwrite(buffer,12,1,funit); + } + } + } + + // close binary file + fclose(funit); + +} + + +/************************************************************* +* subroutine ExportVTK_tensors_Legacy +* creates a .vtk file in the VTK Legacy binary format with +* structured points containing a vector field. +* +* sylvain barbot 10/28/11 - original form +*************************************************************/ +void exportvtk_tensors_legacy_(sig,sx1,sx2,sx3,dx1,dx2,dx3,j1,j2,j3,filename,title,name) + float *sig; /* data array for tensor output */ + int *sx1, *sx2, *sx3; /* number of points */ + double*dx1, *dx2, *dx3; /* sampling distance */ + int *j1, *j2, *j3; /* subsampling rate */ + char *filename; /* output file name */ + char *title; /* output file name */ + char *name; /* output file name */ +{ + + FILE * funit; + float buffer[9]; + int i1,i2,k1,k2,k3,index; + unsigned char endian; +#define DOF 6 + + funit=fopen(filename,"wb"); + if (NULL==funit){ + fprintf(stderr,"could not open file %s for vtk output\n",filename); + fprintf(stderr,"exiting.\n"); + return; + } + + // find endianness + endian=isbigendian(); + + // writing header of file + fprintf(funit,"# vtk DataFile Version 3.0\n"); + fprintf(funit,"%s\n",title); + fprintf(funit,"BINARY\n"); + fprintf(funit,"DATASET STRUCTURED_POINTS\n"); + + // structured points grid + fprintf(funit,"DIMENSIONS %i %i %i\n",(*sx1)/(*j1),(*sx2)/(*j2),(*sx3)/(*j3)); + fprintf(funit,"ORIGIN %f %f %f\n",-(*dx1)*((*sx1)/2),-(*dx2)*((*sx2)/2),0.0); + fprintf(funit,"SPACING %f %f %f\n",(*dx1)*(*j1),(*dx2)*(*j2),(*dx3)*(*j3)); + + // data header for this grid + fprintf(funit,"POINT_DATA %i\n",((*sx1)/(*j1))*((*sx2)/(*j2))*((*sx3)/(*j3))); + + // data array + fprintf(funit,"TENSORS %s float\n",name); + + // data values + for (k3=0; k3<(*sx3); k3=k3+(*j3)){ + for (k2=-(*sx2)/2; k2<(*sx2)/2; k2=k2+(*j2)){ + i2=((*sx2)+fix(k2)) % (*sx2); + + for (k1=-(*sx1)/2; k1<(*sx1)/2; k1+=(*j1)){ + i1=((*sx1)+fix(k1)) % (*sx1); + + // index of first stress component + index=(i1+(i2+k3*(*sx2))*(*sx1))*DOF; + + // convert to big endian if necessary + buffer[0]=(1u==endian)?sig[index+0]:swap(sig[index+0]); + buffer[1]=(1u==endian)?sig[index+1]:swap(sig[index+1]); + buffer[2]=(1u==endian)?sig[index+2]:swap(sig[index+2]); + buffer[3]=(1u==endian)?sig[index+1]:swap(sig[index+1]); + buffer[4]=(1u==endian)?sig[index+3]:swap(sig[index+3]); + buffer[5]=(1u==endian)?sig[index+4]:swap(sig[index+4]); + buffer[6]=(1u==endian)?sig[index+2]:swap(sig[index+2]); + buffer[7]=(1u==endian)?sig[index+4]:swap(sig[index+4]); + buffer[8]=(1u==endian)?sig[index+5]:swap(sig[index+5]); + + // write buffer to disk + fwrite(buffer,36,1,funit); + } + } + } + + // close binary file + fclose(funit); + +} + diff --git a/code/validation/C/0127576_tclLoadDyld.c b/code/validation/C/0127576_tclLoadDyld.c new file mode 100644 index 0000000000000000000000000000000000000000..531a3c214e617b28d403629bcf8577066e35f416 --- /dev/null +++ b/code/validation/C/0127576_tclLoadDyld.c @@ -0,0 +1,228 @@ +/* + * tclLoadDyld.c -- + * + * This procedure provides a version of the TclLoadFile that + * works with Apple's dyld dynamic loading. This file + * provided by Wilfredo Sanchez (wsanchez@apple.com). + * This works on Mac OS X. + * + * Copyright (c) 1995 Apple Computer, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * RCS: @(#) $Id: tclLoadDyld.c,v 1.13 2002/10/10 12:25:53 vincentdarley Exp $ + */ + +#include "tclInt.h" +#include "tclPort.h" +#include + +typedef struct Tcl_DyldModuleHandle { + struct Tcl_DyldModuleHandle *nextModuleHandle; + NSModule module; +} Tcl_DyldModuleHandle; + +typedef struct Tcl_DyldLoadHandle { + const struct mach_header *dyld_lib; + Tcl_DyldModuleHandle *firstModuleHandle; +} Tcl_DyldLoadHandle; + +/* + *---------------------------------------------------------------------- + * + * TclpDlopen -- + * + * Dynamically loads a binary code file into memory and returns + * a handle to the new code. + * + * Results: + * A standard Tcl completion code. If an error occurs, an error + * message is left in the interpreter's result. + * + * Side effects: + * New code suddenly appears in memory. + * + *---------------------------------------------------------------------- + */ + +int +TclpDlopen(interp, pathPtr, loadHandle, unloadProcPtr) + Tcl_Interp *interp; /* Used for error reporting. */ + Tcl_Obj *pathPtr; /* Name of the file containing the desired + * code (UTF-8). */ + Tcl_LoadHandle *loadHandle; /* Filled with token for dynamically loaded + * file which will be passed back to + * (*unloadProcPtr)() to unload the file. */ + Tcl_FSUnloadFileProc **unloadProcPtr; + /* Filled with address of Tcl_FSUnloadFileProc + * function which should be used for + * this file. */ +{ + Tcl_DyldLoadHandle *dyldLoadHandle; + const struct mach_header *dyld_lib; + CONST char *native; + + /* + * First try the full path the user gave us. This is particularly + * important if the cwd is inside a vfs, and we are trying to load + * using a relative path. + */ + native = Tcl_FSGetNativePath(pathPtr); + dyld_lib = NSAddImage(native, + NSADDIMAGE_OPTION_WITH_SEARCHING | + NSADDIMAGE_OPTION_RETURN_ON_ERROR); + + if (!dyld_lib) { + /* + * Let the OS loader examine the binary search path for + * whatever string the user gave us which hopefully refers + * to a file on the binary path + */ + Tcl_DString ds; + char *fileName = Tcl_GetString(pathPtr); + native = Tcl_UtfToExternalDString(NULL, fileName, -1, &ds); + dyld_lib = NSAddImage(native, + NSADDIMAGE_OPTION_WITH_SEARCHING | + NSADDIMAGE_OPTION_RETURN_ON_ERROR); + Tcl_DStringFree(&ds); + } + + if (!dyld_lib) { + NSLinkEditErrors editError; + char *name, *msg; + NSLinkEditError(&editError, &errno, &name, &msg); + Tcl_AppendResult(interp, msg, (char *) NULL); + return TCL_ERROR; + } + + dyldLoadHandle = (Tcl_DyldLoadHandle *) ckalloc(sizeof(Tcl_DyldLoadHandle)); + if (!dyldLoadHandle) return TCL_ERROR; + dyldLoadHandle->dyld_lib = dyld_lib; + dyldLoadHandle->firstModuleHandle = NULL; + *loadHandle = (Tcl_LoadHandle) dyldLoadHandle; + *unloadProcPtr = &TclpUnloadFile; + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TclpFindSymbol -- + * + * Looks up a symbol, by name, through a handle associated with + * a previously loaded piece of code (shared library). + * + * Results: + * Returns a pointer to the function associated with 'symbol' if + * it is found. Otherwise returns NULL and may leave an error + * message in the interp's result. + * + *---------------------------------------------------------------------- + */ +Tcl_PackageInitProc* +TclpFindSymbol(interp, loadHandle, symbol) + Tcl_Interp *interp; + Tcl_LoadHandle loadHandle; + CONST char *symbol; +{ + NSSymbol nsSymbol; + CONST char *native; + Tcl_DString newName, ds; + Tcl_PackageInitProc* proc = NULL; + Tcl_DyldLoadHandle *dyldLoadHandle = (Tcl_DyldLoadHandle *) loadHandle; + /* + * dyld adds an underscore to the beginning of symbol names. + */ + + native = Tcl_UtfToExternalDString(NULL, symbol, -1, &ds); + Tcl_DStringInit(&newName); + Tcl_DStringAppend(&newName, "_", 1); + native = Tcl_DStringAppend(&newName, native, -1); + nsSymbol = NSLookupSymbolInImage(dyldLoadHandle->dyld_lib, native, + NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW | + NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR); + if(nsSymbol) { + Tcl_DyldModuleHandle *dyldModuleHandle; + proc = NSAddressOfSymbol(nsSymbol); + dyldModuleHandle = (Tcl_DyldModuleHandle *) ckalloc(sizeof(Tcl_DyldModuleHandle)); + if (dyldModuleHandle) { + dyldModuleHandle->module = NSModuleForSymbol(nsSymbol); + dyldModuleHandle->nextModuleHandle = dyldLoadHandle->firstModuleHandle; + dyldLoadHandle->firstModuleHandle = dyldModuleHandle; + } + } + Tcl_DStringFree(&newName); + Tcl_DStringFree(&ds); + + return proc; +} + +/* + *---------------------------------------------------------------------- + * + * TclpUnloadFile -- + * + * Unloads a dynamically loaded binary code file from memory. + * Code pointers in the formerly loaded file are no longer valid + * after calling this function. + * + * Results: + * None. + * + * Side effects: + * Code dissapears from memory. + * Note that this is a no-op on older (OpenStep) versions of dyld. + * + *---------------------------------------------------------------------- + */ + +void +TclpUnloadFile(loadHandle) + Tcl_LoadHandle loadHandle; /* loadHandle returned by a previous call + * to TclpDlopen(). The loadHandle is + * a token that represents the loaded + * file. */ +{ + Tcl_DyldLoadHandle *dyldLoadHandle = (Tcl_DyldLoadHandle *) loadHandle; + Tcl_DyldModuleHandle *dyldModuleHandle = dyldLoadHandle->firstModuleHandle; + void *ptr; + + while (dyldModuleHandle) { + NSUnLinkModule(dyldModuleHandle->module, NSUNLINKMODULE_OPTION_NONE); + ptr = dyldModuleHandle; + dyldModuleHandle = dyldModuleHandle->nextModuleHandle; + ckfree(ptr); + } + ckfree(dyldLoadHandle); +} + +/* + *---------------------------------------------------------------------- + * + * TclGuessPackageName -- + * + * If the "load" command is invoked without providing a package + * name, this procedure is invoked to try to figure it out. + * + * Results: + * Always returns 0 to indicate that we couldn't figure out a + * package name; generic code will then try to guess the package + * from the file name. A return value of 1 would have meant that + * we figured out the package name and put it in bufPtr. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TclGuessPackageName(fileName, bufPtr) + CONST char *fileName; /* Name of file containing package (already + * translated to local form if needed). */ + Tcl_DString *bufPtr; /* Initialized empty dstring. Append + * package name to this if possible. */ +{ + return 0; +} diff --git a/code/validation/C/0128657_A.c b/code/validation/C/0128657_A.c new file mode 100644 index 0000000000000000000000000000000000000000..a9d4808bc59b416a4233bf31d8e32d07913da951 --- /dev/null +++ b/code/validation/C/0128657_A.c @@ -0,0 +1,36 @@ +/* + * Copyright 2015 Chen Ruichao + * + * 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. + */ + +#include + +int main(void) +{ + int N, has_class, ans = 0, last_class = -1; + + scanf("%d", &N); + for (int t = 0; t < N; t++) { + scanf("%d", &has_class); + if (has_class) { + if (last_class != -1 && t - last_class == 2) + ans++; /* didn't go home during break */ + ans++; + last_class = t; + } + } + printf("%d\n", ans); + + return 0; +} diff --git a/code/validation/C/0129251_content_factory.c b/code/validation/C/0129251_content_factory.c new file mode 100644 index 0000000000000000000000000000000000000000..8da73337c5babf90094244242cae2ce76eaec177 --- /dev/null +++ b/code/validation/C/0129251_content_factory.c @@ -0,0 +1,201 @@ +/* + * Copyright 2011 John-Mark Bell + * + * This file is part of NetSurf, http://www.netsurf-browser.org/ + * + * NetSurf is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * NetSurf is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** \file + * Content factory (implementation) + */ + +#include +#include +#include + +#include "content/content.h" +#include "content/content_factory.h" +#include "content/content_protected.h" +#include "content/llcache.h" + +/** + * Entry in list of content handlers + */ +typedef struct content_handler_entry { + /** Next entry */ + struct content_handler_entry *next; + + /** MIME type handled by handler */ + lwc_string *mime_type; + /** Content handler object */ + const content_handler *handler; +} content_handler_entry; + +static content_handler_entry *content_handlers; + +/** + * Clean up after the content factory + */ +void content_factory_fini(void) +{ + content_handler_entry *victim; + + while (content_handlers != NULL) { + victim = content_handlers; + + content_handlers = content_handlers->next; + + if (victim->handler->fini != NULL) + victim->handler->fini(); + + lwc_string_unref(victim->mime_type); + + free(victim); + } +} + +/** + * Register a handler with the content factory + * + * \param mime_type MIME type to handle + * \param handler Content handler for MIME type + * \return NSERROR_OK on success, appropriate error otherwise + * + * \note Latest registration for a MIME type wins + */ +nserror content_factory_register_handler(const char *mime_type, + const content_handler *handler) +{ + lwc_string *imime_type; + lwc_error lerror; + content_handler_entry *entry; + bool match; + + lerror = lwc_intern_string(mime_type, strlen(mime_type), &imime_type); + if (lerror != lwc_error_ok) + return NSERROR_NOMEM; + + for (entry = content_handlers; entry != NULL; entry = entry->next) { + if (lwc_string_caseless_isequal(imime_type, entry->mime_type, + &match) == lwc_error_ok && match) + break; + } + + if (entry == NULL) { + entry = malloc(sizeof(content_handler_entry)); + if (entry == NULL) + return NSERROR_NOMEM; + + entry->next = content_handlers; + content_handlers = entry; + + entry->mime_type = imime_type; + } else { + lwc_string_unref(imime_type); + } + + entry->handler = handler; + + return NSERROR_OK; +} + +/** + * Find a handler for a MIME type. + * + * \param mime_type MIME type to search for + * \return Associated handler, or NULL if none + */ +static const content_handler *content_lookup(lwc_string *mime_type) +{ + content_handler_entry *entry; + bool match; + + for (entry = content_handlers; entry != NULL; entry = entry->next) { + if (lwc_string_caseless_isequal(mime_type, entry->mime_type, + &match) == lwc_error_ok && match) + break; + } + + if (entry != NULL) + return entry->handler; + + return NULL; +} + +/** + * Compute the generic content type for a MIME type + * + * \param mime_type MIME type to consider + * \return Generic content type + */ +content_type content_factory_type_from_mime_type(lwc_string *mime_type) +{ + const content_handler *handler; + content_type type = CONTENT_NONE; + + handler = content_lookup(mime_type); + if (handler != NULL) { + type = handler->type(); + } + + return type; +} + +/** + * Create a content object + * + * \param llcache Underlying source data handle + * \param fallback_charset Character set to fall back to if none specified + * \param quirks Quirkiness of containing document + * \param effective_type Effective MIME type of content + * \return Pointer to content object, or NULL on failure + */ +struct content *content_factory_create_content(llcache_handle *llcache, + const char *fallback_charset, bool quirks, + lwc_string *effective_type) +{ + struct content *c; + const char *content_type_header; + const content_handler *handler; + http_content_type *ct = NULL; + nserror error; + + handler = content_lookup(effective_type); + if (handler == NULL) + return NULL; + + assert(handler->create != NULL); + + /* Use the parameters from the declared Content-Type header */ + content_type_header = + llcache_handle_get_header(llcache, "Content-Type"); + if (content_type_header != NULL) { + /* We don't care if this fails */ + http_parse_content_type(content_type_header, &ct); + } + + error = handler->create(handler, effective_type, + ct != NULL ? ct->parameters : NULL, + llcache, fallback_charset, quirks, + &c); + + if (ct != NULL) + http_content_type_destroy(ct); + + if (error != NSERROR_OK) + return NULL; + + return c; +} + diff --git a/code/validation/C/0129728_sysfile_update.c b/code/validation/C/0129728_sysfile_update.c new file mode 100644 index 0000000000000000000000000000000000000000..ec35d2ec53b83324d3dae1b1ec536c84033c4927 --- /dev/null +++ b/code/validation/C/0129728_sysfile_update.c @@ -0,0 +1,90 @@ +/****************************** + *Filname : sysfile_update.c + *Date : 2015-03-05 + * *****************************/ + + +#include +#include +#include +#include +#include +#include "sqlite3.h" + +# define sysfile_db "/ailvgo/system/box/sysfile.db" + +void bail(char *s) +{ + fputs(s, stderr); + fputc('\n', stderr); +} + +int main() +{ + sqlite3 *db = NULL; + sqlite3_stmt *ppstmt = NULL; + int rc = 0; + char sql_cmd[100] = {0}; + char sh_cmd[200] = {0}; + char *errorMsg = NULL; + const char *filename =NULL, *filepath = NULL; + char filename_all[100] = {0}; + int delete_flag = 0; + + printf("**********************************\n"); + printf("sysfile_update : start\n"); + printf("**********************************\n"); + + /*************************************************/ + + //sysfile check + printf("check sysfile in sysfile_update | sysfile.db\n"); + + rc=sqlite3_open(sysfile_db, &db); + if(rc == SQLITE_ERROR) + { + bail("open sysfile.db failed"); + } + ppstmt=NULL; + memset(sql_cmd, 0, sizeof(sql_cmd)); + strcpy(sql_cmd, "select filename, filepath from sysfile_update;"); + printf("sql_cmd : %s\n", sql_cmd); + sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0); + while(sqlite3_step(ppstmt) == SQLITE_ROW) + { + filename=sqlite3_column_text(ppstmt, 0); + printf("filename : %s\n", filename); + filepath=sqlite3_column_text(ppstmt, 1); + printf("filepath : %s\n", filepath); + + delete_flag = 1; + + memset(filename_all, 0, sizeof(filename_all)); + sprintf(filename_all, "/ailvgo/system/temp/%s", filename); + if(access(filename_all, R_OK) == 0) + { + memset(sh_cmd, 0, sizeof(sh_cmd)); + sprintf(sh_cmd, "mv -f %s %s%s", filename_all, filepath, filename); + printf("sh_cmd : %s\n", sh_cmd); + system(sh_cmd); + sleep(1); + } + } + if(delete_flag == 1) + { + printf("delete all files in sysfile_update | sysfile.db!\n"); + memset(sql_cmd, 0, sizeof(sql_cmd)); + strcpy(sql_cmd, "delete from sysfile_update;"); + printf("sql_cmd : %s\n", sql_cmd); + sqlite3_exec(db, sql_cmd, NULL, NULL, &errorMsg); + } + else + printf("no file in sysfile_update | sysfile.db\n"); + + sqlite3_finalize(ppstmt); + sqlite3_close(db); + + printf("sysfile_update : complete!\n"); + + system("chmod -R 777 /ailvgo/system/"); +} diff --git a/code/validation/C/0130318_179_largest_number.c b/code/validation/C/0130318_179_largest_number.c new file mode 100644 index 0000000000000000000000000000000000000000..2d0c68783515622cceae8b9f602e5b03db61e4f0 --- /dev/null +++ b/code/validation/C/0130318_179_largest_number.c @@ -0,0 +1,55 @@ +#include +#include +#include + +static int cmpfun(const void *a, const void *b) +{ + static char buf1[32], buf2[32]; + int i; + + sprintf(buf1, "%d%d", *(int *)a, *(int *)b); + sprintf(buf2, "%d%d", *(int *)b, *(int *)a); + for (i = 0; buf1[i] && buf2[i]; i++) { + if (buf1[i] > buf2[i]) + return(-1); + else if (buf1[i] < buf2[i]) + return(1); + } + return(0); +} + +char *largestNumber(int *nums, int numsSize) +{ + static char buf[16]; + int i, total, len; + char *res; + + if (!numsSize) { + return(strdup("0")); + } + qsort(nums, numsSize, sizeof(int), cmpfun); + res = 0; + total = 1; + for (i = 0; i < numsSize; i++) { + len = sprintf(buf, "%d", nums[i]); + if (!res) { + res = malloc((len + 1)); + res[0] = 0; + } else { + res = realloc(res, total + len); + } + strcat(res, buf); + if (i == 0 && nums[i] == 0) + break; + total += len; + } + return(res); +} + +int main(void) +{ + int x[] = { 824, 938, 1399, 5607, 6973, 5703, 9609, 4398, + 8247}; + printf("%s\n", largestNumber(x, sizeof(x) / sizeof(int))); + return(0); +} diff --git a/code/validation/C/0130513_latticetune.c b/code/validation/C/0130513_latticetune.c new file mode 100644 index 0000000000000000000000000000000000000000..96c40ac5fac94db5038826e98f768e422502aacf --- /dev/null +++ b/code/validation/C/0130513_latticetune.c @@ -0,0 +1,164 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2001 * + * by the Xiph.Org Foundation http://www.xiph.org/ * + * * + ******************************************************************** + + function: utility main for setting entropy encoding parameters + for lattice codebooks + last mod: $Id: latticetune.c,v 1.7 2008-02-02 15:54:08 richardash1981 Exp $ + + ********************************************************************/ + +#include +#include +#include +#include +#include +#include "bookutil.h" + +static int strrcmp_i(char *s,char *cmp){ + return(strncmp(s+strlen(s)-strlen(cmp),cmp,strlen(cmp))); +} + +/* This util takes a training-collected file listing codewords used in + LSP fitting, then generates new codeword lengths for maximally + efficient integer-bits entropy encoding. + + command line: + latticetune book.vqh input.vqd [unused_entriesp] + + latticetune produces book.vqh on stdout */ + +int main(int argc,char *argv[]){ + codebook *b; + static_codebook *c; + long *lengths; + long *hits; + + int entries=-1,dim=-1,guard=1; + FILE *in=NULL; + char *line,*name; + long j; + + if(argv[1]==NULL){ + fprintf(stderr,"Need a lattice codebook on the command line.\n"); + exit(1); + } + if(argv[2]==NULL){ + fprintf(stderr,"Need a codeword data file on the command line.\n"); + exit(1); + } + if(argv[3]!=NULL)guard=0; + + { + char *ptr; + char *filename=strdup(argv[1]); + + b=codebook_load(filename); + c=(static_codebook *)(b->c); + + ptr=strrchr(filename,'.'); + if(ptr){ + *ptr='\0'; + name=strdup(filename); + }else{ + name=strdup(filename); + } + } + + if(c->maptype!=1){ + fprintf(stderr,"Provided book is not a latticebook.\n"); + exit(1); + } + + entries=b->entries; + dim=b->dim; + + hits=_ogg_malloc(entries*sizeof(long)); + lengths=_ogg_calloc(entries,sizeof(long)); + for(j=0;jlengthlist=lengths; + write_codebook(stdout,name,c); + + { + long bins=_book_maptype1_quantvals(c); + long i,k,base=c->lengthlist[0]; + for(i=0;ilengthlist[i]>base)base=c->lengthlist[i]; + + for(j=0;jlengthlist[j]){ + int indexdiv=1; + fprintf(stderr,"%4ld: ",j); + for(k=0;kdim;k++){ + int index= (j/indexdiv)%bins; + fprintf(stderr,"%+3.1f,", c->quantlist[index]*_float32_unpack(c->q_delta)+ + _float32_unpack(c->q_min)); + indexdiv*=bins; + } + fprintf(stderr,"\t|"); + for(k=0;klengthlist[j];k++)fprintf(stderr,"*"); + fprintf(stderr,"\n"); + } + } + } + + fprintf(stderr,"\r " + "\nDone.\n"); + exit(0); +} diff --git a/code/validation/C/0130681_diomdel.c b/code/validation/C/0130681_diomdel.c new file mode 100644 index 0000000000000000000000000000000000000000..d81cd0cf386746bf0051bff0edf048665daf0fbe --- /dev/null +++ b/code/validation/C/0130681_diomdel.c @@ -0,0 +1,45 @@ +/********** +Copyright 1990 Regents of the University of California. All rights reserved. +Author: 1985 Thomas L. Quarles +**********/ +/* + */ + +#include "spice.h" +#include +#include "util.h" +#include "diodefs.h" +#include "sperror.h" +#include "suffix.h" + + +int +DIOmDelete(inModel,modname,kill) + GENmodel **inModel; + IFuid modname; + GENmodel *kill; +{ + DIOmodel **model = (DIOmodel**)inModel; + DIOmodel *modfast = (DIOmodel*)kill; + DIOinstance *here; + DIOinstance *prev = NULL; + DIOmodel **oldmod; + oldmod = model; + for( ; *model ; model = &((*model)->DIOnextModel)) { + if( (*model)->DIOmodName == modname || + (modfast && *model == modfast) ) goto delgot; + oldmod = model; + } + return(E_NOMOD); + +delgot: + *oldmod = (*model)->DIOnextModel; /* cut deleted device out of list */ + for(here = (*model)->DIOinstances ; here ; here = here->DIOnextInstance) { + if(prev) FREE(prev); + prev = here; + } + if(prev) FREE(prev); + FREE(*model); + return(OK); + +} diff --git a/code/validation/C/0130945_readsvf.c b/code/validation/C/0130945_readsvf.c new file mode 100644 index 0000000000000000000000000000000000000000..48d4318da681a3e194d6fb9a1b245fbf03b7e669 --- /dev/null +++ b/code/validation/C/0130945_readsvf.c @@ -0,0 +1,155 @@ +/************************************************************** + * Function Name: READSVF + * + * Purpose: Reads Arc/Info SVF file and puts the image data + * into the array pointed to by "image_ptr". + * + * Passed Parameters: + * filename: name of SVF file + * image_ptr: pointer to image to fill with this data + * + * Returned Parameters: + * min: returned; minimum class value in this dataset + * max: returned; maximum class value in this dataset + * + * Programmer: Barbara Marks + * + * Date: 26 October 1990 + * + * ID: $Id: readsvf.c,v 2.6 1994/10/05 16:07:42 marks Exp marks $ + ***************************************************************/ +#include +#include "stats.h" + +void read_svf(filename,image_ptr,min,max) +char *filename; +short *image_ptr; +short *min,*max; +{ + FILE *fp; + int i,j,k; + int count_intbck,count_bck; + short npairs,value; + short *ptr; + char rowflag; + unsigned char repeat; + + + + if ((fp = fopen(filename,"rb")) == NULL) { + printf ("\nERROR reading file: %s\n",filename); + exit(-1); + } + + ptr = image_ptr; + +/* + * Read the Arc/Info SVF file (compressed format): + * Record 1 contains the number of rows and columns in the image. + * Records 2-n contain the image image in the following format. + * rowstart flag (-1) - indicates the start of an image + * row [char] + * npairs - the number of pairs of (repeat,value) for + * this row [short] + * repeat value - number of times the next value is to be + * repeated [char] + * image value [short] + */ + fread (&num_rows,sizeof(short),1,fp); + fread (&num_cols,sizeof(short),1,fp); + + +/* + * total_size is the number of cells inside the landscape (this + * does not include interior background or landscape border cells). + */ + *min = 9999; + *max = -9999; + total_size = 0; + land_border = FALSE; + MAX_CLASSES = -9999; + count_bck = count_intbck = 0; + + for (i=0; i < num_rows; i++) { + fread(&rowflag,sizeof(char),1,fp); + if (rowflag != -1 ) { + printf("\nROWFLAG not -1: %d",rowflag); + printf ("\nFile [%s] probably not an SVF file\n",filename); + exit(-1); + } + fread (&npairs,sizeof(short),1,fp); + for (j=0; j < npairs; j++) { + fread (&repeat,sizeof(char),1,fp); + fread (&value,sizeof(short),1,fp); + +/* + * If there are negative cell values that are not background, + * then this image includes a landscape border. Set a flag. + */ + if (value < 0 && value != background && value != -background) + land_border = TRUE; + +/* + * Keep track of the minimum and maximum class value inside the + * landscape. + */ + if (value != background && value != -background) { + if (value < *min && value >= 0) *min = value; + if (value > *max) *max = value; + +/* + * If the image includes a landscape border, for contagion we + * need to know the number of different classes in the landscape + * including those in the landsape border. + */ + if (value >= 0 && value > MAX_CLASSES) + MAX_CLASSES = value; + if (value < 0 && -value > MAX_CLASSES) + MAX_CLASSES = -value; + } + +/* + * The value for background cells was input by the user. Set those + * background cells interior to the landscape to -990. Set those + * background cells in the landscape border, or outside the area of + * interest to -999. This makes life easier in several other routines. + */ + if (value == -background) { + count_bck += repeat; + value = -999; + } + + if (value == background) { + count_intbck += repeat; + value = -990; + } + if (value >= 0) total_size += repeat; + + + for (k=0; k < repeat; k++) + *ptr++ = value; + + } + } + + fclose (fp); + MAX_CLASSES ++; + + + + bcode = 0; + printf ("\n"); + if (count_bck > 0) { + printf ("\n... %d cells of background exterior to the landscape found", + count_bck); + bcode ++; + } + if (count_intbck > 0) { + printf ("\n... %d cells of background interior to the landscape found", + count_intbck); + bcode ++; + } + if (count_bck == 0 && count_intbck == 0) + printf ("\n... landscape does not contain background"); + +} diff --git a/code/validation/C/0132309_menu3.c b/code/validation/C/0132309_menu3.c new file mode 100644 index 0000000000000000000000000000000000000000..b46bfbbb26d64a6d1550dac8a8374c3e591f0760 --- /dev/null +++ b/code/validation/C/0132309_menu3.c @@ -0,0 +1,64 @@ +#include +#include +#include + +char *menu[] = { + "a - add new record", + "d - delete record", + "q - quit", + NULL +}; + +int getchoice(char *greet, char *choices[], FILE *in, FILE *out); + +int main(){ + int choice = 0; + FILE *input; + FILE *output; + + if(!isatty(fileno(stdout))){ + fprintf(stderr, "You are not a terminal.\n"); + } + + input = fopen("/dev/tty", "r"); + output = fopen("/dev/tty", "w"); + if(!input || !output){ + fprintf(stderr, "Unable to open /dev/tty\n"); + exit(1); + } + do { + choice = getchoice("Please select an action", menu, input, output); + printf("You've chosen: %c\n", choice); + }while(choice != 'q'); + exit(0); +} + +int getchoice(char *greet, char **choices, FILE *in, FILE *out){ + int chosen = 0; + int selected = 0; + char **option; + do{ + fprintf(out, "Choices: %s.\n", greet); + option = choices; + while(*option){ + fprintf(out,"%s\n", *option); + ++option; + } + + do{ + selected = fgetc(in); + }while(selected == '\n'); + option = choices; + while(*option){ + if(selected == *option[0]){ + chosen = 1; + break; + } + ++option; + } + + if(!chosen) + fprintf(out, "Wrong choice, try again later.\n"); + }while(!chosen); + return selected; +} diff --git a/code/validation/C/0132648_stacklight.c b/code/validation/C/0132648_stacklight.c new file mode 100644 index 0000000000000000000000000000000000000000..874aec197aa22e51587674ed471738550dbe4159 --- /dev/null +++ b/code/validation/C/0132648_stacklight.c @@ -0,0 +1,152 @@ +/******************************************************************************* +* Copyright (C) 2015 Michael R. Ferrara, All rights reserved. +* +* Santa Rosa, CA 95404 +* Tel:(707)536-1330 +* +* Filename: stacklight.c +* +* Description: STACKLIGHT "driver" +* +*******************************************************************************/ +//#define TRACE_PRINT 1 + +#define GLOBAL_STACKLIGHT +#include "stacklight.h" + +#include "OSandPlatform.h" +#include + +// 30ms is enough to switch the stacklightuator +#define STACKLIGHT_DLY 30 + +#define STACKRED S2U +#define STACKYEL S4U +#define STACKGRN S3D + +static uint32_t on_time = 100; +static uint32_t off_time = 900; +static uint32_t color=0; +static uint32_t count=0; +static uint32_t taskRun=1; + +void stackRed(int on) { + + hvOn(1);//Charge up the output cap + + if (on) { + //gpio_clear(STACKYEL); + //gpio_clear(STACKGRN); + gpio_set(STACKRED); + } else { + gpio_clear(STACKRED); + // hvOn(0); + } + +} + +void stackYel(int on) { + + hvOn(1);//Charge up the output cap + + if (on) { + //gpio_clear(STACKRED); + //gpio_clear(STACKGRN); + gpio_set(STACKYEL); + } else { + gpio_clear(STACKYEL); + // hvOn(0); + } + +} + + +void stackGrn(int on) { + + hvOn(1);//Charge up the output cap + + if (on) { + //gpio_clear(STACKRED); + //gpio_clear(STACKYEL); + gpio_set(STACKGRN); + } else { + gpio_clear(STACKGRN); + // hvOn(0); + } + +} + +// Color or 0 for off, on time (ms), off time (ms), count (0 for infinite) +uint32_t stackNotify(uint32_t col, uint32_t on, uint32_t off, uint32_t cnt) +{ + if (col) { + stacklightForceHV=1; + if (on==0) { //Solid on + taskRun=0; + if (col & R) stackRed(1); + if (col & Y) stackYel(1); + if (col & G) stackGrn(1); + } else { + on_time=on; + off_time = (off) ? off : on*2; + color=col; + count=cnt; + taskRun=1; + } + } else { //Turn off + color=0; + stacklightForceHV=0; + taskRun=1; + } + + return(0); +} + +portTASK_FUNCTION(vStackTask, pvParameters) +{ + uint32_t hv = 0; + uint32_t lastColor=0; + (void)pvParameters; + uint32_t cnt = 0; + while (1) { + while (taskRun) { + if (color && !hv) { + hvOn(1); + hv=1; + } + if (color && count) { + if (cnt==0) { + cnt=count; + } else { + cnt--; + if (cnt == 0) color=0; + } + } + + if (color & R) gpio_set(STACKRED); + if (color & Y) gpio_set(STACKYEL); + if (color & G) gpio_set(STACKGRN); + delayms(on_time); + if (color & R) gpio_clear(STACKRED); + if (color & Y) gpio_clear(STACKYEL); + if (color & G) gpio_clear(STACKGRN); + delayms(off_time); + + if (color == 0) { + if (lastColor) { //Toggle off + gpio_clear(STACKRED); + gpio_clear(STACKYEL); + gpio_clear(STACKGRN); + hvOn(0); + hv=0; + cnt=0; + taskRun=0; + } else { + taskYIELD(); //just in case + } + } + lastColor=color; + } + taskYIELD(); + } +} diff --git a/code/validation/C/0134479_DoubleArray.c b/code/validation/C/0134479_DoubleArray.c new file mode 100644 index 0000000000000000000000000000000000000000..a41fd397b7ed34c76ca60e62a3f4b6721dba37a6 --- /dev/null +++ b/code/validation/C/0134479_DoubleArray.c @@ -0,0 +1,97 @@ +#include "DoubleArray.h" + +#include +#include + +struct DoubleArray { + size_t size; + double data[]; +}; + +DoubleArray* DoubleArray_new(size_t size){ + if(size < 1) return NULL; + DoubleArray* ret = malloc(sizeof(DoubleArray) + sizeof(double) * size); + ret->size = size; + return ret; +} + +DoubleArray* DoubleArray_new_with_zeroes(size_t size){ + DoubleArray* ret = DoubleArray_new(size); + if(ret==NULL) return ret; + for(size_t i = 0; i < size ; i++) + ret->data[i] = 0; + return ret; +} + +void DoubleArray_delete(DoubleArray* arr){ + free(arr); +} + +size_t DoubleArray_size(DoubleArray* arr){ + return arr->size; +} + +double* DoubleArray_at(DoubleArray* arr, size_t index){ + #ifndef DOUBLE_ARRAY_NO_INDEX_CHECK + if(arr->size <= index){ + return NULL; + } + #endif + return arr->data + index; +} + +double DoubleArray_min(const DoubleArray* arr){ + return DoubleArray_min_l(arr, 0); +} + +double DoubleArray_min_l(const DoubleArray* arr, size_t last){ + if(last == 0 || last > arr->size) + last = arr->size; + double c_min = arr->data[0]; + for(size_t i = 1; i < last;i++) + if(arr->data[i] < c_min) + c_min = arr->data[i]; + return c_min; +} + +double DoubleArray_max(const DoubleArray* arr) { + return DoubleArray_max_l(arr, 0); +} + +double DoubleArray_max_l(const DoubleArray* arr, size_t last){ + if(last == 0 || last > arr->size) + last = arr->size; + double c_max = arr->data[0]; + for(size_t i = 1; i < last;i++) + if(arr->data[i] > c_max) + c_max = arr->data[i]; + return c_max; +} + +double DoubleArray_max_by(const DoubleArray* arr, int (*double_cmp)(double a, double b)){ + return DoubleArray_max_by_l(arr,double_cmp,0); +} + +double DoubleArray_max_by_l(const DoubleArray* arr, + int (*double_cmp)(double a, double b),size_t last){ + if(last == 0 || last > arr->size) + last = arr->size; + double c_max = arr->data[0]; + for(size_t i = 1; i < last;i++) + if(double_cmp(arr->data[i],c_max) > 0) + c_max = arr->data[i]; + return c_max; +} + +int DoubleArray_contains(const DoubleArray* arr, double element) { + return DoubleArray_contains_l(arr, element, 0); +} + +int DoubleArray_contains_l(const DoubleArray* arr, double element, size_t last){ + if(last == 0 || last > arr->size) + last = arr->size; + for(size_t i = 0; i < last;i++) + if(arr->data[i] == element) + return 1; + return 0; +} diff --git a/code/validation/C/0134752_hash.c b/code/validation/C/0134752_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..9ed09bc7ed713b4bcbe4f0693f5f2211bf385e2e --- /dev/null +++ b/code/validation/C/0134752_hash.c @@ -0,0 +1,96 @@ +#include "hash.h" +#include +#include +#include + +bool hash_equal(const uint8_t *hash_a, const size_t sizeof_hash_a, + const uint8_t *hash_b, const size_t sizeof_hash_b) +{ + if(sizeof_hash_a != sizeof_hash_b) { + return false; + } + + const size_t size = sizeof_hash_a; + + // Constant-time compare. + // Usefull in case this hash is used in a security context. + volatile uint8_t diff = 0; + for(size_t i=0;i bytes_to_read)) { + success = false; + break; + } + + // update the sha256 hash + mbedtls_sha256_update(&sha256, buffer, bytes_read); + + offset+= bytes_read; + } + // finish sha256 hash + mbedtls_sha256_finish(&sha256, result_hash); + mbedtls_sha256_free(&sha256); + + sdcard_close_file(&file); + return success; +} + +bool hash_flash(uint32_t flash_addr, const size_t num_bytes_to_hash, + uint8_t *result_hash, const size_t sizeof_result_hash) +{ + if(sizeof_result_hash != 32) { + return false; + } + + mbedtls_sha256((uint8_t*)flash_addr, num_bytes_to_hash, + result_hash, 0); + return true; +} + diff --git a/code/validation/C/0135097_timer.c b/code/validation/C/0135097_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..6b74e13d9c78b079fd69e230b00f248fccad0aea --- /dev/null +++ b/code/validation/C/0135097_timer.c @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2010 Linaro Limited + * John Rigby + * + * Based on original from Linux kernel source and + * internal ST-Ericsson U-Boot source. + * (C) Copyright 2009 Alessandro Rubini + * (C) Copyright 2010 ST-Ericsson + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +/* + * The MTU device has some interrupt control registers + * followed by 4 timers. + */ + +/* The timers */ +struct u8500_mtu_timer { + u32 lr; /* Load value */ + u32 cv; /* Current value */ + u32 cr; /* Control reg */ + u32 bglr; /* ??? */ +}; + +/* The MTU that contains the timers */ +struct u8500_mtu { + u32 imsc; /* Interrupt mask set/clear */ + u32 ris; /* Raw interrupt status */ + u32 mis; /* Masked interrupt status */ + u32 icr; /* Interrupt clear register */ + struct u8500_mtu_timer pt[4]; +}; + +/* bits for the control register */ +#define MTU_CR_ONESHOT 0x01 /* if 0 = wraps reloading from BGLR */ +#define MTU_CR_32BITS 0x02 + +#define MTU_CR_PRESCALE_1 0x00 +#define MTU_CR_PRESCALE_16 0x04 +#define MTU_CR_PRESCALE_256 0x08 +#define MTU_CR_PRESCALE_MASK 0x0c + +#define MTU_CR_PERIODIC 0x40 /* if 0 = free-running */ +#define MTU_CR_ENA 0x80 + +/* + * The MTU is clocked at 133 MHz by default. (V1 and later) + */ +#define TIMER_CLOCK (133 * 1000 * 1000 / 16) +#define COUNT_TO_USEC(x) ((x) * 16 / 133) +#define USEC_TO_COUNT(x) ((x) * 133 / 16) +#define TICKS_PER_HZ (TIMER_CLOCK / CONFIG_SYS_HZ) +#define TICKS_TO_HZ(x) ((x) / TICKS_PER_HZ) +#define TIMER_LOAD_VAL 0xffffffff + +/* + * MTU timer to use (from 0 to 3). + */ +#define MTU_TIMER 2 + +static struct u8500_mtu_timer *timer_base = + &((struct u8500_mtu *)U8500_MTU0_BASE_V1)->pt[MTU_TIMER]; + +/* macro to read the 32 bit timer: since it decrements, we invert read value */ +#define READ_TIMER() (~readl(&timer_base->cv)) + +/* Configure a free-running, auto-wrap counter with /16 prescaler */ +int timer_init(void) +{ + writel(MTU_CR_ENA | MTU_CR_PRESCALE_16 | MTU_CR_32BITS, + &timer_base->cr); + return 0; +} + +ulong get_timer_masked(void) +{ + /* current tick value */ + ulong now = TICKS_TO_HZ(READ_TIMER()); + + if (now >= gd->arch.lastinc) { /* normal (non rollover) */ + gd->arch.tbl += (now - gd->arch.lastinc); + } else { /* rollover */ + gd->arch.tbl += (TICKS_TO_HZ(TIMER_LOAD_VAL) - + gd->arch.lastinc) + now; + } + gd->arch.lastinc = now; + return gd->arch.tbl; +} + +/* Delay x useconds */ +void __udelay(ulong usec) +{ + long tmo = usec * (TIMER_CLOCK / 1000) / 1000; + ulong now, last = READ_TIMER(); + + while (tmo > 0) { + now = READ_TIMER(); + if (now > last) /* normal (non rollover) */ + tmo -= now - last; + else /* rollover */ + tmo -= TIMER_LOAD_VAL - last + now; + last = now; + } +} + +ulong get_timer(ulong base) +{ + return get_timer_masked() - base; +} + +/* + * Emulation of Power architecture long long timebase. + * + * TODO: Support gd->arch.tbu for real long long timebase. + */ +unsigned long long get_ticks(void) +{ + return get_timer(0); +} + +/* + * Emulation of Power architecture timebase. + * NB: Low resolution compared to Power tbclk. + */ +ulong get_tbclk(void) +{ + return CONFIG_SYS_HZ; +} diff --git a/code/validation/C/0135178_zuncmprss.c b/code/validation/C/0135178_zuncmprss.c new file mode 100644 index 0000000000000000000000000000000000000000..33a2b31ffd7085ac2542abb851c2f12d13c285ff --- /dev/null +++ b/code/validation/C/0135178_zuncmprss.c @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include "zstring.h" +#include "xalt_c_utils.h" + +#define BUFFSZ 32768 +#define MAX(a,b) ((a) > (b) ? (a) : (b)) + +char* uncompress_string(const char* str, int len) +{ + z_stream zs; + memset(&zs, 0, sizeof(zs)); + + if (inflateInit(&zs) != Z_OK) + { + fprintf(stderr,"inflateInit failed while decompressing.\n"); + exit(1); + } + + zs.next_in = (Bytef*)str; + zs.avail_in = len; + + int ret, oldSz; + char outbuffer[BUFFSZ]; + + int totalSz = 4*len; + int szOut = 0; + char* prev; + char* out = (char *) XMALLOC(totalSz+1); + + do + { + zs.next_out = (Bytef *) outbuffer; + zs.avail_out = BUFFSZ; + + ret = inflate(&zs, 0); + + oldSz = szOut; + szOut = zs.total_out; + + if ( szOut > totalSz) + { + totalSz = MAX(2*totalSz,2*szOut); + prev = out; + out = (char *) XMALLOC(totalSz+1); + memcpy(out, prev, oldSz); + my_free(prev, strlen(prev)); + } + + if (oldSz < szOut ) + { + memcpy(&out[oldSz], outbuffer, zs.total_out - oldSz); + out[szOut] = '\0'; + } + } + while(ret == Z_OK); + + inflateEnd(&zs); + if (ret != Z_STREAM_END) + { + // an error occurred that was not EOF + fprintf(stderr,"Exception during zlib decompression: (%d) %s\n",ret, zs.msg); + exit(1); + } + return out; +} diff --git a/code/validation/C/0135331_timer.c b/code/validation/C/0135331_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..12a16b3210aeb401feb0767c6c3e61336e03ab8b --- /dev/null +++ b/code/validation/C/0135331_timer.c @@ -0,0 +1,138 @@ +/* + * (C) Copyright 2008 + * Texas Instruments + * + * Richard Woodruff + * Syed Moahmmed Khasim + * + * (C) Copyright 2002 + * Sysgo Real-Time Solutions, GmbH + * Marius Groeger + * Alex Zuepke + * + * (C) Copyright 2002 + * Gary Jennejohn, DENX Software Engineering, + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include +#include + +static ulong timestamp; +static ulong lastinc; +static struct gptimer *timer_base = (struct gptimer *)CONFIG_SYS_TIMERBASE; + +/* + * Nothing really to do with interrupts, just starts up a counter. + * We run the counter with 13MHz, divided by 8, resulting in timer + * frequency of 1.625MHz. With 32bit counter register, counter + * overflows in ~44min + */ + +/* 13MHz / 8 = 1.625MHz */ +#define TIMER_CLOCK (V_SCLK / (2 << CONFIG_SYS_PTV)) +#define TIMER_LOAD_VAL 0xffffffff + +int timer_init(void) +{ + /* start the counter ticking up, reload value on overflow */ + writel(TIMER_LOAD_VAL, &timer_base->tldr); + /* enable timer */ + writel((CONFIG_SYS_PTV << 2) | TCLR_PRE | TCLR_AR | TCLR_ST, + &timer_base->tclr); + + reset_timer_masked(); /* init the timestamp and lastinc value */ + + return 0; +} + +/* + * timer without interrupts + */ +void reset_timer(void) +{ + reset_timer_masked(); +} + +ulong get_timer(ulong base) +{ + return get_timer_masked() - base; +} + +void set_timer(ulong t) +{ + timestamp = t; +} + +/* delay x useconds */ +void udelay(unsigned long usec) +{ + long tmo = usec * (TIMER_CLOCK / 1000) / 1000; + unsigned long now, last = readl(&timer_base->tcrr); + + while (tmo > 0) { + now = readl(&timer_base->tcrr); + if (last > now) /* count up timer overflow */ + tmo -= TIMER_LOAD_VAL - last + now; + else + tmo -= now - last; + last = now; + } +} + +void reset_timer_masked(void) +{ + /* reset time, capture current incrementer value time */ + lastinc = readl(&timer_base->tcrr) / (TIMER_CLOCK / CONFIG_SYS_HZ); + timestamp = 0; /* start "advancing" time stamp from 0 */ +} + +ulong get_timer_masked(void) +{ + /* current tick value */ + ulong now = readl(&timer_base->tcrr) / (TIMER_CLOCK / CONFIG_SYS_HZ); + + if (now >= lastinc) /* normal mode (non roll) */ + /* move stamp fordward with absoulte diff ticks */ + timestamp += (now - lastinc); + else /* we have rollover of incrementer */ + timestamp += ((TIMER_LOAD_VAL / (TIMER_CLOCK / CONFIG_SYS_HZ)) + - lastinc) + now; + lastinc = now; + return timestamp; +} + +/* + * This function is derived from PowerPC code (read timebase as long long). + * On ARM it just returns the timer value. + */ +unsigned long long get_ticks(void) +{ + return get_timer(0); +} + +/* + * This function is derived from PowerPC code (timebase clock frequency). + * On ARM it returns the number of timer ticks per second. + */ +ulong get_tbclk(void) +{ + return CONFIG_SYS_HZ; +} diff --git a/code/validation/C/0135671_latencytop.c b/code/validation/C/0135671_latencytop.c new file mode 100644 index 0000000000000000000000000000000000000000..ee74b35e528d1f6a909e29cfbe5d76a8a79fc837 --- /dev/null +++ b/code/validation/C/0135671_latencytop.c @@ -0,0 +1,291 @@ +/* + * latencytop.c: Latency display infrastructure + * + * (C) Copyright 2008 Intel Corporation + * Author: Arjan van de Ven + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; version 2 + * of the License. + */ + +/* + * CONFIG_LATENCYTOP enables a kernel latency tracking infrastructure that is + * used by the "latencytop" userspace tool. The latency that is tracked is not + * the 'traditional' interrupt latency (which is primarily caused by something + * else consuming CPU), but instead, it is the latency an application encounters + * because the kernel sleeps on its behalf for various reasons. + * + * This code tracks 2 levels of statistics: + * 1) System level latency + * 2) Per process latency + * + * The latency is stored in fixed sized data structures in an accumulated form; + * if the "same" latency cause is hit twice, this will be tracked as one entry + * in the data structure. Both the count, total accumulated latency and maximum + * latency are tracked in this data structure. When the fixed size structure is + * full, no new causes are tracked until the buffer is flushed by writing to + * the /proc file; the userspace tool does this on a regular basis. + * + * A latency cause is identified by a stringified backtrace at the point that + * the scheduler gets invoked. The userland tool will use this string to + * identify the cause of the latency in human readable form. + * + * The information is exported via /proc/latency_stats and /proc//latency. + * These files look like this: + * + * Latency Top version : v0.1 + * 70 59433 4897 i915_irq_wait drm_ioctl vfs_ioctl do_vfs_ioctl sys_ioctl + * | | | | + * | | | +----> the stringified backtrace + * | | +---------> The maximum latency for this entry in microseconds + * | +--------------> The accumulated latency for this entry (microseconds) + * +-------------------> The number of times this entry is hit + * + * (note: the average latency is the accumulated latency divided by the number + * of times) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static DEFINE_SPINLOCK(latency_lock); + +#define MAXLR 128 +static struct latency_record latency_record[MAXLR]; + +int latencytop_enabled; + +void clear_all_latency_tracing(struct task_struct *p) +{ + unsigned long flags; + + if (!latencytop_enabled) + return; + + spin_lock_irqsave(&latency_lock, flags); + memset(&p->latency_record, 0, sizeof(p->latency_record)); + p->latency_record_count = 0; + spin_unlock_irqrestore(&latency_lock, flags); +} + +static void clear_global_latency_tracing(void) +{ + unsigned long flags; + + spin_lock_irqsave(&latency_lock, flags); + memset(&latency_record, 0, sizeof(latency_record)); + spin_unlock_irqrestore(&latency_lock, flags); +} + +static void __sched +account_global_scheduler_latency(struct task_struct *tsk, struct latency_record *lat) +{ + int firstnonnull = MAXLR + 1; + int i; + + if (!latencytop_enabled) + return; + + /* skip kernel threads for now */ + if (!tsk->mm) + return; + + for (i = 0; i < MAXLR; i++) { + int q, same = 1; + + /* Nothing stored: */ + if (!latency_record[i].backtrace[0]) { + if (firstnonnull > i) + firstnonnull = i; + continue; + } + for (q = 0; q < LT_BACKTRACEDEPTH; q++) { + unsigned long record = lat->backtrace[q]; + + if (latency_record[i].backtrace[q] != record) { + same = 0; + break; + } + + /* 0 and ULONG_MAX entries mean end of backtrace: */ + if (record == 0 || record == ULONG_MAX) + break; + } + if (same) { + latency_record[i].count++; + latency_record[i].time += lat->time; + if (lat->time > latency_record[i].max) + latency_record[i].max = lat->time; + return; + } + } + + i = firstnonnull; + if (i >= MAXLR - 1) + return; + + /* Allocted a new one: */ + memcpy(&latency_record[i], lat, sizeof(struct latency_record)); +} + +/* + * Iterator to store a backtrace into a latency record entry + */ +static inline void store_stacktrace(struct task_struct *tsk, + struct latency_record *lat) +{ + struct stack_trace trace; + + memset(&trace, 0, sizeof(trace)); + trace.max_entries = LT_BACKTRACEDEPTH; + trace.entries = &lat->backtrace[0]; + save_stack_trace_tsk(tsk, &trace); +} + +/** + * __account_scheduler_latency - record an occured latency + * @tsk - the task struct of the task hitting the latency + * @usecs - the duration of the latency in microseconds + * @inter - 1 if the sleep was interruptible, 0 if uninterruptible + * + * This function is the main entry point for recording latency entries + * as called by the scheduler. + * + * This function has a few special cases to deal with normal 'non-latency' + * sleeps: specifically, interruptible sleep longer than 5 msec is skipped + * since this usually is caused by waiting for events via select() and co. + * + * Negative latencies (caused by time going backwards) are also explicitly + * skipped. + */ +void __sched +__account_scheduler_latency(struct task_struct *tsk, int usecs, int inter) +{ + unsigned long flags; + int i, q; + struct latency_record lat; + + /* Long interruptible waits are generally user requested... */ + if (inter && usecs > 5000) + return; + + /* Negative sleeps are time going backwards */ + /* Zero-time sleeps are non-interesting */ + if (usecs <= 0) + return; + + memset(&lat, 0, sizeof(lat)); + lat.count = 1; + lat.time = usecs; + lat.max = usecs; + store_stacktrace(tsk, &lat); + + spin_lock_irqsave(&latency_lock, flags); + + account_global_scheduler_latency(tsk, &lat); + + for (i = 0; i < tsk->latency_record_count; i++) { + struct latency_record *mylat; + int same = 1; + + mylat = &tsk->latency_record[i]; + for (q = 0; q < LT_BACKTRACEDEPTH; q++) { + unsigned long record = lat.backtrace[q]; + + if (mylat->backtrace[q] != record) { + same = 0; + break; + } + + /* 0 and ULONG_MAX entries mean end of backtrace: */ + if (record == 0 || record == ULONG_MAX) + break; + } + if (same) { + mylat->count++; + mylat->time += lat.time; + if (lat.time > mylat->max) + mylat->max = lat.time; + goto out_unlock; + } + } + + /* + * short term hack; if we're > 32 we stop; future we recycle: + */ + if (tsk->latency_record_count >= LT_SAVECOUNT) + goto out_unlock; + + /* Allocated a new one: */ + i = tsk->latency_record_count++; + memcpy(&tsk->latency_record[i], &lat, sizeof(struct latency_record)); + +out_unlock: + spin_unlock_irqrestore(&latency_lock, flags); +} + +static int lstats_show(struct seq_file *m, void *v) +{ + int i; + + seq_puts(m, "Latency Top version : v0.1\n"); + + for (i = 0; i < MAXLR; i++) { + struct latency_record *lr = &latency_record[i]; + + if (lr->backtrace[0]) { + int q; + seq_printf(m, "%i %lu %lu", + lr->count, lr->time, lr->max); + for (q = 0; q < LT_BACKTRACEDEPTH; q++) { + unsigned long bt = lr->backtrace[q]; + if (!bt) + break; + if (bt == ULONG_MAX) + break; + seq_printf(m, " %ps", (void *)bt); + } + seq_printf(m, "\n"); + } + } + return 0; +} + +static ssize_t +lstats_write(struct file *file, const char __user *buf, size_t count, + loff_t *offs) +{ + clear_global_latency_tracing(); + + return count; +} + +static int lstats_open(struct inode *inode, struct file *filp) +{ + return single_open(filp, lstats_show, NULL); +} + +static const struct file_operations lstats_fops = { + .open = lstats_open, + .read = seq_read, + .write = lstats_write, + .llseek = seq_lseek, + .release = single_release, +}; + +static int __init init_lstats_procfs(void) +{ + proc_create("latency_stats", 0644, NULL, &lstats_fops); + return 0; +} +device_initcall(init_lstats_procfs); diff --git a/code/validation/C/0135753_soft_pwm.c b/code/validation/C/0135753_soft_pwm.c new file mode 100644 index 0000000000000000000000000000000000000000..2227204792b778b8d91e360d2489a6f0b3186877 --- /dev/null +++ b/code/validation/C/0135753_soft_pwm.c @@ -0,0 +1,215 @@ +/* +Copyright (c) 2013 Ben Croston + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +#include +#include +#include +#include "c_gpio.h" +#include "common.h" +#include "soft_pwm.h" +pthread_t threads; + +struct pwm +{ + unsigned int gpio; + float freq; + float dutycycle; + float basetime; + float slicetime; + struct timespec req_on, req_off; + int running; + struct pwm *next; +}; +struct pwm *pwm_list = NULL; + +void remove_pwm(unsigned int gpio) +{ + struct pwm *p = pwm_list; + struct pwm *prev = NULL; + struct pwm *temp; + + while (p != NULL) + { + if (p->gpio == gpio) + { + if (prev == NULL) + pwm_list = p->next; + else + prev->next = p->next; + temp = p; + p = p->next; + free(temp); + } else { + prev = p; + p = p->next; + } + } +} + +void calculate_times(struct pwm *p) +{ + long long usec; + + usec = (long long)(p->dutycycle * p->slicetime * 1000.0); + p->req_on.tv_sec = (int)(usec / 1000000LL); + usec -= (long long)p->req_on.tv_sec * 1000000LL; + p->req_on.tv_nsec = (long)usec * 1000L; + + usec = (long long)((100.0-p->dutycycle) * p->slicetime * 1000.0); + p->req_off.tv_sec = (int)(usec / 1000000LL); + usec -= (long long)p->req_off.tv_sec * 1000000LL; + p->req_off.tv_nsec = (long)usec * 1000L; +} + +void full_sleep(struct timespec *req) +{ + struct timespec rem = {0}; + + if (nanosleep(req,&rem) == -1) + full_sleep(&rem); +} + +void *pwm_thread(void *threadarg) +{ + struct pwm *p = (struct pwm *)threadarg; + + while (p->running) + { + + if (p->dutycycle > 0.0) + { + output_gpio(*(pinTobcm_BP + p->gpio), 1); + full_sleep(&p->req_on); + } + + if (p->dutycycle < 100.0) + { + output_gpio(*(pinTobcm_BP + p->gpio), 0); + full_sleep(&p->req_off); + } + } + + // clean up + output_gpio(*(pinTobcm_BP + p->gpio), 0); + remove_pwm(p->gpio); + pthread_exit(NULL); +} + +struct pwm *add_new_pwm(unsigned int gpio) +{ + struct pwm *new_pwm; + + new_pwm = malloc(sizeof(struct pwm)); + new_pwm->gpio = gpio; + new_pwm->running = 0; + new_pwm->next = NULL; + // default to 1 kHz frequency, dutycycle 0.0 + new_pwm->freq = 1000.0; + new_pwm->dutycycle = 0.0; + new_pwm->basetime = 1.0; // 1 ms + new_pwm->slicetime = 0.01; // 0.01 ms + calculate_times(new_pwm); + return new_pwm; +} + +struct pwm *find_pwm(unsigned int gpio) +{ + struct pwm *p = pwm_list; + + if (pwm_list == NULL) + { + pwm_list = add_new_pwm(gpio); + return pwm_list; + } + + while (p != NULL) + { + if (p->gpio == gpio) + return p; + if (p->next == NULL) + { + p->next = add_new_pwm(gpio); + return p->next; + } + p = p->next; + } + return NULL; +} + +void pwm_set_duty_cycle(unsigned int gpio, float dutycycle) +{ + struct pwm *p; + + if (dutycycle < 0.0 || dutycycle > 100.0) + { + // btc fixme - error + return; + } + + if ((p = find_pwm(gpio)) != NULL) + { + p->dutycycle = dutycycle; + calculate_times(p); + } +} + +void pwm_set_frequency(unsigned int gpio, float freq) +{ + struct pwm *p; + + if (freq <= 0.0) // to avoid divide by zero + { + // btc fixme - error + return; + } + + if ((p = find_pwm(gpio)) != NULL) + { + p->basetime = 1000.0 / freq; // calculated in ms + p->slicetime = p->basetime / 100.0; + calculate_times(p); + } +} + +void pwm_start(unsigned int gpio) +{ + struct pwm *p; + + if (((p = find_pwm(gpio)) == NULL) || p->running) + return; + + p->running = 1; + if (pthread_create(&threads, NULL, pwm_thread, (void *)p) != 0) + { + // btc fixme - error + p->running = 0; + return; + } +} + +void pwm_stop(unsigned int gpio) +{ + struct pwm *p; + + if ((p = find_pwm(gpio)) != NULL) + p->running = 0; +} diff --git a/code/validation/C/0136060_testfielddg_bis.c b/code/validation/C/0136060_testfielddg_bis.c new file mode 100644 index 0000000000000000000000000000000000000000..ae1125f65dd7425ee08256705d34d8458c0dc9be --- /dev/null +++ b/code/validation/C/0136060_testfielddg_bis.c @@ -0,0 +1,84 @@ +#include "test.h" +#include "schnaps.h" +#include +#include +#include + + +int TestfieldDG_bis(void){ + + int test = true; + + Model model; + + model.cfl = 0.05; + model.m = 1; // only one conservative variable + model.NumFlux = TransNumFlux; + model.BoundaryFlux = TestTransBoundaryFlux; + model.InitData = TestTransInitData; + model.ImposedData = TestTransImposedData; + model.Source = NULL; + + int deg[]={4, 4, 4}; + int raf[]={1, 1, 1}; + /* int deg[]={1, 1, 1}; */ + /* int raf[]={1, 1, 1}; */ + + MacroMesh mesh; + //ReadMacroMesh(&mesh,"../test/testmacromesh.msh"); + ReadMacroMesh(&mesh,"../test/testcube2.msh"); + BuildConnectivity(&mesh); + + /* real A[3][3] = {{10,2 , 0}, {0, 1, -0.1}, {0, 0.1,1}}; */ + /* real x0[3] = {1, 2, 3}; */ + /* AffineMapMacroMesh(&mesh,A,x0); */ + + CheckMacroMesh(&mesh, deg, raf); + + //PrintMacroMesh(&mesh); + + Simulation simu; + EmptySimulation(&simu); + + InitSimulation(&simu, &mesh, deg, raf, &model); + + simu.tnow = 0; + + DtFields_bis(&simu, simu.w, simu.dtw); + + for(int i = 0; i < simu.wsize; i++){ + printf("i=%d dtw=%.8e\n",i,simu.dtw[i]); + } + //DisplaySimulation(&simu); + + //PlotFields(0, false, &simu, NULL, "visu_spu.msh"); + //PlotFields(0, true, &simu, "error", "error.msh"); + + //Test the time derivative with the exact solution + schnaps_real test2 = 0; + for(int i = 0; + i < model.m * mesh.nbelems * NPG(deg,raf); + i++){ + schnaps_real errloc = fabs(4 * simu.w[i] - pow(simu.dtw[i], 2)); + //real errloc = pow(simu.dtw[i], 2.); + //errloc = fabs(pow(simu.dtw[i], 2)); + test2 += errloc * errloc; + test = test && errloc < 1e-2; + //printf("i=%d err=%f \n",i,4 * w[i] - pow(dtw[i], 2)); + //assert(test); + } + + printf("error=%.10e\n",sqrt(test2/ (mesh.nbelems * NPG(deg,raf)) )); + + FreeMacroMesh(&mesh); + + return test; +}; + +int main(void) { + // Unit tests + int resu = TestfieldDG_bis(); + if (resu) printf("field DG bis test OK !\n"); + else printf("field DG bis test failed !\n"); + return !resu; +} diff --git a/code/validation/C/0136568_dna2div.c b/code/validation/C/0136568_dna2div.c new file mode 100644 index 0000000000000000000000000000000000000000..a9685630a59e23b0901296c96e85034311199eb3 --- /dev/null +++ b/code/validation/C/0136568_dna2div.c @@ -0,0 +1,148 @@ +#include +#include +#include +#include + +#include "pq_htable.h" + +#include "pq_args.h" +#include "pq_parse.h" +#include "pq_limits.h" +#include "pq_generics.h" +#include "pq_div.h" +#include "pq_help.h" +#include "pq_version.h" + +int main(int argc, char **argv) +{ + if (argc > 1 && strcmp(argv[1], "--help") == 0) { + printf("Help!\n"); + exit(0); + } + + if (argc > 1 && strcmp(argv[1], "--version") == 0) { + pq_display_version(); + exit(0); + } + + int i; + int frm_multi; + const char *cmd_defaults; + struct StatObject Stat; + + void (*stat_init)(struct StatObject *, int); + + frm_multi = PQ_DIV_FRMT; + stat_init = PQ_DIV_INIT; + cmd_defaults = PQ_DIV_DEFS; + + FILE *fp; + + int nargs; + char **def_array; + char defaults[128]; + + int ncols; + int nalleles; + char buffer[PQ_LWIDTH]; + char delim = '\t'; + + char chr[PQ_LCOL]; + char factor[PQ_LCOL]; + unsigned long long int startpos; + + unsigned long long int stoppos; + unsigned long long int start_region; + unsigned long long int stop_region; + + struct GenericRow row; + + int argc_wo_file; + + fp = stdin; + argc_wo_file = argc; + if (argc > 1 && access(argv[argc - 1], F_OK) != -1) { + fp = fopen(argv[argc - 1], "r"); + argc_wo_file = argc - 1; + } + + fgets(buffer, sizeof(buffer), fp); + + // add defaults but with dummy -k variable + sprintf(defaults, cmd_defaults, 6); + + nargs = pq_countcols(defaults, " "); + def_array = calloc(nargs, sizeof(char *)); + pq_str2array(def_array, defaults, nargs, " "); + + pq_init_args(); + pq_update_args(nargs, def_array); + pq_update_args(argc_wo_file-1, argv+1); + + // space delimeters must be escaped on the command line (i.e. -d '\ ') + delim = ((char *)pq_lookup_hash(&ARGHASH, "-d"))[1]; + ncols = pq_countcols(buffer, &delim); + sprintf(defaults, cmd_defaults, ncols); + pq_str2array(def_array, defaults, nargs, " "); + + pq_update_args(nargs, def_array); + pq_update_args(argc_wo_file-1, argv+1); + + free(def_array); + + init_row(&row, ncols, CHROM, POS, FCOL); + + nalleles = frm_multi * NKARGS; + stat_init(&Stat, nalleles); + + row.update(&row, buffer, &delim); + strcpy(chr, row.chrom(&row)); + strcpy(factor, row.factor(&row)); + start_region = row.pos(&row) - 1; + + goto POST_INIT; + + while (fgets(buffer, sizeof(buffer), fp)) { + + row.update(&row, buffer, &delim); + + POST_INIT: + + stoppos = row.pos(&row); + startpos = stoppos - 1; + + if (strcmp(row.factor(&row), factor) != 0) { + Stat.write(&Stat); + printf("%s\t%llu\t%llu\t%s", chr, start_region, stop_region, factor); + for (i = 0; i < Stat.nouts; i++) { + printf("\t%s", (char *)Stat.outs[i]); + } + printf("\n"); + Stat.clear(&Stat); + + strcpy(factor, row.factor(&row)); + start_region = startpos; + stop_region = stoppos; + } + + Stat.update(&Stat, row.array); + + stop_region = stoppos; + strcpy(chr, row.chrom(&row)); + } + + Stat.write(&Stat); + printf("%s\t%llu\t%llu\t%s", chr, start_region, stop_region, factor); + for (i = 0; i < Stat.nouts; i++) { + printf("\t%s", (char *)Stat.outs[i]); + } + printf("\n"); + Stat.clear(&Stat); + + pq_free_args(); + pq_swfree(&Stat); + free_row(&row); + fclose(fp); + + return 0; +} diff --git a/code/validation/C/0137156_scan.c b/code/validation/C/0137156_scan.c new file mode 100644 index 0000000000000000000000000000000000000000..4300d9db7d8caab2d70442b7cbd37a9da69adef9 --- /dev/null +++ b/code/validation/C/0137156_scan.c @@ -0,0 +1,231 @@ +/* Helpers for managing scan queues + * + * See copyright notice in main.c + */ + +#include +#include +#include +#include +#include + +#include "hermes.h" +#include "orinoco.h" +#include "main.h" + +#include "scan.h" + +#define ZERO_DBM_OFFSET 0x95 +#define MAX_SIGNAL_LEVEL 0x8A +#define MIN_SIGNAL_LEVEL 0x2F + +#define SIGNAL_TO_DBM(x) \ + (clamp_t(s32, (x), MIN_SIGNAL_LEVEL, MAX_SIGNAL_LEVEL) \ + - ZERO_DBM_OFFSET) +#define SIGNAL_TO_MBM(x) (SIGNAL_TO_DBM(x) * 100) + +static int symbol_build_supp_rates(u8 *buf, const __le16 *rates) +{ + int i; + u8 rate; + + buf[0] = WLAN_EID_SUPP_RATES; + for (i = 0; i < 5; i++) { + rate = le16_to_cpu(rates[i]); + /* NULL terminated */ + if (rate == 0x0) + break; + buf[i + 2] = rate; + } + buf[1] = i; + + return i + 2; +} + +static int prism_build_supp_rates(u8 *buf, const u8 *rates) +{ + int i; + + buf[0] = WLAN_EID_SUPP_RATES; + for (i = 0; i < 8; i++) { + /* NULL terminated */ + if (rates[i] == 0x0) + break; + buf[i + 2] = rates[i]; + } + buf[1] = i; + + /* We might still have another 2 rates, which need to go in + * extended supported rates */ + if (i == 8 && rates[i] > 0) { + buf[10] = WLAN_EID_EXT_SUPP_RATES; + for (; i < 10; i++) { + /* NULL terminated */ + if (rates[i] == 0x0) + break; + buf[i + 2] = rates[i]; + } + buf[11] = i - 8; + } + + return (i < 8) ? i + 2 : i + 4; +} + +static void orinoco_add_hostscan_result(struct orinoco_private *priv, + const union hermes_scan_info *bss) +{ + struct wiphy *wiphy = priv_to_wiphy(priv); + struct ieee80211_channel *channel; + u8 *ie; + u8 ie_buf[46]; + u64 timestamp; + s32 signal; + u16 capability; + u16 beacon_interval; + int ie_len; + int freq; + int len; + + len = le16_to_cpu(bss->a.essid_len); + + /* Reconstruct SSID and bitrate IEs to pass up */ + ie_buf[0] = WLAN_EID_SSID; + ie_buf[1] = len; + memcpy(&ie_buf[2], bss->a.essid, len); + + ie = ie_buf + len + 2; + ie_len = ie_buf[1] + 2; + switch (priv->firmware_type) { + case FIRMWARE_TYPE_SYMBOL: + ie_len += symbol_build_supp_rates(ie, bss->s.rates); + break; + + case FIRMWARE_TYPE_INTERSIL: + ie_len += prism_build_supp_rates(ie, bss->p.rates); + break; + + case FIRMWARE_TYPE_AGERE: + default: + break; + } + + freq = ieee80211_dsss_chan_to_freq(le16_to_cpu(bss->a.channel)); + channel = ieee80211_get_channel(wiphy, freq); + timestamp = 0; + capability = le16_to_cpu(bss->a.capabilities); + beacon_interval = le16_to_cpu(bss->a.beacon_interv); + signal = SIGNAL_TO_MBM(le16_to_cpu(bss->a.level)); + + cfg80211_inform_bss(wiphy, channel, bss->a.bssid, timestamp, + capability, beacon_interval, ie_buf, ie_len, + signal, GFP_KERNEL); +} + +void orinoco_add_extscan_result(struct orinoco_private *priv, + struct agere_ext_scan_info *bss, + size_t len) +{ + struct wiphy *wiphy = priv_to_wiphy(priv); + struct ieee80211_channel *channel; + const u8 *ie; + u64 timestamp; + s32 signal; + u16 capability; + u16 beacon_interval; + size_t ie_len; + int chan, freq; + + ie_len = len - sizeof(*bss); + ie = cfg80211_find_ie(WLAN_EID_DS_PARAMS, bss->data, ie_len); + chan = ie ? ie[2] : 0; + freq = ieee80211_dsss_chan_to_freq(chan); + channel = ieee80211_get_channel(wiphy, freq); + + timestamp = le64_to_cpu(bss->timestamp); + capability = le16_to_cpu(bss->capabilities); + beacon_interval = le16_to_cpu(bss->beacon_interval); + ie = bss->data; + signal = SIGNAL_TO_MBM(bss->level); + + cfg80211_inform_bss(wiphy, channel, bss->bssid, timestamp, + capability, beacon_interval, ie, ie_len, + signal, GFP_KERNEL); +} + +void orinoco_add_hostscan_results(struct orinoco_private *priv, + unsigned char *buf, + size_t len) +{ + int offset; /* In the scan data */ + size_t atom_len; + bool abort = false; + + switch (priv->firmware_type) { + case FIRMWARE_TYPE_AGERE: + atom_len = sizeof(struct agere_scan_apinfo); + offset = 0; + break; + + case FIRMWARE_TYPE_SYMBOL: + /* Lack of documentation necessitates this hack. + * Different firmwares have 68 or 76 byte long atoms. + * We try modulo first. If the length divides by both, + * we check what would be the channel in the second + * frame for a 68-byte atom. 76-byte atoms have 0 there. + * Valid channel cannot be 0. */ + if (len % 76) + atom_len = 68; + else if (len % 68) + atom_len = 76; + else if (len >= 1292 && buf[68] == 0) + atom_len = 76; + else + atom_len = 68; + offset = 0; + break; + + case FIRMWARE_TYPE_INTERSIL: + offset = 4; + if (priv->has_hostscan) { + atom_len = le16_to_cpup((__le16 *)buf); + /* Sanity check for atom_len */ + if (atom_len < sizeof(struct prism2_scan_apinfo)) { + printk(KERN_ERR "%s: Invalid atom_len in scan " + "data: %zu\n", priv->ndev->name, + atom_len); + abort = true; + goto scan_abort; + } + } else + atom_len = offsetof(struct prism2_scan_apinfo, atim); + break; + + default: + abort = true; + goto scan_abort; + } + + /* Check that we got an whole number of atoms */ + if ((len - offset) % atom_len) { + printk(KERN_ERR "%s: Unexpected scan data length %zu, " + "atom_len %zu, offset %d\n", priv->ndev->name, len, + atom_len, offset); + abort = true; + goto scan_abort; + } + + /* Process the entries one by one */ + for (; offset + atom_len <= len; offset += atom_len) { + union hermes_scan_info *atom; + + atom = (union hermes_scan_info *) (buf + offset); + + orinoco_add_hostscan_result(priv, atom); + } + + scan_abort: + if (priv->scan_request) { + cfg80211_scan_done(priv->scan_request, abort); + priv->scan_request = NULL; + } +} diff --git a/code/validation/C/0137951_h8300_timer16.c b/code/validation/C/0137951_h8300_timer16.c new file mode 100644 index 0000000000000000000000000000000000000000..86ca91451b2ece3091fe535d940ace7a8bd46ef7 --- /dev/null +++ b/code/validation/C/0137951_h8300_timer16.c @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * H8/300 16bit Timer driver + * + * Copyright 2015 Yoshinori Sato + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define TSTR 0 +#define TISRC 6 + +#define TCR 0 +#define TCNT 2 + +#define bset(b, a) iowrite8(ioread8(a) | (1 << (b)), (a)) +#define bclr(b, a) iowrite8(ioread8(a) & ~(1 << (b)), (a)) + +struct timer16_priv { + struct clocksource cs; + unsigned long total_cycles; + void __iomem *mapbase; + void __iomem *mapcommon; + unsigned short cs_enabled; + unsigned char enb; + unsigned char ovf; + unsigned char ovie; +}; + +static unsigned long timer16_get_counter(struct timer16_priv *p) +{ + unsigned short v1, v2, v3; + unsigned char o1, o2; + + o1 = ioread8(p->mapcommon + TISRC) & p->ovf; + + /* Make sure the timer value is stable. Stolen from acpi_pm.c */ + do { + o2 = o1; + v1 = ioread16be(p->mapbase + TCNT); + v2 = ioread16be(p->mapbase + TCNT); + v3 = ioread16be(p->mapbase + TCNT); + o1 = ioread8(p->mapcommon + TISRC) & p->ovf; + } while (unlikely((o1 != o2) || (v1 > v2 && v1 < v3) + || (v2 > v3 && v2 < v1) || (v3 > v1 && v3 < v2))); + + if (likely(!o1)) + return v2; + else + return v2 + 0x10000; +} + + +static irqreturn_t timer16_interrupt(int irq, void *dev_id) +{ + struct timer16_priv *p = (struct timer16_priv *)dev_id; + + bclr(p->ovf, p->mapcommon + TISRC); + p->total_cycles += 0x10000; + + return IRQ_HANDLED; +} + +static inline struct timer16_priv *cs_to_priv(struct clocksource *cs) +{ + return container_of(cs, struct timer16_priv, cs); +} + +static u64 timer16_clocksource_read(struct clocksource *cs) +{ + struct timer16_priv *p = cs_to_priv(cs); + unsigned long raw, value; + + value = p->total_cycles; + raw = timer16_get_counter(p); + + return value + raw; +} + +static int timer16_enable(struct clocksource *cs) +{ + struct timer16_priv *p = cs_to_priv(cs); + + WARN_ON(p->cs_enabled); + + p->total_cycles = 0; + iowrite16be(0x0000, p->mapbase + TCNT); + iowrite8(0x83, p->mapbase + TCR); + bset(p->ovie, p->mapcommon + TISRC); + bset(p->enb, p->mapcommon + TSTR); + + p->cs_enabled = true; + return 0; +} + +static void timer16_disable(struct clocksource *cs) +{ + struct timer16_priv *p = cs_to_priv(cs); + + WARN_ON(!p->cs_enabled); + + bclr(p->ovie, p->mapcommon + TISRC); + bclr(p->enb, p->mapcommon + TSTR); + + p->cs_enabled = false; +} + +static struct timer16_priv timer16_priv = { + .cs = { + .name = "h8300_16timer", + .rating = 200, + .read = timer16_clocksource_read, + .enable = timer16_enable, + .disable = timer16_disable, + .mask = CLOCKSOURCE_MASK(sizeof(unsigned long) * 8), + .flags = CLOCK_SOURCE_IS_CONTINUOUS, + }, +}; + +#define REG_CH 0 +#define REG_COMM 1 + +static int __init h8300_16timer_init(struct device_node *node) +{ + void __iomem *base[2]; + int ret, irq; + unsigned int ch; + struct clk *clk; + + clk = of_clk_get(node, 0); + if (IS_ERR(clk)) { + pr_err("failed to get clock for clocksource\n"); + return PTR_ERR(clk); + } + + ret = -ENXIO; + base[REG_CH] = of_iomap(node, 0); + if (!base[REG_CH]) { + pr_err("failed to map registers for clocksource\n"); + goto free_clk; + } + + base[REG_COMM] = of_iomap(node, 1); + if (!base[REG_COMM]) { + pr_err("failed to map registers for clocksource\n"); + goto unmap_ch; + } + + ret = -EINVAL; + irq = irq_of_parse_and_map(node, 0); + if (!irq) { + pr_err("failed to get irq for clockevent\n"); + goto unmap_comm; + } + + of_property_read_u32(node, "renesas,channel", &ch); + + timer16_priv.mapbase = base[REG_CH]; + timer16_priv.mapcommon = base[REG_COMM]; + timer16_priv.enb = ch; + timer16_priv.ovf = ch; + timer16_priv.ovie = 4 + ch; + + ret = request_irq(irq, timer16_interrupt, + IRQF_TIMER, timer16_priv.cs.name, &timer16_priv); + if (ret < 0) { + pr_err("failed to request irq %d of clocksource\n", irq); + goto unmap_comm; + } + + clocksource_register_hz(&timer16_priv.cs, + clk_get_rate(clk) / 8); + return 0; + +unmap_comm: + iounmap(base[REG_COMM]); +unmap_ch: + iounmap(base[REG_CH]); +free_clk: + clk_put(clk); + return ret; +} + +TIMER_OF_DECLARE(h8300_16bit, "renesas,16bit-timer", + h8300_16timer_init); diff --git a/code/validation/C/0138228_selectionSort.c b/code/validation/C/0138228_selectionSort.c new file mode 100644 index 0000000000000000000000000000000000000000..e3649cbda0f51ae618606ea44665635bd3f7ccf7 --- /dev/null +++ b/code/validation/C/0138228_selectionSort.c @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include +#include + +void selection_sort(int *v, int n){ + int i, j, min, tmp; + + for(i = 0; i < n - 1; i++){ + min = i; + + for(j = i + 1; j < n; j++) + if(v[j] < v[min]) + min = j; + + tmp = v[i]; + v[i] = v[min]; + v[min] = tmp; + } +} + +int compare (const void * a, const void * b){ + return (* (int*) a - * (int*) b); /* Do not change it! */ +} + +int main(int argc, char **argv){ + char *awnser[] = { "bad", "ok" }; + int *vector, *test; + int i, n, is_ok; + double elapsed, start, end; + + if(argc != 2){ + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + n = atoi(argv[1]); + + printf("number of elements: %d\n", n); + + vector = (int *) malloc(n * sizeof(int)); + assert(vector != NULL); + + test = (int *) malloc(n * sizeof(int)); + assert(test != NULL); + + srand(time(NULL)); + + for(i = 0; i < n; i++) + vector[i] = rand(); + + memcpy(test, vector, n * sizeof(int)); + + qsort (test, n, sizeof(int), compare); + + start = omp_get_wtime(); + selection_sort(vector, n); + end = omp_get_wtime(); + + elapsed = end - start; + + is_ok = (memcmp(vector, test, n * sizeof(int)) == 0); + + printf("sorted values are %s\ntime: %.3f seconds\n", awnser[is_ok], elapsed); + + free(vector); + free(test); + + return 0; +} \ No newline at end of file diff --git a/code/validation/C/0139142_ex04-14.c b/code/validation/C/0139142_ex04-14.c new file mode 100644 index 0000000000000000000000000000000000000000..48522e83fea7a95b30f645f200ae6278acbd139b --- /dev/null +++ b/code/validation/C/0139142_ex04-14.c @@ -0,0 +1,27 @@ +/* + * Exercise 4-14. + */ +#include + +/* Macro swap(t,x,y) to interchange two args of type t. */ +#define swap(t,x,y) do { t temp; temp = x; x = y; y = temp; } while (0); + +int main(void) +{ + int x, y; + double dx, dy; + + x = 30; + y = 45; + printf("%d, %d\n", x, y); + swap(int, x, y); + printf("%d, %d\n", x, y); + + dx = 44.4; + dy = 33.3; + printf("%g, %g\n", dx, dy); + swap(double, dx, dy); + printf("%g, %g\n", dx, dy); + return 0; +} + diff --git a/code/validation/C/0139843_max-mpi-ppv1.c b/code/validation/C/0139843_max-mpi-ppv1.c new file mode 100644 index 0000000000000000000000000000000000000000..aca6e5e6fb717d69e2f80cf6e881579102f2071e --- /dev/null +++ b/code/validation/C/0139843_max-mpi-ppv1.c @@ -0,0 +1,163 @@ +#include +#include +#include + +int main(int argc, char** argv){ + if(argc < 2){ + printf("Not enough arguments. Provide input file location in the rerun\n"); + return -27; + } + else{ + // initialize MPI and get rank, size + double start, end; + FILE* fout = fopen("max-mpi-ppv1-out.txt", "w"); + fprintf(fout, "Location of the input file is %s\n", argv[1]); + fclose(fout); + MPI_Init(NULL, NULL); + int world_size, world_rank; + MPI_Comm_size(MPI_COMM_WORLD, &world_size); + MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); + MPI_Barrier(MPI_COMM_WORLD); + start = MPI_Wtime(); + + // eachSize will hold the value how many ints one processor will process + int eachSize; + + // basically what happens inside this block is, the root processor reads int values from a file and equally + // distributes them to other processors + if(world_rank == 0){ + char *path = argv[1]; + int integers[10000]; + // printf("Enter path to read the integers from: "); + // scanf("%s", &path); + + //create file pointer + FILE* in; + in = fopen(path, "r"); + if (in != NULL) { + char line[BUFSIZ]; + int count = 0; + + while (fgets(line, sizeof line, in) != NULL) { + char *start = line; + int num; + int n; + + while (sscanf(start, "%d%n", &num, &n) == 1) { + start += n; + integers[count] = num; + count++; + // printf("Added integer %d at index %d\n", num, count); + } + + // puts(""); + } + // printf("error?"); + fclose(in); + + int i; + + // printf("what's happening ere"); + + // THINK HERE WHAT COULD HAPPEN IF NUM OF PROCESSORS IS LAGER THAN NUM OF INTEGERS... + + if(world_size - 1 > count + 1){ + // printf("ord ont'"); + // send all the integers to just one worker then + // since we don't have a supercomputer to work this here it means we have a very small data set and 1 CPU can handle it + eachSize = 1; + MPI_Send(&eachSize, 1, MPI_INT, i, 1, MPI_COMM_WORLD); + MPI_Send(integers, count, MPI_INT, 1, 0, MPI_COMM_WORLD); + } + else{ + //send each worker ~equal~ pieces + // printf("send messages\n"); + + // printf("World size %d\n", world_size); + + // don't skip an element, make sure number of elements are divisible by number of processors, if not send the element at the end too + if((count) % (world_size - 1) == 0){ + eachSize = (count) / (world_size - 1); + } + else{ + eachSize = (count + 1) / (world_size - 1); + } + + + // printf("Each size: %d\n", eachSize); + for(i = 1; i < world_size; i++){ + // (i - 1) * eachSize => offset + // send integers + (i - 1) * eachSize; + // data, count, datatype, destination, tag, communicator + // send array size first, then the part of the array (increment the pointer) + MPI_Send(&eachSize, 1, MPI_INT, i, 1, MPI_COMM_WORLD); + MPI_Send(integers + ((i - 1) * eachSize), eachSize, MPI_INT, i, 0, MPI_COMM_WORLD); + } + } + + // finalMax will go through the local max values from the processors + int finalMax = INT_MIN; + int curMax; + for(i = 1; i < world_size; i++){ + // receive local max from each processor and then check if it is larger than the current max, if it is assign it to current max + MPI_Recv(&curMax, 1, MPI_INT, i, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + if(curMax > finalMax){ + finalMax = curMax; + } + } + + FILE* fout = fopen("max-mpi-ppv1-out.txt", "a"); + if(fout != NULL){ + fprintf(fout, "Total number of integers read: %d\nOverall max value is %d\n", count, finalMax); + } + else{ + printf("Error opening file.\n"); + } + + printf("Overall max value is %d\n", finalMax); + } + } + else{ + // data, count, type, source, tag, comm, status + MPI_Recv(&eachSize, 1, MPI_INT, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + int localInts[eachSize]; + MPI_Recv(localInts, eachSize, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + int j; + int localMax = INT_MIN; + int cur; + // go through the received part of the array and find the largest value there + for(j = 0; j < eachSize; j++){ + cur = localInts[j]; + // printf("At processor %d, index %d value %d\n", world_rank, j, cur); + if(cur > localMax){ + localMax = cur; + } + } + + // send the local maximum value to the root processor + FILE* out = fopen("max-mpi-ppv1-out.txt", "a"); + if(out != NULL){ + fprintf(out, "Local max value at processor %d is %d\n", world_rank, localMax); + } + else{ + printf("Error opening file\n"); + } + fclose(out); + printf("Local max value at processor %d is %d\n", world_rank, localMax); + MPI_Send(&localMax, 1, MPI_INT, 0, 2, MPI_COMM_WORLD); + } + + MPI_Barrier(MPI_COMM_WORLD); + end = MPI_Wtime(); + + if(world_rank == 0){ + fprintf(fout, "Runtime: %f\n", end-start); + printf("Runtime: %f\n", end-start); + fclose(fout); + } + + MPI_Finalize(); + + return 0; + } +} \ No newline at end of file diff --git a/code/validation/C/0140124_tcp_helper.c b/code/validation/C/0140124_tcp_helper.c new file mode 100644 index 0000000000000000000000000000000000000000..147d35fb28fff36a4cdc45b63ff942634e2c163a --- /dev/null +++ b/code/validation/C/0140124_tcp_helper.c @@ -0,0 +1,199 @@ +#include "tcp_helper.h" + /** + * Support and FAQ: visit Atmel Support + */ + +#include "lwip/tcp.h" +#include "lwip/stats.h" +#include "lwip/pbuf.h" +#include "lwip/inet_chksum.h" + +#if !LWIP_STATS || !TCP_STATS || !MEMP_STATS +#error "This tests needs TCP- and MEMP-statistics enabled" +#endif + +/** Remove all pcbs on the given list. */ +static void +tcp_remove(struct tcp_pcb* pcb_list) +{ + struct tcp_pcb *pcb = pcb_list; + struct tcp_pcb *pcb2; + + while(pcb != NULL) { + pcb2 = pcb; + pcb = pcb->next; + tcp_abort(pcb2); + } +} + +/** Remove all pcbs on listen-, active- and time-wait-list (bound- isn't exported). */ +void +tcp_remove_all(void) +{ + //tcp_remove(tcp_bound_pcbs); + tcp_remove(tcp_listen_pcbs.pcbs); + tcp_remove(tcp_active_pcbs); + tcp_remove(tcp_tw_pcbs); + fail_unless(lwip_stats.memp[MEMP_TCP_PCB].used == 0); + fail_unless(lwip_stats.memp[MEMP_TCP_PCB_LISTEN].used == 0); + fail_unless(lwip_stats.memp[MEMP_TCP_SEG].used == 0); + fail_unless(lwip_stats.memp[MEMP_PBUF_POOL].used == 0); +} + +/** Create a TCP segment usable for passing to tcp_input + * - IP-addresses, ports, seqno and ackno are taken from pcb + * - seqno and ackno can be altered with an offset + */ +struct pbuf* +tcp_create_rx_segment(struct tcp_pcb* pcb, void* data, size_t data_len, u32_t seqno_offset, + u32_t ackno_offset, u8_t headerflags) +{ + return tcp_create_segment(&pcb->remote_ip, &pcb->local_ip, pcb->remote_port, pcb->local_port, + data, data_len, pcb->rcv_nxt + seqno_offset, pcb->snd_nxt + ackno_offset, headerflags); +} + +/** Create a TCP segment usable for passing to tcp_input */ +struct pbuf* +tcp_create_segment(struct ip_addr* src_ip, struct ip_addr* dst_ip, + u16_t src_port, u16_t dst_port, void* data, size_t data_len, + u32_t seqno, u32_t ackno, u8_t headerflags) +{ + struct pbuf* p; + struct ip_hdr* iphdr; + struct tcp_hdr* tcphdr; + u16_t pbuf_len = sizeof(struct ip_hdr) + sizeof(struct tcp_hdr) + data_len; + + p = pbuf_alloc(PBUF_RAW, pbuf_len, PBUF_POOL); + EXPECT_RETNULL(p != NULL); + EXPECT_RETNULL(p->next == NULL); + + memset(p->payload, 0, p->len); + + iphdr = p->payload; + /* fill IP header */ + iphdr->dest.addr = dst_ip->addr; + iphdr->src.addr = src_ip->addr; + IPH_VHLTOS_SET(iphdr, 4, IP_HLEN / 4, 0); + IPH_LEN_SET(iphdr, htons(p->tot_len)); + IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, IP_HLEN)); + + pbuf_header(p, -(s16_t)sizeof(struct ip_hdr)); + + tcphdr = p->payload; + tcphdr->src = htons(src_port); + tcphdr->dest = htons(dst_port); + tcphdr->seqno = htonl(seqno); + tcphdr->ackno = htonl(ackno); + TCPH_HDRLEN_SET(tcphdr, sizeof(struct tcp_hdr)/4); + TCPH_FLAGS_SET(tcphdr, headerflags); + tcphdr->wnd = htonl(TCP_WND); + + /* copy data */ + memcpy((char*)tcphdr + sizeof(struct tcp_hdr), data, data_len); + + /* calculate checksum */ + tcphdr->chksum = inet_chksum_pseudo(p, &(iphdr->src), &(iphdr->dest), + IP_PROTO_TCP, p->tot_len); + + pbuf_header(p, sizeof(struct ip_hdr)); + + return p; +} + +/** Safely bring a tcp_pcb into the requested state */ +void +tcp_set_state(struct tcp_pcb* pcb, enum tcp_state state, struct ip_addr* local_ip, + struct ip_addr* remote_ip, u16_t local_port, u16_t remote_port) +{ + /* @todo: are these all states? */ + /* @todo: remove from previous list */ + pcb->state = state; + if (state == ESTABLISHED) { + TCP_REG(&tcp_active_pcbs, pcb); + pcb->local_ip.addr = local_ip->addr; + pcb->local_port = local_port; + pcb->remote_ip.addr = remote_ip->addr; + pcb->remote_port = remote_port; + } else if(state == LISTEN) { + TCP_REG(&tcp_listen_pcbs.pcbs, pcb); + pcb->local_ip.addr = local_ip->addr; + pcb->local_port = local_port; + } else if(state == TIME_WAIT) { + TCP_REG(&tcp_tw_pcbs, pcb); + pcb->local_ip.addr = local_ip->addr; + pcb->local_port = local_port; + pcb->remote_ip.addr = remote_ip->addr; + pcb->remote_port = remote_port; + } else { + fail(); + } +} + +void +test_tcp_counters_err(void* arg, err_t err) +{ + struct test_tcp_counters* counters = arg; + EXPECT_RET(arg != NULL); + counters->err_calls++; + counters->last_err = err; +} + +static void +test_tcp_counters_check_rxdata(struct test_tcp_counters* counters, struct pbuf* p) +{ + struct pbuf* q; + u32_t i, received; + if(counters->expected_data == NULL) { + /* no data to compare */ + return; + } + EXPECT_RET(counters->recved_bytes + p->tot_len <= counters->expected_data_len); + received = counters->recved_bytes; + for(q = p; q != NULL; q = q->next) { + char *data = q->payload; + for(i = 0; i < q->len; i++) { + EXPECT_RET(data[i] == counters->expected_data[received]); + received++; + } + } + EXPECT(received == counters->recved_bytes + p->tot_len); +} + +err_t +test_tcp_counters_recv(void* arg, struct tcp_pcb* pcb, struct pbuf* p, err_t err) +{ + struct test_tcp_counters* counters = arg; + EXPECT_RETX(arg != NULL, ERR_OK); + EXPECT_RETX(pcb != NULL, ERR_OK); + EXPECT_RETX(err == ERR_OK, ERR_OK); + + if (p != NULL) { + if (counters->close_calls == 0) { + counters->recv_calls++; + test_tcp_counters_check_rxdata(counters, p); + counters->recved_bytes += p->tot_len; + } else { + counters->recv_calls_after_close++; + counters->recved_bytes_after_close += p->tot_len; + } + pbuf_free(p); + } else { + counters->close_calls++; + } + EXPECT(counters->recv_calls_after_close == 0 && counters->recved_bytes_after_close == 0); + return ERR_OK; +} + +/** Allocate a pcb and set up the test_tcp_counters_* callbacks */ +struct tcp_pcb* +test_tcp_new_counters_pcb(struct test_tcp_counters* counters) +{ + struct tcp_pcb* pcb = tcp_new(); + if (pcb != NULL) { + /* set up args and callbacks */ + tcp_arg(pcb, counters); + tcp_recv(pcb, test_tcp_counters_recv); + tcp_err(pcb, test_tcp_counters_err); + } + return pcb; +} diff --git a/code/validation/C/0140147_kruskal_using_adjacency_matrix.c b/code/validation/C/0140147_kruskal_using_adjacency_matrix.c new file mode 100644 index 0000000000000000000000000000000000000000..cc06acb25de6f614d378040cac23730180ecd7bf --- /dev/null +++ b/code/validation/C/0140147_kruskal_using_adjacency_matrix.c @@ -0,0 +1,97 @@ +#include +#include + +int +delete_min_edge(int *u, int *v, int c[][1024], int n, int *e) +{ + int min = INT_MAX; + int i, j; + + for (i = 0; i < n; ++i) + for (j = 0; j < n; ++j) + if (c[i][j] < min && c[i][j] != -1) { + min = c[i][j]; + *u = i; + *v = j; + } + + c[*u][*v] = -1; + *e = *e - 1; + return (min); +} + +int +find(int n, int parent[], int i) +{ + while (parent[i] >= 0) + i = parent[i]; + + return (i); +} + +void +Union(int n, int parent[], int p, int q) +{ + int temp = parent[p] + parent[q]; + if (parent[p] > parent[q]) { + parent[p] = q; + parent[q] = temp; + } + else { + parent[q] = p; + parent[p] = temp; + } +} + +int +main() +{ + int n; + int e = 0; + printf("Enter number of nodes in graph: "); + scanf("%d", &n); + + int c[n][1024]; + printf("Enter cost matrix: \n"); + int i, j; + for (i = 0; i < n; ++i) + for (j = 0; j < n; ++j) { + scanf("%d", &c[i][j]); + if (c[i][j] != -1) + ++e; + } + + e = e / 2; + int t[n - 1][2]; + int parent[n]; + for (i = 0; i < n; i++) + parent[i] = -1; + + int mincost = 0; + int u, v, p, q; + i = 0; + while (i < n - 1 && e > 0) { + int min = delete_min_edge(&u, &v, c, n, &e); + p = find(n, parent, u); + q = find(n, parent, v); + if (p != q) { + + t[i][0] = u; + t[i][1] = v; + ++i; + mincost += min; + Union(n, parent, p, q); + } + } + + if(i != n - 1) + printf("There is no spanning tree\n"); + else { + printf("Minimum Spanning Tree:- \n"); + + for (i = 0; i < n - 1; ++i) + printf("%d----%d \n", t[i][0], t[i][1]); + + printf("Mincost: %d \n", mincost); + } +} diff --git a/code/validation/C/0140687_test_except.c b/code/validation/C/0140687_test_except.c new file mode 100644 index 0000000000000000000000000000000000000000..5907caa12c54b89d21c8cf66eef282acb20b9841 --- /dev/null +++ b/code/validation/C/0140687_test_except.c @@ -0,0 +1,242 @@ +#include "except.h" +#include "test.h" + +static char *msg1 = "Message One"; +static char *msg2 = "Message Two"; + +static void raise_exception() +{ + RAISE(EXCEPTION, "%s", msg1); +} + +static void inner_try(TestCase *tc) +{ + volatile bool exception_handled = false; + volatile bool ioerror_called = false; + + TRY + raise_exception(); + Assert(false, "Exception should have been raised"); + break; + case EXCEPTION: + /* This should be called */ + Astrstr(xcontext.msg, msg1); + exception_handled = true; + HANDLED(); + RAISE(IO_ERROR, "%s", msg2); + Assert(false, "Exception should have been raised"); + break; + case IO_ERROR: + ioerror_called = true; + break; + default: + Assert(false, "Exception should have been known"); + break; + case FINALLY: + Assert(exception_handled, "%s", "Exception wasn't handled"); + Assert(ioerror_called, "IO_ERROR wasn't called"); + ENDTRY +} + +static void test_nested_except(TestCase *tc, void *data) +{ + volatile bool ioerror_handled = false; + bool finally_handled = false; + (void)data; + + TRY + inner_try(tc); + Assert(false, "Exception should have been raised"); + break; + case IO_ERROR: + /* This should be called */ + Astrstr(xcontext.msg, msg2); + ioerror_handled = true; + HANDLED(); + break; + case EXCEPTION: + /* This should be called */ + Assert(false, "Exception should not have been raised"); + break; + default: + Assert(false, "Exception should have been known"); + break; + case FINALLY: + finally_handled = true; + ENDTRY + Assert(ioerror_handled, "Exception wasn't handled"); + Assert(finally_handled, "Finally wasn't handled"); +} + +static void test_function_except(TestCase *tc, void *data) +{ + volatile bool exception_handled = false; + bool finally_handled = false; + (void)data; /* suppress warning */ + + TRY + raise_exception(); + Assert(false, "Exception should have been raised"); + break; + case EXCEPTION: + /* This should be called */ + Astrstr(xcontext.msg, msg1); +#if defined(__func__) && defined(FRT_HAS_VARARGS) + Astrstr("raise_exception", msg1); +#endif + exception_handled = true; + HANDLED(); + break; + default: + Assert(false, "Exception should have been known"); + break; + case FINALLY: + finally_handled = true; + ENDTRY + Assert(exception_handled, "Exception wasn't handled"); + Assert(finally_handled, "Finally wasn't handled"); +} + +static void test_simple_except(TestCase *tc, void *data) +{ + volatile bool exception_handled = false; + bool finally_handled = false; + (void)data; /* suppress warning */ + + TRY + RAISE(EXCEPTION, "error message %s %d", "string", 20); + Assert(false, "Exception should have been raised"); + break; + case EXCEPTION: + /* This should be called */ + Astrstr(xcontext.msg, "error message string 20"); +#if defined(__func__) && defined(FRT_HAS_VARARGS) + Astrstr(xcontext.msg, __func__); +#endif +#if defined(FRT_HAS_VARARGS) + Astrstr(xcontext.msg, __FILE__); +#endif + exception_handled = true; + HANDLED(); + break; + default: + Assert(false, "Exception should have been known"); + break; + case FINALLY: + finally_handled = true; + ENDTRY + Assert(exception_handled, "Exception wasn't handled"); + Assert(finally_handled, "Finally wasn't handled"); +} + +static void try_xfinally1(TestCase *tc) +{ + bool finally_handled = false; + + TRY + Assert(true, "No exception raised"); + XFINALLY + RAISE(EXCEPTION, "%s", msg1); + finally_handled = true; + XENDTRY + Assert(finally_handled, "Finally wasn't handled"); + Atrue(finally_handled); +} + +static void try_xfinally2(TestCase *tc) +{ + bool finally_handled = false; + + TRY + RAISE(EXCEPTION, "%s", msg1); + Assert(false, "Exception should have been raised"); + XFINALLY + RAISE(EXCEPTION, "%s", msg1); + finally_handled = true; + XENDTRY + Assert(finally_handled, "Finally wasn't handled"); + Atrue(finally_handled); +} + +static void try_xcatchall(TestCase *tc) +{ + bool catchall_handled = false; + + TRY + RAISE(EXCEPTION, "%s", msg1); + Assert(false, "Exception should have been raised"); + XCATCHALL + HANDLED(); + RAISE(EXCEPTION, "%s", msg1); + catchall_handled = true; + XENDTRY + Assert(catchall_handled, "Finally wasn't handled"); + Atrue(catchall_handled); +} + +static void test_xfinally(TestCase *tc, void *data) +{ + volatile bool exception_handled = false; + bool finally_handled = false; + (void)data; /* suppress warning */ + + TRY + try_xfinally1(tc); + try_xfinally2(tc); + try_xcatchall(tc); + Assert(false, "Exception should have been raised"); + break; + case EXCEPTION: + /* This should be called */ + Astrstr(xcontext.msg, msg1); + exception_handled = true; + HANDLED(); + break; + default: + Assert(false, "Exception should have been known"); + break; + case FINALLY: + finally_handled = true; + ENDTRY + Assert(exception_handled, "Exception wasn't handled"); + Assert(finally_handled, "Finally wasn't handled"); +} + +static void test_uncaught_except(TestCase *tc, void *data) +{ + bool old_abort_setting = x_abort_on_exception; + FILE *old_stream_setting = x_exception_stream; + FILE *exception_output = tmpfile(); + (void)data, (void)tc; /* suppress warning */ + + + x_abort_on_exception = false; + x_exception_stream = exception_output; + + /* Unhandled exception in try block */ + TRY + raise_exception(); + ENDTRY + Assert(x_has_aborted, "Unhandled exception in try block didn't abort"); + + /* Unhandled exception outside of try block */ + x_has_aborted = false; + raise_exception(); + Assert(x_has_aborted, "Unhandled exception didn't cause an abort"); + + x_abort_on_exception = old_abort_setting; + x_exception_stream = old_stream_setting; + fclose(exception_output); +} + +TestSuite *ts_except(TestSuite *suite) +{ + suite = ADD_SUITE(suite); + + tst_run_test(suite, test_simple_except, NULL); + tst_run_test(suite, test_function_except, NULL); + tst_run_test(suite, test_nested_except, NULL); + tst_run_test(suite, test_xfinally, NULL); + tst_run_test(suite, test_uncaught_except, NULL); + return suite; +} diff --git a/code/validation/C/0141348_en_dcb_nl.c b/code/validation/C/0141348_en_dcb_nl.c new file mode 100644 index 0000000000000000000000000000000000000000..9d4a1ea030d84a95055afbc07a08dd131d885f8d --- /dev/null +++ b/code/validation/C/0141348_en_dcb_nl.c @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2011 Mellanox Technologies. All rights reserved. + * + * This software is available to you under a choice of one of two + * licenses. You may choose to be licensed under the terms of the GNU + * General Public License (GPL) Version 2, available from the file + * COPYING in the main directory of this source tree, or the + * OpenIB.org BSD license below: + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the following + * conditions are met: + * + * - Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * + * - Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +#include +#include + +#include "mlx4_en.h" + +static int mlx4_en_dcbnl_ieee_getets(struct net_device *dev, + struct ieee_ets *ets) +{ + struct mlx4_en_priv *priv = netdev_priv(dev); + struct ieee_ets *my_ets = &priv->ets; + + /* No IEEE PFC settings available */ + if (!my_ets) + return -EINVAL; + + ets->ets_cap = IEEE_8021QAZ_MAX_TCS; + ets->cbs = my_ets->cbs; + memcpy(ets->tc_tx_bw, my_ets->tc_tx_bw, sizeof(ets->tc_tx_bw)); + memcpy(ets->tc_tsa, my_ets->tc_tsa, sizeof(ets->tc_tsa)); + memcpy(ets->prio_tc, my_ets->prio_tc, sizeof(ets->prio_tc)); + + return 0; +} + +static int mlx4_en_ets_validate(struct mlx4_en_priv *priv, struct ieee_ets *ets) +{ + int i; + int total_ets_bw = 0; + int has_ets_tc = 0; + + for (i = 0; i < IEEE_8021QAZ_MAX_TCS; i++) { + if (ets->prio_tc[i] > MLX4_EN_NUM_UP) { + en_err(priv, "Bad priority in UP <=> TC mapping. TC: %d, UP: %d\n", + i, ets->prio_tc[i]); + return -EINVAL; + } + + switch (ets->tc_tsa[i]) { + case IEEE_8021QAZ_TSA_STRICT: + break; + case IEEE_8021QAZ_TSA_ETS: + has_ets_tc = 1; + total_ets_bw += ets->tc_tx_bw[i]; + break; + default: + en_err(priv, "TC[%d]: Not supported TSA: %d\n", + i, ets->tc_tsa[i]); + return -ENOTSUPP; + } + } + + if (has_ets_tc && total_ets_bw != MLX4_EN_BW_MAX) { + en_err(priv, "Bad ETS BW sum: %d. Should be exactly 100%%\n", + total_ets_bw); + return -EINVAL; + } + + return 0; +} + +static int mlx4_en_config_port_scheduler(struct mlx4_en_priv *priv, + struct ieee_ets *ets, u16 *ratelimit) +{ + struct mlx4_en_dev *mdev = priv->mdev; + int num_strict = 0; + int i; + __u8 tc_tx_bw[IEEE_8021QAZ_MAX_TCS] = { 0 }; + __u8 pg[IEEE_8021QAZ_MAX_TCS] = { 0 }; + + ets = ets ?: &priv->ets; + ratelimit = ratelimit ?: priv->maxrate; + + /* higher TC means higher priority => lower pg */ + for (i = IEEE_8021QAZ_MAX_TCS - 1; i >= 0; i--) { + switch (ets->tc_tsa[i]) { + case IEEE_8021QAZ_TSA_STRICT: + pg[i] = num_strict++; + tc_tx_bw[i] = MLX4_EN_BW_MAX; + break; + case IEEE_8021QAZ_TSA_ETS: + pg[i] = MLX4_EN_TC_ETS; + tc_tx_bw[i] = ets->tc_tx_bw[i] ?: MLX4_EN_BW_MIN; + break; + } + } + + return mlx4_SET_PORT_SCHEDULER(mdev->dev, priv->port, tc_tx_bw, pg, + ratelimit); +} + +static int +mlx4_en_dcbnl_ieee_setets(struct net_device *dev, struct ieee_ets *ets) +{ + struct mlx4_en_priv *priv = netdev_priv(dev); + struct mlx4_en_dev *mdev = priv->mdev; + int err; + + err = mlx4_en_ets_validate(priv, ets); + if (err) + return err; + + err = mlx4_SET_PORT_PRIO2TC(mdev->dev, priv->port, ets->prio_tc); + if (err) + return err; + + err = mlx4_en_config_port_scheduler(priv, ets, NULL); + if (err) + return err; + + memcpy(&priv->ets, ets, sizeof(priv->ets)); + + return 0; +} + +static int mlx4_en_dcbnl_ieee_getpfc(struct net_device *dev, + struct ieee_pfc *pfc) +{ + struct mlx4_en_priv *priv = netdev_priv(dev); + + pfc->pfc_cap = IEEE_8021QAZ_MAX_TCS; + pfc->pfc_en = priv->prof->tx_ppp; + + return 0; +} + +static int mlx4_en_dcbnl_ieee_setpfc(struct net_device *dev, + struct ieee_pfc *pfc) +{ + struct mlx4_en_priv *priv = netdev_priv(dev); + struct mlx4_en_dev *mdev = priv->mdev; + int err; + + en_dbg(DRV, priv, "cap: 0x%x en: 0x%x mbc: 0x%x delay: %d\n", + pfc->pfc_cap, + pfc->pfc_en, + pfc->mbc, + pfc->delay); + + priv->prof->rx_pause = priv->prof->tx_pause = !!pfc->pfc_en; + priv->prof->rx_ppp = priv->prof->tx_ppp = pfc->pfc_en; + + err = mlx4_SET_PORT_general(mdev->dev, priv->port, + priv->rx_skb_size + ETH_FCS_LEN, + priv->prof->tx_pause, + priv->prof->tx_ppp, + priv->prof->rx_pause, + priv->prof->rx_ppp); + if (err) + en_err(priv, "Failed setting pause params\n"); + + return err; +} + +static u8 mlx4_en_dcbnl_getdcbx(struct net_device *dev) +{ + return DCB_CAP_DCBX_HOST | DCB_CAP_DCBX_VER_IEEE; +} + +static u8 mlx4_en_dcbnl_setdcbx(struct net_device *dev, u8 mode) +{ + if ((mode & DCB_CAP_DCBX_LLD_MANAGED) || + (mode & DCB_CAP_DCBX_VER_CEE) || + !(mode & DCB_CAP_DCBX_VER_IEEE) || + !(mode & DCB_CAP_DCBX_HOST)) + return 1; + + return 0; +} + +#define MLX4_RATELIMIT_UNITS_IN_KB 100000 /* rate-limit HW unit in Kbps */ +static int mlx4_en_dcbnl_ieee_getmaxrate(struct net_device *dev, + struct ieee_maxrate *maxrate) +{ + struct mlx4_en_priv *priv = netdev_priv(dev); + int i; + + for (i = 0; i < IEEE_8021QAZ_MAX_TCS; i++) + maxrate->tc_maxrate[i] = + priv->maxrate[i] * MLX4_RATELIMIT_UNITS_IN_KB; + + return 0; +} + +static int mlx4_en_dcbnl_ieee_setmaxrate(struct net_device *dev, + struct ieee_maxrate *maxrate) +{ + struct mlx4_en_priv *priv = netdev_priv(dev); + u16 tmp[IEEE_8021QAZ_MAX_TCS]; + int i, err; + + for (i = 0; i < IEEE_8021QAZ_MAX_TCS; i++) { + /* Convert from Kbps into HW units, rounding result up. + * Setting to 0, means unlimited BW. + */ + tmp[i] = div_u64(maxrate->tc_maxrate[i] + + MLX4_RATELIMIT_UNITS_IN_KB - 1, + MLX4_RATELIMIT_UNITS_IN_KB); + } + + err = mlx4_en_config_port_scheduler(priv, NULL, tmp); + if (err) + return err; + + memcpy(priv->maxrate, tmp, sizeof(priv->maxrate)); + + return 0; +} + +const struct dcbnl_rtnl_ops mlx4_en_dcbnl_ops = { + .ieee_getets = mlx4_en_dcbnl_ieee_getets, + .ieee_setets = mlx4_en_dcbnl_ieee_setets, + .ieee_getmaxrate = mlx4_en_dcbnl_ieee_getmaxrate, + .ieee_setmaxrate = mlx4_en_dcbnl_ieee_setmaxrate, + .ieee_getpfc = mlx4_en_dcbnl_ieee_getpfc, + .ieee_setpfc = mlx4_en_dcbnl_ieee_setpfc, + + .getdcbx = mlx4_en_dcbnl_getdcbx, + .setdcbx = mlx4_en_dcbnl_setdcbx, +}; + +const struct dcbnl_rtnl_ops mlx4_en_dcbnl_pfc_ops = { + .ieee_getpfc = mlx4_en_dcbnl_ieee_getpfc, + .ieee_setpfc = mlx4_en_dcbnl_ieee_setpfc, + + .getdcbx = mlx4_en_dcbnl_getdcbx, + .setdcbx = mlx4_en_dcbnl_setdcbx, +}; diff --git a/code/validation/C/0142038_lab8.functions.c b/code/validation/C/0142038_lab8.functions.c new file mode 100644 index 0000000000000000000000000000000000000000..8609ee3f85023d6baab89a8b58d2ef019b9e5d5b --- /dev/null +++ b/code/validation/C/0142038_lab8.functions.c @@ -0,0 +1,124 @@ +/* +Lamog-Doiel, Robert +Lab 8 +05/23/2017 + +HEADER DEFINITIONS +Dynamically allocate array of pointers to structs from file input. +Names and addresses are in alphabetical order. +Output based on ascending zip code. +Include duplicate entries. +Use command line arguments with FILE I/O. +*/ + +#include +#include +#include +#include "lab8.h" + +/* + Malloc new address struct. + Return NULL on failure. + Return ptr to new address struct on success. +*/ +Address* newAddress(){ + Address* retVal = malloc(sizeof(Address)); + if (retVal == NULL) return NULL; + + return retVal; +} +void freeAddress(Address* address){ + if (address != NULL) free(address); +} +/* + Set contact->last_name_first_name. + Exit program on failure. +*/ +Address* setLastNameFirstName(Address* contact, char* str){ + if (str == NULL){ + printf("setLastNameFirstName: Unsuccessful.\nProgram terminated.\n"); + exit(EXIT_FAILURE); + } else { + strcpy(contact->last_name_first_name, str); + } + + return contact; +} +/* + Set contact->street_address. + Exit program on failure. +*/ +Address* setStreetAddress(Address* contact, char* str){ + if (str == NULL){ + printf("setStreetAddress: Unsuccessful.\nProgram terminated.\n"); + exit(EXIT_FAILURE); + } else { + strcpy(contact->street_address, str); + } + + return contact; +} +/* + Set contact->city_state. + Exit program on failure. +*/ +Address* setCityState(Address* contact, char* str){ + if (str == NULL){ + printf("setCityState: Unsuccessful.\nProgram terminated.\n"); + exit(EXIT_FAILURE); + } else { + strcpy(contact->city_state, str); + } + + return contact; +} +/* + Set contact->zip_code. + Exit program on failure. +*/ +Address* setZipCode(Address* contact, char* str){ + if (str == NULL){ + printf("setZipCode: Unsuccessful.\nProgram terminated.\n"); + exit(EXIT_FAILURE); + } else { + strcpy(contact->zip_code, str); + } + + return contact; +} +/* + Write single address from ptr to file. +*/ +void writeAddress(Address* address, FILE* output){ + fprintf(output, "%s%s%s%s", + address->last_name_first_name, + address->street_address, + address->city_state, + address->zip_code); +} + +/* + DESTRUCTIVE selection sort utilizing zip code in ascending order. +*/ +Address** zipCodeSort(Address** contact_list, unsigned number_of_contacts){ + unsigned i = 0; + unsigned j = 0; + unsigned min = 0; + Address* tmp; + + for (i; i <= number_of_contacts; ++i){ + min = i; + + for (j = i; j <= number_of_contacts; ++j){ + if (strcmp(contact_list[j]->zip_code, contact_list[min]->zip_code) < 0){ + min = j; + } + } + + tmp = contact_list[i]; + contact_list[i] = contact_list[min]; + contact_list[min] = tmp; + } + + return contact_list; +} \ No newline at end of file diff --git a/code/validation/C/0142159_17.Calculate-GCD.c b/code/validation/C/0142159_17.Calculate-GCD.c new file mode 100644 index 0000000000000000000000000000000000000000..1bb6349e2305db9c565f97a0bf3850800a8b24c5 --- /dev/null +++ b/code/validation/C/0142159_17.Calculate-GCD.c @@ -0,0 +1,43 @@ +/* + * Write a program that calculates the greatest common divisor (GCD) of given + * two integers a and b. Use the Euclidean algorithm. Examples: +a b GCD(a, b) +3 2 1 +60 40 20 +5 -15 5 + */ + +#include + +int gcd(int, int); + +int main() { + int a, b; + printf("a = "); + scanf("%d", &a); + printf("b = "); + scanf("%d", &b); + + if (b > a) { + int oldValue = a; + a = b; + b = oldValue; + } + + int result = gcd(a, b); + + printf("gcd(%d, %d) = %d", a, b, result); + return 0; +} + +int gcd(int a, int b) { + int temp; + while (b != 0) { + temp = b; + b = a % b; + a = temp; + } + + return a; +} + diff --git a/code/validation/C/0143135_cbfscomptool.c b/code/validation/C/0143135_cbfscomptool.c new file mode 100644 index 0000000000000000000000000000000000000000..028893c35f5e01ef282a3c332a537ce39baf8021 --- /dev/null +++ b/code/validation/C/0143135_cbfscomptool.c @@ -0,0 +1,202 @@ +/* + * cbfs-compression-tool, CLI utility for dealing with CBFS compressed data + * + * Copyright (C) 2017 Google, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include + +#include "common.h" + +const char *usage_text = "cbfs-compression-tool benchmark\n" + " runs benchmarks for all implemented algorithms\n" + "cbfs-compression-tool compress inFile outFile algo\n" + " compresses inFile with algo and stores in outFile\n" + "\n" + "'compress' file format:\n" + " 4 bytes little endian: algorithm ID (as used in CBFS)\n" + " 4 bytes little endian: uncompressed size\n" + " ...: compressed data stream\n"; + +static void usage(void) +{ + puts(usage_text); +} + +static int benchmark(void) +{ + const int bufsize = 10*1024*1024; + char *data = malloc(bufsize); + if (!data) { + fprintf(stderr, "out of memory\n"); + return 1; + } + char *compressed_data = malloc(bufsize); + if (!compressed_data) { + free(data); + fprintf(stderr, "out of memory\n"); + return 1; + } + int i, l = strlen(usage_text) + 1; + for (i = 0; i + l < bufsize; i += l) { + memcpy(data + i, usage_text, l); + } + memset(data + i, 0, bufsize - i); + const struct typedesc_t *algo; + for (algo = &types_cbfs_compression[0]; algo->name != NULL; algo++) { + int outsize = bufsize; + printf("measuring '%s'\n", algo->name); + comp_func_ptr comp = compression_function(algo->type); + if (comp == NULL) { + printf("no handler associated with algorithm\n"); + free(data); + free(compressed_data); + return 1; + } + + struct timespec t_s, t_e; + clock_gettime(CLOCK_MONOTONIC, &t_s); + + if (comp(data, bufsize, compressed_data, &outsize)) { + printf("compression failed"); + return 1; + } + + clock_gettime(CLOCK_MONOTONIC, &t_e); + printf("compressing %d bytes to %d took %ld seconds\n", + bufsize, outsize, + (long)(t_e.tv_sec - t_s.tv_sec)); + } + free(data); + free(compressed_data); + return 0; +} + +static int compress(char *infile, char *outfile, char *algoname, + int write_header) +{ + int err = 1; + FILE *fin = NULL; + FILE *fout = NULL; + void *indata = NULL; + + const struct typedesc_t *algo = &types_cbfs_compression[0]; + while (algo->name != NULL) { + if (strcasecmp(algo->name, algoname) == 0) break; + algo++; + } + if (algo->name == NULL) { + fprintf(stderr, "algo '%s' is not supported.\n", algoname); + return 1; + } + + comp_func_ptr comp = compression_function(algo->type); + if (comp == NULL) { + printf("no handler associated with algorithm\n"); + return 1; + } + + fin = fopen(infile, "rb"); + if (!fin) { + fprintf(stderr, "could not open '%s'\n", infile); + return 1; + } + fout = fopen(outfile, "wb"); + if (!fout) { + fprintf(stderr, "could not open '%s' for writing\n", outfile); + goto out; + } + + if (fseek(fin, 0, SEEK_END) != 0) { + fprintf(stderr, "could not seek in input\n"); + goto out; + } + long insize = ftell(fin); + if (insize < 0) { + fprintf(stderr, "could not determine input size\n"); + goto out; + } + rewind(fin); + + indata = malloc(insize); + if (!indata) { + fprintf(stderr, "out of memory\n"); + goto out; + } + + void *outdata = malloc(insize); + if (!outdata) { + fprintf(stderr, "out of memory\n"); + goto out; + } + int outsize; + + int remsize = insize; + while (remsize > 0) { + int readsz = fread(indata, 1, remsize, fin); + if (readsz < 0) { + fprintf(stderr, "failed to read input with %d bytes left\n", remsize); + goto out; + } + remsize -= readsz; + } + + if (comp(indata, insize, outdata, &outsize) == -1) { + outsize = insize; + free(outdata); + outdata = indata; + algo = &types_cbfs_compression[0]; + } + + if (write_header) { + char header[8]; + header[0] = algo->type & 0xff; + header[1] = (algo->type >> 8) & 0xff; + header[2] = (algo->type >> 16) & 0xff; + header[3] = (algo->type >> 24) & 0xff; + header[4] = insize & 0xff; + header[5] = (insize >> 8) & 0xff; + header[6] = (insize >> 16) & 0xff; + header[7] = (insize >> 24) & 0xff; + if (fwrite(header, 8, 1, fout) != 1) { + fprintf(stderr, "failed writing header\n"); + goto out; + } + } + if (fwrite(outdata, outsize, 1, fout) != 1) { + fprintf(stderr, "failed writing compressed data\n"); + goto out; + } + + err = 0; +out: + if (fin) fclose(fin); + if (fout) fclose(fout); + if (indata) free(indata); + return err; +} + +int main(int argc, char **argv) +{ + if ((argc == 2) && (strcmp(argv[1], "benchmark") == 0)) + return benchmark(); + if ((argc == 5) && (strcmp(argv[1], "compress") == 0)) + return compress(argv[2], argv[3], argv[4], 1); + if ((argc == 5) && (strcmp(argv[1], "rawcompress") == 0)) + return compress(argv[2], argv[3], argv[4], 0); + usage(); + return 1; +} diff --git a/code/validation/C/0143226_viz.c b/code/validation/C/0143226_viz.c new file mode 100644 index 0000000000000000000000000000000000000000..019144e26945d259494cc4386eea21b6ccf15c74 --- /dev/null +++ b/code/validation/C/0143226_viz.c @@ -0,0 +1,80 @@ +#include "cdt.h" +#include "gvc.h" + +extern gvplugin_library_t gvplugin_dot_layout_LTX_library; +extern gvplugin_library_t gvplugin_neato_layout_LTX_library; +extern gvplugin_library_t gvplugin_core_LTX_library; + +GVC_t *context = NULL; +char *last_result = NULL; + +__attribute__((used)) char* vizRenderFromString(const char *string, + const char *format, + const char *engine, + char *options) { + if (context == NULL) { + context = gvContext(); + gvAddLibrary(context, &gvplugin_core_LTX_library); + gvAddLibrary(context, &gvplugin_dot_layout_LTX_library); + gvAddLibrary(context, &gvplugin_neato_layout_LTX_library); + } + + // First pass - count the number of extra options separated with '|' + fprintf(stderr, "options is \"%s\"\n", options); + int options_count = 0; + if (options && options[0]) { + char current; + for (int pos = 0; (current = options[pos]); pos++) { + if (current == '|') { + options_count++; + } + } + options_count++; + fprintf(stderr, "Found %d options\n", options_count); + } + // Second pass - fill all the options + const char *argv[3 + options_count]; + argv[0] = engine; + argv[1] = "-T"; + argv[2] = format; + if (options_count > 0) { + options_count = 0; + int pos = 0, prev_pos = 0; + char current; + while ((current = options[pos++])) { + if (current == '|') { + argv[3 + options_count] = options + prev_pos; + options[pos - 1] = 0; + prev_pos = pos; + options_count++; + } + } + argv[3 + options_count] = options + prev_pos; + } + + if (gvParseArgs(context, sizeof(argv) / sizeof(argv[0]), (char**)argv)) { + fprintf(stderr, "viz.js: failed to set the engine or the output format\n"); + return NULL; + } + + Agraph_t *graph = agmemread((char*)string); + if (!graph) { + fprintf(stderr, "viz.js: failed to parse the supplied graph string\n"); + return NULL; + } + gvLayoutJobs(context, graph); + + char *result = NULL; + unsigned int length; + gvRenderData(context, graph, format, &result, &length); + + gvFreeLayout(context, graph); + agclose(graph); + + if (last_result != NULL) { + gvFreeRenderData(last_result); + } + last_result = result; + + return result; +} diff --git a/code/validation/C/0143960_1_16_longest_line.c b/code/validation/C/0143960_1_16_longest_line.c new file mode 100644 index 0000000000000000000000000000000000000000..d4abed2c3d0222f79a4a79c4c0c94e316a1b02eb --- /dev/null +++ b/code/validation/C/0143960_1_16_longest_line.c @@ -0,0 +1,31 @@ +/* + * Print the longest line on stdin and its length + */ + +#include +#include "utils.h" + +int main (void) { + char * line = NULL; + ssize_t len = 0; + + char * longest_line = NULL; + ssize_t max_len = 0; + + while ((len = x_getline (&line, stdin)) != -1) { + if (len > max_len) { + max_len = len; + + free (longest_line); + longest_line = line; + } else + free (line); + } + + if (longest_line) { + printf ("The longest line (%d characters) is:\n %s\n", (int) max_len, longest_line); + free (longest_line); + } + + return 0; +} diff --git a/code/validation/C/0144056_url_stack.c b/code/validation/C/0144056_url_stack.c new file mode 100644 index 0000000000000000000000000000000000000000..2991f6cb52b06e984a907d8eeedca1c489d283b5 --- /dev/null +++ b/code/validation/C/0144056_url_stack.c @@ -0,0 +1,134 @@ +#include "url_stack.h" + +int spotted_pages = 0; +float table_size = (HASH_SIZE * 16) / 1000000; + +int add_url(site_node_t **_top, char *_url, char *_site_name, int _depth) +{ + url_node_t *new_url; + site_node_t *new_site; + site_node_t *aux; + site_node_t *prev; + + new_url = malloc(sizeof(url_node_t)); + new_url->url = strdup(_url); + new_url->next_url = NULL; + + /*cerco in quale sito (stack) inserire il nuovo url (nodo)*/ + aux = *_top; + prev = NULL; + while(aux != NULL && strcmp(_site_name, aux->site_name) != 0) + { + prev = aux; + aux = aux->next_site; + } + + /*se aux non è nullo allora devo aggiornare url_stack del site_node + a cui l'url appartiene.*/ + if(aux) + { + new_url->next_url = aux->url_stack; + aux->url_stack = new_url; + } + + /*se aux è nullo (ossia se il sito a cui l'url appartiene non ha un + suo stack) allora devo creare il site node (ricordo che site node è una coda).*/ + else { + new_site = malloc(sizeof(site_node_t)); + new_site->site_name = strdup(_site_name); + new_site->next_site = NULL; + new_site->url_stack = new_url; + new_site->depth = _depth; + /*il primo inserimento è ovviamente a parte (poiché aggiorna il + puntatore all'intera struttura)*/ + if(prev) + prev->next_site = new_site; + else + *_top = new_site; + } + + spotted_pages++; + table_size += (16 + strlen(_url)) / 1000000; + printf("spotted url: %s at depth: %d\ntotal spotted pages: %d\ttable size: %.2f\n", _url, _depth, spotted_pages, table_size); + + return 0; +} + +char *get_url(site_node_t **_site_queue, int *_depth) +{ + site_node_t *aux1; + url_node_t *aux2; + char *url; + + /*un nodo della site queue non viene eliminato quando l'ultimo url del suo + stack viene estratto. L'eliminazione avverà alla get successiva. Questo + perché quell'ultima pagina estratta potrebbe contenere altri link allo + stesso sito.*/ + + /*se il primo site_node della coda ha lo stack degli url vuoto, allora + seleziono il successivo (se non esiste ho finito tutti i link da visitare)*/ + if((*_site_queue)->url_stack == NULL) + { + aux1 = *_site_queue; + *_site_queue = (*_site_queue)->next_site; + free(aux1->site_name); + free(aux1); + if(!(*_site_queue)) + return NULL; + } + + aux2 = (*_site_queue)->url_stack; + (*_site_queue)->url_stack = (*_site_queue)->url_stack->next_url; + + url = aux2->url; + *_depth = (*_site_queue)->depth; + free(aux2); + + printf("parsing: %s\n", url); + + + return url; +} + +void free_queue(site_node_t *_top) +{ + site_node_t *aux1; + url_node_t *aux2; + + while(_top) + { + while(_top->url_stack) + { + aux2 = _top->url_stack; + _top->url_stack = _top->url_stack->next_url; + free(aux2->url); + free(aux2); + } + free(_top->site_name); + aux1 = _top; + _top = _top->next_site; + free(aux1); + } +} + +int print_queue(site_node_t *_site_queue) +{ + url_node_t *aux; + + while(_site_queue) + { + aux = _site_queue->url_stack; + printf("\n\n*****************************\n"); + printf("%s %d\n\n", _site_queue->site_name, _site_queue->depth); + while(aux) + { + printf("\t%s\n", aux->url); + aux = aux->next_url; + } + printf("*****************************\n"); + _site_queue = _site_queue->next_site; + } + printf("\n\n"); + + return 0; +} \ No newline at end of file diff --git a/code/validation/C/0144828_queue.c b/code/validation/C/0144828_queue.c new file mode 100644 index 0000000000000000000000000000000000000000..fdc1cc010349d27fde21c86cdcf9b7efa973793d --- /dev/null +++ b/code/validation/C/0144828_queue.c @@ -0,0 +1,173 @@ +#include + +#include "queue.h" + +/*------------------------------------------------------------------------*/ + +queue_t* queue_create(void) +{ + queue_t* res; + + if((res = malloc(sizeof(*res)))) + { + res->first = NULL; + res->last = NULL; + res->busy = 0; + + pthread_mutex_init(&res->lock, NULL); + + res->event = event_create(); + } + + return(res); +} + +/*------------------------------------------------------------------------*/ + +void queue_destroy(queue_t* q) +{ + queue_item_t *j, *i; + + if(!q) + /* if NULL nothing to do */ + return; + + i = q->first; + + while (i) + { + j = i; + i = i->next; + + free(j->data); + free(j); + } + + pthread_mutex_destroy(&q->lock); + + event_destroy(q->event); + + free(q); +} + +/*------------------------------------------------------------------------*/ + +int queue_add(queue_t* q, const void* data, size_t size) +{ + queue_item_t *i; + int busy; + + /* check queue busy state */ + pthread_mutex_lock(&q->lock); + busy = q->busy; + pthread_mutex_unlock(&q->lock); + + /* create item if not a busy */ + if(busy || !(i = malloc(sizeof(*i)))) + return(-1); + + if(!(i->data = malloc(size))) + { + free(i); + + return(-1); + } + + /* filling item data */ + memcpy(i->data, data, size); + i->size = size; + i->next = NULL; + + pthread_mutex_lock(&q->lock); + + /* add item to the list */ + if(q->first) + { + q->last->next = i; + q->last = i; + } + else + { + q->first = i; + q->last = i; + } + + /* notify about new item */ + event_signal(q->event); + + pthread_mutex_unlock(&q->lock); + + return(0); +} + +/*------------------------------------------------------------------------*/ + +int queue_pop(queue_t* q, void** data, size_t* size) +{ + queue_item_t *i; + int res = 0; + + pthread_mutex_lock(&q->lock); + + if(!(i = q->first)) + { + res = -1; + goto err; + } + + *data = i->data; + *size = i->size; + + /* pop item from the list */ + q->first = i->next; + + /* if list contain only one item */ + if(i == q->last) + q->last = NULL; + + free(i); + +err: + pthread_mutex_unlock(&q->lock); + + return(res); +} + +/*------------------------------------------------------------------------*/ + +int queue_wait_pop(queue_t* q, int seconds, void** data, size_t* size) +{ + struct timespec timeout; + int res; + + /* try pop message */ + while((res = queue_pop(q, data, size))) + { + /* setup timeout */ + timeout.tv_sec = time(NULL) + seconds; + timeout.tv_nsec = 0; + + /* pop failed wait sec and try it again */ + if(event_wait_time(q->event, seconds)) + /* if timeout exit */ + break; + } + + return(res); +} + +/*------------------------------------------------------------------------*/ + +int queue_busy(queue_t* q, int busy) +{ + pthread_mutex_lock(&q->lock); + + /* swaping values q->busy <=> busy */ + q->busy += busy; + busy = q->busy - busy; + q->busy -= busy; + + pthread_mutex_unlock(&q->lock); + + return(busy); +} diff --git a/code/validation/C/0144939_util-vdso.c b/code/validation/C/0144939_util-vdso.c new file mode 100644 index 0000000000000000000000000000000000000000..65746d914fdd45a1e00d23b46fe5d7116670ee8b --- /dev/null +++ b/code/validation/C/0144939_util-vdso.c @@ -0,0 +1,211 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "asm/string.h" +#include "asm/types.h" + +#include "syscall.h" +#include "image.h" +#include "util-vdso.h" +#include "vma.h" +#include "log.h" +#include "bug.h" + +#ifdef LOG_PREFIX +# undef LOG_PREFIX +#endif +#define LOG_PREFIX "vdso: " + +/* Check if pointer is out-of-bound */ +static bool __ptr_oob(void *ptr, void *start, size_t size) +{ + void *end = (void *)((unsigned long)start + size); + return ptr > end || ptr < start; +} + +/* + * Elf hash, see format specification. + */ +static unsigned long elf_hash(const unsigned char *name) +{ + unsigned long h = 0, g; + + while (*name) { + h = (h << 4) + *name++; + g = h & 0xf0000000ul; + if (g) + h ^= g >> 24; + h &= ~g; + } + return h; +} + +int vdso_fill_symtable(char *mem, size_t size, struct vdso_symtable *t) +{ + const char *vdso_symbols[VDSO_SYMBOL_MAX] = { + ARCH_VDSO_SYMBOLS + }; + + Elf64_Phdr *dynamic = NULL, *load = NULL; + Elf64_Ehdr *ehdr = (void *)mem; + Elf64_Dyn *dyn_strtab = NULL; + Elf64_Dyn *dyn_symtab = NULL; + Elf64_Dyn *dyn_strsz = NULL; + Elf64_Dyn *dyn_syment = NULL; + Elf64_Dyn *dyn_hash = NULL; + Elf64_Word *hash = NULL; + Elf64_Phdr *phdr; + Elf64_Dyn *d; + + Elf64_Word *bucket, *chain; + Elf64_Word nbucket, nchain; + + /* + * See Elf specification for this magic values. + */ + static const char elf_ident[] = { + 0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }; + + char *dynsymbol_names; + unsigned int i, j, k; + + BUILD_BUG_ON(sizeof(elf_ident) != sizeof(ehdr->e_ident)); + + pr_debug("Parsing at %lx %lx\n", (long)mem, (long)mem + (long)size); + + /* + * Make sure it's a file we support. + */ + if (builtin_memcmp(ehdr->e_ident, elf_ident, sizeof(elf_ident))) { + pr_err("Elf header magic mismatch\n"); + return -EINVAL; + } + + /* + * We need PT_LOAD and PT_DYNAMIC here. Each once. + */ + phdr = (void *)&mem[ehdr->e_phoff]; + for (i = 0; i < ehdr->e_phnum; i++, phdr++) { + if (__ptr_oob(phdr, mem, size)) + goto err_oob; + switch (phdr->p_type) { + case PT_DYNAMIC: + if (dynamic) { + pr_err("Second PT_DYNAMIC header\n"); + return -EINVAL; + } + dynamic = phdr; + break; + case PT_LOAD: + if (load) { + pr_err("Second PT_LOAD header\n"); + return -EINVAL; + } + load = phdr; + break; + } + } + + if (!load || !dynamic) { + pr_err("One of obligated program headers is missed\n"); + return -EINVAL; + } + + pr_debug("PT_LOAD p_vaddr: %lx\n", (unsigned long)load->p_vaddr); + + /* + * Dynamic section tags should provide us the rest of information + * needed. Note that we're interested in a small set of tags. + */ + d = (void *)&mem[dynamic->p_offset]; + for (i = 0; i < dynamic->p_filesz / sizeof(*d); i++, d++) { + if (__ptr_oob(d, mem, size)) + goto err_oob; + + if (d->d_tag == DT_NULL) { + break; + } else if (d->d_tag == DT_STRTAB) { + dyn_strtab = d; + pr_debug("DT_STRTAB: %lx\n", (unsigned long)d->d_un.d_ptr); + } else if (d->d_tag == DT_SYMTAB) { + dyn_symtab = d; + pr_debug("DT_SYMTAB: %lx\n", (unsigned long)d->d_un.d_ptr); + } else if (d->d_tag == DT_STRSZ) { + dyn_strsz = d; + pr_debug("DT_STRSZ: %lx\n", (unsigned long)d->d_un.d_val); + } else if (d->d_tag == DT_SYMENT) { + dyn_syment = d; + pr_debug("DT_SYMENT: %lx\n", (unsigned long)d->d_un.d_val); + } else if (d->d_tag == DT_HASH) { + dyn_hash = d; + pr_debug("DT_HASH: %lx\n", (unsigned long)d->d_un.d_ptr); + } + } + + if (!dyn_strtab || !dyn_symtab || !dyn_strsz || !dyn_syment || !dyn_hash) { + pr_err("Not all dynamic entries are present\n"); + return -EINVAL; + } + + dynsymbol_names = &mem[dyn_strtab->d_un.d_val - load->p_vaddr]; + if (__ptr_oob(dynsymbol_names, mem, size)) + goto err_oob; + + hash = (void *)&mem[(unsigned long)dyn_hash->d_un.d_ptr - (unsigned long)load->p_vaddr]; + if (__ptr_oob(hash, mem, size)) + goto err_oob; + + nbucket = hash[0]; + nchain = hash[1]; + bucket = &hash[2]; + chain = &hash[nbucket + 2]; + + pr_debug("nbucket %lx nchain %lx bucket %lx chain %lx\n", + (long)nbucket, (long)nchain, (unsigned long)bucket, (unsigned long)chain); + + for (i = 0; i < VDSO_SYMBOL_MAX; i++) { + const char * symbol = vdso_symbols[i]; + k = elf_hash((const unsigned char *)symbol); + + for (j = bucket[k % nbucket]; j < nchain && chain[j] != STN_UNDEF; j = chain[j]) { + Elf64_Sym *sym = (void *)&mem[dyn_symtab->d_un.d_ptr - load->p_vaddr]; + char *name; + + sym = &sym[j]; + if (__ptr_oob(sym, mem, size)) + continue; + + if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC && + ELF64_ST_BIND(sym->st_info) != STB_GLOBAL) + continue; + + name = &dynsymbol_names[sym->st_name]; + if (__ptr_oob(name, mem, size)) + continue; + + if (builtin_strcmp(name, symbol)) + continue; + + builtin_memcpy(t->symbols[i].name, name, sizeof(t->symbols[i].name)); + t->symbols[i].offset = (unsigned long)sym->st_value - load->p_vaddr; + break; + } + } + + return 0; + +err_oob: + pr_err("Corrupted Elf data\n"); + return -EFAULT; +} + diff --git a/code/validation/C/0147708_freetype.c b/code/validation/C/0147708_freetype.c new file mode 100644 index 0000000000000000000000000000000000000000..9d5acddd495b00ae86ce25996778b74dd25f9209 --- /dev/null +++ b/code/validation/C/0147708_freetype.c @@ -0,0 +1,179 @@ +/* RetroArch - A frontend for libretro. + * Copyright (C) 2010-2013 - Hans-Kristian Arntzen + * + * RetroArch is free software: you can redistribute it and/or modify it under the terms + * of the GNU General Public License as published by the Free Software Found- + * ation, either version 3 of the License, or (at your option) any later version. + * + * RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with RetroArch. + * If not, see . + */ + +#include "fonts.h" +#include "../../file.h" +#include +#include +#include + +#include +#include FT_FREETYPE_H + +struct font_renderer +{ + FT_Library lib; + FT_Face face; +}; + +static void ft_renderer_free(void *data) +{ + font_renderer_t *handle = (font_renderer_t*)data; + if (!handle) + return; + + if (handle->face) + FT_Done_Face(handle->face); + if (handle->lib) + FT_Done_FreeType(handle->lib); + free(handle); +} + +static void *ft_renderer_init(const char *font_path, float font_size) +{ + (void)font_size; + FT_Error err; + font_renderer_t *handle = (font_renderer_t*)calloc(1, sizeof(*handle)); + if (!handle) + goto error; + + err = FT_Init_FreeType(&handle->lib); + if (err) + goto error; + + err = FT_New_Face(handle->lib, font_path, 0, &handle->face); + if (err) + goto error; + + err = FT_Set_Pixel_Sizes(handle->face, 0, font_size); + if (err) + goto error; + + return handle; + +error: + ft_renderer_free(handle); + return NULL; +} + +static void ft_renderer_msg(void *data, const char *msg, struct font_output_list *output) +{ + font_renderer_t *handle = (font_renderer_t*)data; + output->head = NULL; + + FT_GlyphSlot slot = handle->face->glyph; + struct font_output *cur = NULL; + size_t len = strlen(msg); + int off_x = 0, off_y = 0; + + for (size_t i = 0; i < len; i++) + { + FT_Error err = FT_Load_Char(handle->face, msg[i], FT_LOAD_RENDER); + + if (!err) + { + struct font_output *tmp = (struct font_output*)calloc(1, sizeof(*tmp)); + if (!tmp) + break; + + tmp->output = (uint8_t*)malloc(slot->bitmap.pitch * slot->bitmap.rows); + if (!tmp->output) + { + free(tmp); + break; + } + + memcpy(tmp->output, slot->bitmap.buffer, slot->bitmap.pitch * slot->bitmap.rows); + + tmp->width = slot->bitmap.width; + tmp->height = slot->bitmap.rows; + tmp->pitch = slot->bitmap.pitch; + tmp->advance_x = slot->advance.x >> 6; + tmp->advance_y = slot->advance.y >> 6; + tmp->char_off_x = slot->bitmap_left; + tmp->char_off_y = slot->bitmap_top - slot->bitmap.rows; + tmp->off_x = off_x + tmp->char_off_x; + tmp->off_y = off_y + tmp->char_off_y; + tmp->next = NULL; + + if (i == 0) + output->head = tmp; + else + cur->next = tmp; + + cur = tmp; + } + + off_x += slot->advance.x >> 6; + off_y += slot->advance.y >> 6; + } +} + +static void ft_renderer_free_output(void *data, struct font_output_list *output) +{ + (void)data; + + struct font_output *itr = output->head; + struct font_output *tmp = NULL; + while (itr != NULL) + { + free(itr->output); + tmp = itr; + itr = itr->next; + free(tmp); + } + output->head = NULL; +} + +// Not the cleanest way to do things for sure, but should hopefully work ... :) + +static const char *font_paths[] = { +#if defined(_WIN32) + "C:\\Windows\\Fonts\\consola.ttf", + "C:\\Windows\\Fonts\\verdana.ttf", +#elif defined(__APPLE__) + "/Library/Fonts/Microsoft/Candara.ttf", + "/Library/Fonts/Verdana.ttf", + "/Library/Fonts/Tahoma.ttf", +#else + "/usr/share/fonts/TTF/DejaVuSansMono.ttf", + "/usr/share/fonts/TTF/DejaVuSans.ttf", + "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSansMono.ttf", + "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf", +#endif + "osd-font.ttf", // Magic font to search for, useful for distribution. +}; + +// Highly OS/platform dependent. +static const char *ft_renderer_get_default_font(void) +{ + for (size_t i = 0; i < sizeof(font_paths) / sizeof(font_paths[0]); i++) + { + if (path_file_exists(font_paths[i])) + return font_paths[i]; + } + + return NULL; +} + +const font_renderer_driver_t ft_font_renderer = { + ft_renderer_init, + ft_renderer_msg, + ft_renderer_free_output, + ft_renderer_free, + ft_renderer_get_default_font, + "freetype", +}; + diff --git a/code/validation/C/0148075_frcode.c b/code/validation/C/0148075_frcode.c new file mode 100644 index 0000000000000000000000000000000000000000..23f9369b62b42241b5bd0ecdd832a2cc11583be4 --- /dev/null +++ b/code/validation/C/0148075_frcode.c @@ -0,0 +1,363 @@ +/* frcode -- front-compress a sorted list + Copyright (C) 1994,2005,2006,2007 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/* Usage: frcode < sorted-list > compressed-list + + Uses front compression (also known as incremental encoding); + see ";login:", March 1983, p. 8. + + The input is a sorted list of NUL-terminated strings (or + newline-terminated if the -0 option is not given). + + The output entries are in the same order as the input; each entry + consists of a signed offset-differential count byte (the additional + number of characters of prefix of the preceding entry to use beyond + the number that the preceding entry is using of its predecessor), + followed by a null-terminated ASCII remainder. + + If the offset-differential count is larger than can be stored + in a byte (+/-127), the byte has the value LOCATEDB_ESCAPE + and the count follows in a 2-byte word, with the high byte first + (network byte order). + + Example: + + Input, with NULs changed to newlines: + /usr/src + /usr/src/cmd/aardvark.c + /usr/src/cmd/armadillo.c + /usr/tmp/zoo + + Length of the longest prefix of the preceding entry to share: + 0 /usr/src + 8 /cmd/aardvark.c + 14 rmadillo.c + 5 tmp/zoo + + Output, with NULs changed to newlines and count bytes made printable: + 0 LOCATE02 + 0 /usr/src + 8 /cmd/aardvark.c + 6 rmadillo.c + -9 tmp/zoo + + (6 = 14 - 8, and -9 = 5 - 14) + + Written by James A. Woods . + Modified by David MacKenzie . + Modified by James Youngman . +*/ + +#include + + +#include +#include +#include +#include +#include +#include + +#if defined HAVE_STRING_H || defined STDC_HEADERS +#include +#else +#include +#endif + +#ifdef STDC_HEADERS +#include +#endif + +#if ENABLE_NLS +# include +# define _(Text) gettext (Text) +#else +# define _(Text) Text +#define textdomain(Domain) +#define bindtextdomain(Package, Directory) +#endif +#ifdef gettext_noop +# define N_(String) gettext_noop (String) +#else +/* We used to use (String) instead of just String, but apparently ISO C + * doesn't allow this (at least, that's what HP said when someone reported + * this as a compiler bug). This is HP case number 1205608192. See + * also http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11250 (which references + * ANSI 3.5.7p14-15). The Intel icc compiler also rejects constructs + * like: static const char buf[] = ("string"); + */ +# define N_(String) String +#endif + + +#include "locatedb.h" +#include +#include "error.h" +#include "closeout.h" +#include "findutils-version.h" + +char *xmalloc PARAMS((size_t)); + +/* The name this program was run with. */ +char *program_name; + +/* Write out a 16-bit int, high byte first (network byte order). + * Return true iff all went well. + */ +static int +put_short (int c, FILE *fp) +{ + /* XXX: The value of c may be negative. ANSI C 1989 (section 6.3.7) + * indicates that the result of shifting a negative value right is + * implementation defined. + */ + assert (c <= SHRT_MAX); + assert (c >= SHRT_MIN); + return (putc (c >> 8, fp) != EOF) && (putc (c, fp) != EOF); +} + +/* Return the length of the longest common prefix of strings S1 and S2. */ + +static int +prefix_length (char *s1, char *s2) +{ + register char *start; + int limit = INT_MAX; + for (start = s1; *s1 == *s2 && *s1 != '\0'; s1++, s2++) + { + /* Don't emit a prefix length that will not fit into + * our return type. + */ + if (0 == --limit) + break; + } + return s1 - start; +} + +static struct option const longopts[] = +{ + {"help", no_argument, NULL, 'h'}, + {"version", no_argument, NULL, 'v'}, + {"null", no_argument, NULL, '0'}, + {NULL, no_argument, NULL, 0} +}; + +extern char *version_string; + +/* The name this program was run with. */ +char *program_name; + + +static void +usage (FILE *stream) +{ + fprintf (stream, + _("Usage: %s [-0 | --null] [--version] [--help]\n"), + program_name); + fputs (_("\nReport bugs to .\n"), stream); +} + +static long +get_seclevel(char *s) +{ + long result; + char *p; + + /* Reset errno in oreder to be able to distinguish LONG_MAX/LONG_MIN + * from values whichare actually out of range + */ + errno = 0; + + result = strtol(s, &p, 10); + if ((0==result) && (p == optarg)) + { + error(1, 0, _("You need to specify a security level as a decimal integer.")); + /*NOTREACHED*/ + return -1; + } + else if ((LONG_MIN==result || LONG_MAX==result) && errno) + + { + error(1, 0, _("Security level %s is outside the convertible range."), s); + /*NOTREACHED*/ + return -1; + } + else if (*p) + { + /* Some suffix exists */ + error(1, 0, _("Security level %s has unexpected suffix %s."), s, p); + /*NOTREACHED*/ + return -1; + } + else + { + return result; + } +} + +static void +outerr(void) +{ + /* Issue the same error message as closeout() would. */ + error(1, errno, _("write error")); +} + +int +main (int argc, char **argv) +{ + char *path; /* The current input entry. */ + char *oldpath; /* The previous input entry. */ + size_t pathsize, oldpathsize; /* Amounts allocated for them. */ + int count, oldcount, diffcount; /* Their prefix lengths & the difference. */ + int line_len; /* Length of input line. */ + int delimiter = '\n'; + int optc; + int slocate_compat = 0; + long slocate_seclevel = 0L; + + program_name = argv[0]; + if (!program_name) + program_name = "frcode"; + atexit (close_stdout); + + pathsize = oldpathsize = 1026; /* Increased as necessary by getline. */ + path = xmalloc (pathsize); + oldpath = xmalloc (oldpathsize); + + oldpath[0] = 0; + oldcount = 0; + + + while ((optc = getopt_long (argc, argv, "hv0S:", longopts, (int *) 0)) != -1) + switch (optc) + { + case '0': + delimiter = 0; + break; + + case 'S': + slocate_compat = 1; + slocate_seclevel = get_seclevel(optarg); + if (slocate_seclevel < 0 || slocate_seclevel > 1) + { + error(1, 0, + _("slocate security level %ld is unsupported."), + slocate_seclevel); + } + break; + + case 'h': + usage (stdout); + return 0; + + case 'v': + display_findutils_version("frcode"); + return 0; + + default: + usage (stderr); + return 1; + } + + /* We expect to have no arguments. */ + if (optind != argc) + { + usage (stderr); + return 1; + } + + + if (slocate_compat) + { + fputc(slocate_seclevel ? '1' : '0', stdout); + fputc(0, stdout); + + } + else + { + /* GNU LOCATE02 format */ + if (fwrite (LOCATEDB_MAGIC, 1, sizeof (LOCATEDB_MAGIC), stdout) + != sizeof(LOCATEDB_MAGIC)) + { + error(1, errno, _("Failed to write to standard output")); + } + } + + + while ((line_len = getdelim (&path, &pathsize, delimiter, stdin)) > 0) + { + path[line_len - 1] = '\0'; /* FIXME temporary: nuke the newline. */ + + count = prefix_length (oldpath, path); + diffcount = count - oldcount; + if ( (diffcount > SHRT_MAX) || (diffcount < SHRT_MIN) ) + { + /* We do this to prevent overflow of the value we + * write with put_short() + */ + count = 0; + diffcount = (-oldcount); + } + oldcount = count; + + if (slocate_compat) + { + /* Emit no count for the first pathname. */ + slocate_compat = 0; + } + else + { + /* If the difference is small, it fits in one byte; + otherwise, two bytes plus a marker noting that fact. */ + if (diffcount < LOCATEDB_ONEBYTE_MIN + || diffcount > LOCATEDB_ONEBYTE_MAX) + { + if (EOF == putc (LOCATEDB_ESCAPE, stdout)) + outerr(); + if (!put_short (diffcount, stdout)) + outerr(); + } + else + { + if (EOF == putc (diffcount, stdout)) + outerr(); + } + } + + if ( (EOF == fputs (path + count, stdout)) + || (EOF == putc ('\0', stdout))) + { + outerr(); + } + + if (1) + { + /* Swap path and oldpath and their sizes. */ + char *tmppath = oldpath; + size_t tmppathsize = oldpathsize; + oldpath = path; + oldpathsize = pathsize; + path = tmppath; + pathsize = tmppathsize; + } + } + + free (path); + free (oldpath); + + return 0; +} diff --git a/code/validation/C/0148305_select.c b/code/validation/C/0148305_select.c new file mode 100644 index 0000000000000000000000000000000000000000..0f3137645ee05e0a5feb0b0b4de8125db56a6140 --- /dev/null +++ b/code/validation/C/0148305_select.c @@ -0,0 +1,230 @@ +/* + * selet.c - Example of using select() with Comedi + * Part of Comedilib + * + * Copyright (c) 1999,2000 David A. Schleef + * + * This file may be freely modified, distributed, and combined with + * other software, as long as proper attribution is given in the + * source code. + */ + +/* + * An example for using select() with asynchronous input. This + * example requires an asynchronous input subdevice that can + * handle TRIG_TIMER as a scan_begin_src. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "examples.h" + +#define N_SCANS 10 +#define N_CHANS 16 + +#define BUFSZ 1000 +sampl_t buf[BUFSZ]; + +const int n_chans = 1; +const int n_scans = 10; + +unsigned int chanlist[4]; + +comedi_t *device; + +void prepare_cmd(comedi_t *dev,comedi_cmd *cmd, int subdevice); +void do_cmd(comedi_t *dev,comedi_cmd *cmd); + +int main(int argc, char *argv[]) +{ + comedi_cmd cmd; + int i; + struct parsed_options options; + + init_parsed_options(&options); + parse_options(&options, argc, argv); + + device = comedi_open(options.filename); + if(!device){ + perror(options.filename); + exit(1); + } + + fcntl(comedi_fileno(device), F_SETFL, O_NONBLOCK); + + for(i = 0; i < n_chans; i++){ + chanlist[i] = CR_PACK(options.channel + i, options.range, options.aref); + } + + prepare_cmd(device, &cmd, options.subdevice); + + do_cmd(device, &cmd); + + return 0; +} + +void do_cmd(comedi_t *dev,comedi_cmd *cmd) +{ + int total=0; + int ret; + int go; + fd_set rdset; + struct timeval timeout; + + ret=comedi_command_test(dev,cmd); + + printf("test ret=%d\n",ret); + if(ret<0){ + printf("errno=%d\n",errno); + comedi_perror("comedi_command_test"); + return; + } + + dump_cmd(stdout,cmd); + + ret=comedi_command_test(dev,cmd); + + printf("test ret=%d\n",ret); + if(ret<0){ + printf("errno=%d\n",errno); + comedi_perror("comedi_command_test"); + return; + } + + dump_cmd(stdout,cmd); + + comedi_set_read_subdevice(dev, cmd->subdev); + ret = comedi_get_read_subdevice(dev); + if (ret < 0 || ret != cmd->subdev) { + fprintf(stderr, + "failed to change 'read' subdevice from %d to %d\n", + ret, cmd->subdev); + return; + } + + ret=comedi_command(dev,cmd); + + printf("ret=%d\n",ret); + if(ret<0){ + printf("errno=%d\n",errno); + comedi_perror("comedi_command"); + return; + } + + go=1; + while(go){ + FD_ZERO(&rdset); + FD_SET(comedi_fileno(device),&rdset); + timeout.tv_sec = 0; + timeout.tv_usec = 50000; + ret = select(comedi_fileno(dev)+1,&rdset,NULL,NULL,&timeout); + printf("select returned %d\n",ret); + if(ret<0){ + perror("select"); + }else if(ret==0){ + /* hit timeout */ + printf("timeout\n"); + }else if(FD_ISSET(comedi_fileno(device),&rdset)){ + /* comedi file descriptor became ready */ + printf("comedi file descriptor ready\n"); + ret=read(comedi_fileno(dev),buf,sizeof(buf)); + printf("read returned %d\n",ret); + if(ret<0){ + if(errno==EAGAIN){ + go = 0; + perror("read"); + } + }else if(ret==0){ + go = 0; + }else{ + int i; + total+=ret; + //printf("read %d %d\n",ret,total); + for(i=0;isubdev = subdevice; + + /* flags */ + cmd->flags = TRIG_WAKE_EOS; + //cmd.flags = 0; + + /* each event requires a trigger, which is specified + by a source and an argument. For example, to specify + an external digital line 3 as a source, you would use + src=TRIG_EXT and arg=3. */ + + /* In this case, we specify using TRIG_NOW to start + * acquisition immediately when the command is issued. + * The argument of TRIG_NOW is "number of nsec after + * NOW", but no driver supports it yet. Also, no driver + * currently supports using a start_src other than + * TRIG_NOW. */ + cmd->start_src = TRIG_NOW; + cmd->start_arg = 0; + + /* The timing of the beginning of each scan is controlled + * by scan_begin. TRIG_TIMER specifies that scan_start + * events occur periodically at a rate of scan_begin_arg + * nanoseconds between scans. */ + cmd->scan_begin_src = TRIG_TIMER; + cmd->scan_begin_arg = msec_to_nsec(100); + + /* The timing between each sample in a scan is controlled + * by convert. Like above, TRIG_TIMER specifies that + * convert events occur periodically at a rate of convert_arg + * nanoseconds between scans. */ + cmd->convert_src = TRIG_TIMER; + cmd->convert_arg = msec_to_nsec(1); + + /* The end of each scan is almost always specified using + * TRIG_COUNT, with the argument being the same as the + * number of channels in the chanlist. You could probably + * find a device that allows something else, but it would + * be strange. */ + cmd->scan_end_src = TRIG_COUNT; + cmd->scan_end_arg = n_chans; /* number of channels */ + + /* The end of acquisition is controlled by stop_src and + * stop_arg. The src will typically be TRIG_COUNT or + * TRIG_NONE. Specifying TRIG_COUNT will stop acquisition + * after stop_arg number of scans, or TRIG_NONE will + * cause acquisition to continue until stopped using + * comedi_cancel(). */ + cmd->stop_src = TRIG_COUNT; + cmd->stop_arg = n_scans; + + /* the channel list determined which channels are sampled. + In general, chanlist_len is the same as scan_end_arg. Most + boards require this. */ + cmd->chanlist = chanlist; + cmd->chanlist_len = n_chans; +} + diff --git a/code/validation/C/0148471_tizenrt.c b/code/validation/C/0148471_tizenrt.c new file mode 100644 index 0000000000000000000000000000000000000000..b8b8e34dfd3efbb1efa6b256419b3b809c3de95b --- /dev/null +++ b/code/validation/C/0148471_tizenrt.c @@ -0,0 +1,274 @@ +/* Copyright 2017-present Samsung Electronics Co., Ltd. + * + * 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. + */ + +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include +#include + +#include +#include "unix/internal.h" + +//----------------------------------------------------------------------------- +// loop +int uv__platform_loop_init(uv_loop_t* loop) { + loop->npollfds = 0; + return 0; +} + +void uv__platform_loop_delete(uv_loop_t* loop) { + loop->npollfds = 0; +} + + +//----------------------------------------------------------------------------- + +void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) { + int i; + int nfd = loop->npollfds; + for (i = 0; i < nfd; ++i) { + struct pollfd* pfd = &loop->pollfds[i]; + if (fd == pfd->fd) { + pfd->fd = -1; + } + } +} + +//----------------------------------------------------------------------------- + +/* should not clear handle structure with memset as + * *data can be set before calling init function */ + +//----------------------------------------------------------------------------- + +ssize_t readv(int fd, const struct iovec* iiovec, int count) { + ssize_t result = 0; + ssize_t total = 0; + int idx; + + for (idx = 0; idx < count; ++idx) { + result = read(fd, iiovec[idx].iov_base, iiovec[idx].iov_len); + if (result < 0) { + return result; + } else { + total += result; + } + } + return total; +} + + +ssize_t writev(int fd, const struct iovec* iiovec, int count) { + ssize_t result = 0; + ssize_t total = 0; + int idx; + + for (idx = 0; idx < count; ++idx) { + result = write(fd, iiovec[idx].iov_base, iiovec[idx].iov_len); + if (result < 0) { + return result; + } else { + total += result; + } + } + return total; +} + +// From nuttx_clock.c +uint64_t uv__hrtime(uv_clocktype_t type) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + uint64_t ret = (((uint64_t) ts.tv_sec) * ((uint64_t) 1e9) + + (uint64_t) ts.tv_nsec); + return ret; +} + +// From nuttx_io.c +static void uv__add_pollfd(uv_loop_t* loop, struct pollfd* pe) { + int i; + bool exist = false; + int free_idx = -1; + for (i = 0; i < loop->npollfds; ++i) { + struct pollfd* cur = &loop->pollfds[i]; + if (cur->fd == pe->fd) { + cur->events = pe->events; + exist = true; + break; + } + if (cur->fd == -1) { + free_idx = i; + } + } + if (!exist) { + if (free_idx == -1) { + free_idx = loop->npollfds++; + if (free_idx >= TUV_POLL_EVENTS_SIZE) + { + TDLOG("uv__add_pollfd abort, because loop->npollfds (%d) reached maximum size", free_idx); + ABORT(); + } + } + struct pollfd* cur = &loop->pollfds[free_idx]; + + cur->fd = pe->fd; + cur->events = pe->events; + cur->revents = 0; + cur->sem = 0; + cur->priv = 0; + } +} + + +static void uv__rem_pollfd(uv_loop_t* loop, struct pollfd* pe) { + int i = 0; + while (i < loop->npollfds) { + struct pollfd* cur = &loop->pollfds[i]; + if (cur->fd == pe->fd) { + *cur = loop->pollfds[--loop->npollfds]; + } else { + ++i; + } + } +} + + +void uv__io_poll(uv_loop_t* loop, int timeout) { + struct pollfd pfd; + struct pollfd* pe; + QUEUE* q; + uv__io_t* w; + uint64_t base; + uint64_t diff; + int nevents; + int count; + int nfd; + int i; + + if (loop->nfds == 0) { + assert(QUEUE_EMPTY(&loop->watcher_queue)); + return; + } + + while (!QUEUE_EMPTY(&loop->watcher_queue)) { + q = QUEUE_HEAD(&loop->watcher_queue); + QUEUE_REMOVE(q); + QUEUE_INIT(q); + + w = QUEUE_DATA(q, uv__io_t, watcher_queue); + assert(w->pevents != 0); + assert(w->fd >= 0); + assert(w->fd < (int)loop->nwatchers); + + pfd.fd = w->fd; + pfd.events = w->pevents; + uv__add_pollfd(loop, &pfd); + + w->events = w->pevents; + } + + assert(timeout >= -1); + base = loop->time; + count = 5; + + for (;;) { + nfd = poll(loop->pollfds, loop->npollfds, timeout); + + SAVE_ERRNO(uv__update_time(loop)); + + if (nfd == 0) { + assert(timeout != -1); + return; + } + + if (nfd == -1) { + int err = get_errno(); + if (err == EAGAIN) { + set_errno(0); + } + else if (err != EINTR) { + // poll of which the watchers is null should be removed + TDLOG("uv__io_poll abort for errno(%d)", err); + goto handle_poll; + } + if (timeout == -1) { + continue; + } + if (timeout == 0) { + return; + } + goto update_timeout; + } + +handle_poll: + nevents = 0; + + for (i = 0; i < loop->npollfds; ++i) { + pe = &loop->pollfds[i]; + w = loop->watchers[pe->fd]; + + if (w == NULL) { + uv__rem_pollfd(loop, pe); + --i; + continue; + } + + if (pe->fd >= 0 && (pe->revents & (POLLIN | POLLOUT | POLLHUP))) { + w->cb(loop, w, pe->revents); + ++nevents; + } + } + + if (nevents != 0) { + if (--count != 0) { + timeout = 0; + continue; + } + return; + } + if (timeout == 0) { + return; + } + if (timeout == -1) { + continue; + } +update_timeout: + assert(timeout > 0); + + diff = loop->time - base; + if (diff >= (uint64_t)timeout) { + return; + } + timeout -= diff; + } +} diff --git a/code/validation/C/0148869_full_permutation.c b/code/validation/C/0148869_full_permutation.c new file mode 100644 index 0000000000000000000000000000000000000000..17138347f6aaad96150ad3a1d36518cc2b8deff3 --- /dev/null +++ b/code/validation/C/0148869_full_permutation.c @@ -0,0 +1,52 @@ +/************************************************************************* + > File Name: full_permutation.c + > Author: averainy + > Mail: averainy@gmail.com + > Created Time: 2013年04月18日 星期四 12时04分50秒 + ************************************************************************/ +#include +#include +#include +#define SWAP(x,y,t) ((t)=(x),(x)=(y),(y)=(t)) +#define MAX_SIZE101 +void swap(int x, int y) +{ + int temp; + temp = x; + x = y; + y = temp; +} + +void perm(int[], int, int); +int main() +{ + int i, n; + int list[MAX_SIZE]; + printf("Please enter a number:"); + scanf("%d", &n); + for (i = 0; i < n; i++) { + list[i] = i; + // list[i]=rand()%n; + printf("%d ", list[i]); + } + printf("\n"); + perm(list, 0, n - 1); + return 0; +} + +void perm(int list[], int i, int n) +{ + int j, temp; + if (i == n) { + for (j = 0; j <= n; j++) { + printf("%d ", list[j]); + } + printf("\n"); + } else { + for (j = i; j <= n; j++) { + SWAP(list[i], list[j], temp); + perm(list, i + 1, n); + SWAP(list[i], list[j], temp); + } + } +} diff --git a/code/validation/C/0149027_nRF24L01P.c b/code/validation/C/0149027_nRF24L01P.c new file mode 100644 index 0000000000000000000000000000000000000000..99d13487e2e1e108fcfdba87f139b785466e346c --- /dev/null +++ b/code/validation/C/0149027_nRF24L01P.c @@ -0,0 +1,103 @@ + +#include +#include + +#include +#include +#include +#include +#include +#include "user.h" +#include "system.h" +#include "spi.h" +#include "nRF24L01P.h" + +void nRF_Setup() +{ + //setting RXTX adress + uint8_t RXTX_ADDR[5];// = { 0xAA, 0xAA, 0xAA}; //adresa + RXTX_ADDR[4] = 0xAB; + RXTX_ADDR[3] = 0xAC; + RXTX_ADDR[2] = 0xAD; + RXTX_ADDR[1] = 0xAE; + RXTX_ADDR[0] = 0xAF; + + CE = 0; + WriteAddress(TX_ADDR, 5, RXTX_ADDR); // TX addr, 5 bytes + WriteAddress(RX_ADDR_P0, 5, RXTX_ADDR); // RX addr pipe 0 + WriteRegister(EN_AA, 0x01); // enable AA on data pipe 1 + WriteRegister(EN_RXADDR, 0x01); // enable RX address on data pipe 1 + WriteRegister(SETUP_AW, 0x03); // Address width,'01'-3 bytes,'10'-4 bytes,'11'-5 bytes + WriteRegister(SETUP_RETR, 0x2F); // wait 750 us, up to 15 retransmissions + WriteRegister(RF_CH, 0x14); // Channel 20 --> 2.4 GHz + 20 MHz + WriteRegister(RF_SETUP, 0x06); // 1 Mbps, 0 dBm + WriteRegister(NRF_STATUS,0x70); // Reset status register + WriteRegister(RX_PW_P0, 0x02); // Number of bytes in RX payload in data pipe 0 + WriteRegister(NRF_CONFIG,0x7A); // pwr_up , ptx, en crc, 1 byte, interrupt not reflected + __delay_ms(2); //POWER-ON TIME 1.5ms specified + + +} +//FUNCTIONS +//flush TX and RX +void FlushTXRX() +{ + WriteRegister(NRF_STATUS, 0x70); + WriteCommand(FLUSH_RX); + WriteCommand(FLUSH_TX); +} + +// Write to the register +void WriteRegister(uint8_t reg, uint8_t val) +{ + CSN = 0; // CSN enable, negative logic + //MSB first, first command then value + SPI_transfer(W_REG | reg); + SPI_transfer(val); + CSN = 1; // CSN disable +} + +//Address is 3-5 bytes, LSB first +void WriteAddress(uint8_t reg, uint8_t num, uint8_t * addr) +{ + CSN = 0; + SPI_transfer(W_REG | reg); + for (int i=0; i 10 us + CE = 0; +} \ No newline at end of file diff --git a/code/validation/C/0149258_ANDScorer.c b/code/validation/C/0149258_ANDScorer.c new file mode 100644 index 0000000000000000000000000000000000000000..c8950ba0bd71634a21b2235520a732bafd7197d1 --- /dev/null +++ b/code/validation/C/0149258_ANDScorer.c @@ -0,0 +1,157 @@ +#include "Search/Kino03/KinoSearch/Util/ToolSet.h" + +#include "Search/Kino03/KinoSearch/Search/ANDScorer.h" +#include "Search/Kino03/KinoSearch/Search/Similarity.h" +#include "Search/Kino03/KinoSearch/Util/ByteBuf.h" + +ANDScorer* +ANDScorer_new(VArray *children, Similarity *sim) +{ + ANDScorer *self = (ANDScorer*)VTable_Make_Obj(&ANDSCORER); + return ANDScorer_init(self, children, sim); +} + +ANDScorer* +ANDScorer_init(ANDScorer *self, VArray *children, Similarity *sim) +{ + u32_t i; + + /* Init. */ + PolyMatcher_init((PolyMatcher*)self, children, sim); + self->cap = 10; + self->first_time = true; + + /* Assign. */ + self->more = self->num_kids ? true : false; + self->kids = MALLOCATE(self->num_kids, Matcher*); + for (i = 0; i < self->num_kids; i++) { + Matcher *child = (Matcher*)VA_Fetch(children, i); + self->kids[i] = child; + if (!Matcher_Next(child)) self->more = false; + } + + /* Derive. */ + self->matching_kids = self->num_kids; + + return self; +} + +void +ANDScorer_destroy(ANDScorer *self) +{ + free(self->kids); + SUPER_DESTROY(self, ANDSCORER); +} + +i32_t +ANDScorer_next(ANDScorer *self) +{ + if (self->first_time) { + return ANDScorer_Advance(self, 1); + } + if (self->more) { + const i32_t target = Matcher_Get_Doc_ID(self->kids[0]) + 1; + return ANDScorer_Advance(self, target); + } + else { + return 0; + } +} + +i32_t +ANDScorer_advance(ANDScorer *self, i32_t target) +{ + Matcher **const kids = self->kids; + const u32_t num_kids = self->num_kids; + i32_t highest = 0; + + if (!self->more) return 0; + + /* First step: Advance first child and use its doc as a starting point. */ + if (self->first_time) { + self->first_time = false; + } + else { + highest = Matcher_Advance(kids[0], target); + if (!highest) { + self->more = false; + return 0; + } + } + + /* Second step: reconcile. */ + while(1) { + u32_t i; + bool_t agreement = true; + + /* Scoot all scorers up. */ + for (i = 0; i < num_kids; i++) { + Matcher *const child = kids[i]; + i32_t candidate = Matcher_Get_Doc_ID(child); + + /* If this child is highest, others will need to catch up. */ + if (highest < candidate) + highest = candidate; + + /* If least doc scorers can agree on exceeds target, raise bar. */ + if (target < highest) + target = highest; + + /* Scoot this scorer up if not already at highest. */ + if (candidate < target) { + /* This scorer is definitely the highest right now. */ + highest = Matcher_Advance(child, target); + if (!highest) { + self->more = false; + return 0; + } + } + } + + /* If scorers don't agree, send back through the loop. */ + for (i = 0; i < num_kids; i++) { + Matcher *const child = kids[i]; + const i32_t candidate = Matcher_Get_Doc_ID(child); + if (candidate != highest) { + agreement = false; + break; + } + } + + if (!agreement) + continue; + if (highest >= target) + break; + } + + return highest; +} + +i32_t +ANDScorer_get_doc_id(ANDScorer *self) +{ + return Matcher_Get_Doc_ID(self->kids[0]); +} + +float +ANDScorer_score(ANDScorer *self) +{ + u32_t i; + Matcher **const kids = self->kids; + float score = 0.0f; + + for (i = 0; i < self->num_kids; i++) { + score += Matcher_Score(kids[i]); + } + + score *= self->coord_factors[ self->matching_kids ]; + + return score; +} + +/* Copyright 2006-2009 Marvin Humphrey + * + * This program is free software; you can redistribute it and/or modify + * under the same terms as Perl itself. + */ +