diff --git a/pool/shard002/Python/0025232_http_mixin.py b/pool/shard002/Python/0025232_http_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..5fcfaac66bb44b96aef6d2ee19591a1c57695b30 --- /dev/null +++ b/pool/shard002/Python/0025232_http_mixin.py @@ -0,0 +1,51 @@ +import json +import re + +import httpretty + + +class HttpMixin(object): + """Mixin for tests which perform mocked http interactions""" + def setUp(self): + super(HttpMixin, self).setUp() + httpretty.enable() + + def tearDown(self): + super(HttpMixin, self).tearDown() + httpretty.disable() + httpretty.reset() + + def expect_json_http(self, json_dict=None, **kwargs): + """Wraps httpretty.register_uri with some defaults for JSON""" + if json_dict is None: + json_dict = {"key": "value"} + kwargs['body'] = json.dumps(json_dict) + kwargs['content_type'] = 'text/json' + self.expect_http(**kwargs) + + def expect_xml_http(self, xml_str=None, **kwargs): + """Wraps httpretty.register_uri with some defaults for XML""" + if xml_str is None: + xml_str = '' + kwargs['body'] = xml_str + kwargs['content_type'] = 'text/xml' + self.expect_http(**kwargs) + + def expect_http(self, **kwargs): + """Wraps httpretty.register_uri with some defaults""" + kwargs['body'] = kwargs.get('body', b'') + kwargs['content_type'] = kwargs.get('content_type', + 'application/octet-stream') + kwargs['method'] = kwargs.get('method', httpretty.GET) + # Default to catching all requests + kwargs['uri'] = kwargs.get('uri', re.compile(".*")) + httpretty.register_uri(**kwargs) + + def last_http_params(self): + return httpretty.last_request().querystring + + def last_http_headers(self): + return httpretty.last_request().headers.dict + + def last_http_body(self): + return httpretty.last_request().parsed_body diff --git a/pool/shard002/Python/0025242_test_pluginmanager.py b/pool/shard002/Python/0025242_test_pluginmanager.py new file mode 100644 index 0000000000000000000000000000000000000000..aaf7b4909830667168a063ed2e9048b0f1bf740b --- /dev/null +++ b/pool/shard002/Python/0025242_test_pluginmanager.py @@ -0,0 +1,90 @@ +# -*- coding: utf-8 -*- +# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=4 + +############################################################################### +# OpenLP - Open Source Lyrics Projection # +# --------------------------------------------------------------------------- # +# Copyright (c) 2008-2015 OpenLP Developers # +# --------------------------------------------------------------------------- # +# 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. # +# # +# 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 # +############################################################################### +""" +Package to test the openlp.core.lib.pluginmanager package. +""" +import sys +import shutil +import gc +from tempfile import mkdtemp +from unittest import TestCase + +from PyQt4 import QtGui + +from openlp.core.common import Registry, Settings +from openlp.core.lib.pluginmanager import PluginManager +from tests.interfaces import MagicMock +from tests.helpers.testmixin import TestMixin + + +class TestPluginManager(TestCase, TestMixin): + """ + Test the PluginManager class + """ + + def setUp(self): + """ + Some pre-test setup required. + """ + Settings.setDefaultFormat(Settings.IniFormat) + self.build_settings() + self.temp_dir = mkdtemp('openlp') + Settings().setValue('advanced/data path', self.temp_dir) + Registry.create() + Registry().register('service_list', MagicMock()) + self.setup_application() + self.main_window = QtGui.QMainWindow() + Registry().register('main_window', self.main_window) + + def tearDown(self): + Settings().remove('advanced/data path') + self.destroy_settings() + del self.main_window + # On windows we need to manually garbage collect to close sqlalchemy files + # to avoid errors when temporary files are deleted. + gc.collect() + shutil.rmtree(self.temp_dir) + + def find_plugins_test(self): + """ + Test the find_plugins() method to ensure it imports the correct plugins + """ + # GIVEN: A plugin manager + plugin_manager = PluginManager() + + # WHEN: We mock out sys.platform to make it return "darwin" and then find the plugins + old_platform = sys.platform + sys.platform = 'darwin' + plugin_manager.find_plugins() + sys.platform = old_platform + + # THEN: We should find the "Songs", "Bibles", etc in the plugins list + plugin_names = [plugin.name for plugin in plugin_manager.plugins] + self.assertIn('songs', plugin_names, 'There should be a "songs" plugin') + self.assertIn('bibles', plugin_names, 'There should be a "bibles" plugin') + self.assertIn('presentations', plugin_names, 'There should be a "presentations" plugin') + self.assertIn('images', plugin_names, 'There should be a "images" plugin') + self.assertIn('media', plugin_names, 'There should be a "media" plugin') + self.assertIn('custom', plugin_names, 'There should be a "custom" plugin') + self.assertIn('songusage', plugin_names, 'There should be a "songusage" plugin') + self.assertIn('alerts', plugin_names, 'There should be a "alerts" plugin') + self.assertIn('remotes', plugin_names, 'There should be a "remotes" plugin') diff --git a/pool/shard002/Python/0025243_group.py b/pool/shard002/Python/0025243_group.py new file mode 100644 index 0000000000000000000000000000000000000000..20306875bcefbabaffbb74a8cfb0547efa2a30a9 --- /dev/null +++ b/pool/shard002/Python/0025243_group.py @@ -0,0 +1,64 @@ +""" +Gitosis functions to find what groups a given user belongs to. +""" +import logging + +_GROUP_PREFIX = 'group ' + +def _getMembership(config, user, seen): + """ + Internal implementation of getMembership. + Generate groups ``user`` is member of, according to ``config``. + Groups already seen are tracked by ``seen``. + + :type config: RawConfigParser + :type user: str + :type seen: Set + """ + log = logging.getLogger('gitosis.group.getMembership') + + for section in config.sections(): + if not section.startswith(_GROUP_PREFIX): + continue + group = section[len(_GROUP_PREFIX):] + if group in seen: + continue + + members = config.get(section, 'members', "").split() + + # @all is the only group where membership needs to be + # bootstrapped like this, anything else gets started from the + # username itself + if (user in members + or '@all' in members): + log.debug('found %(user)r in %(group)r' % dict( + user=user, + group=group, + )) + seen.add(group) + yield group + + for member_of in _getMembership( + config, '@%s' % group, seen, + ): + yield member_of + for member_of in _getMembership( + config, '@all', seen, + ): + yield member_of + +def getMembership(config, user): + """ + Generate groups ``user`` is member of, according to ``config`` + + :type config: RawConfigParser + :type user: str + """ + + seen = set() + for member_of in _getMembership(config, user, seen): + yield member_of + + # everyone is always a member of group "all" + yield 'all' + diff --git a/pool/shard002/Python/0025247_getSynapseIDS.py b/pool/shard002/Python/0025247_getSynapseIDS.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c7a9cfcc5ee66ac27e4f66b921a6395ecdb737 --- /dev/null +++ b/pool/shard002/Python/0025247_getSynapseIDS.py @@ -0,0 +1,103 @@ +# Copyright 2014 NeuroData (http://neurodata.io) +# +# 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 argparse +import numpy as np +import urllib, urllib2 +import cStringIO +import sys +import h5py +import tempfile + +def main(): + + parser = argparse.ArgumentParser(description='Request a list of RAMON object ids that match specified type and status values') + parser.add_argument('--status', type=int, action="store", default=None ) + parser.add_argument('--type', type=int, action="store", default=None ) + parser.add_argument('--cutout', action="store", help='Cutout arguments of the form resolution/x1,x2/y1,y2/z1,z2.', default=None) + parser.add_argument('baseurl', action="store" ) + parser.add_argument('token', action="store" ) + + result = parser.parse_args() + + url = 'http://%s/emca/%s/list/' % ( result.baseurl, result.token ) + if result.type != None: + url += 'type/%s/' % ( result.type ) + if result.status != None: + url += 'status/%s/' % ( result.status ) + + print url + + if not result.cutout: + + # Get cube in question + try: + f = urllib2.urlopen ( url ) + except urllib2.URLError, e: + print "Failed URL", url + print "Error %s" % (e.read()) + sys.exit(0) + + # POST if we have a cutout + else: + + tmpfile = tempfile.NamedTemporaryFile ( ) + h5f = h5py.File ( tmpfile.name ) + + [ resstr, xstr, ystr, zstr ] = result.cutout.split('/') + ( xlowstr, xhighstr ) = xstr.split(',') + ( ylowstr, yhighstr ) = ystr.split(',') + ( zlowstr, zhighstr ) = zstr.split(',') + + resolution = int(resstr) + xlow = int(xlowstr) + xhigh = int(xhighstr) + ylow = int(ylowstr) + yhigh = int(yhighstr) + zlow = int(zlowstr) + zhigh = int(zhighstr) + + h5f.create_dataset ( "RESOLUTION", (1,), np.uint32, data=resolution ) + h5f.create_dataset ( "XYZOFFSET", (3,), np.uint32, data=[xlow,ylow,zlow] ) + h5f.create_dataset ( "CUTOUTSIZE", (3,), np.uint32, data=[xhigh-xlow,yhigh-ylow,zhigh-zlow] ) + + try: + h5f.flush() + tmpfile.seek(0) + req = urllib2.Request ( url, tmpfile.read()) + f = urllib2.urlopen(req) + except urllib2.URLError, e: + print "Failed URL", url + print "Error %s" % (e.read()) + sys.exit(-1) + + # Now we are processing the return. New tmpfile, new h5f + tmpfile = tempfile.NamedTemporaryFile ( ) + tmpfile.write ( f.read() ) + tmpfile.tell() + h5f = h5py.File ( tmpfile.name, driver='core', backing_store=False ) + + if h5f.get('ANNOIDS'): + if len(h5f['ANNOIDS']) != 0: + print "Found %s matching annotations." % ( len(h5f['ANNOIDS'][:])) + print "values = %s" % ( np.array(h5f['ANNOIDS'][:]) ) + else: + print "Found no annotations matching type and status" + +if __name__ == "__main__": + main() + + + + diff --git a/pool/shard002/Python/0025256_commands.py b/pool/shard002/Python/0025256_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb3fa17de82037aee6d97a243b4ff2d56a74a2e --- /dev/null +++ b/pool/shard002/Python/0025256_commands.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, unicode_literals +from gaebusiness.gaeutil import SaveCommand, ModelSearchCommand +from gaeforms.ndb.form import ModelForm +from gaegraph.business_base import UpdateNode +from linguagem_app.model import Linguagem + +class LinguagemPublicForm(ModelForm): + """ + Form used to show properties on app's home + """ + _model_class = Linguagem + _include = [Linguagem.descricao] + + +class LinguagemForm(ModelForm): + """ + Form used to save and update operations on app's admin page + """ + _model_class = Linguagem + _include = [Linguagem.descricao] + + +class LinguagemDetailForm(ModelForm): + """ + Form used to show entity details on app's admin page + """ + _model_class = Linguagem + _include = [Linguagem.creation, + Linguagem.descricao] + + +class LinguagemShortForm(ModelForm): + """ + Form used to show entity short version on app's admin page, mainly for tables + """ + _model_class = Linguagem + _include = [Linguagem.creation, + Linguagem.descricao] + + +class SaveLinguagemCommand(SaveCommand): + _model_form_class = LinguagemForm + + +class UpdateLinguagemCommand(UpdateNode): + _model_form_class = LinguagemForm + + +class ListLinguagemCommand(ModelSearchCommand): + def __init__(self): + super(ListLinguagemCommand, self).__init__(Linguagem.query_by_creation()) + diff --git a/pool/shard002/Python/0025257_hist.py b/pool/shard002/Python/0025257_hist.py new file mode 100644 index 0000000000000000000000000000000000000000..f489272849d9b7d6bcc6142a82be51fa1c4eae5f --- /dev/null +++ b/pool/shard002/Python/0025257_hist.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +# x.startswith("_") +f = open('/Users/yadvika/.bash_history') +l = f.readlines() +l.reverse() +short = [] +cmdline_included = 0 +for s in l: + if s.startswith("#"): + if cmdline_included == 1: + short.append(s.rstrip()) + continue + # marked not-include unless we really add it to short + cmdline_included = 0 + if s.rstrip() not in short: + cmdline_included = 1 + short.append(s.rstrip()) +short.reverse() +for s in short: + print s diff --git a/pool/shard002/Python/0025258_test_welcomedialog.py b/pool/shard002/Python/0025258_test_welcomedialog.py new file mode 100644 index 0000000000000000000000000000000000000000..dcb07105dc0b7c46141ca46b4f4020aa670f6dd5 --- /dev/null +++ b/pool/shard002/Python/0025258_test_welcomedialog.py @@ -0,0 +1,40 @@ +""" +Test for welcome screen. +""" + +from PyQt4.QtGui import QAction + +from ...resources import icon_loader + +from ..welcomedialog import WelcomeDialog, decorate_welcome_icon + +from ...gui.test import QAppTestCase + + +class TestDialog(QAppTestCase): + def test_dialog(self): + d = WelcomeDialog() + loader = icon_loader() + icon = loader.get("icons/default-widget.svg") + action1 = QAction(decorate_welcome_icon(icon, "light-green"), + "one", self.app) + action2 = QAction(decorate_welcome_icon(icon, "orange"), + "two", self.app) + d.addRow([action1, action2]) + + action3 = QAction(decorate_welcome_icon(icon, "light-green"), + "three", self.app) + d.addRow([action3]) + + self.assertTrue(d.buttonAt(1, 0).defaultAction() == action3) + + d.show() + action = [None] + + def p(a): + print str(a.text()) + action[0] = a + + d.triggered.connect(p) + self.app.exec_() + self.assertIs(action[0], d.triggeredAction()) diff --git a/pool/shard002/Python/0025265_tests.py b/pool/shard002/Python/0025265_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..a21e4ef09a4ba17d8289b1143e1015b4c3a500f4 --- /dev/null +++ b/pool/shard002/Python/0025265_tests.py @@ -0,0 +1,38 @@ +import unittest + +from connectionmon import ConnectionMonitor + +class ConnectionMonitorTest(unittest.TestCase): + """""" + + def test_get_tcp(self): + """Tests that procfs can get tcp connections""" + monitor = ConnectionMonitor() + self.assertIn('rem_address',monitor._get_tcp()[0]) + + def test_get_nonblank_connections(self): + """Tests that NULL addresses in procfs are removed.""" + monitor = ConnectionMonitor() + ip = [] + for item in monitor._get_nonblank_connections(monitor._get_tcp()): + ip.append(item['rem_address'][0]) + self.assertNotIn('0.0.0.0',ip) + + def test_clean_connections(self): + """Tests the ability to remove useless data.""" + monitor = ConnectionMonitor() + conn = monitor._get_nonblank_connections(monitor._get_tcp()) + conn = monitor._clean_connections(conn, 'tcp') + self.assertEqual(len(conn[0]),9) + self.assertEqual('local_address' in conn[0], True) + self.assertEqual('local_port' in conn[0], True) + self.assertEqual('rem_address' in conn[0], True) + self.assertEqual('rem_port' in conn[0], True) + self.assertEqual('domain' in conn[0], True) + self.assertEqual('name' in conn[0], True) + self.assertEqual('transport_layer' in conn[0], True) + self.assertEqual('time_established' in conn[0], True) + self.assertEqual('time_connected' in conn[0], True) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/pool/shard002/Python/0025275_inputhook.py b/pool/shard002/Python/0025275_inputhook.py new file mode 100644 index 0000000000000000000000000000000000000000..a6757ee295a79b107a0db6df9c3c584bef046760 --- /dev/null +++ b/pool/shard002/Python/0025275_inputhook.py @@ -0,0 +1,170 @@ +""" +Similar to `PyOS_InputHook` of the Python API, we can plug in an input hook in +the asyncio event loop. + +The way this works is by using a custom 'selector' that runs the other event +loop until the real selector is ready. + +It's the responsibility of this event hook to return when there is input ready. +There are two ways to detect when input is ready: + +The inputhook itself is a callable that receives an `InputHookContext`. This +callable should run the other event loop, and return when the main loop has +stuff to do. There are two ways to detect when to return: + +- Call the `input_is_ready` method periodically. Quit when this returns `True`. + +- Add the `fileno` as a watch to the external eventloop. Quit when file descriptor + becomes readable. (But don't read from it.) + + Note that this is not the same as checking for `sys.stdin.fileno()`. The + eventloop of prompt-toolkit allows thread-based executors, for example for + asynchronous autocompletion. When the completion for instance is ready, we + also want prompt-toolkit to gain control again in order to display that. +""" +import asyncio +import os +import select +import selectors +import threading +from asyncio import AbstractEventLoop, get_event_loop +from selectors import BaseSelector +from typing import Callable + +from prompt_toolkit.utils import is_windows + +__all__ = [ + "new_eventloop_with_inputhook", + "set_eventloop_with_inputhook", + "InputHookSelector", + "InputHookContext", +] + + +def new_eventloop_with_inputhook( + inputhook: Callable[["InputHookContext"], None] +) -> AbstractEventLoop: + """ + Create a new event loop with the given inputhook. + """ + selector = InputHookSelector(selectors.DefaultSelector(), inputhook) + loop = asyncio.SelectorEventLoop(selector) + return loop + + +def set_eventloop_with_inputhook( + inputhook: Callable[["InputHookContext"], None] +) -> AbstractEventLoop: + """ + Create a new event loop with the given inputhook, and activate it. + """ + loop = new_eventloop_with_inputhook(inputhook) + asyncio.set_event_loop(loop) + return loop + + +class InputHookSelector(BaseSelector): + """ + Usage: + + selector = selectors.SelectSelector() + loop = asyncio.SelectorEventLoop(InputHookSelector(selector, inputhook)) + asyncio.set_event_loop(loop) + """ + + def __init__( + self, selector: BaseSelector, inputhook: Callable[["InputHookContext"], None] + ) -> None: + self.selector = selector + self.inputhook = inputhook + self._r, self._w = os.pipe() + + def register(self, fileobj, events, data=None): + return self.selector.register(fileobj, events, data=data) + + def unregister(self, fileobj): + return self.selector.unregister(fileobj) + + def modify(self, fileobj, events, data=None): + return self.selector.modify(fileobj, events, data=None) + + def select(self, timeout=None): + # If there are tasks in the current event loop, + # don't run the input hook. + if len(get_event_loop()._ready) > 0: + return self.selector.select(timeout=timeout) + + ready = False + result = None + + # Run selector in other thread. + def run_selector() -> None: + nonlocal ready, result + result = self.selector.select(timeout=timeout) + os.write(self._w, b"x") + ready = True + + th = threading.Thread(target=run_selector) + th.start() + + def input_is_ready() -> bool: + return ready + + # Call inputhook. + # The inputhook function is supposed to return when our selector + # becomes ready. The inputhook can do that by registering the fd in its + # own loop, or by checking the `input_is_ready` function regularly. + self.inputhook(InputHookContext(self._r, input_is_ready)) + + # Flush the read end of the pipe. + try: + # Before calling 'os.read', call select.select. This is required + # when the gevent monkey patch has been applied. 'os.read' is never + # monkey patched and won't be cooperative, so that would block all + # other select() calls otherwise. + # See: http://www.gevent.org/gevent.os.html + + # Note: On Windows, this is apparently not an issue. + # However, if we would ever want to add a select call, it + # should use `windll.kernel32.WaitForMultipleObjects`, + # because `select.select` can't wait for a pipe on Windows. + if not is_windows(): + select.select([self._r], [], [], None) + + os.read(self._r, 1024) + except OSError: + # This happens when the window resizes and a SIGWINCH was received. + # We get 'Error: [Errno 4] Interrupted system call' + # Just ignore. + pass + + # Wait for the real selector to be done. + th.join() + return result + + def close(self) -> None: + """ + Clean up resources. + """ + if self._r: + os.close(self._r) + os.close(self._w) + + self._r = self._w = -1 + self.selector.close() + + def get_map(self): + return self.selector.get_map() + + +class InputHookContext: + """ + Given as a parameter to the inputhook. + """ + + def __init__(self, fileno: int, input_is_ready: Callable[[], bool]) -> None: + self._fileno = fileno + self.input_is_ready = input_is_ready + + def fileno(self) -> int: + return self._fileno diff --git a/pool/shard002/Python/0025279_vertex_attrib_integer_64bit.py b/pool/shard002/Python/0025279_vertex_attrib_integer_64bit.py new file mode 100644 index 0000000000000000000000000000000000000000..7bbe885b0d46449055c54498f5486572355ed398 --- /dev/null +++ b/pool/shard002/Python/0025279_vertex_attrib_integer_64bit.py @@ -0,0 +1,72 @@ +'''Autogenerated by xml_generate script, do not edit!''' +from OpenGL import platform as _p, arrays +# Code generation uses this +from OpenGL.raw.GL import _types as _cs +# End users want this... +from OpenGL.raw.GL._types import * +from OpenGL.raw.GL import _errors +from OpenGL.constant import Constant as _C + +import ctypes +_EXTENSION_NAME = 'GL_NV_vertex_attrib_integer_64bit' +def _f( function ): + return _p.createFunction( function,_p.PLATFORM.GL,'GL_NV_vertex_attrib_integer_64bit',error_checker=_errors._error_checker) +GL_INT64_NV=_C('GL_INT64_NV',0x140E) +GL_UNSIGNED_INT64_NV=_C('GL_UNSIGNED_INT64_NV',0x140F) +@_f +@_p.types(None,_cs.GLuint,_cs.GLenum,arrays.GLint64Array) +def glGetVertexAttribLi64vNV(index,pname,params):pass +@_f +@_p.types(None,_cs.GLuint,_cs.GLenum,arrays.GLuint64Array) +def glGetVertexAttribLui64vNV(index,pname,params):pass +@_f +@_p.types(None,_cs.GLuint,_cs.GLint64EXT) +def glVertexAttribL1i64NV(index,x):pass +@_f +@_p.types(None,_cs.GLuint,arrays.GLint64Array) +def glVertexAttribL1i64vNV(index,v):pass +@_f +@_p.types(None,_cs.GLuint,_cs.GLuint64EXT) +def glVertexAttribL1ui64NV(index,x):pass +@_f +@_p.types(None,_cs.GLuint,arrays.GLuint64Array) +def glVertexAttribL1ui64vNV(index,v):pass +@_f +@_p.types(None,_cs.GLuint,_cs.GLint64EXT,_cs.GLint64EXT) +def glVertexAttribL2i64NV(index,x,y):pass +@_f +@_p.types(None,_cs.GLuint,arrays.GLint64Array) +def glVertexAttribL2i64vNV(index,v):pass +@_f +@_p.types(None,_cs.GLuint,_cs.GLuint64EXT,_cs.GLuint64EXT) +def glVertexAttribL2ui64NV(index,x,y):pass +@_f +@_p.types(None,_cs.GLuint,arrays.GLuint64Array) +def glVertexAttribL2ui64vNV(index,v):pass +@_f +@_p.types(None,_cs.GLuint,_cs.GLint64EXT,_cs.GLint64EXT,_cs.GLint64EXT) +def glVertexAttribL3i64NV(index,x,y,z):pass +@_f +@_p.types(None,_cs.GLuint,arrays.GLint64Array) +def glVertexAttribL3i64vNV(index,v):pass +@_f +@_p.types(None,_cs.GLuint,_cs.GLuint64EXT,_cs.GLuint64EXT,_cs.GLuint64EXT) +def glVertexAttribL3ui64NV(index,x,y,z):pass +@_f +@_p.types(None,_cs.GLuint,arrays.GLuint64Array) +def glVertexAttribL3ui64vNV(index,v):pass +@_f +@_p.types(None,_cs.GLuint,_cs.GLint64EXT,_cs.GLint64EXT,_cs.GLint64EXT,_cs.GLint64EXT) +def glVertexAttribL4i64NV(index,x,y,z,w):pass +@_f +@_p.types(None,_cs.GLuint,arrays.GLint64Array) +def glVertexAttribL4i64vNV(index,v):pass +@_f +@_p.types(None,_cs.GLuint,_cs.GLuint64EXT,_cs.GLuint64EXT,_cs.GLuint64EXT,_cs.GLuint64EXT) +def glVertexAttribL4ui64NV(index,x,y,z,w):pass +@_f +@_p.types(None,_cs.GLuint,arrays.GLuint64Array) +def glVertexAttribL4ui64vNV(index,v):pass +@_f +@_p.types(None,_cs.GLuint,_cs.GLint,_cs.GLenum,_cs.GLsizei) +def glVertexAttribLFormatNV(index,size,type,stride):pass diff --git a/pool/shard002/Python/0025283_point.py b/pool/shard002/Python/0025283_point.py new file mode 100644 index 0000000000000000000000000000000000000000..c042b14ebc4441eb6cb152b77b7b44f39be97d63 --- /dev/null +++ b/pool/shard002/Python/0025283_point.py @@ -0,0 +1,69 @@ +import numpy as np + +import logging +logger = logging.getLogger(__name__) + +class Point(np.ndarray): + """ + n-dimensional point used for locations. + inherits +, -, * (as dot-product) + > p1 = Point([1, 2]) + > p2 = Point([4, 5]) + > p1 + p2 + Point([5, 7]) + See ``test()`` for more usage. + """ + + def __new__(cls, coordinates=None, **kwargs): + """ + :param cls: + :param input_array: Defaults to 2d origin + """ + if not coordinates: + coordinates = (0, 0) + logger.info("No coordinates given for point. Defaulting to 2d origin (0,0)") + obj = np.asarray(coordinates).view(cls) + return obj + + @property + def x(self): + return self[0] + + @property + def y(self): + return self[1] + + @property + def z(self): + """ + :return: 3rd dimension element. 0 if not defined + """ + try: + return self[2] + except IndexError: + return 0 + + def __eq__(self, other): + return np.array_equal(self, other) + + def __ne__(self, other): + return not np.array_equal(self, other) + + def __iter__(self): + for x in np.nditer(self): + yield x.item() + + def __repr__(self): + return str(self.serialized) + + @property + def serialized(self): + s = {'coordinates': tuple(pos.item() for pos in np.nditer(self))} + return s + + def dist(self, other): + """ + Both points must have the same dimensions + :return: Euclidean distance + """ + return np.linalg.norm(self - other) diff --git a/pool/shard002/Python/0025287_clausometer.py b/pool/shard002/Python/0025287_clausometer.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3c494e3f523398208b3122809c2e3f10d7deda --- /dev/null +++ b/pool/shard002/Python/0025287_clausometer.py @@ -0,0 +1,96 @@ +# +# Python Twitter monitor for Raspberry Pi +# +# See https://learn.sparkfun.com/tutorials/raspberry-pi-twitter-monitor +# +# For Twitter keys, see: +# https://developer.twitter.com/ +# https://apps.twitter.com/ +# +# Provided under MIT licence. (mostly meaning: use it for anything, don't sue me for anything) + +import time +import RPi.GPIO as GPIO +from twython import TwythonStreamer +from threading import Thread + +# Search terms +TERMS = '#xmas, #santa, #christmas, #navidad' # separate terms with commas. '#xmas, #holiday, #christmas' + +# Christmas spirit tracker: 0 to 100 +spirit = 50.0 + +GPIO.setmode(GPIO.BOARD) +# set GPIO18 to be a PWM output = pin 12 +GPIO.setup(12, GPIO.OUT) +servo = GPIO.PWM(12, 50) +servo.start(7.5) + +# Twitter application authentication +TWITTER_CONSUMER_KEY = 'xxxxxxx' +TWITTER_CONSUMER_SECRET = 'xxxxxxx' +TWITTER_ACCESS_TOKEN = 'xxxxxxx' +TWITTER_ACCESS_TOKEN_SECRET = 'xxxxxxx' + +# To stop twitter thread on app exit +stopping = False + +# Setup callbacks from Twython Streamer +class ClausometerStreamer(TwythonStreamer): + def on_success(self, data): + global spirit, stopping + if stopping: + #print('disconnecting from twitter...') + self.disconnect() + if 'text' in data: + #print (data['text'].encode('utf-8')) + #print ('spirit++') + spirit = spirit + 1.0 + if spirit > 100.0 : + spirit = 100.0 + +def start_twitter_monitoring(): + global stream + stream = ClausometerStreamer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET) + while True: + try: + stream.statuses.filter(track=TERMS) + except: + print("Twitter oops. carrying on.") + # this can happen when connection is lost + # the while loop will start it up again + +# 0 degrees = 2.5 +# 90 degrees = 7.5 +# 180 degrees = 12.5 +previousDutyCycle = 3.0 +def setServoPercent(percent): + global previousDutyCycle, servo + newDutyCycle = 3.0 + percent / 14.3 + #print('New duty cycle = ', newDutyCycle) + increment = (newDutyCycle - previousDutyCycle) / 100.0 + for step in range(0, 100, 1): + servo.ChangeDutyCycle(previousDutyCycle + increment*step) + time.sleep(0.02) + previousDutyCycle = newDutyCycle + +def spirit_fader(): # reduces spirit over time + global spirit + while True: + time.sleep(1) + if spirit > 0 : + spirit = spirit - 1.0 + +# Start the Clausometer +try: + Thread(target=start_twitter_monitoring).start() + Thread(target=spirit_fader).start() + while True: + print ('spirit = ', spirit) + setServoPercent(spirit) + +except KeyboardInterrupt: + stopping = True + print ('Exiting app') + #GPIO.cleanup() + diff --git a/pool/shard002/Python/0025290_Finding_a_Motif_in_DNA.py b/pool/shard002/Python/0025290_Finding_a_Motif_in_DNA.py new file mode 100644 index 0000000000000000000000000000000000000000..57f4d36c3518561c78e8076c4827020cb983a6f9 --- /dev/null +++ b/pool/shard002/Python/0025290_Finding_a_Motif_in_DNA.py @@ -0,0 +1,32 @@ +#! /usr/bin/env python + +import sys + +class Namespace: + pass + +def main(): + ns = Namespace() + ns.dna = sys.argv[1] + repeat = sys.argv[2] + positions = [] + cur_pos = 0 + + while(1): + try: + # index throws an exception when it does not find string :/ + p = ns.dna.index(repeat) + except ValueError: + break + + if p: + positions.append(p + cur_pos + 1) # 1 added for string numbering to start with 1 + cur_pos += p + 1 + ns.dna = ns.dna[p + 1:] + else: break + + print str(positions) + + +if __name__ == "__main__": + main() diff --git a/pool/shard002/Python/0025292_graphline.py b/pool/shard002/Python/0025292_graphline.py new file mode 100644 index 0000000000000000000000000000000000000000..4a7c5a1d95e2c76e460745444e281d267266783e --- /dev/null +++ b/pool/shard002/Python/0025292_graphline.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) +# +# (1) Kamaelia Contributors are listed in the AUTHORS file and at +# http://www.kamaelia.org/AUTHORS - please extend this file, +# not this notice. +# +# 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. + +dir = "/home/jlei/Kamaelia/files" + +for i in range(1,16): + imgs.append(dir + '/' + str(i) + '.jpg') + + +Graphline( + CHOOSER = Chooser(imgs), + IMAGE = Image(size=(800,600), position=(8,48)), + NEXT = Button(caption="Next", msg="NEXT", position=(72,8) ), + PREVIOUS = Button(caption="Previous", msg="PREV" ,position=(8,8) ), + FIRST = Button(caption="First", msg="FIRST",position=(256,8) ), + LAST = Button(caption="Last", msg="LAST" ,position=(320,8) ), + linkages = { + ("NEXT", "outbox") : ("CHOOSER", "inbox"), + ("PREVIOUS", "outbox") : ("CHOOSER", "inbox"), + ("FIRST", "outbox") : ("CHOOSER", "inbox"), + ("LAST", "outbox") : ("CHOOSER", "inbox"), + + ("CHOOSER", "outbox") : ("IMAGE", "inbox"), + } +).run() diff --git a/pool/shard002/Python/0025294_dumpFunctionDefine.py b/pool/shard002/Python/0025294_dumpFunctionDefine.py new file mode 100644 index 0000000000000000000000000000000000000000..43757b0eb2c0f9b418417b6c1c3a24dca20cf4e3 --- /dev/null +++ b/pool/shard002/Python/0025294_dumpFunctionDefine.py @@ -0,0 +1,57 @@ +__author__ = 'Sean Yu' +'''created @2015/6/16''' +import os, sys +pardir =os.path.dirname(os.path.realpath(os.getcwd())) +libpath = os.path.sep.join([pardir,'lib']) +if libpath not in sys.path: + sys.path.insert(0,libpath) +import inspect +from Case import Case +caseInit = inspect.getsource(Case.__init__) +print(caseInit) + + + +#dump description of function +import pydoc +des = pydoc.help(Case.__init__) +class testclass( object): + '''class description''' + def fun1(self,aaa, + bbb, + ccc='aaa'): + '''fun1 description + line2 + line3 + line4''' + print(aaa) + def fun2(self): + '''fun2 description''' + print('function2') + def doc(self, name): + return pydoc.help(name) + + +obj = testclass() +aaa =obj.doc(obj.fun1) + + + +members = dir(obj) +print('#'*16) +pydoc.Doc() +des =pydoc.describe(obj) +print(des) +print('#'*16) +for m in sorted(members): + if m.startswith('__'): + pass + else: + print(m+'\n\t') + fundef = inspect.getsource(eval('obj.%s'%m)) + fundefstr = fundef[:fundef.find(':')] + listoffun =fundef.split('\n') + print(fundefstr) + ret = eval('obj.%s.__doc__'%m) + if ret: + print('\t'+'\n\t'.join(ret.split('\n'))) diff --git a/pool/shard002/Python/0025303_test_del_windows_host.py b/pool/shard002/Python/0025303_test_del_windows_host.py new file mode 100644 index 0000000000000000000000000000000000000000..fbef3d3c0ac61db5abca044d66b65e5b16f1b1f3 --- /dev/null +++ b/pool/shard002/Python/0025303_test_del_windows_host.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python2.6 +# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- +# ex: set expandtab softtabstop=4 shiftwidth=4: +# +# Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor +# +# 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. +"""Module for testing the del windows host command.""" + +import unittest + +if __name__ == "__main__": + import utils + utils.import_depends() + +from brokertest import TestBrokerCommand + + +class TestDelWindowsHost(TestBrokerCommand): + + def testfailnonwindows(self): + command = "del windows host --hostname unittest00.one-nyp.ms.com" + err = self.badrequesttest(command.split(" ")) + self.matchoutput(err, + "Host unittest00.one-nyp.ms.com " + "has archetype aquilon, expected windows.", + command) + + def testdelunittest01(self): + self.dsdb_expect_delete(self.net.unknown[0].usable[10]) + command = "del windows host --hostname unittest01.one-nyp.ms.com" + (out, err) = self.successtest(command.split(" ")) + self.assertEmptyOut(out, command) + self.dsdb_verify() + + def testverifydelunittest01(self): + command = "show host --hostname unittest01.one-nyp.ms.com" + self.notfoundtest(command.split(" ")) + + +if __name__ == '__main__': + suite = unittest.TestLoader().loadTestsFromTestCase(TestDelWindowsHost) + unittest.TextTestRunner(verbosity=2).run(suite) diff --git a/pool/shard002/Python/0025305_para_handler.py b/pool/shard002/Python/0025305_para_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..47b516bed9f0aa9ce2297921a4c561ab90a8bc49 --- /dev/null +++ b/pool/shard002/Python/0025305_para_handler.py @@ -0,0 +1,74 @@ +# Copyright (C) 2021 OpenMotics BV +# +# 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 . +""" +Para packet handler +""" + +from esafe.rfid.idtronic_M890.para.para_packet import ParaPacketType, ParaPacket, CardType +from esafe.rfid.idtronic_M890.para.para_exception import ParaException + +import logging +logger = logging.getLogger(__name__) + +if False: # MyPy + from typing import Any, Dict, Callable + + +# @Injectable.named('para_packet_handler') +class ParaPacketHandler(object): + """ Packet handler for the ParaPackets, this can be extended in the future for multiple requests, and for keeping state of the reader""" + # At this point only one kind of packet is implemented, but can be extended in the future + + def __init__(self, new_scan_callback): + self.handlers = { + ParaPacketType.AutoListCard.value: self.handle_auto_list + } # type: Dict[ParaPacketType.value, Callable[[ParaPacket], Any]] + self.new_scan_callback = new_scan_callback + + def handle_packet(self, para_packet): + # type: (ParaPacket) -> Any + packet_type = para_packet.header.command_type + if packet_type in self.handlers: + handler = self.handlers[packet_type] + return handler(para_packet) + return None + + def handle_auto_list(self, para_packet): + # type: (ParaPacket) -> Any + _ = self + # Ignore the empty list packets + if not para_packet.data: + return + # General scan parameters + card_type = para_packet.data[0] + # scan_period = para_packet.data[1] + # scanned_antenna = para_packet.data[2] + # notice_type = para_packet.data[3] + # reserved_future_use = para_packet.data[4] + + if card_type in [CardType.ISO14443A.value, CardType.ISO14443B.value]: + # auto reporting format for ISO14443 cards + # ATQL = para_packet.data[5] + # ATQH = para_packet.data[6] + # SAK = para_packet.data[7] + uuid_length = para_packet.data[8] + logger.debug('Detected new ISO14443 card scan: Card type: {}, uuid_length: {}'.format(card_type, uuid_length)) + scanned_uuid = para_packet.data[-uuid_length:] + elif card_type == CardType.ISO15693.value: + scanned_uuid = para_packet.data[5:] + else: + raise ParaException('Cannot handle auto list packet: Cannot detect card type') + scanned_uuid_str = ''.join('{:02X}'.format(x) for x in scanned_uuid) + self.new_scan_callback(scanned_uuid_str) diff --git a/pool/shard002/Python/0025311_basepathstestcase.py b/pool/shard002/Python/0025311_basepathstestcase.py new file mode 100644 index 0000000000000000000000000000000000000000..f94b44e44e91206886d0e0fef3af581bd09157ee --- /dev/null +++ b/pool/shard002/Python/0025311_basepathstestcase.py @@ -0,0 +1,113 @@ +# -*- coding: UTF-8 -*- +""" +Basepaths test cases +@author: Aurélien Gâteau +@license: GPL v3 or later +""" +import os +import shutil +import tempfile + +from pathlib import Path + +from yokadi.core import basepaths +from yokadi.tests.yokaditestcase import YokadiTestCase + + +class BasePathsUnixTestCase(YokadiTestCase): + def setUp(self): + YokadiTestCase.setUp(self) + self._oldWindows = basepaths._WINDOWS + basepaths._WINDOWS = False + + def tearDown(self): + basepaths._WINDOWS = self._oldWindows + YokadiTestCase.tearDown(self) + + def testMigrateOldDb(self): + oldDb = Path(self.testHomeDir) / '.yokadi.db' + newDb = Path(basepaths.getDbPath(basepaths.getDataDir())) + + oldDb.touch() + + basepaths.migrateOldDb(str(newDb)) + self.assertFalse(oldDb.exists()) + self.assertTrue(newDb.exists()) + + def testMigrateNothingToDo(self): + newDb = Path(basepaths.getDbPath(basepaths.getDataDir())) + basepaths.migrateOldDb(str(newDb)) + basepaths.migrateOldHistory() + self.assertFalse(newDb.exists()) + + def testMigrateOldDbFails(self): + oldDb = Path(self.testHomeDir) / '.yokadi.db' + newDb = Path(basepaths.getDbPath(basepaths.getDataDir())) + + oldDb.touch() + newDb.parent.mkdir(parents=True) + newDb.touch() + + self.assertRaises(basepaths.MigrationException, basepaths.migrateOldDb, str(newDb)) + + def testMigrateOldHistory(self): + old = Path(self.testHomeDir) / '.yokadi_history' + new = Path(basepaths.getHistoryPath()) + + old.touch() + + basepaths.migrateOldHistory() + self.assertFalse(old.exists()) + self.assertTrue(new.exists()) + + def testMigrateOldHistoryOverwriteNew(self): + old = Path(self.testHomeDir) / '.yokadi_history' + new = Path(basepaths.getHistoryPath()) + + with old.open('w') as f: + f.write('old') + new.parent.mkdir(parents=True) + with new.open('w') as f: + f.write('new') + + basepaths.migrateOldHistory() + self.assertFalse(old.exists()) + with new.open() as f: + newData = f.read() + self.assertEqual(newData, 'old') + + def testHistoryEnvVar(self): + path = "foo" + os.environ["YOKADI_HISTORY"] = path + self.assertEqual(basepaths.getHistoryPath(), path) + + def testDbEnvVar(self): + path = "foo" + os.environ["YOKADI_DB"] = path + self.assertEqual(basepaths.getDbPath(basepaths.getDataDir()), path) + + +class BasePathsWindowsTestCase(YokadiTestCase): + def setUp(self): + YokadiTestCase.setUp(self) + self._oldWindows = basepaths._WINDOWS + basepaths._WINDOWS = True + self.testAppDataDir = tempfile.mkdtemp(prefix="yokadi-basepaths-testcase") + os.environ["APPDATA"] = self.testAppDataDir + + def tearDown(self): + shutil.rmtree(self.testAppDataDir) + basepaths._WINDOWS = self._oldWindows + YokadiTestCase.tearDown(self) + + def testGetCacheDir(self): + expected = os.path.join(self.testAppDataDir, "yokadi", "cache") + self.assertEqual(basepaths.getCacheDir(), expected) + + def testGetDataDir(self): + expected = os.path.join(self.testAppDataDir, "yokadi", "data") + self.assertEqual(basepaths.getDataDir(), expected) + + def testOldHistoryPath(self): + expected = os.path.join(self.testAppDataDir, ".yokadi_history") + self.assertEqual(basepaths._getOldHistoryPath(), expected) diff --git a/pool/shard002/Python/0025315_init__.py b/pool/shard002/Python/0025315_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc4074bdc02141d348f705ca08590076a10581a --- /dev/null +++ b/pool/shard002/Python/0025315_init__.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# Part of bubble. See LICENSE file for full copyright and licensing details. + + +"""store: for getting and putting files +currently only json +and the highly experimental ".bubble" format for testing and comparing purposes""" + +import os + +from ... import Bubble +from ..counter import Counter +from ..zipit import zipit +from ..inside_try import inside_try +from ..generators import make_gen, make_stamping_gen + + +def load_storage_type_class(ctx, storage_type): + ctx.gbc.say('loading module for storage type:' + + storage_type, verbosity=10) + if storage_type == '.json': + return load_storage_type_class_json(ctx) + if storage_type == '.jsonl': + return load_storage_type_class_jsonl(ctx) + +def load_storage_type_class_json(ctx): + from .storage_type_json import JsonKV as STOREM + ctx.gbc.say('storage module loaded', stuff=STOREM, verbosity=10) + return STOREM + + +def load_storage_type_class_jsonl(ctx): + from .storage_type_jsonl import JsonLinesKV as STOREM + ctx.gbc.say('storage module loaded', stuff=STOREM, verbosity=10) + return STOREM + +def get_file_name(ctx, path, step, stage, stype): + ctx.gbc.say('get_file_name:', stuff=(path, step, stage, stype)) + + storage_file = path + 'remember/' + step + '_' + stage + storage_file += '.' + stype + ctx.gbc.say('get_file_name:res:' + storage_file) + return storage_file + + +def get_file_info(ctx, storage_file_name): + file_name, file_extension = os.path.splitext(storage_file_name) + ret = {'file_name': file_name, + 'file_extension': file_extension} + + ctx.gbc.say('file_info:', stuff=ret) + return ret + + +@inside_try +def get_bubble(ctx, bubble_file_name): + # this is the proof of existence for a bubble content directory + # TODO: + # its not in the bubble format yet, when converted to bubble format, + # we can use something like get_file(...,home+"/.bubble") + + ctx.gbc.say('get_bubble:' + bubble_file_name, verbosity=10) + if bubble_file_name.endswith('.bubble'): + with open(bubble_file_name) as bubble_file: + content = bubble_file.read() + ctx.say('get_bubble:content:' + str(content), verbosity=200) + return content + + +def get_file(ctx, storage_file_name, first_only=False): + ctx.gbc.say('get_file:' + storage_file_name, verbosity=10) + file_info = get_file_info(ctx, storage_file_name) + storem = load_storage_type_class(ctx, file_info['file_extension']) + + data = None + + if not os.path.exists(storage_file_name): + if first_only: + ctx.gbc.say('first only: returning empty dict, no such file:' + + storage_file_name, verbosity=10) + return {} + else: + ctx.gbc.say('returning empty list, no such file:' + + storage_file_name, verbosity=10) + return {'lod_gen': make_gen(ctx), + 'total': 0, + 'status': 'no such file:' + storage_file_name} + + bkv = storem(storage_file_name) + bkv.set_parent(ctx.gbc) + data = bkv.load() + count = Counter() + count.set_parent(ctx.gbc) + + ctx.gbc.say('get file:data', stuff=data, verbosity=1000) + ctx.gbc.say('get file:data:type:' + str(type(data)), verbosity=100) + + if data: + ctx.gbc.say('get file:data', stuff=data, verbosity=2000) + else: + ctx.gbc.cry('get file:there is no data', verbosity=10) + + gen_types_23 = ["", # py2 + ""] # py3 + + if str(type(data)) in gen_types_23: + return {'lod_gen': data, + 'total': 'unknown from generator'} + if 'data' in data and str(type(data['data'])) in gen_types_23: + return {'lod_gen': data['data'], + 'total': 'unknown from generator'} + + if isinstance(data, dict) and 'data' in data and isinstance(data['data'], list): + if first_only: + if len(data['data']) >= 1: + return data['data'][0] + else: + return {} + return {'lod_gen': make_gen(ctx, data['data'], count), + 'total': count.get_total()} + elif isinstance(data, list): + # inspect.isgeneratorfunction(data): + return {'lod_gen': make_gen(ctx, data, count), + 'total': 'unknown from generator'} + else: + ctx.gbc.cry('data is not dict with a data list, or list', + stuff=data, verbosity=10) + ctx.gbc.say('make gen and return', verbosity=10) + return {'lod_gen': make_gen(ctx, data, count), + 'total': 'unknown from generator', + 'last_resort': True} + + +@inside_try +def put_file(ctx, storage_file_name, data=[], remove_first=False, archive=True, add_timestamp=True, full_data=True): + + # TODO: ensure no data ->no file + ret = {} + ret['total'] = 'unknown total' + count = Counter() + count.set_parent(ctx.gbc) + data = make_stamping_gen(ctx.gbc, data, full_data, count) + # generator calling should happen in STOREC + + ctx.gbc.say('count', stuff=count, verbosity=100) + ctx.say('count.get_total:', stuff=count.get_total(), verbosity=10) + + file_info = get_file_info(ctx, storage_file_name) + + storec = load_storage_type_class(ctx, file_info['file_extension']) + + if not storec: + ctx.gbc.cry("cannot load storage module for file", verbosity=10) + return False + else: + ctx.gbc.say("will use loaded storage module for file", + stuff=storec, verbosity=10) + + ctx.gbc.say('put_file:' + storage_file_name, verbosity=10) + ctx.gbc.say('put_file:.bubble', verbosity=999) + bkv = storec(storage_file_name, reset=remove_first) + bkv.set_parent(ctx.gbc) + ctx.gbc.say('bubble data type:' + str(type(data)), verbosity=1000) + ret['res'] = bkv.dump(data, full_data) + ctx.gbc.say('counter', stuff=count.get_total(), verbosity=1) + + bkv.close() + zipped = False + if archive: + zipped = zipit(ctx, storage_file_name) + ret['zipped'] = zipped + ret['total'] = count.get_total() + ctx.gbc.say('put_file:return', stuff=ret, verbosity=100) + return ret + + +class BubbleKV(Bubble): + + """store and retrieve a List of dictionaries in any file based type. + """ + + def __init__(self, + file_name='__bubble_kvdb_data_tmp.unknown_type', + name='BubbleKV', + reset=False): + Bubble.__init__(self, name=name) + + self.say(file_name, verbosity=999) + self._file_name = file_name + + self._count = 0 + self._kcount = 0 + self._vcount = 0 + self._kvcount = 0 + self._can_dump_generator = False + self._reset = reset + self.reset() + + def dump(self, lod=[], full_data=True): + self.say('dumping:' + self._file_name, verbosity=1) + ret = {} + + if self._can_dump_generator: + try: + ret = self._dump(lod) + return ret + except Exception as e: + ret['error'] = 'cannot dump data to file %s' % self._file_name + ret['exception'] = e + return ret + + ndata = [] + for item in lod: + try: + self._encode_for_try({'test_enc': item}) + ndata.append(item) + except Exception as encexpt: + self.cry('skipped: cannot encode item: ' + + str(encexpt), stuff=item) + data_to_dump = {'data': ndata} + + ret['notdumped'] = True + if not self._dump: + self.cry('dumping, there is no _dump method', verbosity=1) + + try: + ret = self._dump(data_to_dump) + return ret + except Exception as e: + ret['error'] = 'cannot dump data to file %s' % self._file_name + ret['exception'] = e + return ret + + def load(self): + self.say('loading:' + self._file_name, verbosity=1) + if os.path.exists(self._file_name): + if not self._load: + self.cry('loading, there is no _load method', verbosity=1) + res = self._load() + else: + res = [] + self.say( + 'loading:file does not exist, returning empty list', verbosity=1) + + self.say('loading:res type=' + str(type(res)), verbosity=1) + self.say('loading:res:', stuff=res, verbosity=10001) + + return res + + def close(self): + pass + + def reset(self): + if self._reset: + if os.path.exists(self._file_name): + self.say('reset, removing:' + self._file_name) + os.remove(self._file_name) + else: + self.say('reset, there is no file yet:' + self._file_name) + else: + self.say('no reset:' + self._file_name) diff --git a/pool/shard002/Python/0025319_synth.py b/pool/shard002/Python/0025319_synth.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a097213f3e15ee7e1561e4a2a5b2e17363d9be --- /dev/null +++ b/pool/shard002/Python/0025319_synth.py @@ -0,0 +1,74 @@ +# Copyright 2019 Google LLC +# +# 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 script is used to synthesize generated parts of this library.""" + +import synthtool as s +from synthtool import gcp + +gapic = gcp.GAPICGenerator() +common = gcp.CommonTemplates() +version = 'v1' + +# ---------------------------------------------------------------------------- +# Generate cloudbuild GAPIC layer +# ---------------------------------------------------------------------------- +library = gapic.py_library( + 'cloudbuild', + version, + config_path='/google/devtools/cloudbuild/artman_cloudbuild.yaml', + generator_args=["--dev_samples"], + include_protos=True +) + +s.move( + library, + excludes=[ + 'docs/index.rst', + 'nox*.py', + 'setup.py', + 'setup.cfg', + 'README.rst' + '**/*.proto' + 'google/cloud/devtools/__init__.py' # declare this as a namespace package + ], +) + +# Move protos to the right directory +s.move(library / "google/cloud/cloudbuild_v1/proto/*.proto", "google/cloud/devtools/cloudbuild_v1/proto") + +# Fix up imports +s.replace( + ["google/**/*.py", "tests/unit/**/*.py"], + r"from google.devtools.cloudbuild_v1.proto import ", + r"from google.cloud.devtools.cloudbuild_v1.proto import ", +) + + +# Rename package to `google-cloud-build` +s.replace( + ["**/*.rst", "*/**/*.py", "**/*.md"], + "google-cloud-cloudbuild", + "google-cloud-build" +) + +# ---------------------------------------------------------------------------- +# Add templated files +# ---------------------------------------------------------------------------- + +# coverage level is low because of missing coverage for __init__.py files +templated_files = common.py_library(unit_cov_level=65, cov_level=65) +s.move(templated_files) + +s.shell.run(["nox", "-s", "blacken"], hide_output=False) \ No newline at end of file diff --git a/pool/shard002/Python/0025326_NLP11.py b/pool/shard002/Python/0025326_NLP11.py new file mode 100644 index 0000000000000000000000000000000000000000..2db57c1ec9b1d1824bb3f78f3339f1df4c8f5af1 --- /dev/null +++ b/pool/shard002/Python/0025326_NLP11.py @@ -0,0 +1,13 @@ +#! /usr/bin/env python3 + +import re + +def expand(): + in_file = 'hightemp.txt' + with open(in_file, 'r') as f: + for line in f.readlines(): + print(re.sub('\t+', ' ', line.rstrip())) + f.close() + +if __name__ == '__main__': + expand() diff --git a/pool/shard002/Python/0025327_bot.py b/pool/shard002/Python/0025327_bot.py new file mode 100644 index 0000000000000000000000000000000000000000..a7fc3536755c0b6e0cbf3d63d631fe42784b08dd --- /dev/null +++ b/pool/shard002/Python/0025327_bot.py @@ -0,0 +1,99 @@ +import tweepy +from variable_stuff import * +import requests, bs4 +from PIL import ImageFont +from PIL import Image +from PIL import ImageDraw + +# +# abstract --> image; adapted from https://gist.github.com/destan/5540702 +# + +def text2png(text, fullpath, leftpadding = 6, upperpadding=6, rightpadding = 3, width = 500): + + font = ImageFont.truetype("font.ttf", 20) + text = text.replace('\r\n', '')#.replace('\n', ' ' + '\uFFFD' + ' ') + + lines = [] + line = "" + + for word in text.split(): + if font.getsize( line + ' ' + word )[0] <= (width - rightpadding - leftpadding): + line += ' ' + word + else: #start a new line + lines.append( line[1:] ) #slice the white space in the begining of the line + line = ' ' + word + + if len(line) != 0: + lines.append( line[1:] ) #add the last line + + line_height = font.getsize(text)[1] + img_height = line_height * len(lines) + 12 + + img = Image.new("RGB", (width, img_height), "#FFF") + draw = ImageDraw.Draw(img) + + for line in lines: + draw.text( (leftpadding, upperpadding), line, "#000", font=font) + upperpadding += line_height + + img.save(fullpath) + + +def main(): + + # twitter auth info + auth = tweepy.OAuthHandler(consumer_key, consumer_secret) + auth.set_access_token(access_token, access_token_secret) + api = tweepy.API(auth) + + # repec page with last papers; jel=d82 is mechanism design code + web_page = requests.get('https://econpapers.repec.org/scripts/search.pf?sort=date;jel=' + jel_codes + '&iframes=no') + web_page_text = bs4.BeautifulSoup(web_page.text, "html.parser") + + # get tweets to be able to check if paper was tweeted already + tweets = api.user_timeline(id=user_id, count=1) + + # get parts of web_page with each paper (they're in a list) + parsed_lists = web_page_text.find_all('li') + + # check each paper if it was tweeted already till reach the last one that was tweeted + papers_titles = [None] * 20 + papers_links = [None] * 20 + + for paper in range(0, 20): + # extract title from webpage (they're in bold) + papers_titles[paper] = parsed_lists[paper].find_next('a').getText() + # cut long titles to fit in a tweet + if len(papers_titles[paper]) > 116: + papers_titles[paper] = papers_titles[paper][0:115] + "…" + papers_links[paper] = "https://econpapers.repec.org" + parsed_lists[paper].find_next('a')['href'] + + if tweets: + # if length of paper's title is less than length of tweet, + # then could be the right tweet, since link adds to length + # can't compare directly because then could get out of range for tweet + # + only check last tweet + # -2 appears because twitter adds "…" symbol sometimes and we need to cut it off to make comparison ok + if len(papers_titles[paper]) < len(tweets[0].text): + if papers_titles[paper][0:-2] == tweets[0].text[0:int(len(papers_titles[paper])) - 2]: + # get the number of last paper tweeted + last_tweeted_paper = paper + break + else: + last_tweeted_paper = 19 + + for paper in reversed(range(0,last_tweeted_paper)): + + paper_page = requests.get(papers_links[paper]) + paper_page.encoding = paper_page.apparent_encoding + paper_page_text = bs4.BeautifulSoup(paper_page.text, "html.parser") + if paper_page_text.find(text="Abstract:"): + abstract = paper_page_text.find(text="Abstract:").next_element + text2png(abstract, 'abstract.png') + api.update_with_media("abstract.png", papers_titles[paper] + " " + papers_links[paper]) + else: + api.update_status(papers_titles[paper] + " " + papers_links[paper]) + +if __name__ == "__main__": + main() diff --git a/pool/shard002/Python/0025328_simple_model.py b/pool/shard002/Python/0025328_simple_model.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd7a81d4e6c02b9f99df5fb2bda80e7dc9b5e16 --- /dev/null +++ b/pool/shard002/Python/0025328_simple_model.py @@ -0,0 +1,52 @@ +__author__ = 'Federico Vaggi' + +n_vars = 1 + + +def simple_model(y, t, *args): + p = args[0] + +#*! Parameters Start + k_deg = p[0] + k_synt = p[1] +#*! Parameters End + + +#*! Variables Start + _y = y[0] +#*! Variables End + + +#*! Differential Equations Start + d_y = k_synt - k_deg * _y +#*! Differential Equations End + return d_y + + +if __name__ == '__main__': + from scipy.integrate import odeint + import numpy as np + import matplotlib.pyplot as plt + init_conditions = [0] + param_idx = {'k_deg': 0, 'k_synt': 1} + param_vector = np.array([0.001, 0.01]) + t_sim = np.linspace(0, 100, 100) + low_deg = odeint(simple_model, init_conditions, t_sim, args=(param_idx, None, param_vector)) + t_exp = np.array([0. , 11.11111111, 22.22222222, 33.33333333, + 44.44444444, 55.55555556, 66.66666667, 77.77777778, + 88.88888889, 100.]) + t_idx = np.searchsorted(t_sim, t_exp) + print t_sim[t_idx] + print low_deg[t_idx].flatten() + + print '_____________________________________________________________________________________' + + param_vector = np.array([0.01, 0.01]) + high_deg = odeint(simple_model, init_conditions, t_sim, args=(param_idx, None, param_vector)) + plt.plot(t_sim, high_deg, 'r-') + plt.plot(t_sim, low_deg, 'b-') + + t_idx = np.searchsorted(t_sim, np.arange(5, 95, 3.5)) + print t_sim[t_idx] + print high_deg[t_idx].flatten() + diff --git a/pool/shard002/Python/0025330_main.py b/pool/shard002/Python/0025330_main.py new file mode 100644 index 0000000000000000000000000000000000000000..59e7c07c7ee0e56686a7ec4eac4659b1ce8c83c9 --- /dev/null +++ b/pool/shard002/Python/0025330_main.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Copyright 2010-2012 Asidev s.r.l. + +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 logging +import os +import plac +import sys +import requests + +from . instance import InstanceInterface +from . task import TaskInterface +from . environment import EnvironmentInterface +from . theme import ThemeInterface +from . group import GroupInterface +from . user import UserInterface +from . redirect import RedirectInterface +from . archive import ArchiveInterface +from . alias import AliasInterface +from . client import AybuManagerClient +from . autocomplete import AybuManagerCliReadline + + +def string_to_level(level): + try: + level = level.upper() + return getattr(logging, level) + + except AttributeError: + sys.stderr.write('Cannot find logging level {}'.format(level)) + sys.stderr.flush() + return None + + +class AybuManagerCliInterface(object): + + interfaces = (InstanceInterface, TaskInterface, EnvironmentInterface, + ThemeInterface, GroupInterface, UserInterface, + RedirectInterface, ArchiveInterface, AliasInterface) + interface_instances = {} + commands = set(('exit', 'quit', 'help_commands', 'set_log_level', + 'connect', 'show_remote')) + + def create_commands_for_interface(self, intf_cls): + interface = intf_cls(self.api_client, self) + self.__class__.interface_instances[intf_cls.name] = interface + for command in interface.commands: + command_name = "{}_{}".format(intf_cls.name, command) + setattr(self, command_name, getattr(interface, command)) + self.__class__.commands.add(command_name) + + @plac.annotations( + level=('logging level to set', 'positional', None, string_to_level) + ) + def set_log_level(self, level): + if level is None: + return + try: + if level == self.loglevel: + return + self.log + + except AttributeError: + self.log = logging.getLogger('aybu') + self.log.addHandler(logging.StreamHandler()) + + self.loglevel = level + self.log.setLevel(self.loglevel) + if level == logging.DEBUG: + requests.defaults.defaults['verbose'] = sys.stderr + else: + requests.defaults.defaults['verbose'] = None + + @plac.annotations( + remote=('remote configuration section name', 'positional') + ) + def connect(self, remote): + """ Connect to a new remote """ + try: + api_client = AybuManagerClient.create_from_config( + self.configfile, + remote=remote, + debug=self.verbose) + + except Exception as e: + self.log.error('Cannot connect to %s: %s', remote, e) + + else: + self.api_client = api_client + self.log.info("Using remote %s: %s", remote, self.api_client) + for intf in self.__class__.interface_instances.values(): + intf.api = api_client + self.remote_name = remote + + @plac.annotations( + configfile=('Path to the config file', 'option', "F"), + remote=('Remote server to connect to', 'option', "R"), + verbose=('Be verbose', 'flag', 'V') + ) + def __init__(self, configfile, verbose, remote): + + self.__doc__ = "\nUse help to see subcommands" + self.remote_name = remote or "default" + self.configfile = configfile or '~/.aybu_manager_cli.conf' + self.configfile = os.path.expanduser(self.configfile) + llevel = logging.INFO if not verbose else logging.DEBUG + self.set_log_level(llevel) + self.verbose = verbose + + try: + self.api_client = AybuManagerClient.create_from_config( + self.configfile, + remote=self.remote_name, + debug=verbose) + self.log.info("Using remote %s: %s", self.remote_name, + self.api_client) + except: + self.log.exception('Error creating API client') + sys.exit() + + for intf in self.interfaces: + self.create_commands_for_interface(intf) + + def show_remote(self): + """ Show current remote """ + self.log.info("Connected to %s: %s", self.remote_name, self.api_client) + + def __enter__(self): + return self + + def __exit__(self, etype, exc, tb): + "Will be called automatically at the end of the intepreter loop" + if etype in (None, GeneratorExit): # success + if self._interact_: + self.log.info("exiting...") + + def exit(self): + raise plac.Interpreter.Exit + + def quit(self): + self.exit() + + def help_commands(self): + self.log.info(" ".join([c for c in self.commands if c not in ("help", + "help_commands", + "exit", + ".last_tb", + "quit")])) + + +def main(): + try: + histfile = os.path.expanduser('~/.{}.history'.format(__name__)) + completer = AybuManagerCliReadline(histfile=histfile, + factory=AybuManagerCliInterface) + plac.Interpreter.call(AybuManagerCliInterface, + stdin=completer, verbose=True, prompt='aybu> ') + except KeyboardInterrupt: + print "interrupted" diff --git a/pool/shard002/Python/0025331_American.py b/pool/shard002/Python/0025331_American.py new file mode 100644 index 0000000000000000000000000000000000000000..2158eddfbf1ad57ab705e20f37d6f360adee9460 --- /dev/null +++ b/pool/shard002/Python/0025331_American.py @@ -0,0 +1,50 @@ + +from math import * + +# Initialize parameters +S = 150 +r = 0.06 +sigma = 0.3 +T = 1 +K = 150 +N = 100 +option = 'Put' + +def american(S,r,sigma,T,K,N,option): + dt = T/N + u = exp(sigma * sqrt(dt)) + d = 1/u + p = (exp(r*dt)-d)/(u-d) + disc = exp(-r*dt) + + St = [0]*(N+1) + C = [0]*(N+1) + + St[0] = S*d**N + for j in range(1, N): + St[j] = St[j-1]*(u/d) + + for j in range(0, N): + if option == 'Put': + C[j] = max(0.0, K - St[j]) + elif option == 'Call': + C[j] = max(0.0, St[j] - K) + else: + break + + for i in range(N-1, 0): + for j in range(0, i): + C[j] = disc*(p*C[j+1]+(1-p)*C[j]) + St[j] = (St[j])/d + if option == 'Put': + C[j] = max(C[j], K - St[j]) + elif option == 'Call': + C[j] = max(C[j], St[j] - K) + next(j) + next(i) + if option =='Call': + return C[52] + elif option =='Put': + return C[0] + +print(american(S,r,sigma,T,K,N,option)) \ No newline at end of file diff --git a/pool/shard002/Python/0025335_admin.py b/pool/shard002/Python/0025335_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..17463d257c31ad1933fbce06a26006195e7fc7f3 --- /dev/null +++ b/pool/shard002/Python/0025335_admin.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +""" +Administration interface options for ``critica.apps.videos`` models. + +""" +from django.contrib import admin +from django.utils.translation import ugettext_lazy as _ +from critica.apps.custom_admin.sites import custom_site +from critica.apps.videos.models import Video +from critica.apps.issues.models import Issue +from critica.apps.videos.forms import VideoAdminModelForm + + +class VideoAdmin(admin.ModelAdmin): + """ + Administration interface for ``Video`` model. + + """ + fieldsets = ( + (_('Video'), {'fields': ('name', 'widget')}), + (_('Filling'), {'fields': ('issues', 'tags')}), + (_('Publication'), {'fields': ('is_reserved', 'is_ready_to_publish')}), + ) + list_display = ('name', 'ald_issues', 'creation_date', 'modification_date', 'is_reserved', 'is_ready_to_publish', 'ald_submitter') + list_filter = ('issues',) + filter_horizontal = ('issues',) + search_fields = ('name',) + ordering = ('-creation_date',) + date_hierarchy = 'creation_date' + exclude = ['author'] + form = VideoAdminModelForm + _object = None + + def __call__(self, request, url): + """ + Adds current request object and current URL to this class. + + """ + self.request = request + return super(VideoAdmin, self).__call__(request, url) + + def change_view(self, request, object_id): + """ + Custom change view. + + """ + self._request = request + self._object = None + try: + self._object = self.model._default_manager.get(pk=object_id) + except model.DoesNotExist: + self._object = None + self._action = "change" + return super(VideoAdmin, self).change_view(request, object_id) + + def formfield_for_dbfield(self, db_field, **kwargs): + """ + Hook for specifying the form Field instance for a given database Field + instance. If kwargs are given, they're passed to the form Field's constructor. + + """ + field = super(VideoAdmin, self).formfield_for_dbfield(db_field, **kwargs) + if db_field.name == 'issues': + my_choices = [('', '---------')] + my_choices.extend(Issue.objects.order_by('-number').values_list('id','number')) + print my_choices + field.choices = my_choices + return field + + def save_model(self, request, obj, form, change): + """ + Given a model instance save it to the database. + Auto-save submitter. + + """ + if change == False: + obj.submitter = request.user + obj.save() + + def ald_submitter(self, obj): + """ + Formatted submitter for admin list_display option. + + """ + if obj.submitter.get_full_name(): + return obj.submitter.get_full_name() + else: + return obj.submitter + ald_submitter.short_description = _('submitter') + + def ald_issues(self, obj): + """ + Formatted issue list for admin list_display option." + + """ + issues = [issue.number for issue in obj.issues.all()] + return ', '.join(['%s' % issue for issue in issues]) + ald_issues.short_description = _('issues') + + +# Registers +# ------------------------------------------------------------------------------ +admin.site.register(Video, VideoAdmin) +custom_site.register(Video, VideoAdmin) + diff --git a/pool/shard002/Python/0025344_import_codex.py b/pool/shard002/Python/0025344_import_codex.py new file mode 100644 index 0000000000000000000000000000000000000000..f7e6f80fa8198bbc8d07f8515a07043d48f7ba98 --- /dev/null +++ b/pool/shard002/Python/0025344_import_codex.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- + +""" + Read from dbf's with codepage unsupported by modules dbf and codecs (like 895 cz Kamenicky) +""" + +import os +import re + +from books import isxn_to_ean, parse_pubyear + +from c_utils import REPEATJOINER, DEFAULT_SUBTITLE_JOINER, parse_year_from_text, normalize_authors, publ_fastinfo_and_hash +from dal_import import (place_to_place_id, update_or_insert_answer, update_or_insert_owned_book, update_or_insert_impressions, + counter_and_commit_if_100, finished, init_param, init_import, set_proc) + +from gluon.tools import Storage # or other class used to create empty object + +import dbf +from dbf_read_iffy import fix_init, fix_895 +fix_init(dbf) + +""" + import dbf + from dbf_read_iffy import fix_init, fix_895 + fix_init(dbf) + t = dbf.Table('autori.dbf') + t.open('read-only') + for record in t: + print fix_895(record.autor) + t.close() +""" + + +def imp_codex(db, library_id, src_folder): + """ + This is the main (entry) function. + """ + param = init_param() + set_proc(library_id, 0.1) + param['autori'] = read_xbase_as_dict(os.path.join(src_folder, 'autori.dbf'), key='id_autora') # AUTOR , need ","->", " + set_proc(library_id, 0.2) + param['k_autori'] = read_xbase_as_list_dict(os.path.join(src_folder, 'k_autori.dbf'), key='id_publ') # VZTAH, ID_AUTORA + set_proc(library_id, 0.4) + param['klsl'] = read_xbase_as_dict(os.path.join(src_folder, 'klsl.dbf'), key='id_klsl') # KLSL + set_proc(library_id, 0.5) + param['k_klsl'] = read_xbase_as_list_dict(os.path.join(src_folder, 'k_klsl.dbf'), key='id_publ') # ID_KLSL + set_proc(library_id, 0.9) + #param['dt'] = read_xbase_as_dict(os.path.join(src_folder, 'dt.dbf'), key='dt') # DT, DT_TXT + param['k_dt'] = read_xbase_as_list_dict(os.path.join(src_folder, 'k_dt.dbf'), key='id_publ') # POM_ZNAK, DT + set_proc(library_id, 1.2) + param['nakl'] = read_xbase_as_dict(os.path.join(src_folder, 'dodavat.dbf'), key='id_dodav') # ICO, NAZEV1, NAZEV2, NAZEV_ZKR, MISTO + set_proc(library_id, 1.5) + param['vytisky'] = read_xbase_as_list_dict(os.path.join(src_folder, 'vytisk.dbf'), key='id_publ', left=4) + # value: (tail, record) # PC, SIGNATURA, UC, ZARAZENO, VYRAZENO, CENA, ID_DODAV, UMISTENI, BARCODE, REVIZE, POZNAMKA + set_proc(library_id, 1.9) # < 2.0 ! + # TODO: VYPUJCKY? + + param['_library_id'] = library_id + read_xbase(os.path.join(src_folder, 'knihy.dbf'), import_publ, param, do_init=True) + finished(param) # commit tail records after nnn % 100 and set imp_proc=100.0 + + +def import_publ(record, param): + # KNIHY: ID_PUBL, RADA_PC, RADA_KNIHY, SIGNATURA, TEMATIKA, EAN, AUTORI, NAZEV, PODNAZEV, PUVOD, KNPOZNAMKA, + # JAZYK, VYDANI, IMPRESUM, ANOTACE, ISBN, KS_CELK, KS, KS_JE, POZNAMKA, STUDOVNA, ID_NAKL + def impression_iter(impressions): + for record in impressions: + impression = {} + impression['iid'] = record['pc'] + impression['sgn'] = record['signatura'] + impression['barcode'] = record['barcode'] + impression['place_id'] = place_to_place_id(param['places'], record['umisteni'].strip()) + yield impression + + id_publ = record['id_publ'] + nazev = fix_895(record['nazev'].strip()) + podnazev = fix_895(record['podnazev'].strip()) + pubplace = publisher = '' + nakl_id = record['id_nakl'] + nakladatel = param['nakl'].get(nakl_id) + if nakladatel: + pubplace = fix_895(nakladatel['misto'].strip()) + publisher = fix_895(nakladatel['nazev1'].strip() or nakladatel['nazev_zkr'].strip()) # prefer Nazev1 ? + pubyear = parse_year_from_text(record['impresum'], as_string=True) + + klsl = [] + for klic in param['k_klsl'].get(id_publ, ()): + klsl.append(fix_895(param['klsl'][klic['id_klsl']]['klsl'].strip())) + for klic in param['k_dt'].get(id_publ, ()): + klsl.append(fix_895(klic['dt'].strip())) # zatím neukládám k_dt.pom_znak a dt.dt_txt + surnamed = [] + full = [] + for osoba in param['k_autori'].get(id_publ, ()): + osoba_tuple = (fix_895(param['autori'][osoba['id_autora']]['autor']),) + surnamed1, full1 = normalize_authors(osoba_tuple, string_surnamed=True, string_full=True) + if osoba['vztah'] == 'A': # aut + surnamed.append(surnamed1) + full.append(full1) + else: # ostatní osoby + klsl.append(full1) # zatím neukládám k_autori.vztah + auth_surnamed = REPEATJOINER.join(surnamed) + auth_full = REPEATJOINER.join(full) + + origin = fix_895(record['puvod'].strip()) + knpoznamka = fix_895(record['knpoznamka'].strip()) + impresum = fix_895(record['impresum'].strip()) + anotace = fix_895(record['anotace'].strip()) + # TODO: promyslet, jak spojit a kam uložit <<<<<<<<<<<<<<<<<<<<<< + + answer_rec = Storage() # get an empty object + answer_rec.pubyears = parse_pubyear(impresum) + answer_rec.country = 'cze' # ??? + # zatim ignorujeme JAZYK (Manetin: jazyk originalu nebo ORI pro knihy v originale) + + isbn = '' + if record['isbn']: + isbn_candidates = re.findall(r'\b[0-9X\-]\b', record['isbn']) + isbn_candidates = [candidate for candidate in isbn_candidates if len(candidate.replace('-', '')) in (8, 10, 13)] + if isbn_candidates: + isbn = isbn_candidates[0] + ean = record['ean'].strip() + if not ean: + ean = isxn_to_ean(isbn) + + # always, because in case of other system import fastinfo can change together with same ean & md5publ + fastinfo, md5publ = publ_fastinfo_and_hash(nazev, auth_surnamed, auth_full, pubplace, publisher, pubyear, + subtitles=((DEFAULT_SUBTITLE_JOINER, podnazev),) if podnazev else None, origin=origin, keys=klsl) + + impressions = param['vytisky'].get(id_publ, ()) + added, answer_id = update_or_insert_answer(ean, md5publ, fastinfo, md5redirects=param['redirects'], marcrec=answer_rec) + owned_book_id = update_or_insert_owned_book(answer_id, fastinfo, len(impressions)) + # impression_gen je generátor podle impression/impressions + impression_gen = impression_iter(impressions) + update_or_insert_impressions(answer_id, owned_book_id, impression_gen) + + counter_and_commit_if_100(param, added) + + +#TODO: rest should be moved into modules/c_import with next xBase import (import dbf + fix_init(dbf) can be used in c_import too) +def read_xbase(filename, callback, *args, **kwargs): + """ + run the callback function for each row in the table (similar to xBase SCAN) + """ + flds = dbf.get_fields(filename) + t = dbf.Table(filename) + t.open('read-only') + if kwargs.get('do_init'): + del kwargs['do_init'] # to avoid error in the callback function + init_import(args[0], cnt_total=len(t)) # args[0] ~ param + for record in t: + # callback(record, *args, **kwargs) # this run extremely slow !!! + callback({fld: record[fld] for fld in flds}, *args, **kwargs) # with real python dict it run well + t.close() + + +def read_xbase_as_dict(filename, key='id'): + """ + get rows as dict where keys are primary keys, values are records (without primary key) + """ + def rec_to_dict(record, key, rows): + current_id = record[key] + rows[current_id] = record + + rows = {} + read_xbase(filename, rec_to_dict, key, rows) + return rows + + +def read_xbase_as_list_dict(filename, key, left=None): + """ + get rows as dict where keys are given keys (can be non-unique), values are list records (without given key) + """ + def rec_to_list_dict(record, key, rows, left): + current_id = record[key] + if left: + current_id = current_id[:left] + if current_id in rows: + rows[current_id].append(record) + else: + rows[current_id] = [record] + + rows = {} + read_xbase(filename, rec_to_list_dict, key, rows, left) + return rows +#TODO: end diff --git a/pool/shard002/Python/0025345_check.py b/pool/shard002/Python/0025345_check.py new file mode 100644 index 0000000000000000000000000000000000000000..70aa5af2249b9435fde3d10b0119d15749ffdc78 --- /dev/null +++ b/pool/shard002/Python/0025345_check.py @@ -0,0 +1,48 @@ +import logging +from optparse import Values +from typing import Any, List + +from pip._internal.cli.base_command import Command +from pip._internal.cli.status_codes import ERROR, SUCCESS +from pip._internal.operations.check import ( + check_package_set, + create_package_set_from_installed, +) +from pip._internal.utils.misc import write_output + +logger = logging.getLogger(__name__) + + +class CheckCommand(Command): + """Verify installed packages have compatible dependencies.""" + + usage = """ + %prog [options]""" + + def run(self, options, args): + # type: (Values, List[Any]) -> int + + package_set, parsing_probs = create_package_set_from_installed() + missing, conflicting = check_package_set(package_set) + + for project_name in missing: + version = package_set[project_name].version + for dependency in missing[project_name]: + write_output( + "%s %s requires %s, which is not installed.", + project_name, version, dependency[0], + ) + + for project_name in conflicting: + version = package_set[project_name].version + for dep_name, dep_version, req in conflicting[project_name]: + write_output( + "%s %s has requirement %s, but you have %s %s.", + project_name, version, req, dep_name, dep_version, + ) + + if missing or conflicting or parsing_probs: + return ERROR + else: + write_output("No broken requirements found.") + return SUCCESS diff --git a/pool/shard002/Python/0025356_flip.py b/pool/shard002/Python/0025356_flip.py new file mode 100644 index 0000000000000000000000000000000000000000..e0b708584ed00b2cc52f1f9b53763b2c6deaddd5 --- /dev/null +++ b/pool/shard002/Python/0025356_flip.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python +# Pyctools - a picture processing algorithm development kit. +# http://github.com/jim-easterbrook/pyctools +# Copyright (C) 2014-18 Pyctools contributors +# +# 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 +# . + +"""Turn a picture upside down or reflect it left to right. + +""" + +__all__ = ['Flip'] +__docformat__ = 'restructuredtext en' + +import PIL.Image + +from pyctools.core.base import Transformer +from pyctools.core.config import ConfigEnum + +class Flip(Transformer): + def initialise(self): + self.config['direction'] = ConfigEnum(choices=('vertical', 'horizontal')) + + def transform(self, in_frame, out_frame): + self.update_config() + direction = self.config['direction'] + if direction == 'vertical': + flip = PIL.Image.FLIP_TOP_BOTTOM + else: + flip = PIL.Image.FLIP_LEFT_RIGHT + in_data = in_frame.as_PIL() + out_frame.data = in_data.transpose(flip) + audit = out_frame.metadata.get('audit') + audit += 'data = Flip(data)\n' + audit += ' direction: %s\n' % direction + out_frame.metadata.set('audit', audit) + return True diff --git a/pool/shard002/Python/0025357_setup.py b/pool/shard002/Python/0025357_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e2df6c8e4137a507e23e1e3f0b35cfff147a0a0d --- /dev/null +++ b/pool/shard002/Python/0025357_setup.py @@ -0,0 +1,238 @@ +#! /usr/bin/env python3 + +import imp +import os +import sys +import subprocess + +import setuptools + +NAME = 'Orange' + +VERSION = '3.2' +ISRELEASED = False + +DESCRIPTION = 'Orange, a component-based data mining framework.' +README_FILE = os.path.join(os.path.dirname(__file__), 'README.md') +LONG_DESCRIPTION = open(README_FILE).read() +AUTHOR = 'Bioinformatics Laboratory, FRI UL' +AUTHOR_EMAIL = 'contact@orange.biolab.si' +URL = 'http://orange.biolab.si/' +DOWNLOAD_URL = 'https://bitbucket.org/biolab/orange/downloads' +LICENSE = 'GPLv3' + +KEYWORDS = ( + 'data mining', + 'machine learning', + 'artificial intelligence', +) + +CLASSIFIERS = ( + 'Development Status :: 4 - Beta', + 'Environment :: X11 Applications :: Qt', + 'Environment :: Console', + 'Environment :: Plugins', + 'Programming Language :: Python', + 'Framework :: Orange', + 'License :: OSI Approved :: ' + 'GNU General Public License v3 or later (GPLv3+)', + 'Operating System :: POSIX', + 'Operating System :: Microsoft :: Windows', + 'Topic :: Scientific/Engineering :: Artificial Intelligence', + 'Topic :: Scientific/Engineering :: Visualization', + 'Topic :: Software Development :: Libraries :: Python Modules', + 'Intended Audience :: Education', + 'Intended Audience :: Science/Research', + 'Intended Audience :: Developers', +) + + +INSTALL_REQUIRES = ( + 'setuptools', + 'numpy>=1.9.0', + 'scipy', + 'scikit-learn>=0.16', + 'bottlechest', + 'openpyxl>=2.1.2', +) + +if sys.version_info < (3, 4): + INSTALL_REQUIRES = INSTALL_REQUIRES + ("singledispatch",) + + +ENTRY_POINTS = { + "orange.canvas.help": ( + "html-index = Orange.widgets:WIDGET_HELP_PATH",) +} + + +# Return the git revision as a string +def git_version(): + """Return the git revision as a string. + + Copied from numpy setup.py + """ + def _minimal_ext_cmd(cmd): + # construct minimal environment + env = {} + for k in ['SYSTEMROOT', 'PATH']: + v = os.environ.get(k) + if v is not None: + env[k] = v + # LANGUAGE is used on win32 + env['LANGUAGE'] = 'C' + env['LANG'] = 'C' + env['LC_ALL'] = 'C' + out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0] + return out + + try: + out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) + GIT_REVISION = out.strip().decode('ascii') + except OSError: + GIT_REVISION = "Unknown" + return GIT_REVISION + + +def write_version_py(filename='Orange/version.py'): + # Copied from numpy setup.py + cnt = """ +# THIS FILE IS GENERATED FROM ORANGE SETUP.PY +short_version = '%(version)s' +version = '%(version)s' +full_version = '%(full_version)s' +git_revision = '%(git_revision)s' +release = %(isrelease)s + +if not release: + version = full_version + short_version += ".dev" +""" + FULLVERSION = VERSION + if os.path.exists('.git'): + GIT_REVISION = git_version() + elif os.path.exists('Orange/version.py'): + # must be a source distribution, use existing version file + version = imp.load_source("Orange.version", "Orange/version.py") + GIT_REVISION = version.git_revision + else: + GIT_REVISION = "Unknown" + + if not ISRELEASED: + FULLVERSION += '.dev0+' + GIT_REVISION[:7] + + a = open(filename, 'w') + try: + a.write(cnt % {'version': VERSION, + 'full_version': FULLVERSION, + 'git_revision': GIT_REVISION, + 'isrelease': str(ISRELEASED)}) + finally: + a.close() + +from numpy.distutils.core import setup + +def configuration(parent_package='', top_path=None): + if os.path.exists('MANIFEST'): + os.remove('MANIFEST') + + from numpy.distutils.misc_util import Configuration + config = Configuration(None, parent_package, top_path) + + # Avoid non-useful msg: + # "Ignoring attempt to set 'name' (from ... " + config.set_options(ignore_setup_xxx_py=True, + assume_default_configuration=True, + delegate_options_to_subpackages=True, + quiet=True) + + config.add_subpackage('Orange') + + config.get_version('Orange/version.py') # sets config.version + + return config + + +PACKAGES = [ + "Orange", + "Orange.canvas", + "Orange.canvas.application", + "Orange.canvas.application.tutorials", + "Orange.canvas.canvas", + "Orange.canvas.canvas.items", + "Orange.canvas.document", + "Orange.canvas.gui", + "Orange.canvas.help", + "Orange.canvas.preview", + "Orange.canvas.registry", + "Orange.canvas.scheme", + "Orange.canvas.styles", + "Orange.canvas.utils", + "Orange.classification", + "Orange.clustering", + "Orange.data", + "Orange.data.sql", + "Orange.distance", + "Orange.evaluation", + "Orange.misc", + "Orange.preprocess", + "Orange.projection", + "Orange.regression", + "Orange.statistics", + "Orange.testing", + "Orange.widgets", + "Orange.widgets.data", + "Orange.widgets.visualize", + "Orange.widgets.classify", + "Orange.widgets.regression", + "Orange.widgets.evaluate", + "Orange.widgets.unsupervised", + "Orange.widgets.utils", + "Orange.widgets.utils.plot", + "Orange.widgets.utils.plot.primitives" +] + +PACKAGE_DATA = { + "Orange": ["datasets/*.{}".format(ext) + for ext in ["tab", "csv", "basket", "info"]], + "Orange.canvas": ["icons/*.png", "icons/*.svg"], + "Orange.canvas.styles": ["*.qss", "orange/*.svg"], + "Orange.canvas.application.tutorials": ["*.ows"], + "Orange.widgets": ["icons/*.png", "icons/*.svg"], + "Orange.widgets.data": ["icons/*.svg", "icons/paintdata/*.png", "icons/paintdata/*.svg"], + "Orange.widgets.visualize": ["icons/*.svg"], + "Orange.widgets.classify": ["icons/*.svg"], + "Orange.widgets.regression": ["icons/*.svg"], + "Orange.widgets.evaluate": ["icons/*.svg"], + "Orange.widgets.unsupervised": ["icons/*.svg"], + "Orange.widgets.plot": ["*.fs", "*.gs", "*.vs"], + "Orange.widgets.plot.primitives": ["*.obj"], +} + + +def setup_package(): + write_version_py() + setup( + configuration=configuration, + name=NAME, + description=DESCRIPTION, + long_description=LONG_DESCRIPTION, + author=AUTHOR, + author_email=AUTHOR_EMAIL, + url=URL, + download_url=DOWNLOAD_URL, + license=LICENSE, + keywords=KEYWORDS, + classifiers=CLASSIFIERS, + packages=PACKAGES, + package_data=PACKAGE_DATA, + install_requires=INSTALL_REQUIRES, + entry_points=ENTRY_POINTS, + zip_safe=False, + include_package_data=True, + test_suite='Orange.tests.test_suite', + + ) + +if __name__ == '__main__': + setup_package() diff --git a/pool/shard002/Python/0025359_transfer.py b/pool/shard002/Python/0025359_transfer.py new file mode 100644 index 0000000000000000000000000000000000000000..d9fcb6355bdf40a30035f0016231d3c3a1ca9089 --- /dev/null +++ b/pool/shard002/Python/0025359_transfer.py @@ -0,0 +1,238 @@ +# coding=utf-8 +from flask import request, jsonify, g +from flask_sqlalchemy import SQLAlchemy +import random + +tasks = [] +done = [] + + +def register_front(app): + + db = SQLAlchemy(app) + # users = cur = g.Post.query.all() + + @app.route('/api/user/add/', methods=['GET', 'POST']) + def signup(): + username = request.values.get('username', '') + password = request.values.get('password', '') + email = request.values.get('email', '') + + # cur = g.User.query.filter_by(username='admin').filter_by(password='123') + ex = g.User.query.filter_by(del_status=False) + user = ex.filter_by(username=username).first() or ex.filter_by(email=email).first() + if user: + return jsonify({ 'code': -2 }) + + user = db.User(username=username, email=email, psw=password) + db.session.add(user) + db.session.commit() + + return jsonify({ 'code': 1 }) + # return jsonify({'code':[ dict(un=row.username, ps=row.password) for row in cur] }) + + @app.route('/api/user/query/', methods=['GET', 'POST']) + def signin(): + # cur = g.User.query.all() + username = request.values.get('username', '') + password = request.values.get('password', '') + user = g.User.query.filter_by(del_status=False, username=username).first() + if not user: + return jsonify({ 'code': -1 }) + + fw = [i.to_user.username for i in g.FollowUser.query.filter_by(del_status=False, from_user_id=user.id).all()] + fd = [i.from_user.username for i in g.FollowUser.query.filter_by(del_status=False, to_user_id=user.id).all()] + + res = { + 'code': 1, + 'username': user.username, + 'email': user.email, + 'login': False, + 'follow_user': fw, + 'followed_user': fd, + } + res_secret = { + 'login': True, + 'id': user.id, + } + if user and user.password == password: + res.update(res_secret) + + return jsonify(res) + + + # return jsonify({'code':[ dict(un=row.username, ps=row.password) for row in cur] }) + + @app.route('/api/user/follow/', methods=['GET', 'POST']) + def follow_user(): + from_user_name = request.values.get('from_user_name', '') + to_user_name = request.values.get('to_user_name', '') + follow_bool = request.values.get('follow_bool', '1') # 1 or 0 + + from_user = g.User.query.filter_by(username=from_user_name).first() + to_user = g.User.query.filter_by(username=to_user_name).first() + if not (from_user and to_user): + return jsonify({ 'code': -1 }) + + args = { + 'from_user_id': from_user.id, + 'to_user_id': to_user.id, + } + + follow = g.FollowUser.query.filter_by(**args).first() + want_to_follow = bool(int(follow_bool)) + if follow: + follow.del_status = not want_to_follow + elif want_to_follow: + follow = g.FollowUser(**args) + db.session.add(follow) + db.session.commit() + + return jsonify({ 'code': 1 }) + + + @app.route('/api/image/addinfo/', methods=['GET', 'POST']) + def image_info(): + kwargs = { + 'url': request.values.get('url', ''), + 'filename': request.values.get('filename', ''), + 'param': request.values.get('param', '') + } + user_id = request.values.get('user_id', '') + if user_id: + kwargs.update({ 'user_id': user_id }) + + item = g.Item.query.filter_by(name=filename).first() + if item: + return jsonify({'code': '-2'}) + + item = g.Item(**kwargs) + g.db.session.add(item) + g.db.session.commit() + + return jsonify({ 'code': 1 }) + + + @app.route('/api/tasks/add/', methods=['GET', 'POST']) + def add_image_task(): + """add task to a queue""" + task = { + 'url': request.values.get('url', ''), + 'type': request.values.get('type', 'model'), + 'model': request.values.get('model', 'mosaic'), + } + tasks.append(task) + return jsonify({ 'code': 1, 'task':task }) + + # @app.route('/defaultstyles/') + # def defaultstyles(): + # """获取系统所有风格信息""" + # styles = [] + # styles.append({ + # 'styleName':'123', + # 'styleId':123, + # 'styleImgUrl':'iii' + # }) + # return jsonify(styles) + # + # + # @app.route('/process/human-mask-picture/') + # def human_mask_picture(): + # """风格转化结果图处理-获取人像遮罩图""" + # originImgUrl = request.values.get('originImgUrl', '') + # + # return jsonify({ + # 'maskImgUrl':'iii' + # }) + # + # @app.route('/users//styletransfer', methods=['POST']) + # def users_styletransfer(userId): + # """ + # 风格转化—系统风格 + # 风格转化—自定义风格 + # """ + # styleId = request.values.get('styleId ', '') + # originImgUrl = request.values.get('originImgUrl', '') + # + # return jsonify({ + # 'processImgUrl':'iii' + # }) + # + # @app.route('/process/mask/', methods=['POST']) + # def process_mask(): + # """风格转化结果图处理-遮罩""" + # originImgUrl = request.values.get('originImgUrl', '') + # resultImgUrl = request.values.get('resultImgUrl', '') + # maskImgUrl = request.values.get('maskImgUrl', '') + # + # return jsonify({ + # 'processImgUrl': 'iii' + # }) + # + # @app.route('/process/colorpreserve/', methods=['POST']) + # def process_colorpreserve(): + # originImgUrl = request.values.get('originImgUrl', '') + # resultImgUrl = request.values.get('resultImgUrl', '') + # colorMaskImgUrl = request.values.get('colorMaskImgUrl', '') + # + # return jsonify({ + # 'processImgUrl': 'iii' + # }) + + + +def register_calculate(app): + + @app.route('/tasks/add/model/') + def add_model(): + task = { + 'url':'https://oi3qt7c8d.qnssl.com/res.jpg', + 'type':'model', + 'model':'mosaic', + } + tasks.append(task) + return jsonify(task) + + @app.route('/tasks/add/') + def add_task(): + ID = random.randint(10001, 99999) + tasks.append({'id':ID}) + return jsonify({ + 'code':1, + 'id':ID + }) + + @app.route('/tasks/query/') + def task_query(): + return jsonify({ + 'tasks':tasks, + 'done':done, + }) + + @app.route('/tasks/pop/') + def task_pop(): + if tasks: + return jsonify(tasks.pop(0)) + return jsonify('Empty') + + + @app.route('/tasks/callback/', methods=['POST']) + def task_cb(): + """callback from qiniu""" + qiniu_setting = { + 'access_key' : 'iQ3ndG5uRpwdeln_gcrH3iiZ7E3KbMdJVkdYV9Im', + 'secret_key' : 'AGsp6K7fu1NsH2DnsPi7hW3qa3JXb4dtfeGvkm-A', + 'bucket_name' : 'image', + 'bucket_domain' : 'https://oi3qt7c8d.qnssl.com/', + 'callbakUrl' : 'http://139.129.24.151/tasks/callback/', + 'callbackBody' : 'filename:$(fname)' + } + filename = request.values.get('filename', '') + imageInfo = request.values.get('imageInfo', '') + url = qiniu_setting['bucket_domain'] + filename + print(filename, url, imageInfo) + done.append({ + 'url':url, + }) + + return url diff --git a/pool/shard002/Python/0025361_load_as_driver.py b/pool/shard002/Python/0025361_load_as_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c47f5f61ddb79111143af715871d9ac2ddfa1c --- /dev/null +++ b/pool/shard002/Python/0025361_load_as_driver.py @@ -0,0 +1,37 @@ +from __future__ import print_function + +import argparse + +from stevedore import driver + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument( + 'format', + nargs='?', + default='simple', + help='the output format', + ) + parser.add_argument( + '--width', + default=60, + type=int, + help='maximum output width for text', + ) + parsed_args = parser.parse_args() + + data = { + 'a': 'A', + 'b': 'B', + 'long': 'word ' * 80, + } + + mgr = driver.DriverManager( + namespace='stevedore.example.formatter', + name=parsed_args.format, + invoke_on_load=True, + invoke_args=(parsed_args.width,), + ) + for chunk in mgr.driver.format(data): + print(chunk, end='') diff --git a/pool/shard002/Python/0025362_ptest.py b/pool/shard002/Python/0025362_ptest.py new file mode 100644 index 0000000000000000000000000000000000000000..66f906130c4951a14a29e2350b5cec655c359bde --- /dev/null +++ b/pool/shard002/Python/0025362_ptest.py @@ -0,0 +1,70 @@ +from django.core.management.base import BaseCommand +import pytest +import optparse + +from django.conf import settings + +class Command(BaseCommand): + option_list = BaseCommand.option_list + ( + optparse.make_option('-s', + action='store_false', + dest='capture', + default=True, + help='Capture output'), + optparse.make_option('-k', + dest='keyword', + default='', + help='Limit by keyword'), + optparse.make_option('-p', + action='store_false', + dest='paste', + default=True, + help='Paste result to pastebin'), + optparse.make_option('-f', + action='store_true', + dest='functional', + default=False, + help='Include functional tests'), + optparse.make_option('-c', + dest='coverage', + default="", + help='Perform coverage analysis, restrict to modules'), + ) + + def handle(self, *a, **b): + ## http://pytest.org/latest/usage.html + ## --tb=native is also usable + coverage = False + opts = ["--tb=short"] + + keyword_specified = False + + settings.DATABASES = dict(default=settings.TEST_DB) + if not b.get('capture'): + opts.append("-s") + if b.get('keyword') and b['keyword']: + opts.append("-k") + opts.append(b['keyword']) + keyword_specified = True + + if not b.get('paste'): + opts.append("--pastebin=all") + if not b.get('functional') and not keyword_specified: + opts.append("-k") + opts.append("not functional_") + + if b.get('coverage'): + coverage = True + coverage_modules = b.get('coverage', '').split(",") + + if coverage: + import coverage + conf = getattr(settings, 'COVERAGE_CONF', '') + cov = coverage.coverage(source=coverage_modules, config_file=conf) + cov.start() + pytest.main(opts + list(a)) + if coverage: + cov.stop() + cov.report() + + diff --git a/pool/shard002/Python/0025370_orderedset.py b/pool/shard002/Python/0025370_orderedset.py new file mode 100644 index 0000000000000000000000000000000000000000..bf1c369c5395fe6ce0e52842c7c4a3a599918a06 --- /dev/null +++ b/pool/shard002/Python/0025370_orderedset.py @@ -0,0 +1,92 @@ +# ================================================================================================== +# Copyright 2011 Twitter, Inc. +# -------------------------------------------------------------------------------------------------- +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this work except in compliance with the License. +# You may obtain a copy of the License in the LICENSE file, or 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. +# ================================================================================================== +# OrderedSet recipe referenced in the Python standard library docs (bottom): +# http://docs.python.org/library/collections.html +# +# Copied from recipe code found here: http://code.activestate.com/recipes/576694/ with small +# modifications +# + +import collections + + +class OrderedSet(collections.MutableSet): + KEY, PREV, NEXT = range(3) + + def __init__(self, iterable=None): + self.end = end = [] + end += [None, end, end] # sentinel node for doubly linked list + self.map = {} # key --> [key, prev, next] + if iterable is not None: + self |= iterable + + def __len__(self): + return len(self.map) + + def __contains__(self, key): + return key in self.map + + def add(self, key): + if key not in self.map: + end = self.end + curr = end[self.PREV] + curr[self.NEXT] = end[self.PREV] = self.map[key] = [key, curr, end] + + def update(self, iterable): + for key in iterable: + self.add(key) + + def discard(self, key): + if key in self.map: + key, prev, next = self.map.pop(key) + prev[self.NEXT] = next + next[self.PREV] = prev + + def __iter__(self): + end = self.end + curr = end[self.NEXT] + while curr is not end: + yield curr[self.KEY] + curr = curr[self.NEXT] + + def __reversed__(self): + end = self.end + curr = end[self.PREV] + while curr is not end: + yield curr[self.KEY] + curr = curr[self.PREV] + + def pop(self, last=True): + if not self: + raise KeyError('set is empty') + key = next(reversed(self)) if last else next(iter(self)) + self.discard(key) + return key + + def __repr__(self): + if not self: + return '%s()' % (self.__class__.__name__,) + return '%s(%r)' % (self.__class__.__name__, list(self)) + + def __eq__(self, other): + if other is None: + return False + if isinstance(other, OrderedSet): + return len(self) == len(other) and list(self) == list(other) + return set(self) == set(other) + + def __del__(self): + self.clear() # remove circular references diff --git a/pool/shard002/Python/0025372_custom_freeze_graph.py b/pool/shard002/Python/0025372_custom_freeze_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..a5e69885a005e77879cd03e46568b4d39d821219 --- /dev/null +++ b/pool/shard002/Python/0025372_custom_freeze_graph.py @@ -0,0 +1,69 @@ +import os +import argparse + +import tensorflow.compat.v1 as tf + +# from: https://blog.metaflow.fr/tensorflow-how-to-freeze-a-model-and-serve-it-with-a-python-api-d4f3596b3adc + +# The original freeze_graph function +# from tensorflow.python.tools.freeze_graph import freeze_graph + +dir = os.path.dirname(os.path.realpath(__file__)) + + +def freeze_graph(model_dir, output_node_names): + """Extract the sub graph defined by the output nodes and convert + all its variables into constant + Args: + model_dir: the root folder containing the checkpoint state file + output_node_names: a string, containing all the output node's names, + comma separated + """ + if not tf.gfile.Exists(model_dir): + raise AssertionError( + "Export directory doesn't exists. Please specify an export " + "directory: %s" % model_dir) + + if not output_node_names: + print("You need to supply the name of a node to --output_node_names.") + return -1 + + # We retrieve our checkpoint fullpath + checkpoint = tf.train.get_checkpoint_state(model_dir) + print(model_dir) + input_checkpoint = checkpoint.model_checkpoint_path + + # We precise the file fullname of our freezed graph + absolute_model_dir = "/".join(input_checkpoint.split('/')[:-1]) + output_graph = absolute_model_dir + "/frozen_model.pb" + + # We clear devices to allow TensorFlow to control on which device it will load operations + clear_devices = True + + # We start a session using a temporary fresh Graph + with tf.Session(graph=tf.Graph()) as sess: + # We import the meta graph in the current default Graph + saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices) + + # We restore the weights + saver.restore(sess, input_checkpoint) + + # We use a built-in TF helper to export variables to constants + output_graph_def = tf.graph_util.convert_variables_to_constants( + sess, # The session is used to retrieve the weights + tf.get_default_graph().as_graph_def(), # The graph_def is used to retrieve the nodes + output_node_names.split(",") # The output node names are used to select the usefull nodes + ) + + # # Finally we serialize and dump the output graph to the filesystem + with tf.gfile.GFile(output_graph, "wb") as f: + f.write(output_graph_def.SerializeToString()) + print("%d ops in the final graph." % len(output_graph_def.node)) + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument("--model_dir", type=str, default="", help="Model folder to export") + parser.add_argument("--output_node_names", type=str, default="", help="The name of the output nodes, comma separated.") + args = parser.parse_args() + + freeze_graph(args.model_dir, args.output_node_names) diff --git a/pool/shard002/Python/0025379_routes.py b/pool/shard002/Python/0025379_routes.py new file mode 100644 index 0000000000000000000000000000000000000000..705fd1d9dd2348ce5b41cbf1b7b994b12c9a368b --- /dev/null +++ b/pool/shard002/Python/0025379_routes.py @@ -0,0 +1,101 @@ +import os +import json +import tempfile +import shutil + +from flask import request, redirect, url_for +from werkzeug.utils import secure_filename + +from findex_gui.web import app, themes, db +from findex_gui.bin.misc import version +from findex_gui.controllers.admin.status.status import AdminStatusController +from findex_gui.controllers.amqp.forms import FormAmqpAdd +from findex_gui.controllers.options.options import OptionsController +from findex_gui.controllers.user.decorators import admin_required +from findex_gui.controllers.news.news import NewsController + + +# +# general +# + +@app.route("/admin") +@admin_required +def admin_home(): + return themes.render("main/home", theme="_admin", version=version) + +@admin_required +def admin_appearance(): + return themes.render("main/appearance", theme="_admin") + +@app.route("/admin/metadata", methods=["POST", "GET"]) +@admin_required +def admin_metadata(): + if request.method == 'POST': + from findex_gui.bin.utils import log_msg + from findex_gui.controllers.meta.controller import MetaController + try: + MetaController.load_new_db() + except Exception as ex: + log_msg(str(ex), category="meta_import", level=3) + + return redirect(request.url) + + meta_movies_count = db.session.execute("SELECT COUNT(*) FROM meta_movies;").fetchone() + if meta_movies_count: + meta_movies_count = meta_movies_count[0] + + meta_version = OptionsController.get("meta") + if meta_version: + meta_version = meta_version.val + + return themes.render("main/metadata", theme="_admin", + meta_movies_count=meta_movies_count, + meta_version=meta_version) + +# +# News +# + +@app.route("/admin/news/overview") +@admin_required +def admin_news(): + posts = NewsController.get(limit=10) + return themes.render("main/news/overview", theme="_admin", posts=posts) + + +@app.route("/admin/news/add") +@admin_required +def admin_news_add(): + return themes.render("main/news/edit_add", theme="_admin") + +@app.route("/admin/news/edit/") +@admin_required +def admin_news_edit(uid): + if not uid.isdigit(): + raise Exception("uid must be an integer") + post = NewsController.get(uid=int(uid)) + return themes.render("main/news/edit_add", theme="_admin", post=post) + +@app.route("/admin/news/remove/") +@admin_required +def admin_news_remove(uid): + if not uid.isdigit(): + raise Exception("uid must be an integer") + NewsController.remove(uid=int(uid)) + return redirect(url_for("admin_news")) + +# +# AMQP +# + +@app.route("/admin/amqp/overview") +@admin_required +def admin_amqp_list(): + return themes.render("main/amqp", theme="_admin") + +@app.route("/admin/amqp/add") +@admin_required +def admin_amqp_add(): + amqp_add = FormAmqpAdd(request.form) + return themes.render("main/amqp_add", theme="_admin", form_add=amqp_add) diff --git a/pool/shard002/Python/0025385_data_to_text_file.py b/pool/shard002/Python/0025385_data_to_text_file.py new file mode 100644 index 0000000000000000000000000000000000000000..cec5214c54e01c2066665ad0f7b74694b6549475 --- /dev/null +++ b/pool/shard002/Python/0025385_data_to_text_file.py @@ -0,0 +1,28 @@ +''' + +Write a list of numbers to a text file + +----------------------------------------------------------- +(c) 2013 Allegra Via and Kristian Rother + Licensed under the conditions of the Python License + + This code appears in section 3.3.6 of the book + "Managing Biological Data with Python". +----------------------------------------------------------- +''' + +data = [16.38, 139.90, 441.46, 29.03, 40.93, 202.07, 142.30, 346.00, 300.00] + +out = [] +for value in data: + out.append(str(value) + '\n') +open('results.txt', 'w').writelines(out) + + +# Test +outP = [] +num = 0 +for valueP in data: + outP.append(str(num) + ':' + str(valueP) + '\n') + num = num + 1 +open('resultsP.txt', 'w').writelines(outP) \ No newline at end of file diff --git a/pool/shard002/Python/0025387_stats.py b/pool/shard002/Python/0025387_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..ab194b3debc04cc55c536c2ba1a3d1fbbb0dc5f3 --- /dev/null +++ b/pool/shard002/Python/0025387_stats.py @@ -0,0 +1,85 @@ +# 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. + +from blog.models import Post +import datetime +from bs4 import BeautifulSoup +import urllib2 + +def getWordCount(): + posts = Post.objects.all() + + wordcount = 0 + + for i in posts: + + wordcount += len(i.content.split(' ')) + + wordcountInt = wordcount + + wordcountString = format(wordcount, ",d") + + return wordcountInt, wordcountString + +def getPostCount(): + posts = Post.objects.all() + + postcount = len(posts) + + return postcount + +def daysSince(): + last = Post.objects.all().order_by('-published')[0].published.replace(tzinfo=None) + now = datetime.datetime.now() + delta = now - last + return delta.days + 1 + +def suggestion(): + page = urllib2.urlopen('http://techmeme.com').read() + soup = BeautifulSoup(page) + + topItem = soup.find('strong').contents + + + firstLinkChar = str(topItem).find('href="') + 6 + + newlink = str(topItem)[firstLinkChar:] + + lastLinkChar = newlink.find('"') + + link = newlink[:lastLinkChar] + + title = topItem[0].contents[0] + + newtitle = "" + + for char in title: + try: + newtitle += str(char) + except UnicodeEncodeError: + pass + + return newtitle, link + + + + + + + + + diff --git a/pool/shard002/Python/0025391_urls.py b/pool/shard002/Python/0025391_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..374d9fe548a065b6eea1826da6fc3ffc20232b49 --- /dev/null +++ b/pool/shard002/Python/0025391_urls.py @@ -0,0 +1,88 @@ +import core +from core.urls import urls_base +from django.contrib import admin +from django.urls import include, path +from django.conf.urls.i18n import i18n_patterns +from django.contrib.sitemaps.views import sitemap +from .sitemaps import RootSitemap +from .api.urls import urlpatterns as api_urls +from .views import ( + Index, + FAQ, + Contacts, + Students, + CourseView, + PayView, + Agreement, + TestCallback, +) + + +courses_urls = ([ + path('', CourseView.as_view(), name="course"), + # path(r'^$', include('core.urls', namespace='core')), + # path(r'^articles/', include('articles.urls', namespace='articles')), +], 'courses') + +# Error handlers +# +# https://docs.djangoproject.com/en/dev/ref/urls/#django.conf.urls.handler400 +# +# def err404(request): +# if request.method == 'GET': +# return HttpResponseNotFound(render_to_string('404.html', locals())) +# else: +# return HttpResponseNotFound('404') + + +# def err500(request): +# if request.method == 'GET': +# return HttpResponseNotFound(render_to_string('500.html', locals())) +# else: +# return HttpResponseNotFound('500') + + +# handler404 = 'proj.urls.err404' +# handler500 = 'pashinin.urls.err500' +# handler404 = IndexView.as_view() + +sitemaps = { + 'static': RootSitemap, +} + +urlpatterns = [ + *core.urls.urlpatterns, + path('accounts/', include('allauth.urls')), + # path('accounts/vk/login/callback/', TestCallback.as_view(), name='cb'), + path( + 'sitemap.xml', + sitemap, + {'sitemaps': sitemaps}, + name='django.contrib.sitemaps.views.sitemap' + ), + path('articles/', include('articles.urls', namespace='articles')), + path('api/', include(api_urls, namespace='api')), + path('courses/', include(courses_urls, namespace='courses')), +] + +urlpatterns += i18n_patterns( + path('', Index.as_view(), name="index"), + # path(r'^$', Index.as_view(), name="lazysignup_convert"), + path('pay', PayView.as_view(), name='pay'), + path('contacts', Contacts.as_view(), name='contacts'), + path('students', Students.as_view(), name='students'), + path('faq', FAQ.as_view(), name="faq"), + path('agreement', Agreement.as_view(), name="agreement"), + # path('login', Login.as_view(), name='login'), + + # This really needs to be here, not just in 'core' urls.py. + # Because admin templates are getting reverse urls with "admin:..." + # So if you wrap admin inside some app - reverse will throw an error + # path('_/django/', admin.site.urls), + + prefix_default_language=False +) + +# urlpatterns += [ +# path(r'^cas/', include('mama_cas.urls')) +# ] diff --git a/pool/shard002/Python/0025397_sitemap.py b/pool/shard002/Python/0025397_sitemap.py new file mode 100644 index 0000000000000000000000000000000000000000..2871dea86b4d2047133af7fe49dd16792a94b19e --- /dev/null +++ b/pool/shard002/Python/0025397_sitemap.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (C) <2013> Gabriel Falc達o +# +# 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 __future__ import unicode_literals +from markment.events import after +from markment.fs import Node +from lxml import etree + + +@after.all +def save_sitemap(event, args, project, theme, generated): + if not args.SITEMAP_PREFIX: + return + + urlset = etree.Element("urlset") + destination = Node(args.OUTPUT) + + NAME = 'sitemap.xml' + + for item in filter(lambda x: x.endswith('html'), generated): + relative = destination.relative(item) + url = etree.SubElement(urlset, "url") + loc = etree.SubElement(url, "loc") + loc.text = "{0}/{1}".format( + args.SITEMAP_PREFIX.rstrip('/'), + relative, + ) + + with destination.open(NAME, 'w') as f: + f.write(etree.tostring(urlset, pretty_print=True).decode('utf-8')) diff --git a/pool/shard002/Python/0025398_test_parse_omim.py b/pool/shard002/Python/0025398_test_parse_omim.py new file mode 100644 index 0000000000000000000000000000000000000000..93e315ad50ae79c1b3698eab27de99a1678238ca --- /dev/null +++ b/pool/shard002/Python/0025398_test_parse_omim.py @@ -0,0 +1,109 @@ +from scout.parse.omim import ( + get_mim_phenotypes, + parse_genemap2, + parse_genemap2_phenotypes, + parse_mim2gene, + parse_mim_titles, + parse_omim_line, +) + + +def test_parse_omim_line(): + ## GIVEN a header and a line + header = ["a", "b", "c"] + line = "1\t2\t3" + ## WHEN parsing the omim line + res = parse_omim_line(line, header) + + ## THEN assert a dict was built by the header and the line + assert res["a"] == "1" + assert res["b"] == "2" + assert res["c"] == "3" + + +def test_parse_genemap2_phenotype_entry_single(): + # GIVEN a phenotype description with one entry + entry = "Ehlers-Danlos syndrome, progeroid type," " 2, 615349 (3), Autosomal recessive" + # WHEN parsing the entry + parsed_entries = parse_genemap2_phenotypes(entry) + parsed_entry = parsed_entries[0] + # THEN assert that the information was parsed correct + + assert parsed_entry["mim_number"] == 615349 + assert parsed_entry["inheritance"] == {"AR"} + assert parsed_entry["status"] == "established" + + +def test_parse_genemap(genemap_lines): + + for res in parse_genemap2(genemap_lines): + assert res["Chromosome"] == "chr1" + assert res["mim_number"] == 615291 + assert res["hgnc_symbol"] == "B3GALT6" + assert res["inheritance"] == set(["AR"]) + for phenotype in res["phenotypes"]: + assert phenotype["mim_number"] + assert phenotype["inheritance"] + + +def test_parse_genemap_file(genemap_handle): + # WHEN parsing a valid genemap handle + i = 0 + for i, res in enumerate(parse_genemap2(genemap_handle)): + assert "mim_number" in res + # THEN items are returned + assert i > 0 + + +def test_parse_mim2gene(mim2gene_lines): + ## GIVEN some lines from a mim2gene file + mim2gene_info = parse_mim2gene(mim2gene_lines) + + ## WHEN parsing the lines + first_entry = next(mim2gene_info) + + ## ASSERT that they are correctly parsed + + # First entry is a gene so it should have a hgnc symbol + assert first_entry["mim_number"] == 615291 + assert first_entry["entry_type"] == "gene" + assert first_entry["hgnc_symbol"] == "B3GALT6" + + +def test_parse_mim2gene_file(mim2gene_handle): + i = 0 + # Just check that the file exists and that some result is given + for i, res in enumerate(parse_mim2gene(mim2gene_handle)): + assert "mim_number" in res + assert i > 0 + + +def test_get_mim_phenotypes(genemap_lines): + ## GIVEN a small testdata set + + # This will return a dictionary with mim number as keys and + # phenotypes as values + + ## WHEN parsing the phenotypes + phenotypes = get_mim_phenotypes(genemap_lines=genemap_lines) + + ## THEN assert they where parsed in a correct way + + # There was only one line in genemap_lines that have two phenotypes + # so we expect that there should be two phenotypes + + assert len(phenotypes) == 2 + + term = phenotypes[615349] + + assert term["inheritance"] == set(["AR"]) + assert term["hgnc_symbols"] == set(["B3GALT6"]) + + +def test_get_mim_phenotypes_file(genemap_handle): + phenotypes = get_mim_phenotypes(genemap_lines=genemap_handle) + i = 0 + for i, mim_nr in enumerate(phenotypes): + assert phenotypes[mim_nr]["mim_number"] + + assert i > 0 diff --git a/pool/shard002/Python/0025400_sparql.py b/pool/shard002/Python/0025400_sparql.py new file mode 100644 index 0000000000000000000000000000000000000000..47c0210f5c4a04c8edc5747bcddb6cd14b98a606 --- /dev/null +++ b/pool/shard002/Python/0025400_sparql.py @@ -0,0 +1,103 @@ +""" +Utilities for SPARQL language +""" + +from __future__ import unicode_literals +from common.settings import ONLINE_ENABLED +from knowledge.namespaces import NAMESPACES_DICT, RDF, RDFS, FOAF, ONTOLOGY, DCTERMS +from rdflib.plugins.sparql import prepareQuery +from rdflib import Graph, Literal, URIRef +from SPARQLWrapper import SPARQLWrapper, JSON +from urllib import quote_plus +from urllib2 import HTTPError + +import cjson +import logging +#import traceback + + +logger = logging.getLogger(__name__) + + +def prepared_query(query_string): + """ + Returns prepared query with initialized standard namespaces bindings. + """ + return prepareQuery(query_string, initNs=NAMESPACES_DICT) + + +def retrieve_graph_from_dbpedia(term): + assert ONLINE_ENABLED + logger.info('online access - DBpedia: {term}'.format(term=unicode(term))) + term_utf = term.encode('utf-8') + term_url = quote_plus(term_utf, safe=str("/:#,()'")) + #print '---' + #print 'term_url', term_url + sparql = SPARQLWrapper("http://dbpedia.org/sparql") + #query = """ + # SELECT ?p ?o + # WHERE {{ <{term_url}> ?p ?o }} + #""".format(term_url=term_url) + query = """ + SELECT ?p ?o + WHERE {{ + <{term_url}> ?p ?o + FILTER( STRSTARTS(STR(?p), "{foaf}") + || STRSTARTS(STR(?p), "{rdf}") + || STRSTARTS(STR(?p), "{rdfs}") + || STRSTARTS(STR(?p), "{dcterms}") + || STRSTARTS(STR(?p), "{ontology}")) + FILTER (isURI(?o) || langMatches(lang(?o), "EN")) + }} + """.format(term_url=term_url, + foaf=unicode(FOAF), + rdf=unicode(RDF), + rdfs=unicode(RDFS), + dcterms=unicode(DCTERMS), + ontology=unicode(ONTOLOGY)) + + sparql.setQuery(query.encode('utf-8')) + sparql.setReturnFormat(JSON) + try: + results = sparql.query() + # workaround for "Invalid \escape" error which can be raised by + # convert() + body = results.response.read() + results = cjson.decode(body) + except HTTPError as exc: + # can occur if DBpedia is under maintenance (quite often) + logger.error('Getting graph for {term} failed; {message}; {excType}' + .format(term=term, message=exc.message, excType=unicode(type(exc)))) + return None + + # create graph and bind relevant namespaces + graph = Graph() + for prefix, namespace in NAMESPACES_DICT.items(): + graph.bind(prefix, namespace) + + LITERAL_MAX_LENGTH = 600 + for result in results["results"]["bindings"]: + try: + p = URIRef(result['p']['value']) + # filter wikiPageRevisionID, wikiPageExternalLike etc. + if p.startswith(ONTOLOGY['wiki']): + continue + if result['o']['type'] == 'uri': + o = URIRef(result['o']['value']) + else: + o = Literal(result['o']['value']) + # if object is too long (e.g. abstract, ignore it) + if len(o) > LITERAL_MAX_LENGTH: + continue + graph.add((term, p, o)) + #print type(p), p + #print type(o), o + #print '*' + except KeyError: + continue + + # check if the graph is not empty + if not graph: + logger.warning('Retrieved empty graph for ' + unicode(term)) + + return graph diff --git a/pool/shard002/Python/0025403_handshake.py b/pool/shard002/Python/0025403_handshake.py new file mode 100644 index 0000000000000000000000000000000000000000..322d5557a5a65bb7f3ddd9fcb4219d9aeab05c43 --- /dev/null +++ b/pool/shard002/Python/0025403_handshake.py @@ -0,0 +1,133 @@ +""" +The :mod:`websockets.handshake` module deals with the WebSocket opening +handshake according to `section 4 of RFC 6455`_. + +.. _section 4 of RFC 6455: http://tools.ietf.org/html/rfc6455#section-4 + +It provides functions to implement the handshake with any existing HTTP +library. You must pass to these functions: + +- A ``set_header`` function accepting a header name and a header value, +- A ``get_header`` function accepting a header name and returning the header + value. + +The inputs and outputs of ``get_header`` and ``set_header`` are :class:`str` +objects containing only ASCII characters. + +Some checks cannot be performed because they depend too much on the +context; instead, they're documented below. + +To accept a connection, a server must: + +- Read the request, check that the method is GET, and check the headers with + :func:`check_request`, +- Send a 101 response to the client with the headers created by + :func:`build_response` if the request is valid; otherwise, send an + appropriate HTTP error code. + +To open a connection, a client must: + +- Send a GET request to the server with the headers created by + :func:`build_request`, +- Read the response, check that the status code is 101, and check the headers + with :func:`check_response`. +""" + +__all__ = [ + 'build_request', 'check_request', + 'build_response', 'check_response', +] + +import base64 +import hashlib +import random + +from .exceptions import InvalidHandshake + + +GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + +def build_request(set_header): + """ + Build a handshake request to send to the server. + + Return the ``key`` which must be passed to :func:`check_response`. + """ + rand = bytes(random.getrandbits(8) for _ in range(16)) + key = base64.b64encode(rand).decode() + set_header('Upgrade', 'WebSocket') + set_header('Connection', 'Upgrade') + set_header('Sec-WebSocket-Key', key) + set_header('Sec-WebSocket-Version', '13') + return key + + +def check_request(get_header): + """ + Check a handshake request received from the client. + + If the handshake is valid, this function returns the ``key`` which must be + passed to :func:`build_response`. + + Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` + exception and the server must return an error like 400 Bad Request. + + This function doesn't verify that the request is an HTTP/1.1 or higher GET + request and doesn't perform Host and Origin checks. These controls are + usually performed earlier in the HTTP request handling code. They're the + responsibility of the caller. + """ + try: + assert get_header('Upgrade').lower() == 'websocket' + assert any( + token.strip() == 'upgrade' + for token in get_header('Connection').lower().split(',')) + key = get_header('Sec-WebSocket-Key') + assert len(base64.b64decode(key.encode(), validate=True)) == 16 + assert get_header('Sec-WebSocket-Version') == '13' + except Exception as exc: + raise InvalidHandshake("Invalid request") from exc + else: + return key + + +def build_response(set_header, key): + """ + Build a handshake response to send to the client. + + ``key`` comes from :func:`check_request`. + """ + set_header('Upgrade', 'WebSocket') + set_header('Connection', 'Upgrade') + set_header('Sec-WebSocket-Accept', accept(key)) + + +def check_response(get_header, key): + """ + Check a handshake response received from the server. + + ``key`` comes from :func:`build_request`. + + If the handshake is valid, this function returns ``None``. + + Otherwise it raises an :exc:`~websockets.exceptions.InvalidHandshake` + exception. + + This function doesn't verify that the response is an HTTP/1.1 or higher + response with a 101 status code. These controls are the responsibility of + the caller. + """ + try: + assert get_header('Upgrade').lower() == 'websocket' + assert any( + token.strip() == 'upgrade' + for token in get_header('Connection').lower().split(',')) + assert get_header('Sec-WebSocket-Accept') == accept(key) + except Exception as exc: + raise InvalidHandshake("Invalid response") from exc + + +def accept(key): + sha1 = hashlib.sha1((key + GUID).encode()).digest() + return base64.b64encode(sha1).decode() diff --git a/pool/shard002/Python/0025409_vcftobedpeconverter_tests.py b/pool/shard002/Python/0025409_vcftobedpeconverter_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..16e2c2165f572267dc6c9b224d4479808b75f1c8 --- /dev/null +++ b/pool/shard002/Python/0025409_vcftobedpeconverter_tests.py @@ -0,0 +1,62 @@ +from unittest import TestCase +from svtools.vcftobedpeconverter import VcfToBedpeConverter +from svtools.vcf.file import Vcf +from svtools.vcf.variant import Variant +from svtools.bedpe import Bedpe + +class TestVcfToBedpeConverter(TestCase): + def setUp(self): + self.converter = VcfToBedpeConverter() + header_lines = [ + '##fileformat=VCFv4.2', + '##fileDate=20090805', + '##reference=file:///seq/references/1000GenomesPilot-NCBI36.fasta', + '##INFO=', + '##INFO=', + '##INFO=', + '##FORMAT=', + '#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT NA00001'] + self.vcf = Vcf() + self.vcf.add_header(header_lines) + + def test_bnd_breakpoints(self): + vcf_array1 = ['1', '20000', '235', 'T', 'A[1:6[', '0.00', '.', '.', 'GT', '0/0'] + v1 = Variant(vcf_array1, self.vcf) + self.assertEqual( + self.converter.bnd_breakpoints(v1), + ('1', 20000, 20000, '1', 5, 5, '+', '-')) + vcf_array2 = ['1', '20000', '235', 'T', ']1:6]N', '0.00', '.', '.', 'GT', '0/0'] + v2 = Variant(vcf_array2, self.vcf) + self.assertEqual( + self.converter.bnd_breakpoints(v2), + ('1', 19999, 19999, '1', 6, 6, '-', '+')) + + def test_simple_breakpoints(self): + vcf_array1 = ['1', '20000', '235', 'T', '', '0.00', '.', 'END=20500', 'GT', '0/0'] + v1 = Variant(vcf_array1, self.vcf) + self.assertEqual( + self.converter.simple_breakpoints(v1), + ('1', 20000, 20000, '1', 20500, 20500, '+', '-')) + vcf_array2 = ['1', '20000', '235', 'T', '', '0.00', '.', 'END=20500;STRANDS=-+:2', 'GT', '0/0'] + v2 = Variant(vcf_array2, self.vcf) + self.assertEqual( + self.converter.simple_breakpoints(v2), + ('1', 20000, 20000, '1', 20500, 20500, '-', '+')) + vcf_array3 = ['1', '20000', '235', 'T', '', '0.00', '.', 'STRANDS=--:2', 'GT', '0/0'] + v3 = Variant(vcf_array3, self.vcf) + with self.assertRaises(ValueError): + self.converter.simple_breakpoints(v3) + + def test_adjust_coordinate(self): + vcf_array1 = ['1', '20000', '235', 'T', '', '0.00', '.', 'CIEND=-50,50', 'GT', '0/0'] + v1 = Variant(vcf_array1, self.vcf) + self.assertEqual( + self.converter.adjust_coordinate(v1, 'CIEND', 500, 1000), + (450, 1050)) + self.assertEqual( + self.converter.adjust_coordinate(v1, 'CIPOS', 500, 1000), + (500, 1000)) + vcf_array2 = ['1', '20000', '235', 'T', '', '0.00', '.', 'CIEND=50', 'GT', '0/0'] + v2 = Variant(vcf_array2, self.vcf) + with self.assertRaises(ValueError): + self.converter.adjust_coordinate(v2, 'CIEND', 500, 1000) diff --git a/pool/shard002/Python/0025418_feedback_tags.py b/pool/shard002/Python/0025418_feedback_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..0708594867e6f1f320439fc7d5e6b440a6633a00 --- /dev/null +++ b/pool/shard002/Python/0025418_feedback_tags.py @@ -0,0 +1,83 @@ +from django import template + +import random + +from feedback.models import Feedback, Favorite, Event + +register = template.Library() + +@register.filter +def rating_average(feedback, num=False): + ratings = [f.rating for f in feedback if f.rating] + if not ratings: + return '' + avg = sum(ratings) / float(len(ratings)) + if num: + return avg + return '%.2f' % avg + +@register.filter +def interest_average(feedback, num=False): + ratings = [f.interest for f in feedback if f.interest] + if not ratings: + return '' + avg = sum(ratings) / float(len(ratings)) + if num: + return avg + return '%.2f' % avg + +@register.filter +def feedback_count(feedback): + non_empty = [f for f in feedback if (f.interest or f.rating or f.comments)] + return str(len(non_empty)) + +@register.filter +def all_feedback(applicant): + feedback = Feedback.objects.filter(applicant=applicant) + return [f for f in feedback] + +@register.filter +def alumni_filter(feedback): + return [f for f in feedback if (f.scholar.class_year < 2013 or f.scholar.class_year is None)] + +@register.filter +def senior_filter(feedback): + return [f for f in feedback if f.scholar.class_year == 2013] + +@register.filter +def other_filter(feedback): + return [f for f in feedback if f.scholar.class_year > 2013] + +@register.filter +def favorite_filter(applicant): + favs = Favorite.objects.filter(applicant=applicant) + return [f for f in favs] + +@register.inclusion_tag('macro/feedback_header.html') +def feedback_header(active, user, event_name): + return {'active': active, 'user': user, 'event_name': event_name} + +@register.inclusion_tag('macro/form_element.html') +def form_element(element, label, style, add_form_control=True): + return {'element': element, 'style': style, 'label': label, 'add_form_control': add_form_control} + +@register.filter +def convert_attended(attended): + return 'Yes' if attended else 'No' + +# works on the Django user, not McUser +@register.filter +def is_staff_for(user, event_name): + try: + event = Event.objects.get(name=event_name) + except Event.DoesNotExist: + return False + return user.mcuser in event.staff.all() + +@register.filter +def can_read_data_for(user, event_name): + try: + event = Event.objects.get(name=event_name) + except Event.DoesNotExist: + return False + return user.mcuser in event.staff.all() or user.mcuser in event.selection.all() \ No newline at end of file diff --git a/pool/shard002/Python/0025419_disk_filter.py b/pool/shard002/Python/0025419_disk_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..dd2a255545aecece2520d52227abbb04be8ea0a1 --- /dev/null +++ b/pool/shard002/Python/0025419_disk_filter.py @@ -0,0 +1,81 @@ +# Copyright (c) 2012 OpenStack Foundation +# 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 oslo_log import log as logging + +import nova.conf +from nova.i18n import _LW +from nova.scheduler import filters +from nova.scheduler.filters import utils + +LOG = logging.getLogger(__name__) + +CONF = nova.conf.CONF + + +class DiskFilter(filters.BaseHostFilter): + """Disk Filter with over subscription flag.""" + + def _get_disk_allocation_ratio(self, host_state, spec_obj): + return CONF.disk_allocation_ratio + + def host_passes(self, host_state, spec_obj): + """Filter based on disk usage.""" + requested_disk = (1024 * (spec_obj.root_gb + + spec_obj.ephemeral_gb) + + spec_obj.swap) + + free_disk_mb = host_state.free_disk_mb + total_usable_disk_mb = host_state.total_usable_disk_gb * 1024 + + disk_allocation_ratio = self._get_disk_allocation_ratio( + host_state, spec_obj) + + disk_mb_limit = total_usable_disk_mb * disk_allocation_ratio + used_disk_mb = total_usable_disk_mb - free_disk_mb + usable_disk_mb = disk_mb_limit - used_disk_mb + + if not usable_disk_mb >= requested_disk: + LOG.debug("%(host_state)s does not have %(requested_disk)s MB " + "usable disk, it only has %(usable_disk_mb)s MB usable " + "disk.", {'host_state': host_state, + 'requested_disk': requested_disk, + 'usable_disk_mb': usable_disk_mb}) + return False + + disk_gb_limit = disk_mb_limit / 1024 + host_state.limits['disk_gb'] = disk_gb_limit + return True + + +class AggregateDiskFilter(DiskFilter): + """AggregateDiskFilter with per-aggregate disk allocation ratio flag. + + Fall back to global disk_allocation_ratio if no per-aggregate setting + found. + """ + + def _get_disk_allocation_ratio(self, host_state, spec_obj): + aggregate_vals = utils.aggregate_values_from_key( + host_state, + 'disk_allocation_ratio') + try: + ratio = utils.validate_num_values( + aggregate_vals, CONF.disk_allocation_ratio, cast_to=float) + except ValueError as e: + LOG.warning(_LW("Could not decode disk_allocation_ratio: '%s'"), e) + ratio = CONF.disk_allocation_ratio + + return ratio diff --git a/pool/shard002/Python/0025420_committees.py b/pool/shard002/Python/0025420_committees.py new file mode 100644 index 0000000000000000000000000000000000000000..ebd7379cc80d472bf1bf4d7c5ae45ba94456da9c --- /dev/null +++ b/pool/shard002/Python/0025420_committees.py @@ -0,0 +1,68 @@ +import lxml.html +from openstates.scrape import Scraper, Organization + +from .common import SESSION_TERMS + + +class WICommitteeScraper(Scraper): + def scrape_committee(self, name, url, chamber): + org = Organization(name=name, chamber=chamber, classification="committee") + org.add_source(url) + data = self.get(url).text + doc = lxml.html.fromstring(data) + + for leg in doc.xpath('//div[@id="members"]/div[@id="members"]/p/a/text()'): + leg = leg.replace("Representative ", "") + leg = leg.replace("Senator ", "") + leg = leg.strip() + if " (" in leg: + leg, role = leg.split(" (") + if "Vice-Chair" in role: + role = "vice-chair" + elif "Co-Chair" in role: + role = "co-chair" + elif "Chair" in role: + role = "chair" + else: + raise Exception("unknown role: %s" % role) + else: + role = "member" + org.add_member(leg, role) + + return org + + def scrape(self, chamber=None, session=None): + if session is None: + session = self.latest_session() + self.info("no session specified, using %s", session) + term = SESSION_TERMS[session] + + chambers = [chamber] if chamber is not None else ["upper", "lower"] + + for chamber in chambers + ["legislature"]: + url = "http://docs.legis.wisconsin.gov/{}/committees/".format( + term.split("-")[0] + ) + if chamber == "legislature": + url += "joint" + elif chamber == "upper": + url += "senate" + else: + url += "assembly" + data = self.get(url).text + doc = lxml.html.fromstring(data) + doc.make_links_absolute(url) + + for a in doc.xpath('//ul[@class="docLinks"]/li/p/a'): + if "(Disbanded" not in a.text: + comm_name = a.text + comm_name = comm_name.replace("Committee on", "") + comm_name = comm_name.replace("Assembly", "") + comm_name = comm_name.replace("Joint Survey", "") + comm_name = comm_name.replace("Joint Review", "") + comm_name = comm_name.replace("Joint", "") + comm_name = comm_name.replace("Senate", "") + comm_name = comm_name.replace("Committee for", "") + comm_name = comm_name.replace("Committee", "") + comm_name = comm_name.strip() + yield self.scrape_committee(comm_name, a.get("href"), chamber) diff --git a/pool/shard002/Python/0025434_kernel.py b/pool/shard002/Python/0025434_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..11b87574d40916b96e36db46a6a8bb71096129ee --- /dev/null +++ b/pool/shard002/Python/0025434_kernel.py @@ -0,0 +1,186 @@ +"""IPython kernel for parallel computing""" + +import sys +from datetime import datetime + +from ipython_genutils.py3compat import cast_bytes, cast_unicode_py2 +from traitlets import Integer, Type + +from ipykernel.ipkernel import IPythonKernel +from ipykernel.jsonutil import json_clean +from ipyparallel.serialize import serialize_object, unpack_apply_message +from .datapub import ZMQDataPublisher + + +class IPythonParallelKernel(IPythonKernel): + """Extend IPython kernel for parallel computing""" + engine_id = Integer(-1) + msg_types = getattr(IPythonKernel, 'msg_types', []) + ['apply_request'] + _execute_sleep = 0 + data_pub_class = Type(ZMQDataPublisher) + + def _topic(self, topic): + """prefixed topic for IOPub messages""" + base = "engine.%s" % self.engine_id + + return cast_bytes("%s.%s" % (base, topic)) + + + def __init__(self, **kwargs): + super(IPythonParallelKernel, self).__init__(**kwargs) + # add apply_request, in anticipation of upstream deprecation + self.shell_handlers['apply_request'] = self.apply_request + # set up data pub + data_pub = self.shell.data_pub = self.data_pub_class(parent=self) + self.shell.configurables.append(data_pub) + data_pub.session = self.session + data_pub.pub_socket = self.iopub_socket + + def init_metadata(self, parent): + """init metadata dict, for execute/apply_reply""" + return { + 'started': datetime.now(), + 'dependencies_met' : True, + 'engine' : self.ident, + } + + def finish_metadata(self, parent, metadata, reply_content): + """Finish populating metadata. + + Run after completing a request handler. + """ + # FIXME: remove ipyparallel-specific code + metadata['status'] = reply_content['status'] + if reply_content['status'] == 'error': + if reply_content['ename'] == 'UnmetDependency': + metadata['dependencies_met'] = False + metadata['engine_info'] = dict( + engine_uuid=self.ident, + engine_id=self.engine_id, + ) + + return metadata + + def execute_request(self, stream, ident, parent): + """handle an execute_request - overridden for ipyparallel metadata + + Once ipykernel has init/finish_metadata, this should be removed. + """ + + try: + content = parent[u'content'] + code = cast_unicode_py2(content[u'code']) + silent = content[u'silent'] + store_history = content.get(u'store_history', not silent) + user_expressions = content.get('user_expressions', {}) + allow_stdin = content.get('allow_stdin', False) + except: + self.log.error("Got bad msg: ") + self.log.error("%s", parent) + return + + stop_on_error = content.get('stop_on_error', True) + + md = self.init_metadata(parent) + + # Re-broadcast our input for the benefit of listening clients, and + # start computing output + if not silent: + self.execution_count += 1 + self._publish_execute_input(code, parent, self.execution_count) + + reply_content = self.do_execute(code, silent, store_history, + user_expressions, allow_stdin) + # finish building metadata + md = self.finish_metadata(parent, md, reply_content) + + # Flush output before sending the reply. + sys.stdout.flush() + sys.stderr.flush() + + # Send the reply. + reply_content = json_clean(reply_content) + + reply_msg = self.session.send(stream, u'execute_reply', + reply_content, parent, metadata=md, + ident=ident) + + self.log.debug("%s", reply_msg) + + if not silent and reply_msg['content']['status'] == u'error' and stop_on_error: + self._abort_queues() + + def apply_request(self, stream, ident, parent): + try: + content = parent[u'content'] + bufs = parent[u'buffers'] + msg_id = parent['header']['msg_id'] + except: + self.log.error("Got bad msg: %s", parent, exc_info=True) + return + + md = self.init_metadata(parent) + + reply_content, result_buf = self.do_apply(content, bufs, msg_id, md) + + # put 'ok'/'error' status in header, for scheduler introspection: + md = self.finish_metadata(parent, md, reply_content) + + # flush i/o + sys.stdout.flush() + sys.stderr.flush() + + self.session.send(stream, u'apply_reply', reply_content, + parent=parent, ident=ident, buffers=result_buf, metadata=md) + + def do_apply(self, content, bufs, msg_id, reply_metadata): + shell = self.shell + try: + working = shell.user_ns + + prefix = "_"+str(msg_id).replace("-","")+"_" + + f,args,kwargs = unpack_apply_message(bufs, working, copy=False) + + fname = getattr(f, '__name__', 'f') + + fname = prefix+"f" + argname = prefix+"args" + kwargname = prefix+"kwargs" + resultname = prefix+"result" + + ns = { fname : f, argname : args, kwargname : kwargs , resultname : None } + # print ns + working.update(ns) + code = "%s = %s(*%s,**%s)" % (resultname, fname, argname, kwargname) + try: + exec(code, shell.user_global_ns, shell.user_ns) + result = working.get(resultname) + finally: + for key in ns: + working.pop(key) + + result_buf = serialize_object(result, + buffer_threshold=self.session.buffer_threshold, + item_threshold=self.session.item_threshold, + ) + + except: + # invoke IPython traceback formatting + shell.showtraceback() + # FIXME - fish exception info out of shell, possibly left there by + # run_code. We'll need to clean up this logic later. + reply_content = {} + if shell._reply_content is not None: + reply_content.update(shell._reply_content) + # reset after use + shell._reply_content = None + + self.send_response(self.iopub_socket, u'error', reply_content, + ident=self._topic('error')) + self.log.info("Exception in apply request:\n%s", '\n'.join(reply_content['traceback'])) + result_buf = [] + else: + reply_content = {'status' : 'ok'} + + return reply_content, result_buf diff --git a/pool/shard002/Python/0025443_get_oss.py b/pool/shard002/Python/0025443_get_oss.py new file mode 100644 index 0000000000000000000000000000000000000000..54a000ecd01b10169ea90b87c1f2570bc6441d89 --- /dev/null +++ b/pool/shard002/Python/0025443_get_oss.py @@ -0,0 +1,51 @@ +#coding=utf8 +# windows环境oss下载程序 +from __future__ import print_function +import oss2 +import sys,os + +def percentage(consumed_bytes, total_bytes): + if total_bytes: + rate = int(100 * (float(consumed_bytes) / float(total_bytes))) + print('\r{0}% '.format(rate), end='') + sys.stdout.flush() + +def download(filename): + auth = oss2.Auth('您的AccessKeyId', '您的AccessKeySecret') + bucket = oss2.Bucket(auth, '您的Endpoint', '您的Bucket名') + bucket.get_object_to_file(filename,filename, progress_callback=percentage) + +def start(filename): + curdir_list = os.listdir('.') + filename = filename.decode('utf8').encode('gbk') + print('start downloading [%s]......'%filename) + if filename in curdir_list: + raise Exception,'%s already in the current directory,can\'t download.'%filename + else: + download(filename.decode('gbk').encode('utf8')) + print('Download success.') + +if __name__=='__main__': + # 获取下载列表 + if len(sys.argv)==1: + files = raw_input('Please input download filename : ') + files = files.strip().decode('gbk').encode('utf8').split() + elif len(sys.argv)>=2: + files = sys.argv[1:] + files = map(lambda x:x.decode('gbk').encode('utf8'),files) + + # 开始下载 + for i,filename in enumerate(files): + print ("[%d]"%(i+1),end=' ') + try: + start(filename) + except Exception,e: + print('Download failed.') + print('[ERROR]:%s'%e) + # 删除多余创建的文件 + if str(e).find('already')==-1 and os.path.exists(filename): + os.remove(filename) + # 下载完成 + os.system('pause') + + diff --git a/pool/shard002/Python/0025448_test1.py b/pool/shard002/Python/0025448_test1.py new file mode 100644 index 0000000000000000000000000000000000000000..0b7fd808df26e8dd7982245ac0f90cf8a3312976 --- /dev/null +++ b/pool/shard002/Python/0025448_test1.py @@ -0,0 +1,159 @@ +#!/usr/bin/python +'''Test for an openGL based renderer - testing scene graph features (parenting, dirty propigation, animation) + +David Dunn +Feb 2017 - created test suite + +www.qenops.com + +''' +__author__ = ('David Dunn') +__version__ = '1.0' + +import OpenGL +OpenGL.ERROR_CHECKING = False # Uncomment for 2x speed up +OpenGL.ERROR_LOGGING = False # Uncomment for speed up +#OpenGL.FULL_LOGGING = True # Uncomment for verbose logging +#OpenGL.ERROR_ON_COPY = True # Comment for release +import OpenGL.GL as GL +import math, os +import numpy as np +import dGraph as dg +import dGraph.ui as dgui +import dGraph.render as dgr +import dGraph.cameras as dgc +import dGraph.shapes as dgs +import dGraph.materials as dgm +import dGraph.config as config +import dGraph.util.imageManip as im +import time + +MODELDIR = '%s/data'%os.path.dirname(__file__) + +def loadScene(renderGraph): + '''Load or create our sceneGraph''' + scene = dg.SceneGraph('Test1_SG') + cam = scene.add(dgc.Camera('cam', scene)) + cam.setResolution((renderGraph.width, renderGraph.height)) + cam.setTranslate(0.,0.,0.) + cam.setFOV(50.) + sun = scene.add(dgs.PolySurface.polySphere('sun', scene, radius=.2)) + sun.setTranslate(0.,0.,-2.) + sun.setRotate(10.,0.,0.) + sunMaterial = scene.add(dgm.Lambert('sunMaterial',ambient=(1,1,0), amb_coeff=1., diffuse=(0,0,0), diff_coeff=0)) + sun.setMaterial(sunMaterial) + mercury = scene.add(dgs.PolySurface.polySphere('mercury', sun, radius=.01)) + mercury.setTranslate(0.3,0.,0.) + mercuryMaterial = scene.add(dgm.Lambert('mercuryMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(1.,.5,.3), diff_coeff=1)) + mercury.setMaterial(mercuryMaterial) + venus = scene.add(dgs.PolySurface.polySphere('venus', sun, radius=.028)) + venus.setTranslate(0.425,0.,0.) + venusMaterial = scene.add(dgm.Lambert('venusMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(1.,.6,.6), diff_coeff=1)) + venus.setMaterial(venusMaterial) + earth = scene.add(dgs.PolySurface.polySphere('earth', sun, radius=.03)) + earth.setTranslate(0.6,0.,0.) + earth.setRotate(0.,0.,15.) + earthMaterial = scene.add(dgm.Lambert('earthMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(.25,.41,.879), diff_coeff=1)) + earth.setMaterial(earthMaterial) + moon = scene.add(dgs.PolySurface.polySphere('moon', earth, radius=.005)) + moon.setTranslate(0.075,0.,0.) + moonMaterial = scene.add(dgm.Lambert('moonMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(.7,.7,.7), diff_coeff=1)) + moon.setMaterial(moonMaterial) + mars = scene.add(dgs.PolySurface.polySphere('mars', sun, radius=.015)) + mars.setTranslate(0.8,0.,0.) + marsMaterial = scene.add(dgm.Lambert('marsMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(.8,.2,.2), diff_coeff=1)) + mars.setMaterial(marsMaterial) + jupiter = scene.add(dgs.PolySurface.polySphere('jupiter', sun, radius=.1)) + jupiter.setTranslate(1.2,0.,0.) + jupiterMaterial = scene.add(dgm.Lambert('jupiterMaterial',ambient=(0,0,0), amb_coeff=0., diffuse=(.867,.71875,.527), diff_coeff=1)) + jupiter.setMaterial(jupiterMaterial) + renderGraph.frameBuffer.connectInput(cam) + scene.add(renderGraph) + return scene # Initialization Successful + +def animateScene(scene, frame): + ''' Create motion in our scene ''' + # name: (distance, orbit, rotation ) + speeds = {'mercury':(0.3, 87.969, 58.646 ), + 'venus': (0.425, 224.7, 243 ), + 'earth': (0.6, 365.2564, 1 ), + 'moon': (0.075, 28, 28 ), + 'mars': (0.8, 687, 1.03 ), + 'jupiter':(1.2, 4332.59, 0.4135 )} + for k in scene.shapes: + if k in speeds: + dist, orbit, rot = speeds[k] + # add rot when we have textures - but will mess up children + x = math.cos(math.pi/2/orbit*frame) * dist + z = math.sin(math.pi/2/orbit*frame) * dist + scene[k].translate = np.array((x,0.,z)) + +def addInput(scene): + dgui.add_key_callback(arrowKey, dgui.KEY_RIGHT, scene=scene, direction=3) + dgui.add_key_callback(arrowKey, dgui.KEY_LEFT, scene=scene, direction=2) + dgui.add_key_callback(arrowKey, dgui.KEY_UP, scene=scene, direction=1) + dgui.add_key_callback(arrowKey, dgui.KEY_DOWN, scene=scene, direction=0) + +''' In order to do input with mouse and keyboard, we need to setup a state machine with +states switches from mouse presses and releases and certain key presses +- maybe enable a glfwSetCursorPosCallback when button is pressed, or +- more likely just poll cursor position since you can't disable a callback''' +def arrowKey(window,scene,direction): + if direction == 3: # print "right" + pass + elif direction == 2: # print "left" + pass + elif direction == 1: # print 'up' + scene['sun'].rotate += np.array((5.,0.,0.)) + print(scene['sun'].rotate) + else: # print "down" + scene['sun'].rotate -= np.array((5.,0.,0.)) + print(scene['sun'].rotate) + +def setup(): + renderGraph = dgr.RenderGraph('Test1_RG') + display = renderGraph.add(dgui.Display('Fake Display',resolution=(1920,1200))) + dgui.init() + offset = (0,0) + mainWindow = renderGraph.add(dgui.open_window('Scene Graph Test', offset[0], offset[1], display.width, display.height)) + if not mainWindow: + dgui.terminate() + exit(1) + x, y = dgui.get_window_pos(mainWindow) + width, height = dgui.get_window_size(mainWindow) + dgui.add_key_callback(dgui.close_window, dgui.KEY_ESCAPE) + dg.initGL() + scene = loadScene(renderGraph) + renderGraph.graphicsCardInit() + return scene, [mainWindow] + +def runLoop(scene, mainWindow): + # Print message to console, and kick off the loop to get it rolling. + print("Hit ESC key to quit.") + frame = 0 + totalSleep = 0 + start = time.time() + while not dgui.window_should_close(mainWindow): + dgui.make_context_current(mainWindow) + scene.render() + now = time.time() + toSleep = max(0,(frame+1)/config.maxFPS+start-now) + time.sleep(toSleep) + dgui.swap_buffers(mainWindow) + dgui.poll_events() + animateScene(scene, frame) + totalSleep += toSleep + frame += 1 + end = time.time() + dgui.terminate() + elapsed = end-start + computePct = (1-totalSleep/elapsed)*100 + renderTime = elapsed-totalSleep + frameTime = renderTime/frame*1000 + print('Average frame took %.4f ms to render.\nRendered %.4f seconds of a total %.4f seconds.\nRendering %.2f%% of the time.'%(frameTime,renderTime,elapsed,computePct)) + exit(0) + +if __name__ == '__main__': + scene, windows = setup() + addInput(scene) + runLoop(scene, windows[0]) diff --git a/pool/shard002/Python/0025454_exceptions.py b/pool/shard002/Python/0025454_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..2fddd18ec06112a6eacb597e0fdc34f9c1e5b032 --- /dev/null +++ b/pool/shard002/Python/0025454_exceptions.py @@ -0,0 +1,28 @@ +from __future__ import unicode_literals +from moto.core.exceptions import RESTError + + +class AutoscalingClientError(RESTError): + code = 400 + + +class ResourceContentionError(RESTError): + code = 500 + + def __init__(self): + super(ResourceContentionError, self).__init__( + "ResourceContentionError", + "You already have a pending update to an Auto Scaling resource (for example, a group, instance, or load balancer).", + ) + + +class InvalidInstanceError(AutoscalingClientError): + def __init__(self, instance_id): + super(InvalidInstanceError, self).__init__( + "ValidationError", "Instance [{0}] is invalid.".format(instance_id) + ) + + +class ValidationError(AutoscalingClientError): + def __init__(self, message): + super(ValidationError, self).__init__("ValidationError", message) diff --git a/pool/shard002/Python/0025455_pe025.py b/pool/shard002/Python/0025455_pe025.py new file mode 100644 index 0000000000000000000000000000000000000000..eb1600f702536daedde8d688b622377d75341fb9 --- /dev/null +++ b/pool/shard002/Python/0025455_pe025.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 + +def main(): + """ this computes projecteuler.net problem 025 """ + + limit = 1000 + i = 0 + vector = [] + fib(i, vector) + while (len(str(vector[i])) < limit): + i += 1 + fib(i, vector) + + print(i) + return 0 + +def fib(n, vector): + """ this computes the fibonacci number of the passed number """ + if n < 2: + vector.append(n) + else: + vector.append(vector[n - 2] + vector[n - 1]) + +if __name__ == "__main__": + main() diff --git a/pool/shard002/Python/0025458_uniform.py b/pool/shard002/Python/0025458_uniform.py new file mode 100644 index 0000000000000000000000000000000000000000..b87c67bfad02f88e6e6078c4e3e88b4a009ef762 --- /dev/null +++ b/pool/shard002/Python/0025458_uniform.py @@ -0,0 +1,203 @@ +# Copyright 2016 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. +# ============================================================================== +"""The Uniform distribution class.""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math + +from tensorflow.contrib.distributions.python.ops import distribution +from tensorflow.contrib.framework.python.framework import tensor_util as contrib_tensor_util +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops + + +class Uniform(distribution.Distribution): + """Uniform distribution with `low` and `high` parameters. + + #### Mathematical Details + + The probability density function (pdf) is, + + ```none + pdf(x; a, b) = I[a <= x < b] / Z + Z = b - a + ``` + + where: + * `low = a`, + * `high = b`, + * `Z` is the normalizing constant, and, + * `I[predicate]` is the [indicator function]( + https://en.wikipedia.org/wiki/Indicator_function) for `predicate`. + + The parameters `low` and `high` must be shaped in a way that supports + broadcasting (e.g., `high - low` is a valid operation). + + #### Examples + + ```python + # Without broadcasting: + u1 = Uniform(low=3.0, high=4.0) # a single uniform distribution [3, 4] + u2 = Uniform(low=[1.0, 2.0], + high=[3.0, 4.0]) # 2 distributions [1, 3], [2, 4] + u3 = Uniform(low=[[1.0, 2.0], + [3.0, 4.0]], + high=[[1.5, 2.5], + [3.5, 4.5]]) # 4 distributions + ``` + + ```python + # With broadcasting: + u1 = Uniform(low=3.0, high=[5.0, 6.0, 7.0]) # 3 distributions + ``` + + """ + + def __init__(self, + low=0., + high=1., + validate_args=False, + allow_nan_stats=True, + name="Uniform"): + """Initialize a batch of Uniform distributions. + + Args: + low: Floating point tensor, lower boundary of the output interval. Must + have `low < high`. + high: Floating point tensor, upper boundary of the output interval. Must + have `low < high`. + validate_args: Python `bool`, default `False`. When `True` distribution + parameters are checked for validity despite possibly degrading runtime + performance. When `False` invalid inputs may silently render incorrect + outputs. + allow_nan_stats: Python `bool`, default `True`. When `True`, statistics + (e.g., mean, mode, variance) use the value "`NaN`" to indicate the + result is undefined. When `False`, an exception is raised if one or + more of the statistic's batch members are undefined. + name: Python `str` name prefixed to Ops created by this class. + + Raises: + InvalidArgumentError: if `low >= high` and `validate_args=False`. + """ + parameters = locals() + with ops.name_scope(name, values=[low, high]) as ns: + with ops.control_dependencies([ + check_ops.assert_less( + low, high, message="uniform not defined when low >= high.") + ] if validate_args else []): + self._low = array_ops.identity(low, name="low") + self._high = array_ops.identity(high, name="high") + contrib_tensor_util.assert_same_float_dtype([self._low, self._high]) + super(Uniform, self).__init__( + dtype=self._low.dtype, + reparameterization_type=distribution.FULLY_REPARAMETERIZED, + validate_args=validate_args, + allow_nan_stats=allow_nan_stats, + parameters=parameters, + graph_parents=[self._low, + self._high], + name=ns) + + @staticmethod + def _param_shapes(sample_shape): + return dict( + zip(("low", "high"), + ([ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)] * 2))) + + @property + def low(self): + """Lower boundary of the output interval.""" + return self._low + + @property + def high(self): + """Upper boundary of the output interval.""" + return self._high + + def range(self, name="range"): + """`high - low`.""" + with self._name_scope(name): + return self.high - self.low + + def _batch_shape_tensor(self): + return array_ops.broadcast_dynamic_shape( + array_ops.shape(self.low), + array_ops.shape(self.high)) + + def _batch_shape(self): + return array_ops.broadcast_static_shape( + self.low.get_shape(), + self.high.get_shape()) + + def _event_shape_tensor(self): + return constant_op.constant([], dtype=dtypes.int32) + + def _event_shape(self): + return tensor_shape.scalar() + + def _sample_n(self, n, seed=None): + shape = array_ops.concat([[n], self.batch_shape_tensor()], 0) + samples = random_ops.random_uniform(shape=shape, + dtype=self.dtype, + seed=seed) + return self.low + self.range() * samples + + def _log_prob(self, x): + return math_ops.log(self._prob(x)) + + def _prob(self, x): + broadcasted_x = x * array_ops.ones(self.batch_shape_tensor()) + return array_ops.where( + math_ops.is_nan(broadcasted_x), + broadcasted_x, + array_ops.where( + math_ops.logical_or(broadcasted_x < self.low, + broadcasted_x >= self.high), + array_ops.zeros_like(broadcasted_x), + array_ops.ones_like(broadcasted_x) / self.range())) + + def _log_cdf(self, x): + return math_ops.log(self.cdf(x)) + + def _cdf(self, x): + broadcast_shape = array_ops.broadcast_dynamic_shape( + array_ops.shape(x), self.batch_shape_tensor()) + zeros = array_ops.zeros(broadcast_shape, dtype=self.dtype) + ones = array_ops.ones(broadcast_shape, dtype=self.dtype) + broadcasted_x = x * ones + result_if_not_big = array_ops.where( + x < self.low, zeros, (broadcasted_x - self.low) / self.range()) + return array_ops.where(x >= self.high, ones, result_if_not_big) + + def _entropy(self): + return math_ops.log(self.range()) + + def _mean(self): + return (self.low + self.high) / 2. + + def _variance(self): + return math_ops.square(self.range()) / 12. + + def _stddev(self): + return self.range() / math.sqrt(12.) diff --git a/pool/shard002/Python/0025464_test_adminlog.py b/pool/shard002/Python/0025464_test_adminlog.py new file mode 100644 index 0000000000000000000000000000000000000000..14715a0e9c32f2c9faff86ff81518897a7cec7e1 --- /dev/null +++ b/pool/shard002/Python/0025464_test_adminlog.py @@ -0,0 +1,18 @@ +from datetime import datetime + +from pynga.user import AdminLog + + +def test_adminlog(): + log = AdminLog(( + '{"0":123,"1":19,"2":456,"3":789,"4":987,' + '"5":"test_action","6":1515495369}' + )) + assert log.log_id == 123 + assert log.type == '移动主题' + assert log.source_uid == 456 + assert log.target_uid == 789 + assert log.tid == 987 + assert log.message == 'test_action' + assert log.time == datetime(2018, 1, 9, 18, 56, 9) + assert repr(log) == '' diff --git a/pool/shard002/Python/0025466_blocks_test.py b/pool/shard002/Python/0025466_blocks_test.py new file mode 100644 index 0000000000000000000000000000000000000000..289949bc87fb1625d438efb064330069390004ba --- /dev/null +++ b/pool/shard002/Python/0025466_blocks_test.py @@ -0,0 +1,49 @@ +''' Copyright (c) 2008, Kent S Johnson + + 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 +''' + +import unittest + +from blocks import unicodeBlock + +class blocks_test(unittest.TestCase): + def test_unicodeBlock(self): + for c in range(128): + self.assertBlock('Basic Latin', c) + + for c in range(0x80, 0x180) + range(0x250, 0x2B0): + self.assertBlock('Extended Latin', c) + + self.assertBlock('Thai', 0xE00) + self.assertBlock('Thai', 0xE7F) + self.assertBlock('Lao', 0xE80) + self.assertBlock('Lao', 0x0EFF) + self.assertBlock('Tibetan', 0xF00) + self.assertBlock('Tibetan', 0xFFF) + self.assertBlock('Cyrillic', 0x421) + + def assertBlock(self, name, c): + c = unichr(c) + block = unicodeBlock(c) + self.assertEquals(name, unicodeBlock(c), '%s != %s for %r' % (name, block, c)) + + + def setUp(self): + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard002/Python/0025468_setup.py b/pool/shard002/Python/0025468_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..155d96f484f273f42faaffacbe4564c3c19c5785 --- /dev/null +++ b/pool/shard002/Python/0025468_setup.py @@ -0,0 +1,43 @@ +#coding:utf-8 +import sys +from distutils.core import setup + +from setuptools.command.test import test as TestCommand + + +class PyTest(TestCommand): + user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] + + def initialize_options(self): + TestCommand.initialize_options(self) + self.pytest_args = [] + + def finalize_options(self): + TestCommand.finalize_options(self) + self.test_args = ['tests/'] + self.test_suite = True + + def run_tests(self): + #import here, cause outside the eggs aren't loaded + import pytest + errno = pytest.main(self.pytest_args) + sys.exit(errno) + + +setup( + name='fantasy_data', + version='1.0.4', + description='FantasyData Python', + author='Fantasy Football Calculator', + author_email='support@fantasyfootballcalculator.com', + url='https://github.com/ffcalculator/fantasydata-python', + packages=['fantasy_data'], + keywords=['fantasy', 'sports', 'football'], + install_requires=[ + "requests", + "six", + ], + tests_require=['pytest'], + cmdclass = {'test': PyTest}, + download_url='https://github.com/ffcalculator/fantasydata-python/archive/v1.0.4.tar.gz' +) diff --git a/pool/shard002/Python/0025474_config.py b/pool/shard002/Python/0025474_config.py new file mode 100644 index 0000000000000000000000000000000000000000..205ebe88da6f64839af888a7d0c0fc374e5c7ebb --- /dev/null +++ b/pool/shard002/Python/0025474_config.py @@ -0,0 +1,82 @@ +from livesettings import * +from django.utils.translation import ugettext_lazy as _ + +gettext = lambda s:s +_strings = (gettext('CreditCard'), gettext('Credit Card')) + +PAYMENT_GROUP = ConfigurationGroup('PAYMENT_TRUSTCOMMERCE', + _('TrustCommerce Payment Settings'), + ordering=102) + +config_register_list( + + StringValue(PAYMENT_GROUP, + 'KEY', + description=_("Module key"), + hidden=True, + default = 'TRUSTCOMMERCE'), + + ModuleValue(PAYMENT_GROUP, + 'MODULE', + description=_('Implementation module'), + hidden=True, + default = 'payment.modules.trustcommerce'), + + BooleanValue(PAYMENT_GROUP, + 'AVS', + description=_("Use Address Verification System (AVS)?"), + default=False), + + BooleanValue(PAYMENT_GROUP, + 'LIVE', + description=_("Accept real payments"), + help_text=_("False if you want to be in test mode"), + default=False), + + StringValue(PAYMENT_GROUP, + 'AUTH_TYPE', + description=_("Type of authorization to perform."), + help_text = _("Refer to manual for details on the different types."), + default = 'sale', + choices = [('sale', _('Sale')), + ('preauth', _('Preauth'))] + ), + + StringValue(PAYMENT_GROUP, + 'LABEL', + description=_('English name for this group on the checkout screens'), + default = 'Credit Cards', + dummy = _('Credit Cards'), # Force this to appear on po-files + help_text = _('This will be passed to the translation utility')), + + StringValue(PAYMENT_GROUP, + 'URL_BASE', + description=_('The url base used for constructing urlpatterns which will use this module'), + default = r'^credit/'), + + MultipleStringValue(PAYMENT_GROUP, + 'CREDITCHOICES', + description=_('Available credit cards'), + choices = ( + (('American Express', 'American Express')), + (('Visa','Visa')), + (('Mastercard','Mastercard')), + (('Discover','Discover'))), + default = ('Visa', 'Mastercard', 'Discover')), + + StringValue(PAYMENT_GROUP, + 'LOGIN', + description=_('Your TrustCommerce login'), + default=""), + + StringValue(PAYMENT_GROUP, + 'PASSWORD', + description=_('Your TrustCommerce password'), + default=""), + + BooleanValue(PAYMENT_GROUP, + 'EXTRA_LOGGING', + description=_("Verbose logs"), + help_text=_("Add extensive logs during post."), + default=False) +) diff --git a/pool/shard002/Python/0025478_l2capserver.py b/pool/shard002/Python/0025478_l2capserver.py new file mode 100644 index 0000000000000000000000000000000000000000..d03690862167d83a670b17053fd5e547ac78325e --- /dev/null +++ b/pool/shard002/Python/0025478_l2capserver.py @@ -0,0 +1,32 @@ +# file: l2capclient.py +# desc: Demo L2CAP server for pybluez. +# $Id: l2capserver.py 524 2007-08-15 04:04:52Z albert $ + +import bluetooth + +server_sock=bluetooth.BluetoothSocket( bluetooth.L2CAP ) + +port = 0x1001 + +server_sock.bind(("",port)) +server_sock.listen(1) + +#uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ef" +#bluetooth.advertise_service( server_sock, "SampleServerL2CAP", +# service_id = uuid, +# service_classes = [ uuid ] +# ) + +client_sock,address = server_sock.accept() +print("Accepted connection from ",address) + +data = client_sock.recv(1024) +print("Data received:", data) + +while data: + client_sock.send('Echo =>' + data) + data = client_sock.recv(1024) + print("Data received:",data) + +client_sock.close() +server_sock.close() diff --git a/pool/shard002/Python/0025479_printproxy.py b/pool/shard002/Python/0025479_printproxy.py new file mode 100644 index 0000000000000000000000000000000000000000..82f04b386d9c16f309bd8659103ad1645bee4db9 --- /dev/null +++ b/pool/shard002/Python/0025479_printproxy.py @@ -0,0 +1,164 @@ +# -*- coding: utf-8 -*- + +# Copyright (c) 2011-2015, Camptocamp SA +# 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 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. + +# The views and conclusions contained in the software and documentation are those +# of the authors and should not be interpreted as representing official policies, +# either expressed or implied, of the FreeBSD Project. + +import logging +import os + +import simplejson as json + +from pyramid.view import view_config +from pyramid.httpexceptions import HTTPBadRequest + +from crdppf.views.proxy import Proxy + +from crdppf.lib.cached_content import get_cached_content, get_cached_content_l10n +from crdppf.lib.content import get_content + +log = logging.getLogger(__name__) + + +class PrintProxy(Proxy): # pragma: no cover + + def __init__(self, request): + Proxy.__init__(self, request) + self.config = self.request.registry.settings + + @view_config(route_name='printproxy_report_create') + def report_create(self): + """ Create PDF and store a copy for archive purposes. """ + + id = self.request.matchdict.get("id") + self.request.session['parcel_id'] = id + outputFilename = "static_plr_extract" + + body = { + "layout": "report", + "outputFormat": "pdf", + "outputFilename": outputFilename, + "attributes": {} + } + + body["attributes"].update(get_cached_content_l10n(self.request.params.get( + "lang", + self.request.registry.settings["app_config"]["lang"] + ))) + + cached_content = get_cached_content(self.request) + dynamic_content = get_content(id, self.request) + + if dynamic_content is False: + return HTTPBadRequest(detail='Found more than one geometry') + + body["attributes"].update(cached_content) + body["attributes"].update(dynamic_content["attributes"]) + + if dynamic_content["outputFilename"]: + body["outputFilename"] = dynamic_content["outputFilename"] + outputFilename = body["outputFilename"] + + directprint = False + if body["attributes"]['directprint'] is True: + directprint = body["attributes"]['directprint'] + _string = "%s/%s/buildreport.%s" % ( + self.config['print_url'], + "crdppf", + "pdf" + ) + else: + _string = "%s/%s/report.%s" % ( + self.config['print_url'], + "crdppf", + "pdf" + ) + + body = json.dumps(body) + + # Specify correct content type in headers + h = dict(self.request.headers) + h["Content-Type"] = "application/json" + + print_result = self._proxy_response( + _string, + body=body, + method='POST', + headers=h + ) + + if directprint is True: + try: + archive_path = self.config['pdf_archive_path'] + except: + archive_path = None + + if archive_path is not None: + with open(os.path.join(archive_path, outputFilename+'.pdf'), 'wb') as f: + f.write(print_result.body) + else: + log.warning('Optional archive_path not set.') + + return print_result + + @view_config(route_name='printproxy_status') + def status(self): + """ PDF status. """ + + _string = "%s/status/%s.json" % ( + self.config['print_url'], + self.request.matchdict.get('ref') + ) + + return self._proxy_response( + _string, + headers=self.request.headers + ) + + @view_config(route_name='printproxy_report_get') + def report_get(self): + """ Get the PDF. """ + + pdf = self._proxy_response( + "%s/report/%s" % ( + self.config['print_url'], + self.request.matchdict.get('ref') + ), + ) + + try: + archive_path = self.config['pdf_archive_path'] + except: + archive_path = None + + if archive_path is not None: + filename = pdf.content_disposition.split('=')[1] + with open(os.path.join(archive_path, filename), 'wb') as f: + f.write(pdf.body) + else: + log.warning('Optional archive_path not set.') + + return pdf diff --git a/pool/shard002/Python/0025488_test_dlpoly.py b/pool/shard002/Python/0025488_test_dlpoly.py new file mode 100644 index 0000000000000000000000000000000000000000..df2a38ef61fe6bc3950de903134aec2731e0d6a0 --- /dev/null +++ b/pool/shard002/Python/0025488_test_dlpoly.py @@ -0,0 +1,102 @@ +# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- +# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 +# +# MDAnalysis --- http://www.mdanalysis.org +# Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors +# (see the file AUTHORS for the full list of names) +# +# Released under the GNU Public Licence, v2 or any higher version +# +# Please cite your use of MDAnalysis in published work: +# +# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler, +# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein. +# MDAnalysis: A Python package for the rapid analysis of molecular dynamics +# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th +# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy. +# +# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein. +# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations. +# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787 +# +from numpy.testing import ( + assert_, + assert_array_equal, +) + +import MDAnalysis as mda + +from MDAnalysisTests.topology.base import ParserBase +from MDAnalysisTests.datafiles import ( + DLP_CONFIG, + DLP_CONFIG_order, + DLP_CONFIG_minimal, + DLP_HISTORY, + DLP_HISTORY_order, + DLP_HISTORY_minimal, +) + + +class DLPUniverse(ParserBase): + def test_creates_universe(self): + u = mda.Universe(self.filename, topology_format=self.format) + assert_(isinstance(u, mda.Universe)) + +class DLPBase2(DLPUniverse): + expected_attrs = ['ids', 'names'] + guessed_attrs = ['types', 'masses'] + expected_n_atoms = 216 + expected_n_residues = 1 + expected_n_segments = 1 + + def test_names(self): + assert_(self.top.names.values[0] == 'K+') + assert_(self.top.names.values[4] == 'Cl-') + + +class TestDLPHistoryParser(DLPBase2): + parser = mda.topology.DLPolyParser.HistoryParser + filename = DLP_HISTORY + format='HISTORY' + + +class TestDLPConfigParser(DLPBase2): + parser = mda.topology.DLPolyParser.ConfigParser + filename = DLP_CONFIG + format='CONFIG' + + +class DLPBase(DLPUniverse): + expected_attrs = ['ids', 'names'] + guessed_attrs = ['types', 'masses'] + expected_n_atoms = 3 + expected_n_residues = 1 + expected_n_segments = 1 + + def test_dlp_names(self): + assert_array_equal(self.top.names.values, + ['C', 'B', 'A']) + + +class TestDLPConfigMinimal(DLPBase): + parser = mda.topology.DLPolyParser.ConfigParser + filename = DLP_CONFIG_minimal + format='CONFIG' + + +class TestDLPConfigOrder(DLPBase): + parser = mda.topology.DLPolyParser.ConfigParser + filename = DLP_CONFIG_order + format='CONFIG' + + +class TestDLPHistoryMinimal(DLPBase): + parser = mda.topology.DLPolyParser.HistoryParser + filename = DLP_HISTORY_minimal + format='HISTORY' + + +class TestDLPHistoryOrder(DLPBase): + parser = mda.topology.DLPolyParser.HistoryParser + filename = DLP_HISTORY_order + format='HISTORY' diff --git a/pool/shard002/Python/0025492_test_erfc_neuron.py b/pool/shard002/Python/0025492_test_erfc_neuron.py new file mode 100644 index 0000000000000000000000000000000000000000..4325ac1834fbcab7040b3c01552381aea5f0b582 --- /dev/null +++ b/pool/shard002/Python/0025492_test_erfc_neuron.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- +# +# test_erfc_neuron.py +# +# This file is part of NEST. +# +# Copyright (C) 2004 The NEST Initiative +# +# NEST 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. +# +# NEST 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 NEST. If not, see . + +""" +Test implementation of erfc-neuron. +""" + +import unittest +import nest +import numpy as np +from scipy.special import erfc + + +def get_mean_activity(detector, T): + """ + returns the mean activity of a single binary neuron connected to a spin + detector. + """ + states = nest.GetStatus(detector)[0]['events']['weights'] + times = nest.GetStatus(detector)[0]['events']['times'] + # add total duration at the end, since we need to take into account + # the time between the last state change and end of simulation + times = np.hstack((times, T)) + if len(times) > 1: + assert(states[0] == 1) + # since neuron is starting in 0 state, summing every second period + # will give us the total time in the up state + activity = np.sum(np.diff(times)[::2]) / (T - times[0]) + # if we have more than one update, we calculate a more accurate value + # for the mean activity, taking into account that our measurements are + # biased (we only record /given/ that a state change happened) + if len(times) > 2: + # biased average starting at down state, p(m(t)=1|m(t-1)=0) + M0 = 1. - (np.sum(np.diff(times)[1::2]) / (T - times[1])) + # biased average starting at up state, p(m(t)=1|m(t-1)=1) + M1 = activity + # unbiased estimate, + # p(m(t)=1)=\sum_{s \in {0,1}} p(m(t)=1|m(t-1)=s)p(m(t-1)=s), + # assuming stationary state: p(m(t)) = p(m(t-1)), solved for p(m=1) + activity = M0 / (1. + M0 - M1) + return activity + else: + return 0. + + +def activation_function_theory(sigma, theta): + """ + returns the probability for a binary neuron to be in the up state, given + the parameters sigma and theta. + """ + return 0.5 * erfc(theta / (np.sqrt(2.) * sigma)) + + +class ErfcNeuronTheoryTestCase(unittest.TestCase): + + """Compare results to theoretical predictions""" + + def setUp(self): + """defines parameters of simulation""" + self.sigma = np.logspace(-1, 1.1, 4) + self.theta = np.linspace(-6, 6, 15) + self.neuron = None + self.detector = None + self.T = 30000. + + def build_and_connect_nodes(self, sigma, theta): + """ sets up an erfc neuron and spin detector. """ + nest.hl_api.set_verbosity('M_WARNING') + nest.ResetKernel() + + self.neuron = nest.Create('erfc_neuron', 1, + {'sigma': sigma, 'theta': theta}) + self.detector = nest.Create('spin_detector', 1) + nest.Connect(self.neuron, self.detector) + + def test_activation_function(self): + """ + simulates erfc neuron for different parameter sets and compares + activity to theoretical value. + """ + for sigma in self.sigma: + for theta in self.theta: + self.build_and_connect_nodes(sigma, theta) + nest.Simulate(self.T) + mean_activity = get_mean_activity(self.detector, self.T) + mean_activity_theory = activation_function_theory(sigma, theta) + delta = np.max([2e-1 * mean_activity_theory * + (1. - + mean_activity_theory), + 1e-2]) + self.assertAlmostEqual( + mean_activity, + mean_activity_theory, + delta=delta) + + +def suite(): + suite1 = unittest.TestLoader().loadTestsFromTestCase( + ErfcNeuronTheoryTestCase) + return unittest.TestSuite([suite1]) + + +def run(): + runner = unittest.TextTestRunner(verbosity=2) + runner.run(suite()) + + +if __name__ == "__main__": + run() diff --git a/pool/shard002/Python/0025494_date9.py b/pool/shard002/Python/0025494_date9.py new file mode 100644 index 0000000000000000000000000000000000000000..a7a454e27f157aabc25a62520c72b41923b4f5a2 --- /dev/null +++ b/pool/shard002/Python/0025494_date9.py @@ -0,0 +1,121 @@ +#!/usr/bin/python3 + +days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] +days_in_months_leap_year = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] +months_names = ['January', 'February', 'March', 'April', 'May', 'June', + 'July', 'August', 'September', 'October', 'November', 'December'] +name_to_days_num = {} +for i in range(12): + name_to_days_num[months_names[i]] = days_in_months[i] + + +def get_num_of_days_in_month(month_name): + ''' Given a month name, + return the number of days in this month''' + if month_name in name_to_days_num: + return name_to_days_num[months_name] + else: + print('No such month') + + +def get_following_month(month_name): + ''' Given a month name, + return the name of the following month''' + if month_name in name_to_days_num: + i = months_names.index(month_name) + return months_names[(i + 1) % 12] + else: + print('No such month') + + +def is_leap_year(year): + ''' Return True if the year is a leap year, False otherwise''' + return year % 4 == 0 and year % 1000 != 0 + + +class Calendar: + + ''' A callender of events, has an entry for every event, + which is a mapping from event name to Date o bject''' + + def __init__(self): + self.events = {} + + def add_event(self, name, date): + ''' Add a new entry to the callender''' + self.events[name] = date + + def is_event(self, date): + ''' Check if the given date appears in the callender''' + return date in self.events.values() + + def get_date(self, name): + ''' Return the date of the given event name''' + return self.events[name] + + def get_all_events_in_month(self, month): + ''' Return a dictionary with all the events in the given month + month is the number of the month ''' + month_events = {} + for name in self.events.keys(): + if self.events[name].month == month: + month_events[name] = self.events[name] + + return month_events + + +class Date: + + def __init__(self, day, month, year): + if not isinstance(day, int) or not isinstance(month, int) or not isinstance(year, int): + print('Date must be initialized with numbers') + return + if month < 1 or month > 12: + print('Month must be between 1 and 12') + return + if is_leap_year(year): + if day < 0 or day > days_in_months_leap_year[month - 1]: + print('Day must be between 1 and ', days_in_months[month - 1]) + return + else: + if day < 0 or day > days_in_months[month - 1]: + print('Day must be between 1 and ', days_in_months[month - 1]) + return + self.day = day + self.month = month + self.year = year + + def __gt__(self, other): + ''' Overloading operator>for dates ''' + if self.year > other.year: + return True + elif self.year == other.year: + if self.month > other.month: + return True + elif self.month == other.month: + if self.day > other.day: + return True + return False + + def __lt__(self, other): + ''' Overloading operator self + + def __eq__(self, other): + ''' Overloading operator==for dates ''' + return self.year == other.year and self.month == other.month and self.day == other.day + + def __ne__(self, other): + ''' Overloading operator!=for dates ''' + return not (self == other) + + def __le__(self, other): + ''' Overloading operator<=for dates ''' + return self < other or self == other + + def __ge__(self, other): + ''' Overloading operator>=for dates ''' + return self > other or self == other + + def __str__(self): + return str(self.day) + '.' + str(self.month) + '.' + str(self.year) diff --git a/pool/shard002/Python/0025498_posix_utils.py b/pool/shard002/Python/0025498_posix_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c69fa6fb642c1a2848fde266dd0da40c27324ac0 --- /dev/null +++ b/pool/shard002/Python/0025498_posix_utils.py @@ -0,0 +1,97 @@ +from __future__ import unicode_literals + +from codecs import getincrementaldecoder +import os +import six +import select + +__all__ = [ + 'PosixStdinReader', +] + + +class PosixStdinReader(object): + """ + Wrapper around stdin which reads (nonblocking) the next available 1024 + bytes and decodes it. + + Note that you can't be sure that the input file is closed if the ``read`` + function returns an empty string. When ``errors=ignore`` is passed, + ``read`` can return an empty string if all malformed input was replaced by + an empty string. (We can't block here and wait for more input.) So, because + of that, check the ``closed`` attribute, to be sure that the file has been + closed. + + :param stdin_fd: File descriptor from which we read. + :param errors: Can be 'ignore', 'strict' or 'replace'. + On Python3, this can be 'surrogateescape', which is the default. + + 'surrogateescape' is preferred, because this allows us to transfer + unrecognised bytes to the key bindings. Some terminals, like lxterminal + and Guake, use the 'Mxx' notation to send mouse events, where each 'x' + can be any possible byte. + """ + # By default, we want to 'ignore' errors here. The input stream can be full + # of junk. One occurrence of this that I had was when using iTerm2 on OS X, + # with "Option as Meta" checked (You should choose "Option as +Esc".) + + def __init__(self, stdin_fd, + errors=('ignore' if six.PY2 else 'surrogateescape')): + assert isinstance(stdin_fd, int) + self.stdin_fd = stdin_fd + self.errors = errors + + # Create incremental decoder for decoding stdin. + # We can not just do `os.read(stdin.fileno(), 1024).decode('utf-8')`, because + # it could be that we are in the middle of a utf-8 byte sequence. + self._stdin_decoder_cls = getincrementaldecoder('utf-8') + self._stdin_decoder = self._stdin_decoder_cls(errors=errors) + + #: True when there is nothing anymore to read. + self.closed = False + + def read(self, count=1024): + # By default we choose a rather small chunk size, because reading + # big amounts of input at once, causes the event loop to process + # all these key bindings also at once without going back to the + # loop. This will make the application feel unresponsive. + """ + Read the input and return it as a string. + + Return the text. Note that this can return an empty string, even when + the input stream was not yet closed. This means that something went + wrong during the decoding. + """ + if self.closed: + return u'' + + # Check whether there is some input to read. `os.read` would block + # otherwise. + # (Actually, the event loop is responsible to make sure that this + # function is only called when there is something to read, but for some + # reason this happens in certain situations.) + try: + if not select.select([self.stdin_fd], [], [], 0)[0]: + return u'' + except IOError: + # Happens for instance when the file descriptor was closed. + # (We had this in ptterm, where the FD became ready, a callback was + # scheduled, but in the meantime another callback closed it already.) + self.closed = True + + # Note: the following works better than wrapping `self.stdin` like + # `codecs.getreader('utf-8')(stdin)` and doing `read(1)`. + # Somehow that causes some latency when the escape + # character is pressed. (Especially on combination with the `select`.) + try: + data = os.read(self.stdin_fd, count) + + # Nothing more to read, stream is closed. + if data == b'': + self.closed = True + return '' + except OSError: + # In case of SIGWINCH + data = b'' + + return self._stdin_decoder.decode(data) diff --git a/pool/shard002/Python/0025501_settings.py b/pool/shard002/Python/0025501_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..cc2c62e99893eb4b1c577929db0c1aaabbdc1856 --- /dev/null +++ b/pool/shard002/Python/0025501_settings.py @@ -0,0 +1,185 @@ +# +# Copyright (c) 2013 Big Switch Networks, Inc. +# +# Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html +# +# 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. +# + +# Django settings for sdncon project. + +import os, sys +from cassandra.ttypes import ConsistencyLevel + +DEBUG = True +DEBUG_PROPAGATE_EXCEPTIONS = DEBUG +TEMPLATE_DEBUG = DEBUG + +ADMINS = ( + # ('Your Name', 'your_email@domain.com'), +) + +MANAGERS = ADMINS + +DATABASES = { + 'default': { + 'ENGINE': 'django_cassandra.db', + 'NAME': 'sdncon', + 'USER': '', # Not used with sqlite3. + 'PASSWORD': '', # Not used with sqlite3. + 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. + 'PORT': '', # Set to empty string for default. Not used with sqlite3. + } +} + +# Settings for accessing the stats database/keyspace. +# This does not go through the usual Django model/database layer, but +# instead accesses Cassandra directly. +STATS_DATABASE = { + 'NAME': 'sdnstats', + #'HOST': '', + #'USER': '', + #'PASSWORD': '', + #'CASSANDRA_REPLICATION_FACTOR': 1 +} + +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# On Unix systems, a value of None will cause Django to use the same +# timezone as the operating system. +# If running in a Windows environment this must be set to the same as your +# system time zone. +#TIME_ZONE = 'America/Los_Angeles' +TIME_ZONE = None + +# Language code for this installation. All choices can be found here: +# http://www.i18nguy.com/unicode/language-identifiers.html +LANGUAGE_CODE = 'en-us' + +SITE_ID = '1' + +# Tell Django where is the profile object +#AUTH_PROFILE_MODULE = "sdncon.account.UserProfile" + +# If you set this to False, Django will make some optimizations so as not +# to load the internationalization machinery. +USE_I18N = True + +# If you set this to False, Django will not format dates, numbers and +# calendars according to the current locale +USE_L10N = True + +# Absolute path to the directory that holds media. +# Example: "/home/media/media.lawrence.com/" +SDN_ROOT = "/opt/sdnplatform" if not 'SDN_ROOT' in os.environ else os.environ['SDN_ROOT'] +MEDIA_ROOT = "%s/con/lib/python/django/contrib/admin/media/" % SDN_ROOT + +# URL that handles the media served from MEDIA_ROOT. Make sure to use a +# trailing slash if there is a path component (optional in other cases). +# Examples: "http://media.lawrence.com", "http://example.com/media/" +MEDIA_URL = '' +STATIC_URL = '/static/' + +# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a +# trailing slash. +# Examples: "http://foo.com/media/", "/media/". +ADMIN_MEDIA_PREFIX = '/media/' + +# URL prefixes exempted from login requirements +EXEMPT_URLS = ['/coreui/static/', '/coreui/img/', '/favicon.ico'] + +# Make this unique, and don't share it with anybody. +SECRET_KEY = 'p+7!f6@8ry2%faunco@u@$wzq7_jpyw4w7+sn=&xpuvo%2!uw(' + +# List of callables that know how to import templates from various sources. +TEMPLATE_LOADERS = ( + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', +# 'django.template.loaders.eggs.Loader', +) + +from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as GLOBAL_TEMPLATE_CONTEXT_PROCESSORS +TEMPLATE_CONTEXT_PROCESSORS = GLOBAL_TEMPLATE_CONTEXT_PROCESSORS + ( + 'sdncon.clusterAdmin.utils.uicontext', +) + +MIDDLEWARE_CLASSES = ( + 'sdncon.HARedirectMiddleWare', + 'django.middleware.common.CommonMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'sdncon.clusterAdmin.middleware.ClusterAuthenticate', + 'sdncon.clusterAdmin.middleware.RequireAuthMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'sdncon.SDNConAppLoaderMiddleWare', +) + +# Django uses browser-length cookies that expire as soon as the user closes the browser. +SESSION_EXPIRE_AT_BROWSER_CLOSE = True +SESSION_COOKIE_AGE = 2592000 # 30 days, in seconds + +ROOT_URLCONF = 'sdncon.urls' + +TEMPLATE_DIRS = ( + # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". + # Always use forward slashes, even on Windows. + # Don't forget to use absolute paths, not relative paths. + os.path.dirname(__file__), + os.path.join(os.path.dirname(__file__),'clusterAdmin/templates'), +) + +# Include applications dynamically from the apps folder + +APP_DIR = os.path.join(os.path.dirname(__file__),'apps') +sys.path.append(APP_DIR) + +apps_array = [ + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.staticfiles', + #'django.contrib.sites', + 'django.contrib.messages', + # Uncomment the next line to enable the admin: + 'django.contrib.admin', + 'djangotoolbox', + 'sdncon.rest', + 'sdncon.controller', + 'django_cassandra', + 'sdncon.coreui', + 'sdncon.clusterAdmin', + #'sdncon.account', + 'sdncon.ui', + 'sdncon.stats', + 'sdncon.syncd', + 'sdncon.statdropd' +] + +directory = os.listdir(APP_DIR) +for filename in directory: + if not filename.startswith('.'): + apps_array.append(os.path.basename(filename)) + +INSTALLED_APPS = tuple(apps_array) + +STATS_METADATA_MODULES = [] + +_stats_meatadata_dir_name = 'stats_metadata' +_stats_metadata_dir = os.path.join(os.path.dirname(__file__), _stats_meatadata_dir_name) +_directory = os.listdir(_stats_metadata_dir) + +for _filename in _directory: + _basename = os.path.basename(_filename) + if _basename.endswith('.py') and _basename != '__init__.py': + _module_name = os.path.splitext(_basename)[0] + STATS_METADATA_MODULES.append('sdncon.%s.%s' % (_stats_meatadata_dir_name, _module_name)) diff --git a/pool/shard002/Python/0025516_settings.py b/pool/shard002/Python/0025516_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..eb3b9e03afd340d4c37aca8dac969ddbd56a3a84 --- /dev/null +++ b/pool/shard002/Python/0025516_settings.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python +# -*- coding: UTF-8 -*- +# vim: set fileencoding=utf-8 +# Run as root + +''' + This script allows to configure latch settings (application id and secret key) + Copyright (C) 2013 Eleven Paths + + 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 +''' + + +import sys +from latchHelper import * + +if len(sys.argv) == 3 and sys.argv[1] == "-f": + secret_key = getConfigParameter("secret_key", sys.argv[2]) + app_id = getConfigParameter("app_id", sys.argv[2]) + if app_id == None or secret_key == None: + print("Can't read config file"); + exit() + + replaceConfigParameters(app_id, secret_key) + +elif len(sys.argv) != 1: + print("use 'settings.py -f '") + exit() diff --git a/pool/shard002/Python/0025523_list.py b/pool/shard002/Python/0025523_list.py new file mode 100644 index 0000000000000000000000000000000000000000..d1d90df1af5dfe07659f3ba0eb4b3d8fe56d6ac9 --- /dev/null +++ b/pool/shard002/Python/0025523_list.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# This file is part of Shoop. +# +# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. +# +# This source code is licensed under the AGPLv3 license found in the +# LICENSE file in the root directory of this source tree. +from __future__ import unicode_literals + +from django.utils.translation import ugettext_lazy as _ + +from shoop.admin.utils.picotable import ( + Column, TextFilter, true_or_false_filter +) +from shoop.admin.utils.views import PicotableListView +from shoop.core.models import CustomerTaxGroup, Tax, TaxClass +from shoop.utils.i18n import format_percent + + +def _format_rate(tax_rule): + if tax_rule.rate is None: + return "" + return format_percent(tax_rule.rate, digits=3) + + +class TaxListView(PicotableListView): + model = Tax + + columns = [ + Column( + "name", _("Name"), sort_field="translations__name", + filter_config=TextFilter( + filter_field="translations__name", + placeholder=_("Filter by name..."), + ), + ), + Column("code", _(u"Code")), + Column("rate", _("Rate"), display=_format_rate), + # Column("amount", _(u"Amount")), + Column("enabled", _(u"Enabled"), filter_config=true_or_false_filter), + ] + + +class CustomerTaxGroupListView(PicotableListView): + model = CustomerTaxGroup + + columns = [ + Column( + "name", _("Name"), sort_field="translations__name", + filter_config=TextFilter( + filter_field="translations__name", + placeholder=_("Filter by name..."), + ), + ), + ] + + +class TaxClassListView(PicotableListView): + model = TaxClass + + columns = [ + Column( + "name", _("Name"), sort_field="translations__name", + filter_config=TextFilter( + filter_field="translations__name", + placeholder=_("Filter by name..."), + ), + ), + ] diff --git a/pool/shard002/Python/0025524_settings.py b/pool/shard002/Python/0025524_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..db072ad36f7873cce1958a56945f482c0e0d73e8 --- /dev/null +++ b/pool/shard002/Python/0025524_settings.py @@ -0,0 +1,32 @@ +## Copyright 2013 Luc Saffre +## This file is part of the Lino project. + +from lino.projects.std.settings import * + + +class Site(Site): + + demo_fixtures = "std demo demo2" + languages = 'en' + + def get_installed_apps(self): + + yield super(Site, self).get_installed_apps() + + yield 'lino.modlib.gfks' + yield 'lino.modlib.system' + yield 'lino.modlib.users' + yield 'lino.modlib.changes' + + yield 'lino_xl.lib.countries' + yield 'lino_xl.lib.contacts' + #~ yield 'lino_xl.lib.notes' + + yield 'workflows_tutorial' + + def setup_menu(self, profile, main): + m = main.add_menu("entries", _("Entries")) + m.add_action(MyEntries) + +SITE = Site(globals()) + diff --git a/pool/shard002/Python/0025525_parent.py b/pool/shard002/Python/0025525_parent.py new file mode 100644 index 0000000000000000000000000000000000000000..f307bda5e3fc010088f2999a9ce95c5f2331390f --- /dev/null +++ b/pool/shard002/Python/0025525_parent.py @@ -0,0 +1,194 @@ +# +# Copyright (c) 2016 Red Hat, Inc. +# +# This software is licensed to you under the GNU Lesser General Public +# License as published by the Free Software Foundation; either version +# 2 of the License (LGPLv2) or (at your option) any later version. +# There is NO WARRANTY for this software, express or implied, +# including the implied warranties of MERCHANTABILITY, +# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should +# have received a copy of LGPLv2 along with this software; if not, see +# http://www.gnu.org/licenses/old-licenses/lgpl-2.0.txt. +# +# Jeff Ortel +# + +from logging import getLogger +from time import sleep + +from gofer.mp import Process, Pipe +from gofer.common import Thread +from gofer.rmi.context import Context +from gofer.rmi.model import protocol +from gofer.rmi.model.child import Call as Target + + +log = getLogger(__file__) + + +POLL = 0.10 + + +class Call(protocol.Call): + """ + The parent-side of the RMI call invoked in a child process. + After the fork, the child invokes the method and relays events + back using the inter-process queue. + """ + + def __call__(self): + """ + Invoke the RMI as follows: + - Fork + - Start the monitor. + - Read and dispatch reply messages. + :return: Whatever method returned. + """ + pipe = Pipe() + target = Target(self.method, *self.args, **self.kwargs) + child = Process(target, pipe) + monitor = Monitor(Context.current(), child) + try: + child.start() + monitor.start() + pipe.writer.close() + retval = self.read(pipe.reader) + return retval + finally: + pipe.close() + monitor.stop() + child.wait() + + def read(self, pipe): + """ + Read the reply queue and dispatch messages until *End* is raised.. + :param pipe: A message queue. + :type pipe: gofer.mp.Reader + """ + while True: + try: + reply = protocol.Reply.read(pipe) + reply() + except protocol.End as end: + return end.result + + +class Monitor(Thread): + """ + Provides monitoring of cancellation. + When cancel is detected, the child process is terminated. + :ivar context: The RMI context. + :type context: Context + :ivar child: The child process. + :type child: Process + :ivar poll: Main polling loop boolean. + :type poll: bool + """ + + NAME = 'monitor' + POLL = 0.10 + + def __init__(self, context, child): + """ + :param context: The RMI context. + :type context: Context + :param child: The child process. + :type child: Process + """ + super(Monitor, self).__init__(name=Monitor.NAME) + self.context = context + self.child = child + self.poll = True + self.setDaemon(True) + + def stop(self): + """ + Stop the thread. + """ + self.poll = False + self.join() + + def run(self): + """ + Test for cancellation. + When cancel is detected, the child process is terminated. + """ + while self.poll: + if self.context.cancelled(): + self.child.terminate() + break + else: + sleep(Monitor.POLL) + + +class Result(protocol.Result): + """ + Called when a RESULT message is received. + """ + + def __call__(self): + """ + :raise End: always. + """ + raise protocol.End(self.payload) + + +class Progress(protocol.Progress): + """ + Called when a PROGRESS message is received. + """ + + def __call__(self): + """ + Relay to RMI context progress reporter. + """ + context = Context.current() + context.progress.__dict__.update(self.payload.__dict__) + context.progress.report() + + +class Error(protocol.Error): + """ + Called when a ERROR message is received. + """ + + def __call__(self): + """ + An exception is raised to report the error. + :raise Exception: always. + """ + raise Exception(self.payload) + + +class Raised(protocol.Raised): + """ + Called when a RAISED (exception) message is received. + """ + + def __call__(self): + """ + The reported exception is instantiated and raised. + :raise Exception: always. + """ + raise self.payload + + +class Ping(protocol.Ping): + """ + Called when a PING message is received. + """ + + def __call__(self): + """ + The reported exception is instantiated and raised. + :raise Exception: always. + """ + log.debug('pinged by %d', self.payload) + + +# register reply message handling. +protocol.Reply.register(Result.CODE, Result) +protocol.Reply.register(Progress.CODE, Progress) +protocol.Reply.register(Error.CODE, Error) +protocol.Reply.register(Raised.CODE, Raised) +protocol.Reply.register(Ping.CODE, Ping) diff --git a/pool/shard002/Python/0025532_init__.py b/pool/shard002/Python/0025532_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c3b7c00bbe41313142f861234e1170e41e02c90 --- /dev/null +++ b/pool/shard002/Python/0025532_init__.py @@ -0,0 +1,87 @@ +# MIT License +# +# Copyright (c) 2017 Changsung +# +# 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. + +class BaseStrategy: + ''' class for strategy. + write an algorithm in this class''' + + __signals = {} + + def __init__(self): + pass + + def addSignals(self, key, signal): + self.__signals[key] = signal + signal.setStrategy(self) + + def getSignal(self, key): + return self.__signals[key].getSignal() + + def handleData(self): + raise NotImplementedError() + + def setAlphaman(self, alphaman): + self.__alphaman = alphaman + + def buy(self, instrument, volume, limit_price=None, stop_price=None, days=None): + self.__alphaman.buy(instrument, volume, limit_price, stop_price, days) + + def sell(self, instrument, volume, limit_price=None, stop_price=None, days=None): + self.__alphaman.sell(instrument, volume, limit_price, stop_price, days) + + def orderTarget(self, instrument, percentage, limit_price=None, stop_price=None, days=None): + self.__alphaman.orderTarget(instrument, percentage, limit_price, stop_price, days) + + def getSchedules(self): + return self.__alphaman.getSchedules() + + def getFeed(self): + return self.__alphaman.getFeed() + + def get(self, instrument, key, date_idx): + # assert to only access to previous data + feed = self.getFeed() + if isinstance(date_idx, int): + assert(date_idx <= 0) + today_idx = self.__alphaman.getTodayIdx() + date_idx + if today_idx < 0: + today_idx = 0 + try: + return feed.getDailyInstrumentData(today_idx, instrument).getBarData(key) + except KeyError: + return feed.getDailyInstrumentData(today_idx, instrument).getExtraData(key) + elif isinstance(date_idx, list): + assert(date_idx[-1] <= 0) + today_idx_list = map(lambda x: x+self.__alphaman.getTodayIdx(), date_idx) + #today_idx_list = list(set(today_idx_list)).sort() + data_list = [] + for today_idx in today_idx_list: + if today_idx < 0: + continue + try: + data_list.append(feed.getDailyInstrumentData(today_idx, instrument).getBarData(key)) + except KeyError: + data_list.append(feed.getDailyInstrumentData(today_idx, instrument).getExtraData(key)) + return data_list + else: + raise Exception('date_idx must be int or list of int') + diff --git a/pool/shard002/Python/0025536_test_Ebsd.py b/pool/shard002/Python/0025536_test_Ebsd.py new file mode 100644 index 0000000000000000000000000000000000000000..4baffed7cff6695b61311c494eb46ba28d1b1b49 --- /dev/null +++ b/pool/shard002/Python/0025536_test_Ebsd.py @@ -0,0 +1,29 @@ +import unittest +import numpy as np +from pymicro.crystal.ebsd import OimScan, OimPhase +from pymicro.crystal.microstructure import Orientation + + +class EbsdTests(unittest.TestCase): + + def setUp(self): + print('testing the OimScan class') + # create a test EBSD scan + self.scan = OimScan((10, 10)) + phase = OimPhase(1) + self.scan.phase_list.append(phase) + # populate the euler field with 4 random grains + for i in range(2): + for j in range(2): + o = Orientation.random() + phi1, Phi, phi2 = np.radians(o.euler) + self.scan.euler[i * 5:(i + 1) * 5, j * 5:(j + 1) * 5, 0] = phi1 + self.scan.euler[i * 5:(i + 1) * 5, j * 5:(j + 1) * 5, 1] = Phi + self.scan.euler[i * 5:(i + 1) * 5, j * 5:(j + 1) * 5, 2] = phi2 + self.scan.ci = 1.0 # mark all pixels as good + self.scan.euler.shape + + def test_segment_grains(self): + grain_ids = self.scan.segment_grains() + n = len(np.unique(grain_ids)) + self.assertEqual(n, 4) diff --git a/pool/shard002/Python/0025543_importer.py b/pool/shard002/Python/0025543_importer.py new file mode 100644 index 0000000000000000000000000000000000000000..45401f4b425dbcbe7456aabe6669d07a034c0309 --- /dev/null +++ b/pool/shard002/Python/0025543_importer.py @@ -0,0 +1,93 @@ +''' +Imports a book from files in a directory (the source_path) +Expects the following structure: + title.txt with yaml metadata + 01-somename.md (or .markdown) + 02-someothername.md (or .markdown) + +Note that everything left of and including the first occurance of "-" will be +removed from the filename. +For now the title of the book is the name of the directory. + +''' +import os +import os.path +import yaml +import json +import pypandoc +from jinja2 import Environment, FileSystemLoader + +from bookhelper.utils import on_no_errors +from . import SiteAction +from .create import CreateAction + + +class ImportAction(SiteAction): + '''Makes a book from files in conf.sourcepath (if valid)''' + + def validate(self): + spath = getattr(self.conf, 'source_path', None) + if spath.endswith('/'): + spath = spath[:-1] + if not spath: + self.errors.append("No sourcecpath given") + + elif not os.path.isdir(spath): + self.errors.append("%s is not a directory" % spath) + + elif not os.path.isfile(os.path.join(spath, 'title.txt')): + self.errors.append( + "%s not found" % (os.path.join(spath, 'title.txt'))) + + self.source_path = spath + self.title = os.path.basename(os.path.abspath(self.source_path)) + + @on_no_errors + def mk_pages(self): + env = Environment(loader=FileSystemLoader(searchpath=self.source_path)) + templatenames = sorted(env.list_templates("md")) + vars_dict = {} + try: + with open(os.path.join(self.source_path, "vars.json")) as vars_json: + vars_dict = json.load(vars_json) + except Exception as e: + import sys + sys.exit(e) + pass + + self.pagesdata = [] + for templatename in templatenames: + template = env.get_template(templatename) + md = template.render(vars_dict) + body = pypandoc.convert(md, "mediawiki", format="md") + title = templatename.split("-", maxsplit=1)[-1] # rm "01-" ... + title = title.rsplit(".", maxsplit=1)[0] # rm filetype + p = { + 'title': title, + 'body': body + } + self.pagesdata.append(p) + + @on_no_errors + def mk_info(self): + with open(os.path.join(self.source_path, 'title.txt')) as f: + self.infodata = yaml.safe_load(f) + + @on_no_errors + def create(self): + self.conf.json_source = json.dumps({ + 'title': self.title, + 'pages': self.pagesdata, + 'info': self.infodata + }) + + ca = CreateAction(self.conf) + ca.validate() + ca.run() + self.errors += ca.errors + + def run(self): + self.validate() + self.mk_pages() + self.mk_info() + self.create() diff --git a/pool/shard002/Python/0025544_init__.py b/pool/shard002/Python/0025544_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..348f4b5ad53a8baba6b40bfdf9eb872947cb4503 --- /dev/null +++ b/pool/shard002/Python/0025544_init__.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python +# +# Greek New Testament +# Copyright (C) 2010 Honza Pokorny +# +# 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 sqlite3 +import config + +books = { + '1 Corinthians': 'cor1', + '1 John': 'john1', + '1 Peter': 'peter1', + '1 Thessalonians': 'thess1', + '1 Timothy': 'tim1', + '2 Corinthians': 'cor2', + '2 John': 'john2', + '2 Peter': 'peter2', + '2 Thessalonians': 'thess2', + '2 Timothy': 'tim2', + '3 John': 'john3', + 'Acts': 'acts', + 'Colossians': 'col', + 'Ephesians': 'eph', + 'Galatians': 'gal', + 'Hebrews': 'heb', + 'James': 'james', + 'John': 'john', + 'Jude': 'jude', + 'Luke': 'luke', + 'Mark': 'mark', + 'Matthew': 'matthew', + 'Philemon': 'phm', + 'Phillipians': 'phil', + 'Revelation': 'revelation', + 'Romans': 'romans', + 'Titus': 'titus' +} + +class LookUp: + + def __init__(self): + self.connection = sqlite3.connect(config.db_name) + self.cursor = self.connection.cursor() + self.passage = '' + + def set_passage(self, passage): + self.passage = self.extract_passage(passage) + + def extract_passage(self, passage): + # 1 Cor 5:21 Luke 12:11 + result = [] + pieces = passage.split(" ") + numbers = '' + + if len(pieces) == 2: + result.append(pieces[0]) + numbers = pieces[1] + elif len(pieces) == 3: + numbers = pieces[2] + name = [] + name.append(pieces[0]) + name.append(pieces[1]) + space = ' ' + long_book = space.join(name) + result.append(long_book) + + n_pieces = numbers.split(":") + result.append(n_pieces[0]) + result.append(n_pieces[1]) + + return result + + def get_passage(self): + return self.passage + + def get_db_name_for_book(self, book): + if book in books: + return books[book] + else: + return book + + + def get_verse(self): + book = str(self.get_db_name_for_book(self.passage[0])) + chapter = self.passage[1] + verse = self.passage[2] + t = (chapter, verse,) + m = self.cursor.execute('select * from ' + book + ' where chapter=? and verse=?', t) + space = ' ' + words = [] + for a in m: + words.append(a[2]) + + result = space.join(words) + return result + + def get_words(self): + print 'get words...' + book = str(self.get_db_name_for_book(self.passage[0])) + chapter = self.passage[1] + verse = self.passage[2] + t = (chapter, verse,) + print t + m = self.cursor.execute('select * from ' + book + ' where chapter=? and verse=?', t) + + words = [] + for a in m: + words.append(a) + return words + + def get_hint(self): + words = self.get_words() + space = ' ' + new_words = [] + for word in words: + definition = self.get_definition(word[4]) + st = str(word[2]) + ': ' + str(definition) + '\n----------------\n' + new_words.append(st) + + result = space.join(new_words) + return result + + def get_definition(self, number): + t = (number,) + m = self.cursor.execute('select * from strong where number=?', t) + for a in m: + return a[1] + + + diff --git a/pool/shard002/Python/0025545_dyndns.py b/pool/shard002/Python/0025545_dyndns.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a9b57bf7e78862416cd6b0de2e9b3ecabf1a7c --- /dev/null +++ b/pool/shard002/Python/0025545_dyndns.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +""" +dyndns.py -- Dynamic DNS for Linode +Copyright 2011 Michael S. Yanovich + +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 . + + +This script is a dynamic dns script for Linode. Simply provide the +appropriate command line arguments and it will update the IP address in +Linode's Domain Manager. +""" + +import argparse +import api +import sys +import urllib2 + +def getip(): + u = urllib2.urlopen("http://yano.me/ip/") + ip = u.read().rstrip().lstrip() + u.close() + return ip + +def updateip(apikey, domain_name, subdomain, port, domain_type): + if port == None: + port = 22 + if domain_type == None: + domain_type = "A" + + FLAG = True + linode = api.Api(apikey) + domains = linode.domain_list() + + for domain in domains: + if domain["DOMAIN"] == domain_name: + did = domain["DOMAINID"] + + for each in linode.domain_resource_list(DomainID=did): + if each["NAME"] == subdomain: + FLAG = False + resource_id = each["RESOURCEID"] + + ## grab IP address + ip = getip() + if FLAG == True: + a = linode.domain_resource_create(Port=port, DomainID=did, + Type=domain_type, Name=subdomain, Target=ip) + else: + a = linode.domain_resource_update(Port=port, DomainID=did, + ResourceID=resource_id, Target=ip) + + +def main(): + desc = "This script is a Dynamic DNS updater for Linode." + + parser = argparse.ArgumentParser(description=desc) + parser.add_argument('-p', type=int, dest='port', + help='specifies the port number') + parser.add_argument('-ak', action='store', dest='apikey', + required=True, help='specifies the api key') + parser.add_argument('-dt', action='store', dest='domain_type', + help='specifies the domain type') + parser.add_argument('-dn', action='store', dest='domain_name', + required=True, help='specifies the domain name') + parser.add_argument('-sd', action='store', dest='subdomain', + required=True, help='specifies the subdomain') + results = parser.parse_args() + + updateip(results.apikey, results.domain_name, results.subdomain, + results.port, results.domain_type) + +if __name__ == '__main__': + main() diff --git a/pool/shard002/Python/0025549_whiteboard.py b/pool/shard002/Python/0025549_whiteboard.py new file mode 100644 index 0000000000000000000000000000000000000000..bb495ce5a9fa2258b941d1affce4f815e8516708 --- /dev/null +++ b/pool/shard002/Python/0025549_whiteboard.py @@ -0,0 +1,119 @@ +# -*- coding: utf-8 -*- +# +# Copyright © 2012 - 2016 Michal Čihař +# +# This file is part of Weblate +# +# 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 . +# + +"""Whiteboard model.""" + +from django.db import models +from django.db.models import Q +from django.utils.translation import ugettext_lazy, ugettext as _ +from django.utils.encoding import python_2_unicode_compatible +from django.core.exceptions import ValidationError +from weblate.lang.models import Language + + +class WhiteboardManager(models.Manager): + def context_filter(self, project=None, subproject=None, language=None): + """Filters whiteboard messages by context.""" + base = self.all() + + if language and project is None and subproject is None: + return base.filter( + project=None, subproject=None, language=language + ) + + if project: + return base.filter(Q(project=project) & Q(subproject=None)) + + if subproject: + if language: + return base.filter( + Q(language=language) | + Q(subproject=subproject) | + Q(project=subproject.project) + ) + + return base.filter( + Q(subproject=subproject) | Q(project=subproject.project) + ) + + # All are None + return base.filter( + project=None, subproject=None, language=None + ) + + +@python_2_unicode_compatible +class WhiteboardMessage(models.Model): + message = models.TextField( + verbose_name=ugettext_lazy('Message'), + ) + + project = models.ForeignKey( + 'Project', + verbose_name=ugettext_lazy('Project'), + null=True, + blank=True, + ) + subproject = models.ForeignKey( + 'SubProject', + verbose_name=ugettext_lazy('Component'), + null=True, + blank=True + ) + language = models.ForeignKey( + Language, + verbose_name=ugettext_lazy('Language'), + null=True, + blank=True + ) + category = models.CharField( + max_length=25, + verbose_name=ugettext_lazy('Category'), + help_text=ugettext_lazy( + 'Category defines color used for the message.' + ), + choices=( + ('info', ugettext_lazy('Info (light blue)')), + ('warning', ugettext_lazy('Warning (yellow)')), + ('danger', ugettext_lazy('Danger (red)')), + ('success', ugettext_lazy('Success (green)')), + ('primary', ugettext_lazy('Primary (dark blue)')), + ), + default='info', + ) + + objects = WhiteboardManager() + + class Meta(object): + app_label = 'trans' + verbose_name = ugettext_lazy('Whiteboard message') + verbose_name_plural = ugettext_lazy('Whiteboard messages') + + def __str__(self): + return self.message + + def clean(self): + if self.project and self.subproject: + if self.subproject.project != self.project: + raise ValidationError( + _('Do not specify both component and project!') + ) + if not self.project and self.subproject: + self.project = self.subproject.project diff --git a/pool/shard002/Python/0025550_pyplots.py b/pool/shard002/Python/0025550_pyplots.py new file mode 100644 index 0000000000000000000000000000000000000000..f74e1e656593dbb143fc695d6f329f916b27d1a0 --- /dev/null +++ b/pool/shard002/Python/0025550_pyplots.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- + +# Copyright © 2012-2015 Roberto Alsina and others. + +# 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. + +from hashlib import md5 +import io +import os + +from docutils import nodes +from docutils.parsers.rst import directives +from docutils.parsers.rst.directives import images + +try: + import matplotlib + import matplotlib._pylab_helpers + import matplotlib.pyplot as plt +except ImportError: + matplotlib = None + +from nikola.plugin_categories import RestExtension +from nikola.utils import req_missing, makedirs + +_site = None + + +class Plugin(RestExtension): + + name = "pyplots" + + def set_site(self, site): + global _site + _site = self.site = site + directives.register_directive('plot', PyPlot) + PyPlot.out_dir = os.path.join(site.config['OUTPUT_FOLDER'], 'pyplots') + return super(Plugin, self).set_site(site) + + +pyplot_spec = images.Image.option_spec +pyplot_spec['include-source'] = directives.flag + + +class PyPlot(images.Image): + """ Reimplementation of http://matplotlib.org/sampledoc/extensions.html#inserting-matplotlib-plots.""" + + has_content = True + option_spec = pyplot_spec + optional_arguments = 1 + required_arguments = 0 + + def run(self): + if matplotlib is None: + msg = req_missing(['matplotlib'], 'use the plot directive', optional=True) + return [nodes.raw('', '
{0}
'.format(msg), format='html')] + + if not self.arguments and not self.content: + raise self.error('The plot directive needs either an argument or content.') + + if self.arguments and self.content: + raise self.error('The plot directive needs either an argument or content, not both.') + + if self.arguments: + plot_path = self.arguments[0] + with io.open(plot_path, encoding='utf-8') as fd: + data = fd.read() + elif self.content: + data = '\n'.join(self.content) + plot_path = md5(data).hexdigest() + + # Always reset context + plt.close('all') + matplotlib.rc_file_defaults() + # Run plot + exec(data) + + out_path = os.path.join(self.out_dir, plot_path + '.svg') + plot_url = '/' + os.path.join('pyplots', plot_path + '.svg').replace(os.sep, '/') + + figures = [manager.canvas.figure for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()] + for figure in figures: + makedirs(os.path.dirname(out_path)) + figure.savefig(out_path, format='svg') # Yes, if there's more than one, it's overwritten, sucks. + self.arguments = [plot_url] + return super(PyPlot, self).run() diff --git a/pool/shard002/Python/0025554_eval_metric.py b/pool/shard002/Python/0025554_eval_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..1fcdc1c1fa93c16e27697f4c7dbf5974b6252681 --- /dev/null +++ b/pool/shard002/Python/0025554_eval_metric.py @@ -0,0 +1,80 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse + +import mmcv +from mmcv import Config, DictAction + +from mmdet.datasets import build_dataset + + +def parse_args(): + parser = argparse.ArgumentParser(description='Evaluate metric of the ' + 'results saved in pkl format') + parser.add_argument('config', help='Config of the model') + parser.add_argument('pkl_results', help='Results in pickle format') + parser.add_argument( + '--format-only', + action='store_true', + help='Format the output results without perform evaluation. It is' + 'useful when you want to format the result to a specific format and ' + 'submit it to the test server') + parser.add_argument( + '--eval', + type=str, + nargs='+', + help='Evaluation metrics, which depends on the dataset, e.g., "bbox",' + ' "segm", "proposal" for COCO, and "mAP", "recall" for PASCAL VOC') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--eval-options', + nargs='+', + action=DictAction, + help='custom options for evaluation, the key-value pair in xxx=yyy ' + 'format will be kwargs for dataset.evaluate() function') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + + cfg = Config.fromfile(args.config) + assert args.eval or args.format_only, ( + 'Please specify at least one operation (eval/format the results) with ' + 'the argument "--eval", "--format-only"') + if args.eval and args.format_only: + raise ValueError('--eval and --format_only cannot be both specified') + + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + cfg.data.test.test_mode = True + + dataset = build_dataset(cfg.data.test) + outputs = mmcv.load(args.pkl_results) + + kwargs = {} if args.eval_options is None else args.eval_options + if args.format_only: + dataset.format_results(outputs, **kwargs) + if args.eval: + eval_kwargs = cfg.get('evaluation', {}).copy() + # hard-code way to remove EvalHook args + for key in [ + 'interval', 'tmpdir', 'start', 'gpu_collect', 'save_best', + 'rule' + ]: + eval_kwargs.pop(key, None) + eval_kwargs.update(dict(metric=args.eval, **kwargs)) + print(dataset.evaluate(outputs, **eval_kwargs)) + + +if __name__ == '__main__': + main() diff --git a/pool/shard002/Python/0025560_addr.py b/pool/shard002/Python/0025560_addr.py new file mode 100644 index 0000000000000000000000000000000000000000..a4370b550e5e0e21b546fa8ce663c6239bd24397 --- /dev/null +++ b/pool/shard002/Python/0025560_addr.py @@ -0,0 +1,88 @@ +# Copyright 2014-2017 Red Hat, 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 +# +# Refer to the README and COPYING files for full details of the license +# + +from __future__ import absolute_import +from __future__ import division +from functools import partial +import errno + +from . import _cache_manager +from . import _pool +from . import libnl +from .link import _nl_link_cache, _link_index_to_name + + +def iter_addrs(): + """Generator that yields an information dictionary for each network address + in the system.""" + with _pool.socket() as sock: + with _nl_addr_cache(sock) as addr_cache: + with _nl_link_cache(sock) as link_cache: # for index to label + addr = libnl.nl_cache_get_first(addr_cache) + while addr: + yield _addr_info(addr, link_cache=link_cache) + addr = libnl.nl_cache_get_next(addr) + + +def _addr_info(addr, link_cache=None): + """Returns a dictionary with the address information.""" + index = libnl.rtnl_addr_get_ifindex(addr) + local_address = libnl.rtnl_addr_get_local(addr) + data = { + 'index': index, + 'family': libnl.nl_af2str(libnl.rtnl_addr_get_family(addr)), + 'prefixlen': libnl.rtnl_addr_get_prefixlen(addr), + 'scope': libnl.rtnl_scope2str(libnl.rtnl_addr_get_scope(addr)), + 'flags': _addr_flags(addr), + 'address': libnl.nl_addr2str(local_address) if local_address else None, + } + try: + data['label'] = _link_index_to_name(index, cache=link_cache) + except IOError as err: + if err.errno != errno.ENODEV: + raise + return data + + +def split(addr): + """Split an addr dict from iter_addrs""" + # for 32bits address, the address field is slashless + return addr['address'].split('/')[0], addr['prefixlen'] + + +def cidr_form(addr): + return '{}/{}'.format(*split(addr)) + + +def is_primary(addr): + return 'secondary' not in addr['flags'] + + +def is_permanent(addr): + return 'permanent' in addr['flags'] + + +def _addr_flags(addr): + """Returns the textual representation of the address flags""" + return frozenset( + libnl.rtnl_addr_flags2str(libnl.rtnl_addr_get_flags(addr)).split(',') + ) + + +_nl_addr_cache = partial(_cache_manager, libnl.rtnl_addr_alloc_cache) diff --git a/pool/shard002/Python/0025562_redirector.py b/pool/shard002/Python/0025562_redirector.py new file mode 100644 index 0000000000000000000000000000000000000000..00d7e40082899a7a600dfeb63df9212e79d5df82 --- /dev/null +++ b/pool/shard002/Python/0025562_redirector.py @@ -0,0 +1,112 @@ +# Copyright 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 posixpath +from urlparse import urlsplit + +from file_system import FileNotFoundError +from future import All +from path_util import Segment, Join, SplitParent + +class Redirector(object): + def __init__(self, compiled_fs_factory, file_system): + self._file_system = file_system + self._cache = compiled_fs_factory.ForJson(file_system) + + def Redirect(self, host, path): + ''' Check if a path should be redirected, first according to host + redirection rules, then from rules in redirects.json files. + + Returns the path that should be redirected to, or None if no redirection + should occur. + ''' + return self._RedirectOldHosts(host, path) or self._RedirectFromConfig(path) + + def _RedirectFromConfig(self, url): + ''' Look up redirects.json file in the directory hierarchy of |url|. + Directory-level redirects occur first, followed by the specific file + redirects. Returns the URL to the redirect, if any exist, or None. + ''' + dirname, filename = posixpath.split(url) + redirected_dirname = self._RedirectDirectory(dirname) + + # Set up default return value. + default_redirect = None + if redirected_dirname != dirname: + default_redirect = posixpath.normpath(Join(redirected_dirname, filename)) + + try: + rules = self._cache.GetFromFile( + posixpath.normpath(Join(redirected_dirname, + 'redirects.json'))).Get() + except FileNotFoundError: + return default_redirect + + redirect = rules.get(filename) + if redirect is None: + return default_redirect + if (redirect.startswith('/') or + urlsplit(redirect).scheme in ('http', 'https')): + return redirect + + return posixpath.normpath(Join(redirected_dirname, redirect)) + + def _RedirectDirectory(self, real_url): + ''' Returns the final redirected directory after all directory hops. + If there is a circular redirection, it skips the redirection that would + cause the infinite loop. + If no redirection rule is matched, the base directory is returned. + ''' + seen_redirects = set() + + def lookup_redirect(url): + sub_url = url + + for sub_url, _ in Segment(url): + for base, filename in Segment(sub_url): + try: + redirects = self._cache.GetFromFile(posixpath.normpath( + posixpath.join(base, 'redirects.json'))).Get() + except FileNotFoundError: + continue + + redirect = redirects.get(posixpath.join(filename, '...')) + + if redirect is None: + continue + + redirect = Join(base, redirect.rstrip('...')) + + # Avoid infinite redirection loops by breaking if seen before. + if redirect in seen_redirects: + break + seen_redirects.add(redirect) + return lookup_redirect( + Join(redirect, posixpath.relpath(url, sub_url))) + return url + + return lookup_redirect(real_url) + + def _RedirectOldHosts(self, host, path): + ''' Redirect paths from the old code.google.com to the new + developer.chrome.com, retaining elements like the channel and https, if + used. + ''' + if urlsplit(host).hostname != 'code.google.com': + return None + + path = path.split('/') + if path and path[0] == 'chrome': + path.pop(0) + + return 'https://developer.chrome.com/' + posixpath.join(*path) + + def Refresh(self): + ''' Load files during a cron run. + ''' + futures = [] + for root, dirs, files in self._file_system.Walk(''): + if 'redirects.json' in files: + futures.append(self._cache.GetFromFile(Join(root, 'redirects.json'))) + return All(futures) diff --git a/pool/shard002/Python/0025567_checkerboardpuzzle_utils.py b/pool/shard002/Python/0025567_checkerboardpuzzle_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7605a19f9b2d6ac1ad76c9fa6ebc15bc68ff6e56 --- /dev/null +++ b/pool/shard002/Python/0025567_checkerboardpuzzle_utils.py @@ -0,0 +1,53 @@ +from numpy import array, rot90, fliplr, array_equal +from checkerboardpuzzle_stone import Rotation + +def generate_rotated_nparrays(nparray): + """generate rotated and mirrored versions of given nparray.""" + r1 = rot90(nparray) + r2 = rot90(r1) + r3 = rot90(r2) + f1 = fliplr(nparray) + f2 = fliplr(r1) + f3 = fliplr(r2) + f4 = fliplr(r3) + all_rot = [nparray,r1,r2,r3,f1,f2,f3,f4] + return all_rot + +def generate_rotations(fields): + """generate all rotations of that stone.""" + #r1 = rot90(fields) + #r2 = rot90(r1) + #r3 = rot90(r2) + #f1 = fliplr(fields) + #f2 = fliplr(r1) + #f3 = fliplr(r2) + #f4 = fliplr(r3) + #all_rot = [r1,r2,r3,f1,f2,f3,f4] + all_rot = generate_rotated_nparrays(fields) + # check if rotations are equal + rotations = [] # [Rotation(fields)] + for r_new in all_rot: + l = len(filter(lambda r_old:array_equal(r_old.nparray,r_new), rotations)) + if l > 1: + raise Exception('Rotations doubled? That should be impossible!') + elif l == 0: + # not in rotations yet, add + rotations = rotations + [Rotation(r_new)] + return rotations + +def unique_nparrays(nparrays): + """return unique list of nparrays.""" + unique = [] + for a in nparrays: + for u in unique: + if (a == u).all(): + break + else: + unique = unique + [a] + return unique + +def append_to_file(filepath, text): + """append text to given file.""" + with open(filepath, 'a') as myfile: + myfile.write(text) + myfile.close() \ No newline at end of file diff --git a/pool/shard002/Python/0025569_test_obdsim.py b/pool/shard002/Python/0025569_test_obdsim.py new file mode 100644 index 0000000000000000000000000000000000000000..9367a34847109e16b0abf6951907915701aa7fec --- /dev/null +++ b/pool/shard002/Python/0025569_test_obdsim.py @@ -0,0 +1,146 @@ +import time + +import pytest + +from obd import commands, Unit + +# NOTE: This is purposefully tuned slightly higher than the ELM's default +# message timeout of 200 milliseconds. This prevents us from +# inadvertently marking the first query of an async connection as +# null, since it may be the case that the first transaction incurs the +# ELM's internal timeout. +STANDARD_WAIT_TIME = 0.3 + + +@pytest.fixture(scope="module") +def obd(request): + """provides an OBD connection object for obdsim""" + import obd + port = request.config.getoption("--port") + return obd.OBD(port) + + +@pytest.fixture(scope="module") +def asynchronous(request): + """provides an OBD *Async* connection object for obdsim""" + import obd + port = request.config.getoption("--port") + return obd.Async(port) + + +def good_rpm_response(r): + return (not r.is_null()) and \ + (r.value.u == Unit.rpm) and \ + (r.value >= 0.0 * Unit.rpm) + + +@pytest.fixture +def skip_if_port_unspecified(request): + if not request.config.getoption("--port"): + pytest.skip("needs --port= to run") + + +def test_supports(skip_if_port_unspecified, obd): + assert (len(obd.supported_commands) > 0) + assert (obd.supports(commands.RPM)) + + +def test_rpm(skip_if_port_unspecified, obd): + r = obd.query(commands.RPM) + assert (good_rpm_response(r)) + + +# Async tests + +def test_async_query(skip_if_port_unspecified, asynchronous): + rs = [] + asynchronous.watch(commands.RPM) + asynchronous.start() + + for i in range(5): + time.sleep(STANDARD_WAIT_TIME) + rs.append(asynchronous.query(commands.RPM)) + + asynchronous.stop() + asynchronous.unwatch_all() + + # make sure we got data + assert (len(rs) > 0) + assert (all([good_rpm_response(r) for r in rs])) + + +def test_async_callback(skip_if_port_unspecified, asynchronous): + rs = [] + asynchronous.watch(commands.RPM, callback=rs.append) + asynchronous.start() + time.sleep(STANDARD_WAIT_TIME) + asynchronous.stop() + asynchronous.unwatch_all() + + # make sure we got data + assert (len(rs) > 0) + assert (all([good_rpm_response(r) for r in rs])) + + +def test_async_paused(skip_if_port_unspecified, asynchronous): + assert (not asynchronous.running) + asynchronous.watch(commands.RPM) + asynchronous.start() + assert asynchronous.running + + with asynchronous.paused() as was_running: + assert not asynchronous.running + assert was_running + + assert asynchronous.running + asynchronous.stop() + assert not asynchronous.running + + +def test_async_unwatch(skip_if_port_unspecified, asynchronous): + watched_rs = [] + unwatched_rs = [] + + asynchronous.watch(commands.RPM) + asynchronous.start() + + for i in range(5): + time.sleep(STANDARD_WAIT_TIME) + watched_rs.append(asynchronous.query(commands.RPM)) + + with asynchronous.paused(): + asynchronous.unwatch(commands.RPM) + + for i in range(5): + time.sleep(STANDARD_WAIT_TIME) + unwatched_rs.append(asynchronous.query(commands.RPM)) + + asynchronous.stop() + + # the watched commands + assert (len(watched_rs) > 0) + assert (all([good_rpm_response(r) for r in watched_rs])) + + # the unwatched commands + assert (len(unwatched_rs) > 0) + assert (all([r.is_null() for r in unwatched_rs])) + + +def test_async_unwatch_callback(skip_if_port_unspecified, asynchronous): + a_rs = [] + b_rs = [] + asynchronous.watch(commands.RPM, callback=a_rs.append) + asynchronous.watch(commands.RPM, callback=b_rs.append) + + asynchronous.start() + time.sleep(STANDARD_WAIT_TIME) + + with asynchronous.paused(): + asynchronous.unwatch(commands.RPM, callback=b_rs.append) + + time.sleep(STANDARD_WAIT_TIME) + asynchronous.stop() + asynchronous.unwatch_all() + + assert (all([good_rpm_response(r) for r in a_rs + b_rs])) + assert (len(a_rs) > len(b_rs)) diff --git a/pool/shard002/Python/0025571_init__.py b/pool/shard002/Python/0025571_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c428bf0d1d222e4c161eb86ce4f00ce69c2c2e68 --- /dev/null +++ b/pool/shard002/Python/0025571_init__.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python +# +# Copyright 2007 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. +# + + + + +"""Repository for all builtin handlers information. + +On initialization, this file generates a list of builtin handlers that have +associated app.yaml information. This file can then be called to read that +information and make it available. +""" + + + + + + + + + + + + + +import logging +import os + + + +DEFAULT_DIR = os.path.join(os.path.dirname(__file__)) +_handler_dir = None + + + +_available_builtins = None + + +INCLUDE_FILENAME_TEMPLATE = 'include-%s.yaml' +DEFAULT_INCLUDE_FILENAME = 'include.yaml' + + +class InvalidBuiltinName(Exception): + """Raised whenever a builtin handler name is specified that is not found.""" + + +def reset_builtins_dir(): + """Public method for resetting builtins directory to default.""" + set_builtins_dir(DEFAULT_DIR) + + +def set_builtins_dir(path): + """Sets the appropriate path for testing and reinitializes the module.""" + global _handler_dir, _available_builtins + _handler_dir = path + _available_builtins = [] + _initialize_builtins() + + +def _initialize_builtins(): + """Scan the immediate subdirectories of the builtins module. + + Encountered subdirectories with an app.yaml file are added to + AVAILABLE_BUILTINS. + """ + for filename in os.listdir(_handler_dir): + if os.path.isfile(_get_yaml_path(filename, '')): + _available_builtins.append(filename) + + +def _get_yaml_path(builtin_name, runtime): + """Return expected path to a builtin handler's yaml file without error check. + """ + runtime_specific = os.path.join(_handler_dir, builtin_name, + INCLUDE_FILENAME_TEMPLATE % runtime) + if runtime and os.path.exists(runtime_specific): + return runtime_specific + return os.path.join(_handler_dir, builtin_name, DEFAULT_INCLUDE_FILENAME) + + +def get_yaml_path(builtin_name, runtime=''): + """Returns the full path to a yaml file by giving the builtin module's name. + + Args: + builtin_name: single word name of builtin handler + runtime: name of the runtime + + Raises: + ValueError: if handler does not exist in expected directory + + Returns: + the absolute path to a valid builtin handler include.yaml file + """ + if _handler_dir is None: + set_builtins_dir(DEFAULT_DIR) + + if builtin_name not in _available_builtins: + raise InvalidBuiltinName('%s is not the name of a valid builtin handler.\n' + 'Available handlers are: %s' % ( + builtin_name, ', '.join(_available_builtins))) + return _get_yaml_path(builtin_name, runtime) + + + + +def get_yaml_basepath(): + """Returns the full path of the directory in which builtins are located.""" + if _handler_dir is None: + set_builtins_dir(DEFAULT_DIR) + return _handler_dir diff --git a/pool/shard002/Python/0025572_story.py b/pool/shard002/Python/0025572_story.py new file mode 100644 index 0000000000000000000000000000000000000000..13b1eee088e2f8a62eb7661bba2be9cf6675e45a --- /dev/null +++ b/pool/shard002/Python/0025572_story.py @@ -0,0 +1,77 @@ +# coding=utf-8 +""" +Embedded Demo story, start it with python -m tale.demo.story + +'Tale' mud driver, mudlib and interactive fiction framework +Copyright by Irmen de Jong (irmen@razorvine.net) +""" + +from __future__ import absolute_import, print_function, division, unicode_literals +import os +import sys +import tale +from tale.driver import StoryConfig +from tale.main import run_story + + +class Story(object): + config = StoryConfig( + name="Tale demo story", + author="Irmen de Jong", + author_address="irmen@razorvine.net", + version=tale.__version__, # arbitrary but is used to check savegames for compatibility + requires_tale=tale.__version__, # tale library required to run the game + supported_modes={"if", "mud"}, # what driver modes (if/mud) are supported by this story + player_name="julie", # set a name to create a prebuilt player, None to use the character builder + player_gender="f", # m/f/n + player_race="human", # default is "human" ofcourse, but you can select something else if you want + player_money=15.5, # starting money + money_type="modern", # money type modern/fantasy + server_tick_method="timer", # 'command' (waits for player entry) or 'timer' (async timer driven) + server_tick_time=1.0, # time between server ticks (in seconds) (usually 1.0 for 'timer' tick method) + gametime_to_realtime=5, # meaning: game time is X times the speed of real time (only used with "timer" tick method) (>=0) + max_wait_hours=2, # the max. number of hours (gametime) the player is allowed to wait (>=0) + display_gametime=True, # enable/disable display of the game time at certain moments + epoch=None, # start date/time of the game clock + startlocation_player="house.livingroom", + startlocation_wizard="house.livingroom", + savegames_enabled=False, + show_exits_in_look=True, + license_file=None, + mud_host=None, + mud_port=None + ) + + driver = None # will be set by driver init() + + def init(self, driver): + self.driver = driver + self.driver.load_zones(["house"]) + + def init_player(self, player): + player.money = 12.65 + + def welcome(self, player): + player.tell("Welcome to '%s'." % self.config.name, end=True) + player.tell("This is a tiny embedded story to check out a running Tale environment.") + player.tell("Try to fool around with your pet, and exit the house to win the game.") + player.tell("\n") + + def welcome_savegame(self, player): + pass # not supported in demo + + def goodbye(self, player): + player.tell("Thanks for trying out Tale!") + + def completion(self, player): + """congratulation text / finale when player finished the game (story_complete event)""" + player.tell("Congratulations on finding the exit! Someone else has to look after Garfield now though...") + + +if __name__ == "__main__": + # story is invoked as a script, start it in the Tale Driver. + gamedir = os.path.dirname(__file__) + gui = len(sys.argv) > 1 and sys.argv[1] == "--gui" + web = len(sys.argv) > 1 and sys.argv[1] == "--web" + mud = len(sys.argv) > 1 and sys.argv[1] == "--mud" + run_story(gamedir, gui, web, mud) diff --git a/pool/shard002/Python/0025574_views.py b/pool/shard002/Python/0025574_views.py new file mode 100644 index 0000000000000000000000000000000000000000..4c6c8cc1d78d0a5fbb269d96fa87074285a5477f --- /dev/null +++ b/pool/shard002/Python/0025574_views.py @@ -0,0 +1,93 @@ +from flask import request, current_app +from flask.ext.restful import Resource +from flask.ext.consulate import ConsulService +from urlparse import urljoin +import requests +import json + + +class ProxyView(Resource): + """Proxies a request to a remote webservice""" + + def __init__(self, endpoint, service_uri, deploy_path): + self.endpoint = endpoint + self.service_uri = service_uri + self.deploy_path = deploy_path + self.cs = None + if service_uri.startswith('consul://'): + self.cs = ConsulService( + service_uri, + nameservers=[current_app.config.get("CONSUL_DNS", "172.17.42.1")] + ) + self.session = self.cs + else: + self.session = requests.Session() + + @staticmethod + def get_body_data(request): + """ + Returns the correct payload data coming from the flask.Request object + """ + payload = request.get_json(silent=True) + if payload: + return json.dumps(payload) + return request.form or request.data + + def dispatcher(self, **kwargs): + """ + Having a dispatch based on request.method solves being able to set up + ProxyViews on the same resource for different routes. However, it + limits the ability to scope a resouce on a per-method basis + """ + path = request.full_path.replace(self.deploy_path, '', 1) + path = path[1:] if path.startswith('/') else path + if self.cs is None: + ep = urljoin(self.service_uri, path) + else: + ep = path + resp = self.__getattribute__(request.method.lower())(ep, request) + + headers = {} + if resp.headers: + [headers.update({key: resp.headers[key]}) for key in current_app.config['REMOTE_PROXY_ALLOWED_HEADERS'] if key in resp.headers] + + if headers: + return resp.text, resp.status_code, headers + else: + return resp.text, resp.status_code + + def get(self, ep, request): + """ + Proxy to remote GET endpoint, should be invoked via self.dispatcher() + """ + return self.session.get(ep, headers=request.headers) + + def post(self, ep, request): + """ + Proxy to remote POST endpoint, should be invoked via self.dispatcher() + """ + if not isinstance(request.data, basestring): + request.data = json.dumps(request.data) + return self.session.post( + ep, data=ProxyView.get_body_data(request), headers=request.headers + ) + + def put(self, ep, request): + """ + Proxy to remote PUT endpoint, should be invoked via self.dispatcher() + """ + if not isinstance(request.data, basestring): + request.data = json.dumps(request.data) + return self.session.put( + ep, data=ProxyView.get_body_data(request), headers=request.headers + ) + + def delete(self, ep, request): + """ + Proxy to remote PUT endpoint, should be invoked via self.dispatcher() + """ + if not isinstance(request.data, basestring): + request.data = json.dumps(request.data) + return self.session.delete( + ep, data=ProxyView.get_body_data(request), headers=request.headers + ) diff --git a/pool/shard002/Python/0025575_event.py b/pool/shard002/Python/0025575_event.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa371ff6c29f32b2b01c88a8e63f0f84cb973b7 --- /dev/null +++ b/pool/shard002/Python/0025575_event.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- + +import os +import logging +import sqlite3 + + +class Event: + """Class representing a single Event.""" + def __init__(self, db_id, title, datum, url): + self.data = dict() + + # Get Information for this event from the sqlite DB + try: + conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), "../locations.sqlite")) + conn.row_factory = sqlite3.Row + c = conn.cursor() + except: + logging.error("Cant connect to database!") + + c.execute('select * from locations where id=?', [db_id]) + r = c.fetchone() + + for key in list(r.keys()): # Populate list with data from database + self.data[key] = r[key] + + # Populate list with data from web + self.data["title"] = title + self.data["datetime"] = datum + self.data["datum"] = datum.strftime("%a, %d. %b") + uhrzeit = datum.strftime("%H:%M") + if uhrzeit == "00:00": # "probably" no specific time set for this event...' + uhrzeit = "" + self.data["uhrzeit"] = uhrzeit # uhrzeit = german time + self.data["event_url"] = url + + logging.info(" Found Event: " + str(self.data["title"]) + " at " + str(self.data["name"])) + + def get(self, param): + return self.data[param] + + def get_all(self): + return self.data + + +class EventVault: + """Central Storage for events""" + def __init__(self): + self.events = [] + + def add(self, e): + self.events.append(e) + + def get_events_for_date(self, date): + e_subset = [] + for e in self.events: + if e.get("datetime").date() == date: + logging.info("%s: %s" % (date, e.get("title"))) + e_subset.append(e) + + if len(e_subset) > 0: + e_subset = sorted(e_subset, key=lambda e: e.data["uhrzeit"]) # Sort by uhrzeit + return e_subset + else: + return False + + def get_all_events(self): + if len(self.events) > 0: + return self.events + else: + return False diff --git a/pool/shard002/Python/0025576_BuildManPage.py b/pool/shard002/Python/0025576_BuildManPage.py new file mode 100644 index 0000000000000000000000000000000000000000..cc3724752dc2a45ea011f8600d645d1d4ecb3850 --- /dev/null +++ b/pool/shard002/Python/0025576_BuildManPage.py @@ -0,0 +1,219 @@ +import argparse +import datetime +from distutils.core import Command +from distutils.errors import DistutilsOptionError + + +class BuildManPage(Command): + """ + Add a ``build_manpage`` command to your setup.py. + To use this Command class add a command to call this class:: + + # For setuptools + setup( + entry_points={ + "distutils.commands": [ + "build_manpage = coalib.misc.BuildManPage:BuildManPage" + ] + } + ) + + # For distutils + from coalib.misc.BuildManPage import BuildManPage + setup( + cmdclass={'build_manpage': BuildManPage} + ) + + You can then use the following setup command to produce a man page:: + + $ python setup.py build_manpage --output=coala.1 \ + --parser=coalib.parsing.DefaultArgParser:default_arg_parser + + If automatically want to build the man page every time you invoke + your build, add to your ```setup.cfg``` the following:: + + [build_manpage] + output = .1 + parser = + """ + user_options = [ + ('output=', 'O', 'output file'), + ('parser=', None, 'module path to an ArgumentParser instance' + '(e.g. mymod:func, where func is a method or function which return' + 'an arparse.ArgumentParser instance.'), + ] + + def initialize_options(self): + self.output = None + self.parser = None + + def finalize_options(self): + if self.output is None: + raise DistutilsOptionError('\'output\' option is required') + if self.parser is None: + raise DistutilsOptionError('\'parser\' option is required') + mod_name, func_name = self.parser.split(':') + fromlist = mod_name.split('.') + mod = __import__(mod_name, fromlist=fromlist) + self._parser = ( + getattr(mod, func_name)(formatter_class=ManPageFormatter)) + + self.announce('Writing man page %s' % self.output) + self._today = datetime.date.today() + + def run(self): + dist = self.distribution + homepage = dist.get_url() + maintainer = dist.get_maintainer() + _license = dist.get_license() + appname = self._parser.prog + + sections = {"see also": ("Online documentation: {}".format(homepage)), + "maintainer(s)": maintainer, + "license": _license} + + dist = self.distribution + mpf = ManPageFormatter(appname, + desc=dist.get_description(), + long_desc=dist.get_long_description(), + ext_sections=sections, + parser=self._parser) + + formatted_man_page = mpf.format_man_page() + + with open(self.output, 'w') as man_file: + man_file.write(formatted_man_page) + + +class ManPageFormatter(argparse.HelpFormatter): + + def __init__(self, + prog, + indent_increment=2, + max_help_position=24, + width=None, + desc=None, + long_desc=None, + ext_sections=None, + parser=None): + argparse.HelpFormatter.__init__(self, prog) + + self._prog = prog + self._section = 1 + self._today = datetime.date.today().strftime('%Y\\-%m\\-%d') + self._desc = desc + self._long_desc = long_desc + self._ext_sections = ext_sections + self._parser = parser + + def _format_action_invocation(self, action): + if not action.option_strings: + metavar, = self._metavar_formatter(action, action.dest)(1) + return metavar + + else: + # if the Optional doesn't take a value, format is: + # -s, --long + if action.nargs == 0: + parts = [ManPageFormatter._bold(action_str) + for action_str in action.option_strings] + + # if the Optional takes a value, format is: + # -s ARGS, --long ARGS + else: + default = ManPageFormatter._underline(action.dest.upper()) + args_string = self._format_args(action, default) + parts = ['%s %s' % (self._bold(option_string), args_string) + for option_string in action.option_strings] + + return ', '.join(parts) + + @staticmethod + def _markup(string): + return string.replace('-', '\\-') + + @staticmethod + def _add_format(string, front, back): + if not string.strip().startswith(front): + string = front + string + if not string.strip().endswith(back): + string = string + back + return string + + @staticmethod + def _underline(string): + return ManPageFormatter._add_format(string, "\\fI", "\\fR") + + @staticmethod + def _bold(string): + return ManPageFormatter._add_format(string, "\\fB", "\\fR") + + def _mk_title(self): + return '.TH {0} {1} {2}\n'.format(self._prog, + self._section, + self._today) + + def _mk_name(self): + return '.SH NAME\n%s\n' % (self._parser.prog) + + def _mk_synopsis(self): + self.add_usage(self._parser.usage, + self._parser._actions, + self._parser._mutually_exclusive_groups, + prefix='') + usage = self._format_usage(None, + self._parser._actions, + self._parser._mutually_exclusive_groups, + '') + + usage = usage.replace('%s ' % self._prog, '') + usage = ('.SH SYNOPSIS\n \\fB%s\\fR %s\n' + % (ManPageFormatter._markup(self._prog), usage)) + return usage + + def _mk_description(self): + if self._long_desc: + long_desc = self._long_desc.replace('\n', '\n.br\n') + return '.SH DESCRIPTION\n%s\n' % self._markup(long_desc) + else: + return '' + + def _mk_options(self): + formatter = self._parser._get_formatter() + + # positionals, optionals and user-defined groups + for action_group in self._parser._action_groups: + formatter.start_section(None) + formatter.add_text(None) + formatter.add_arguments(action_group._group_actions) + formatter.end_section() + + # epilog + formatter.add_text(self._parser.epilog) + + # determine help from format above + return '.SH OPTIONS\n' + formatter.format_help() + + def _mk_footer(self): + sections = self._ext_sections + if not hasattr(sections, '__iter__'): + return '' + + footer = [] + + for section in sorted(sections.keys()): + part = ".SH {}\n {}".format(section.upper(), sections[section]) + footer.append(part) + + return '\n'.join(footer) + + def format_man_page(self): + page = [] + page.append(self._mk_title()) + page.append(self._mk_name()) + page.append(self._mk_synopsis()) + page.append(self._mk_description()) + page.append(self._mk_options()) + page.append(self._mk_footer()) + + return ''.join(page) diff --git a/pool/shard002/Python/0025578_checks.py b/pool/shard002/Python/0025578_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..45640220984042434dd0892a9ee07cb11e3c82b7 --- /dev/null +++ b/pool/shard002/Python/0025578_checks.py @@ -0,0 +1,213 @@ +""" +dj-stripe System Checks +""" +from django.conf import settings +from django.core import checks +from django.utils.dateparse import date_re + + +@checks.register("djstripe") +def check_stripe_api_key(app_configs=None, **kwargs): + """Check the user has configured API live/test keys correctly.""" + from . import settings as djstripe_settings + + messages = [] + + if not djstripe_settings.STRIPE_SECRET_KEY: + msg = "Could not find a Stripe API key." + hint = "Add STRIPE_TEST_SECRET_KEY and STRIPE_LIVE_SECRET_KEY to your settings." + messages.append(checks.Critical(msg, hint=hint, id="djstripe.C001")) + elif djstripe_settings.STRIPE_LIVE_MODE: + if not djstripe_settings.LIVE_API_KEY.startswith(("sk_live_", "rk_live_")): + msg = "Bad Stripe live API key." + hint = 'STRIPE_LIVE_SECRET_KEY should start with "sk_live_"' + messages.append(checks.Critical(msg, hint=hint, id="djstripe.C002")) + else: + if not djstripe_settings.TEST_API_KEY.startswith(("sk_test_", "rk_test_")): + msg = "Bad Stripe test API key." + hint = 'STRIPE_TEST_SECRET_KEY should start with "sk_test_"' + messages.append(checks.Critical(msg, hint=hint, id="djstripe.C003")) + + return messages + + +def validate_stripe_api_version(version): + """ + Check the API version is formatted correctly for Stripe. + + The expected format is an iso8601 date: `YYYY-MM-DD` + + :param version: The version to set for the Stripe API. + :type version: ``str`` + :returns bool: Whether the version is formatted correctly. + """ + return date_re.match(version) + + +@checks.register("djstripe") +def check_stripe_api_version(app_configs=None, **kwargs): + """Check the user has configured API version correctly.""" + from . import settings as djstripe_settings + + messages = [] + default_version = djstripe_settings.DEFAULT_STRIPE_API_VERSION + version = djstripe_settings.get_stripe_api_version() + + if not validate_stripe_api_version(version): + msg = "Invalid Stripe API version: {}".format(version) + hint = "STRIPE_API_VERSION should be formatted as: YYYY-MM-DD" + messages.append(checks.Critical(msg, hint=hint, id="djstripe.C004")) + + if version != default_version: + msg = ( + "The Stripe API version has a non-default value of '{}'. " + "Non-default versions are not explicitly supported, and may " + "cause compatibility issues.".format(version) + ) + hint = "Use the dj-stripe default for Stripe API version: {}".format(default_version) + messages.append(checks.Warning(msg, hint=hint, id="djstripe.W001")) + + return messages + + +@checks.register("djstripe") +def check_native_jsonfield_postgres_engine(app_configs=None, **kwargs): + """ + Check that the DJSTRIPE_USE_NATIVE_JSONFIELD isn't set unless Postgres is in use. + """ + from . import settings as djstripe_settings + + messages = [] + error_msg = "DJSTRIPE_USE_NATIVE_JSONFIELD is not compatible with engine {engine} for database {name}" + + if djstripe_settings.USE_NATIVE_JSONFIELD: + for db_name, db_config in settings.DATABASES.items(): + # Hi there. + # You may be reading this because you are using Postgres, but + # dj-stripe is not detecting that correctly. For example, maybe you + # are using multiple databases with different engines, or you have + # your own backend. As long as you are certain you can support jsonb, + # you can use the SILENCED_SYSTEM_CHECKS setting to ignore this check. + engine = db_config.get("ENGINE", "") + if "postgresql" not in engine and "postgis" not in engine: + messages.append( + checks.Critical( + error_msg.format(name=repr(db_name), engine=repr(engine)), + hint="Switch to Postgres, or unset DJSTRIPE_USE_NATIVE_JSONFIELD", + id="djstripe.C005", + ) + ) + + return messages + + +@checks.register("djstripe") +def check_stripe_api_host(app_configs=None, **kwargs): + """ + Check that STRIPE_API_HOST is not being used in production. + """ + from django.conf import settings + + messages = [] + + if not settings.DEBUG and hasattr(settings, "STRIPE_API_HOST"): + messages.append( + checks.Warning( + "STRIPE_API_HOST should not be set in production! This is most likely unintended.", + hint="Remove STRIPE_API_HOST from your Django settings.", + id="djstripe.W002", + ) + ) + + return messages + + +@checks.register("djstripe") +def check_webhook_secret(app_configs=None, **kwargs): + """ + Check that DJSTRIPE_WEBHOOK_SECRET looks correct + """ + from . import settings as djstripe_settings + + messages = [] + + secret = djstripe_settings.WEBHOOK_SECRET + if secret and not secret.startswith("whsec_"): + messages.append( + checks.Warning( + "DJSTRIPE_WEBHOOK_SECRET does not look valid", + hint="It should start with whsec_...", + id="djstripe.W003", + ) + ) + + return messages + + +@checks.register("djstripe") +def check_webhook_validation(app_configs=None, **kwargs): + """ + Check that DJSTRIPE_WEBHOOK_VALIDATION is valid + """ + from . import settings as djstripe_settings + + messages = [] + + validation_options = ("verify_signature", "retrieve_event") + + if djstripe_settings.WEBHOOK_VALIDATION is None: + messages.append( + checks.Warning( + "Webhook validation is disabled, this is a security risk if the webhook view is enabled", + hint="Set DJSTRIPE_WEBHOOK_VALIDATION to one of {}".format( + ", ".join(validation_options) + ), + id="djstripe.W004", + ) + ) + elif djstripe_settings.WEBHOOK_VALIDATION == "verify_signature": + if not djstripe_settings.WEBHOOK_SECRET: + messages.append( + checks.Critical( + "DJSTRIPE_WEBHOOK_VALIDATION='verify_signature' but DJSTRIPE_WEBHOOK_SECRET is not set", + hint="Set DJSTRIPE_WEBHOOK_SECRET or set DJSTRIPE_WEBHOOK_VALIDATION='retrieve_event'", + id="djstripe.C006", + ) + ) + elif djstripe_settings.WEBHOOK_VALIDATION not in validation_options: + messages.append( + checks.Critical( + "DJSTRIPE_WEBHOOK_VALIDATION is invalid", + hint="Set DJSTRIPE_WEBHOOK_VALIDATION to one of {} or None".format( + ", ".join(validation_options) + ), + id="djstripe.C007", + ) + ) + + return messages + + +@checks.register("djstripe") +def check_subscriber_key_length(app_configs=None, **kwargs): + """ + Check that DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY fits in metadata. + + Docs: https://stripe.com/docs/api#metadata + """ + from . import settings as djstripe_settings + + messages = [] + + key = djstripe_settings.SUBSCRIBER_CUSTOMER_KEY + key_size = len(str(key)) + if key and key_size > 40: + messages.append( + checks.Error( + "DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY must be no more than 40 characters long", + hint="Current value: %r (%i characters)" % (key, key_size), + id="djstripe.E001", + ) + ) + + return messages diff --git a/pool/shard002/Python/0025579_box.py b/pool/shard002/Python/0025579_box.py new file mode 100644 index 0000000000000000000000000000000000000000..760bdc56769ba833a69d6a3f86def7edfb83a220 --- /dev/null +++ b/pool/shard002/Python/0025579_box.py @@ -0,0 +1,72 @@ +""" Base classes for boxes of Gst pipeline elements. +""" + +import re +from gi.repository import GObject, Gst as gst # noqa + + +class ElementProxy(object): + def __init__(self, elem): + self.__dict__['_elem'] = elem + + def __getattr__(self, name): + return getattr(self._elem.props, name) + + def __setattr__(self, name, value): + return setattr(self._elem.props, name, value) + + +class Box(object): + def __init__(self, name, pipeline): + self.name = name + self.pipeline = pipeline + self.elements = {} + self._prev = None + self.first = None + self.last = None + + def __repr__(self): + return "<%s name='%s'>" % (self.__class__.__name__, self.name) + + def __getattr__(self, name): + if name in self.elements: + return ElementProxy(self.elements[name]) + raise AttributeError("Unknown element %r" % (name,)) + + def _set_elem_name(self, elem_def): + name_re = re.compile("name=([^ ]*)") + name = name_re.search(elem_def) + if name is None: + name = elem_def.split()[0] + name = name.replace('-', '_') + return "%s name=%s_%s" % (elem_def, self.name, name) + else: + name = "name=%s_%s" % (self.name, name.group(1)) + return name_re.sub(name, elem_def) + + def _get_elem_name(self, elem): + return elem.name[len(self.name) + 1:] + + def add_element(self, elem_def): + elem_def = self._set_elem_name(elem_def) + elem = gst.parse_launch(elem_def) + self.elements[self._get_elem_name(elem)] = elem + self.pipeline.add(elem) + if self._prev: + self._prev.link(elem) + if not self.first: + self.first = elem + self.last = elem + self._prev = elem + + def add_sequence(self, element_defs): + for elem_def in element_defs: + self.add_element(elem_def) + + def link(self, other): + print 'link: %s >>> %s ' % ( + self.last.name, other.first.name) + self.last.link(other.first) + + def terminate(self): + self.add_element("fakesink") diff --git a/pool/shard002/Python/0025587_function_printer.py b/pool/shard002/Python/0025587_function_printer.py new file mode 100644 index 0000000000000000000000000000000000000000..54ee15ebf60f7712301baacf089a64f0dda1e298 --- /dev/null +++ b/pool/shard002/Python/0025587_function_printer.py @@ -0,0 +1,40 @@ +from mms_keps_p1p1_bouss_tools import * +from numpy import * +import matplotlib +import matplotlib.pyplot as plt +import sys + +''' +run using: +python3 function_printer.py AA BB CC DD .. n_rows +where: + AA, BB, CC, DD are names of functions in mms_keps_p1p1_bouss_tools.py (any number can be entered) + n_rows is the number of rows to display the functions on +''' + +functions = [] +for arg in sys.argv[1:-1]: + functions.append(arg) +n_rows = int(sys.argv[-1]) + +matplotlib.rcParams['xtick.direction'] = 'out' +matplotlib.rcParams['ytick.direction'] = 'out' +plt.subplots_adjust(left=None, bottom=None, right=None, top=None, + wspace=0.2, hspace=0.2) + +res = 50 +X = linspace(0.0, pi, res) +Y = linspace(0.0, pi, res) +x = [0,0] + +data = empty([len(functions), res, res]) +for z, function in enumerate(functions): + for j, x[0] in enumerate(X): + for i, x[1] in enumerate(Y): + data[z,i,j] = eval(function + '(x)') + plt.subplot(n_rows, len(functions)/n_rows + 1, z+1) + CS = plt.contour(X, Y, data[z]) + plt.clabel(CS, inline=1, fontsize=10) + plt.title(functions[z]) + +plt.show() diff --git a/pool/shard002/Python/0025588_Server.py b/pool/shard002/Python/0025588_Server.py new file mode 100644 index 0000000000000000000000000000000000000000..c2b3cce5cfd72461e7565252ed3c3e47ade11e36 --- /dev/null +++ b/pool/shard002/Python/0025588_Server.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +import socketserver as SocketServer +import json, re, time + +class ClientHandler(SocketServer.BaseRequestHandler): + """ + This is the ClientHandler class. Everytime a new client connects to the + server, a new ClientHandler object will be created. This class represents + only connected clients, and not the server itself. If you want to write + logic for the server, you must write it outside this class + """ + + def handle(self): + """ + This method handles the connection between a client and the server. + """ + self.ip = self.client_address[0] + self.port = self.client_address[1] + self.connection = self.request + self.user = None + server.connections.append(self) + + # Loop that listens for messages from the client + while True: + try: + recv = json.loads(self.connection.recv(4096).decode('utf-8')) + except Exception as e: + self.logout() + break + + if(recv['request'] == 'login'): + self.login(recv) + elif(recv['request'] == 'logout'): + if(self.user == None): + self.error('Not logged in') + else: + self.logout() + break + elif(recv['request'] == 'msg'): + if(self.user == None): + self.error('Not logged in') + else: + self.message(recv) + pass + elif(recv['request'] == 'names'): + if(self.user == None): + self.error('Not logged in') + else: + self.names() + elif(recv['request'] == 'help'): + self.help() + else: + self.error('Unknown request') + + def history(self): + payload = {'timestamp': int(time.time()), 'sender': '[Server]', 'response': 'history', 'content': []} + for message in server.messages: + payload['content'].append(message) + self.send_payload(json.dumps(payload)) + + def login(self, recv): + if re.match("^[A-Za-z0-9_-]+$", recv['content']): + print(recv['content'],'logged in') + self.user = recv['content'] + + #GET HISTORY + self.history() + + msg = {'timestamp': int(time.time()), 'sender': '[Server]', 'response': 'info', 'content': self.user+' connected'} + payload = json.dumps(msg) + for connected in server.connections: + if(connected.user != None): + connected.send_payload(payload) + server.messages.append(msg) + else: + self.error('Invalid username') + + def logout(self): + server.connections.remove(self) + self.connection.close() + if(self.user != None): + print(self.user,'logged out') + msg = {'timestamp': int(time.time()), 'sender': '[Server]', 'response': 'info', 'content': self.user+' disconnected'} + payload = json.dumps(msg) + for connected in server.connections: + if(connected.user != None): + connected.send_payload(payload) + server.messages.append(msg) + + def message(self, recv): + msg = {'timestamp': int(time.time()), 'sender': self.user, 'response': 'msg', 'content': recv['content']} + payload = json.dumps(msg) + for connected in server.connections: + if(connected.user != None): + connected.send_payload(payload) + server.messages.append(msg) + + def names(self): + names="" + for connected in server.connections: + if(connected.user != None): + names+=connected.user+', ' + payload=json.dumps({'timestamp': int(time.time()), 'sender': '[Server]', 'response': 'info', 'content': 'Connected users: '+names}) + self.send_payload(payload) + + def help(self): + payload=json.dumps({'timestamp': int(time.time()), 'sender': '[Help]', 'response': 'info', 'content': 'Avaleable commands: login , logout, msg , names, help'}) + self.send_payload(payload) + + def send_payload(self, data): + self.connection.send(bytes(data, 'UTF-8')) + + def error(self, msg): + payload=json.dumps({'timestamp': int(time.time()), 'sender': '[Error]', 'response': 'error', 'content': msg}) + self.send_payload(payload) + +class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): + """ + This class is present so that each client connected will be ran as a own + thread. In that way, all clients will be served by the server. + + No alterations is necessary + """ + allow_reuse_address = True + + connections=[] + messages=[] + +if __name__ == "__main__": + """ + This is the main method and is executed when you type "python Server.py" + in your terminal. + + No alterations is necessary + """ + HOST, PORT = '', 9998 + print('Server running...') + + # Set up and initiate the TCP server + server = ThreadedTCPServer((HOST, PORT), ClientHandler) + server.serve_forever() \ No newline at end of file diff --git a/pool/shard002/Python/0025597_about_scope.py b/pool/shard002/Python/0025597_about_scope.py new file mode 100644 index 0000000000000000000000000000000000000000..3cde1a47ec416c907917f6ac265c8c3ce95df0d6 --- /dev/null +++ b/pool/shard002/Python/0025597_about_scope.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from runner.koan import * + +from . import jims +from . import joes + +counter = 0 # Global + +class AboutScope(Koan): + # + # NOTE: + # Look in jims.py and joes.py to see definitions of Dog used + # for this set of tests + # + + def test_dog_is_not_available_in_the_current_scope(self): + with self.assertRaises(NameError): fido = Dog() + + def test_you_can_reference_nested_classes_using_the_scope_operator(self): + fido = jims.Dog() + # name 'jims' module name is taken from jims.py filename + + rover = joes.Dog() + self.assertEqual('jims dog', fido.identify()) + self.assertEqual('joes dog', rover.identify()) + + self.assertEqual(False, type(fido) == type(rover)) + self.assertEqual(False, jims.Dog == joes.Dog) + + # ------------------------------------------------------------------ + + class str: + pass + + def test_bare_bones_class_names_do_not_assume_the_current_scope(self): + self.assertEqual(False, AboutScope.str == str) + + def test_nested_string_is_not_the_same_as_the_system_string(self): + self.assertEqual(False, self.str == type("HI")) + + def test_str_without_self_prefix_stays_in_the_global_scope(self): + self.assertEqual(True, str == type("HI")) + + # ------------------------------------------------------------------ + + PI = 3.1416 + + def test_constants_are_defined_with_an_initial_uppercase_letter(self): + self.assertAlmostEqual(3.14160001, self.PI) + # Note, floating point numbers in python are not precise. + # assertAlmostEqual will check that it is 'close enough' + + def test_constants_are_assumed_by_convention_only(self): + self.PI = "rhubarb" + self.assertEqual('rhubarb', self.PI) + # There aren't any real constants in python. Its up to the developer + # to keep to the convention and not modify them. + + # ------------------------------------------------------------------ + + def increment_using_local_counter(self, counter): + counter = counter + 1 + + def increment_using_global_counter(self): + global counter + counter = counter + 1 + + def test_incrementing_with_local_counter(self): + global counter + start = counter + self.increment_using_local_counter(start) + self.assertEqual(False, counter == start + 1) + + def test_incrementing_with_global_counter(self): + global counter + start = counter + self.increment_using_global_counter() + self.assertEqual(True, counter == start + 1) + + # ------------------------------------------------------------------ + + def local_access(self): + stuff = 'eels' + def from_the_league(): + stuff = 'this is a local shop for local people' + return stuff + return from_the_league() + + def nonlocal_access(self): + stuff = 'eels' + def from_the_boosh(): + nonlocal stuff + return stuff + return from_the_boosh() + + def test_getting_something_locally(self): + self.assertEqual('this is a local shop for local people', self.local_access()) + + def test_getting_something_nonlocally(self): + self.assertEqual('eels', self.nonlocal_access()) + + # ------------------------------------------------------------------ + + global deadly_bingo + deadly_bingo = [4, 8, 15, 16, 23, 42] + + def test_global_attributes_can_be_created_in_the_middle_of_a_class(self): + self.assertEqual(42, deadly_bingo[5]) diff --git a/pool/shard002/Python/0025598_0001_initial.py b/pool/shard002/Python/0025598_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..88d0dea6480c886c92f12f7a6cdaa0fe591abb79 --- /dev/null +++ b/pool/shard002/Python/0025598_0001_initial.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import flowjs.utils + + +class Migration(migrations.Migration): + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='FlowFile', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('identifier', models.SlugField(unique=True, max_length=255)), + ('original_filename', models.CharField(max_length=200)), + ('total_size', models.IntegerField(default=0)), + ('total_chunks', models.IntegerField(default=0)), + ('total_chunks_uploaded', models.IntegerField(default=0)), + ('state', models.IntegerField(default=1, choices=[(1, b'Uploading'), (2, b'Completed'), (3, b'Upload Error')])), + ('created', models.DateTimeField(auto_now_add=True)), + ('updated', models.DateField(auto_now=True)), + ], + options={ + }, + bases=(models.Model,), + ), + migrations.CreateModel( + name='FlowFileChunk', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('file', models.FileField(max_length=255, upload_to=flowjs.utils.chunk_upload_to)), + ('number', models.IntegerField()), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('parent', models.ForeignKey(related_name='chunks', to='flowjs.FlowFile')), + ], + options={ + 'ordering': ['number'], + }, + bases=(models.Model,), + ), + ] diff --git a/pool/shard002/Python/0025602_combatManager.py b/pool/shard002/Python/0025602_combatManager.py new file mode 100644 index 0000000000000000000000000000000000000000..9f0a0756dc0737fa3226ebe1bc483b58d977e897 --- /dev/null +++ b/pool/shard002/Python/0025602_combatManager.py @@ -0,0 +1,211 @@ +__author__ = 'jon' + +from fife import fife +from combat import * + +class Graveyard(fife.InstanceActionListener): + ''' + Pure virtual class. Handles proper destruction of instances. + ''' + def __init__(self, layer): + super(Graveyard, self).__init__() + + self.layer = layer + self.instances = [] + self.busy = False + + def add(self, instance): + self.instances.append(instance) + # instance.addActionListener(self) + + def next(self): + if not self.busy: + self.removeDead() + + def onInstanceActionFinished(self, instance, action): + pass + + def onInstanceActionFrame(self, instance, action, frame): + pass + + def onInstanceActionCancelled(self, instance, action): + pass + + def isEmpty(self): + return ( len(self.instances) == 0 ) + + def removeDead(self, instances=None): + if not instances: + instances = self.instances + + while instances: + instance = instances.pop() + if not self.isInLayer(instance): + continue + instance.removeActionListener(self) + self.layer.deleteInstance(instance) + + def isInLayer(self, instance): + ''' + Checks if an instance is in the layer. + ''' + instances = self.layer.getInstances() + id = instance.getFifeId() + for inst in instances: + if inst.getFifeId() == id: + return True + + return False + + +class ProjectileGraveyard(Graveyard): + ''' + Handles the destruction of projectiles. + ''' + def __init__(self, layer, combatManager): + super(ProjectileGraveyard, self).__init__(layer) + # self.combatManager = combatManager + # self.projectile = None + + # def onInstanceActionFinished(self, instance, action): + # if action.getId() == "move": + # print "ProjectileGraveyard: projectile moved." + # self.instances.append(instance) + # self.busy = False + # self.projectile = None + # self.combatManager.resume() + + # def add(self, instance): + # instance.addActionListener(self) + # self.busy = True + + # def addProjectile(self, projectile): + # ''' + # Adds the projectile and waits till it moves. + # ''' + # self.projectile = projectile + # self.add(projectile.getInstance()) + + +class UnitGraveyard(Graveyard): + ''' + Handles destruction of units (including explosions). + ''' + + def __init__(self, unitLayer): + super(UnitGraveyard, self).__init__(unitLayer) + self.toExplode = [] + self.toDelete = [] + + def isEmpty(self): + return not (self.toExplode or self.toDelete) + + def next(self): + if self.busy: + return + + self.removeDead(self.toDelete) + + if self.toExplode: + self.explodeUnit(self.toExplode.pop()) + + + def add(self, instance, explode=False): + if explode: + self.toExplode.append(instance) + else: + self.toDelete.append(instance) + + + def explodeUnit(self, instance): + ''' + Shows the explosion animation + ''' + instance.addActionListener(self) + instance.actOnce("explode") + self.busy = True + + def onInstanceActionFinished(self, instance, action): + if action.getId() == "explode": + instance.removeActionListener(self) + self.toDelete.append(instance) + self.busy = False + + +class CombatManager(object): + ''' + Keeps track of the events in world. Blocks world execution until all the events have been taken care of. + ''' + + def __init__(self, world): + self.world = world + self.retaliation = None + self.projectile = None + self.inCombat = False + + + def next(self): + ''' + Handles the next thing to do. + :return: + ''' + + # if self.paused: + # return + if self.projectile: + if self.projectile.active: + self.projectile.pump() + return + else: + self.projectile = None + + if self.world.projectileGraveyard and not self.world.projectileGraveyard.isEmpty(): + self.world.projectileGraveyard.next() + return + + if self.world.unitGraveyard and not self.world.unitGraveyard.isEmpty(): + self.world.unitGraveyard.next() + return + + ## Handle retaliation. + if self.retaliation: + if self.retaliation.active: + if not self.retaliation.blocked: + self.retaliation.next() + return + else: + self.retaliation = None + + self.combatFinished() + + def newCombat(self, attackerAgent): + ''' + Starts a combat round with retaliation. + :param attackerAgent: Agent that attacks + :return: + ''' + if self.inCombat: + return + self.inCombat = True + self.retaliation = Retaliation(self.world, attackerAgent) + + def resume(self): + self.paused = False + + def combatFinished(self): + self.inCombat = False + self.retaliation = None + + def addProjectile(self, origin, destination, weapon=None, callback=None): + ''' + Adds a projectile to the scene and takes care of its construction and destruction. + :param unit: Unit that is firing. + :param origin: Location where the projectile will start from + :param destination: Location where the projectile will travel + :param callback: What will be run right after it ends. + :return: + ''' + self.projectile = Projectile(self.world, origin, destination, weapon=weapon, callback=callback) + if self.retaliation: + self.retaliation.unblock() + # self.paused = True \ No newline at end of file diff --git a/pool/shard002/Python/0025604_helpers.py b/pool/shard002/Python/0025604_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac83be9068c1cc5fd5b7c4bbf3a000c8faea754 --- /dev/null +++ b/pool/shard002/Python/0025604_helpers.py @@ -0,0 +1,102 @@ +import flask +import sqlalchemy +from collections import OrderedDict + +from ruddock import auth_utils +from ruddock.resources import Permissions + +def get_memberlist(search_type): + """ + Retrieves the full memberlist. Valid values for search_type + are 'all', 'current', or 'alumni'. + or various graduation years. + """ + search_filters_grad_year = get_all_grad_years() + tables = "members NATURAL JOIN members_extra NATURAL JOIN membership_types" + if search_type == "all": + # Nothing to be done + pass + elif search_type == "current": + tables += " NATURAL JOIN members_current" + elif search_type == "alumni": + tables += " NATURAL JOIN members_alumni" + elif search_type in search_filters_grad_year: + pass + else: + # Something went wrong (this should have been validated earlier). + raise ValueError("Failed to get members with search filter: " + search_type) + + # We also want usernames, or NULL if they don't exist. + tables += " NATURAL LEFT JOIN users" + + sqlText = """ + SELECT user_id, username, first_name, last_name, email, + matriculation_year, graduation_year, membership_desc + FROM {} + """ + + if search_type in ["all", "current", "alumni"]: + pass + elif search_type in search_filters_grad_year: + # Note: following line is not vulnerable to sql injection attack + # because search_type can only be from the list pulled from the database + sqlText += "WHERE graduation_year=" + search_type + " " + else: + # This should never happen + pass + + sqlText += "ORDER BY first_name" + query = sqlalchemy.text(sqlText.format(tables)) + return flask.g.db.execute(query).fetchall() + +def get_user_info(username): + """Retrieves a user's info.""" + query = sqlalchemy.text(""" + SELECT + username, + name, + email, + phone, + msc, + birthday, + matriculation_year, + graduation_year, + major, + membership_desc, + building, + room_number + FROM members + NATURAL JOIN members_extra + NATURAL JOIN membership_types + NATURAL JOIN users + WHERE username=:u + """) + return flask.g.db.execute(query, u=username).first() + +def get_office_info(username): + """Procedure to get a user's officer info.""" + query = sqlalchemy.text(""" + SELECT office_name, start_date, end_date + FROM office_assignments NATURAL JOIN users NATURAL JOIN offices + WHERE username = :u + ORDER BY start_date, end_date, office_name + """) + return flask.g.db.execute(query, u=username).fetchall() + +def get_all_grad_years(): + """ Returns a list of strings of all graduation years with no dupliacates """ + query = "SELECT graduation_year FROM members NATURAL JOIN members_extra" + grad_years_set = {'2020'} # need to put an initial value to make this a set instead of dict + all_grad_years = flask.g.db.execute(query).fetchall() + for grad_year in all_grad_years: + cleaned_grad_year = grad_year[0] + if cleaned_grad_year == None: + continue + grad_years_set.add(str(cleaned_grad_year)) + grad_years_list_sorted = list(grad_years_set) + grad_years_list_sorted.sort() + grad_years_list_sorted.reverse() + if len(grad_years_list_sorted) > 5: # Only show the 5 most recent years + grad_years_list_sorted = grad_years_list_sorted[0: 5] + return grad_years_list_sorted + diff --git a/pool/shard002/Python/0025611_game.py b/pool/shard002/Python/0025611_game.py new file mode 100644 index 0000000000000000000000000000000000000000..59c814f613e46e02bb923e1044d4f561ebeecf2b --- /dev/null +++ b/pool/shard002/Python/0025611_game.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 + +"""game + +This file contains the function that prepares +the game resources and runs the game.""" + +# Import built-in libraries. +import os +import sys + +# Import supplementary libraries. +os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = 'hide' +import pygame +from pygame.locals import * + +# Import local modules. +import mgr_video +import mgr_audio +import mgr_input +import mgr_scene +import mgr_sprite + +from uevents import uEvent + + + + + +# Constants +name = "Untitled" +version = 'v0' +date = 'DATE' +author = "AUTHOR" + +def showDetailsConsole(): + """A quick text script to display information in the console when starting.""" + # NOTE: This will not show up if the main script is a .pyw file. + + global name, version, date, author + + output = name + """ - """ + version + """ +""" + date + """ """ + author + """ + +This is an example of what the console would output when the game runs. +You can form this and above text however you like. + +Alternatively, you can make the main execution script have a .pyw +extension instead, and that will disable the console from popping up +before the game.""" + print(output) + print('') + +def run(): + """Run the game.""" + global name + + # Show Details (Console) + showDetailsConsole() + + # Start Pygame + pygame.init() + + # Splash Screen + mgr_video.showSplashScreen('splash.png') + + # Prepare Managers + mgr_video.showMainScreen(name) # Show display. + mgr_video.clock.tick() + mgr_audio.preinitMixer() + mgr_audio.loadMixer() + mgr_audio.setChannels() + mgr_audio.setSongs() + mgr_input.setControllers() # Set up controllers if any. + mgr_scene.setScenes() + #mgr_sprite for spritesheets. + + # Starting Scene + mgr_scene.currentScene = mgr_scene.scene['G']() + + # Core Loop + loop_active = True + while loop_active is True: + # Handle Framerate/Delta-Frame + mgr_video.handleFramerate() + + # Input Tracking + mgr_input.updateCheck() + + # Scene Tracking + if mgr_scene.currentScene.nextScene == 'TERMINATE': + loop_active = False + elif mgr_scene.currentScene.nextScene == 'CURRENT': + pass + else: + # NOTE: The game will crash if a non-existent scene is called. + mgr_scene.swap = mgr_scene.currentScene.nextScene + mgr_scene.currentScene = mgr_scene.scene[mgr_scene.swap] + mgr_scene.currentScene.nextScene = 'CURRENT' + mgr_scene.swap = '' + + # Event Tracking + pygame.event.pump() + filtered_events = [] + for eachEvent in pygame.event.get(): + if eachEvent.type == QUIT: + loop_active = False + else: + filtered_events.append(eachEvent) + + # Cycle Scene + mgr_sprite.changerects = [] # Clear changerects from any scenes that use RenderUpdates. + mgr_scene.currentScene.process(filtered_events) + mgr_scene.currentScene.update() + mgr_scene.currentScene.render(mgr_video.display) + + # Display Frame + mgr_video.showFrame(mgr_sprite.changerects) + + # Close + pygame.quit() + sys.exit(0) diff --git a/pool/shard002/Python/0025615_Telescope.py b/pool/shard002/Python/0025615_Telescope.py new file mode 100644 index 0000000000000000000000000000000000000000..772dc5de988fc025895dd243a8772db94848b08d --- /dev/null +++ b/pool/shard002/Python/0025615_Telescope.py @@ -0,0 +1,195 @@ +""" +Author: Alex Walter +Date: Jul 8, 2016 + +This class grabs info from the Palomar telescope +""" +from socket import * +import time, math +import datetime +from PyQt4 import QtGui +from PyQt4.QtGui import * +from PyQt4 import QtCore +import ephem +#from lib.getSeeing import getPalomarSeeing # From old SDR code +from lib.getSeeing import getPalomarSeeing # From old SDR code + +class TelescopeWindow(QMainWindow): + + def __init__(self, telescope, parent=None): + """ + INPUTES: + telescope - Telescope object + """ + super(QMainWindow, self).__init__(parent) + self.setWindowTitle("Palomar Telescope") + self._want_to_close = False + self.telescope = telescope + self.create_main_frame() + updater = QtCore.QTimer(self) + updater.setInterval(1003) + updater.timeout.connect(self.updateTelescopeInfo) + updater.start() + + def updateTelescopeInfo(self, target='sky'): + if not self.isVisible(): + return + tel_dict = self.telescope.get_telescope_position() + for key in tel_dict.keys(): + try: + self.label_dict[key].setText(str(tel_dict[key])) + except: + layout = self.main_frame.layout() + label = QLabel(key) + label_val = QLabel(str(tel_dict[key])) + hbox = QHBoxLayout() + hbox.addWidget(label) + hbox.addWidget(label_val) + layout.addLayout(hbox) + self.main_frame.setLayout(layout) + self.label_dict[key] = label_val + + def create_main_frame(self): + self.main_frame = QWidget() + vbox = QVBoxLayout() + + def add2layout(vbox, *args): + hbox = QHBoxLayout() + for arg in args: + hbox.addWidget(arg) + vbox.addLayout(hbox) + + label_telescopeStatus = QLabel('Telescope Status') + font = label_telescopeStatus.font() + font.setPointSize(24) + label_telescopeStatus.setFont(font) + vbox.addWidget(label_telescopeStatus) + + tel_dict = self.telescope.get_telescope_position() + self.label_dict={} + for key in tel_dict.keys(): + label = QLabel(key) + label.setMaximumWidth(150) + label_val = QLabel(str(tel_dict[key])) + label_val.setMaximumWidth(150) + add2layout(vbox,label,label_val) + self.label_dict[key] = label_val + + self.main_frame.setLayout(vbox) + self.setCentralWidget(self.main_frame) + + def closeEvent(self, event): + if self._want_to_close: + self.close() + else: + self.hide() + + +class Telescope(): + + def __init__(self, ipaddress="198.202.125.194", port = 5004, receivePort=1024): + self.address = (ipaddress, port) + self.receivePort = receivePort + + #Palomar's position + self.observatory = 'Palomar 200" Hale Telescope' + self.lat = 33.0 + 21.0/60.0 + 21.6/3600.0 + self.lon = 116.0 + 51.0/60.0 + 46.8/3600.0 + self.latStr = '33.0:21.0:21.6' + self.lonStr = '-116.0:51.0:46.80' + self.elevation = 1706.0 + + def getAllTelescopeInfo(self,targetName='sky'): + telescopeDict = self.get_telescope_position(targetName) + telescopeDict.update(self.get_telescope_status()) + telescopeDict.update(self.get_parallactic()) + telescopeDict.update(self.get_seeing()) + telescopeDict.update({'telescope':self.observatory, 'obslat':self.lat, 'obslon':self.lon, 'obsalt':self.elevation}) + return telescopeDict + + def sendTelescopeCommand(self, command): + try: + self.client_socket = socket(AF_INET, SOCK_STREAM) #Set Up the Socket + self.client_socket.connect(self.address) + except: + print "Connection to TCS failed" + print "Telescope IP: ",self.address + return + response = None + try: + self.client_socket.send(command) + response = self.client_socket.recv(self.receivePort) + except: + print "Command to TCS failed: "+str(command) + print "Received at: ",self.receivePort + self.client_socket.close() + return response + + def get_telescope_status(self): + response = self.sendTelescopeCommand('REQSTAT\r') + if response is None: + return {} + + utc, line2, line3, line4, cass_angle = response.split('\n') + telescope_id, focus, tubelength = line2.split(', ') + focus_title, focus_val = focus.split(' = ') + cassAngle_key, cassAngle_val = cass_angle.split(' = ') + cassAngle_val = cassAngle_val.split('\x00')[0] + telescopeID_key, telescopeID_val = telescope_id.split(' = ') + utc = utc.split(' = ')[1] + tubeLength_key, tubeLength_val = tubelength.split(' = ') + return {'Status UTC':utc, cassAngle_key: cassAngle_val, + telescopeID_key: telescopeID_val, tubeLength_key: tubeLength_val, + focus_title:focus_val} + + def get_parallactic(self): + response = self.sendTelescopeCommand('?PARALLACTIC\r') + if response is None: + return {} + parallactic = response.split('\n') + title, par_value = parallactic[0].split('= ') + return {str(title):float(par_value)} + + def get_telescope_position(self,targetName='sky'): + if targetName is None or len(targetName)==0: targetName='sky' + response = self.sendTelescopeCommand('REQPOS\r') + if response is None: + return {} + + #split response into status fields + line1,line2,airmass = response.split('\n') + + utc, lst = line1.split(', ') + utc_title, junk, utc_day, utc_time = utc.split(' ') + lst_title, junk, lst_time = lst.split(' ') + + ra, dec, ha = line2.split(', ') + ra_title, junk, ra_val = ra.split(' ') + dec_title, junk, dec_val = dec.split(' ') + ha_title, junk, ha_val = ha.split(' ') + + airmass_title, airmass_val = airmass.split('= ') + + + #calculate alt and az of current target + target = ephem.readdb(str(targetName)+',f|L,'+str(ra_val)+','+str(dec_val)+',2000') + + lt = time.time() + dt = datetime.datetime.utcfromtimestamp(lt) + + palomar = ephem.Observer() + palomar.long, palomar.lat = self.lonStr, self.latStr + palomar.date = ephem.Date(dt) + palomar.elevation = self.elevation + target.compute(palomar) + alt, az = target.alt*(180./math.pi), target.az*(180/math.pi) + + return {str(utc_title):utc_time, str(lst_title):lst_time, str(ra_title):ra_val, + str(dec_title):dec_val, str(ha_title):ha_val,str(airmass_title):float(airmass_val[:-1]), + 'alt':alt, 'az':az} + + def get_seeing(self): + return {'seeing':getPalomarSeeing()} + + + diff --git a/pool/shard002/Python/0025616_sale_order.py b/pool/shard002/Python/0025616_sale_order.py new file mode 100644 index 0000000000000000000000000000000000000000..d411b2dca6d2e8283649269aaa6fb0558c779df0 --- /dev/null +++ b/pool/shard002/Python/0025616_sale_order.py @@ -0,0 +1,30 @@ +# Copyright 2019 Alfredo de la Fuente - AvanzOSC +# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html +from odoo import models, fields + + +class SaleOrder(models.Model): + _inherit = 'sale.order' + + sale_product_ids = fields.Many2many( + string='Sale order products', comodel_name='product.product', + compute='_compute_sale_product_ids') + + def _compute_sale_product_ids(self): + for sale in self: + lines = sale.order_line.filtered(lambda x: x.state != 'cancel') + if lines: + products = lines.mapped('product_id') + sale.sale_product_ids = [(6, 0, products.ids)] + + def action_view_products_stock_forecast_from_sale(self): + self.ensure_one() + if self.sale_product_ids: + self.env['product.product.stock.forecast']. _calc_qty_per_day( + products_lst=self.sale_product_ids) + action = self.env.ref( + 'stock_forecast.action_product_stock_forecast_from' + '_sale').read()[0] + action['domain'] = [ + ('product_id', 'in', self.sale_product_ids.ids)] + return action diff --git a/pool/shard002/Python/0025617_init__.py b/pool/shard002/Python/0025617_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d132dd3e5ce265afbb53bb274efeb3c577c321b6 --- /dev/null +++ b/pool/shard002/Python/0025617_init__.py @@ -0,0 +1,32 @@ +# Author: Nicolas VERDIER +# This file is part of memorpy. +# +# memorpy 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. +# +# memorpy 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 memorpy. If not, see . + + +import logging +logger=logging.getLogger("memorpy") +logger.setLevel(logging.WARNING) +ch = logging.StreamHandler() +ch.setLevel(logging.WARNING) +logger.addHandler(ch) + +import sys +from MemWorker import * +from Locator import * +from Address import * +from Process import * +from utils import * +#if sys.platform=="win32": +# from wintools import * #not a necessary dependency, just used for debugging diff --git a/pool/shard002/Python/0025619_views.py b/pool/shard002/Python/0025619_views.py new file mode 100644 index 0000000000000000000000000000000000000000..5719910442db2245be1b9ae6f51b1d9012ac4bc8 --- /dev/null +++ b/pool/shard002/Python/0025619_views.py @@ -0,0 +1,92 @@ +""" +OAuth2 Adapter for Battle.net + +Resources: + +* Battle.net OAuth2 documentation: + https://dev.battle.net/docs/read/oauth +* Battle.net API documentation: + https://dev.battle.net/io-docs +* Original announcement: + https://us.battle.net/en/forum/topic/13979297799 +* The Battle.net API forum: + https://us.battle.net/en/forum/15051532/ +""" +import requests +from allauth.socialaccount.providers.oauth2.client import OAuth2Error +from allauth.socialaccount.providers.oauth2.views import ( + OAuth2Adapter, OAuth2CallbackView, OAuth2LoginView +) +from .provider import BattleNetProvider + + +def _check_errors(data): + # The expected output from the Battle.net API follows this format: + # {"id": 12345, "battletag": "Example#12345"} + # The battletag is optional. + if "error" in data: + # For errors, we expect the following format: + # {"error": "error_name", "error_description": "Oops!"} + # For example, if the token is not valid, we will get: + # { + # "error": "invalid_token", + # "error_description": "Invalid access token: abcdef123456" + # } + error = data["error"] + desc = data.get("error_description", "") + raise OAuth2Error("Battle.net error: %s (%s)" % (error, desc)) + elif "id" not in data: + # If the id is not present, the output is not usable (no UID) + raise OAuth2Error("Invalid data from Battle.net API: %r" % (data)) + + +class BattleNetOAuth2Adapter(OAuth2Adapter): + """ + OAuth2 adapter for Battle.net + https://dev.battle.net/docs/read/oauth + + Region is set to us by default. + Set the `battlenet_region` attribute to change it. + Can be any of eu, us, kr, sea, tw or cn + """ + provider_id = BattleNetProvider.id + battlenet_region = "us" + + @property + def battlenet_base_url(self): + region = self.battlenet_region + if region == "cn": + return "https://www.battlenet.com.cn" + return "https://%s.battle.net" % ("us" if region == "sea" else region) + + @property + def battlenet_api_url(self): + if self.battlenet_region == "cn": + return "https://www.battlenet.com.cn/api" + return "https://%s.api.battle.net" % (self.battlenet_region) + + @property + def access_token_url(self): + return self.battlenet_base_url + "/oauth/token" + + @property + def authorize_url(self): + return self.battlenet_base_url + "/oauth/authorize" + + @property + def profile_url(self): + return self.battlenet_api_url + "/account/user" + + def complete_login(self, request, app, token, **kwargs): + params = {"access_token": token.token} + response = requests.get(self.profile_url, params=params) + data = response.json() + _check_errors(data) + + # Add the region to the data so that we can have it in `extra_data`. + data["region"] = self.battlenet_region + + return self.get_provider().sociallogin_from_response(request, data) + +oauth2_login = OAuth2LoginView.adapter_view(BattleNetOAuth2Adapter) +oauth2_callback = OAuth2CallbackView.adapter_view(BattleNetOAuth2Adapter) diff --git a/pool/shard002/Python/0025624_test_timeout_manager.py b/pool/shard002/Python/0025624_test_timeout_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..3254a5d647b6cd0b71427f83594534d602d03ae2 --- /dev/null +++ b/pool/shard002/Python/0025624_test_timeout_manager.py @@ -0,0 +1,54 @@ +########################################################################## +#This file is part of WTFramework. +# +# WTFramework 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. +# +# WTFramework 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 WTFramework. If not, see . +########################################################################## +from wtframework.wtf.config import ConfigReader, TimeOutManager +import unittest + + +class TestTimeOutManager(unittest.TestCase): + + + def setUp(self): + config_reader = ConfigReader('tests/timeout-manager-testfile') + self.timeout_manager = TimeOutManager(config_reader=config_reader) + + def tearDown(self): + self.timeout_manager = None + + def test_timeout_manager_grabs_value_from_config_file(self): + "Test timeout manager returns value from our timeout settings." + self.assertEqual(6, self.timeout_manager.BRIEF) + self.assertEqual(11, self.timeout_manager.SHORT) + self.assertEqual(31, self.timeout_manager.NORMAL) + self.assertEqual(61, self.timeout_manager.LONG) + self.assertEqual(301, self.timeout_manager.EPIC) + + def test_timeout_manager_uses_default_value_when_not_specified_in_config(self): + "Test timeout manager returns value from our timeout settings." + config_reader = ConfigReader('tests/TestConfig1') + timeout_manager = TimeOutManager(config_reader=config_reader) + + self.assertEqual(5, timeout_manager.BRIEF) + self.assertEqual(10, timeout_manager.SHORT) + self.assertEqual(30, timeout_manager.NORMAL) + self.assertEqual(60, timeout_manager.LONG) + self.assertEqual(300, timeout_manager.EPIC) + + + +if __name__ == "__main__": + #import sys;sys.argv = ['', 'Test.testName'] + unittest.main() \ No newline at end of file diff --git a/pool/shard002/Python/0025630_0165_auto_20160902_1420.py b/pool/shard002/Python/0025630_0165_auto_20160902_1420.py new file mode 100644 index 0000000000000000000000000000000000000000..58398867e4f22dda1c7317dd6beba78b7b7367a1 --- /dev/null +++ b/pool/shard002/Python/0025630_0165_auto_20160902_1420.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.9 on 2016-09-02 14:20 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('goals', '0164_auto_20160829_2145'), + ] + + operations = [ + migrations.AddField( + model_name='customaction', + name='goal', + field=models.ForeignKey(blank=True, help_text='The goal to which this custom action is associated.', null=True, on_delete=django.db.models.deletion.CASCADE, to='goals.Goal'), + ), + migrations.AlterField( + model_name='customaction', + name='customgoal', + field=models.ForeignKey(blank=True, help_text='The custom goal to which this action belongs.', null=True, on_delete=django.db.models.deletion.CASCADE, to='goals.CustomGoal'), + ), + ] diff --git a/pool/shard002/Python/0025631_servo_gdb.py b/pool/shard002/Python/0025631_servo_gdb.py new file mode 100644 index 0000000000000000000000000000000000000000..31f2a8962d921f22ba637cae52b9d81e17a70f24 --- /dev/null +++ b/pool/shard002/Python/0025631_servo_gdb.py @@ -0,0 +1,152 @@ +# Copyright 2013 The Servo Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution. +# +# Licensed under the Apache License, Version 2.0 or the MIT license +# , at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +""" +A set of simple pretty printers for gdb to make debugging Servo a bit easier. + +To load these, you need to add something like the following to your .gdbinit file: + +python +import sys +sys.path.insert(0, '/home//servo/src/etc') +import servo_gdb +servo_gdb.register_printers(None) +end +""" + +import gdb + + +# Print Au in both raw value and CSS pixels +class AuPrinter: + def __init__(self, val): + self.val = val + + def to_string(self): + i32_type = gdb.lookup_type("i32") + au = self.val.cast(i32_type) + return "{0}px".format(au / 60.0) + + +# Print a U8 bitfield as binary +class BitFieldU8Printer: + def __init__(self, val): + self.val = val + + def to_string(self): + u8_type = gdb.lookup_type("u8") + value = self.val.cast(u8_type) + return "[{0:#010b}]".format(int(value)) + + +# Print a struct with fields as children +class ChildPrinter: + def __init__(self, val): + self.val = val + + def children(self): + children = [] + for f in self.val.type.fields(): + children.append((f.name, self.val[f.name])) + return children + + def to_string(self): + return None + + +# Allow a trusted node to be dereferenced in the debugger +class TrustedNodeAddressPrinter: + def __init__(self, val): + self.val = val + + def children(self): + node_type = gdb.lookup_type("struct script::dom::node::Node").pointer() + value = self.val.cast(node_type) + return [('Node', value)] + + def to_string(self): + return self.val.address + + +# Extract a node type ID from enum +class NodeTypeIdPrinter: + def __init__(self, val): + self.val = val + + def to_string(self): + u8_ptr_type = gdb.lookup_type("u8").pointer() + enum_0 = self.val.address.cast(u8_ptr_type).dereference() + enum_type = self.val.type.fields()[int(enum_0)].type + return str(enum_type).lstrip('struct ') + + +# Printer for std::Option<> +class OptionPrinter: + def __init__(self, val): + self.val = val + + def is_some(self): + # Get size of discriminator + d_size = self.val.type.fields()[0].type.sizeof + + if d_size > 0 and d_size <= 8: + # Read first byte to check if None or Some + ptr = self.val.address.cast(gdb.lookup_type("unsigned char").pointer()) + discriminator = int(ptr.dereference()) + return discriminator != 0 + + raise "unhandled discriminator size" + + def children(self): + if self.is_some(): + option_type = self.val.type + + # Get total size and size of value + ptr = self.val.address.cast(gdb.lookup_type("unsigned char").pointer()) + t_size = option_type.sizeof + value_type = option_type.fields()[1].type.fields()[1].type + v_size = value_type.sizeof + data_ptr = (ptr + t_size - v_size).cast(value_type.pointer()).dereference() + return [('Some', data_ptr)] + return [('None', None)] + + def to_string(self): + return None + + +# Useful for debugging when type is unknown +class TestPrinter: + def __init__(self, val): + self.val = val + + def to_string(self): + return "[UNKNOWN - type = {0}]".format(str(self.val.type)) + +type_map = [ + ('struct Au', AuPrinter), + ('FlowFlags', BitFieldU8Printer), + ('IntrinsicWidths', ChildPrinter), + ('PlacementInfo', ChildPrinter), + ('TrustedNodeAddress', TrustedNodeAddressPrinter), + ('NodeTypeId', NodeTypeIdPrinter), + ('Option', OptionPrinter), +] + + +def lookup_servo_type(val): + val_type = str(val.type) + for (type_name, printer) in type_map: + if val_type == type_name or val_type.endswith("::" + type_name): + return printer(val) + return None + # return TestPrinter(val) + + +def register_printers(obj): + gdb.pretty_printers.append(lookup_servo_type) diff --git a/pool/shard002/Python/0025643_multi_thread_3.py b/pool/shard002/Python/0025643_multi_thread_3.py new file mode 100644 index 0000000000000000000000000000000000000000..30299d96a81b37184d1967c9a860bce40bf57266 --- /dev/null +++ b/pool/shard002/Python/0025643_multi_thread_3.py @@ -0,0 +1,43 @@ +import threading +import time + + +class test: + # 新线程执行的代码: + + def __init__(self): + self.num = 0 + + def Name(self, name): + self.num = self.num + 1 + print("num is %s" % self.num) + + def fib(self, n): + if n == 1 or n == 2: + return 1 + else: + return self.fib(n - 1) + self.fib(n - 2) + + +def loop(): + print('thread %s is running...' % threading.current_thread().name) + n = 0 + while n < 5: + n = n + 1 + print('thread %s -- %s' % (threading.current_thread().name, n)) + time.sleep(1) + print('thread %s ended.' % threading.current_thread().name) + +if __name__ == "__main__": + print('thread %s is running...' % threading.current_thread().name) + test = test() + t = [30, 30, 30, 30, 30] + start = time.time() + v = [] + for i in t: + m = threading.Thread(target=test.fib, name='LoopThread', args=(i,)) + m.start() + m.join() + + print("消耗时间:%s" % (time.time() - start)) + print('thread %s ended.' % threading.current_thread().name) diff --git a/pool/shard002/Python/0025649_role_window.py b/pool/shard002/Python/0025649_role_window.py new file mode 100644 index 0000000000000000000000000000000000000000..a1d040ac9ae004ee5ae1b24e572ef540343158df --- /dev/null +++ b/pool/shard002/Python/0025649_role_window.py @@ -0,0 +1,24 @@ +#!/usr/bin/python + +"""Test of window title output.""" + +from macaroon.playback import * +import utils + +sequence = MacroSequence() + +sequence.append(KeyComboAction("Down")) +sequence.append(PauseAction(3000)) + +sequence.append(utils.StartRecordingAction()) +sequence.append(KeyPressAction(0, None, "KP_Insert")) +sequence.append(KeyComboAction("KP_Enter")) +sequence.append(KeyReleaseAction(0, None, "KP_Insert")) +sequence.append(utils.AssertPresentationAction( + "1. Window Where Am I", + ["BRAILLE LINE: 'GTK+ Code Demos'", + " VISIBLE: 'GTK+ Code Demos', cursor=0", + "SPEECH OUTPUT: 'GTK+ Code Demos'"])) + +sequence.append(utils.AssertionSummaryAction()) +sequence.start() diff --git a/pool/shard002/Python/0025651_bslurp.py b/pool/shard002/Python/0025651_bslurp.py new file mode 100644 index 0000000000000000000000000000000000000000..485b4c3b4626867ef90277c79c51feb992d4e16a --- /dev/null +++ b/pool/shard002/Python/0025651_bslurp.py @@ -0,0 +1,189 @@ +#!/usr/bin/python + +# Copyright 2015 Sam Yaple +# +# 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 module has been relicensed from the source below: +# https://github.com/SamYaple/yaodu/blob/master/ansible/library/bslurp + +DOCUMENTATION = ''' +--- +module: bslurp +short_description: Slurps a file from a remote node +description: + - Used for fetching a binary blob containing the file, then push that file + to other hosts. +options: + src: + description: + - File to fetch. When dest is used, src is expected to be a str with data + required: True + type: str + compress: + description: + - Compress file with zlib + default: True + type: bool + dest: + description: + - Where to write out binary blob + required: False + type: str + mode: + description: + - Destination file permissions + default: '0644' + type: str + sha1: + description: + - sha1 hash of the underlying data + default: None + type: bool +author: Sam Yaple +''' + +EXAMPLES = ''' +Distribute a file from single to many host: + +- hosts: web_servers + tasks: + - name: Pull in web config + bslurp: src="/path/to/file" + register: file_data + run_once: True + - name: Push if changed + bslurp: + src: "{{ file_data.content }}" + dest: "{{ file_data.source }}" + mode: "{{ file_data.mode }}" + sha1: "{{ file_data.sha1 }}" + +Distribute multiple files from single to many host: + +- hosts: web_servers + tasks: + - name: Pull in web config + bslurp: src="{{ item }}" + with_items: + - "/path/to/file1" + - "/path/to/file2" + - "/path/to/file3" + register: file_data + run_once: True + - name: Push if changed + bslurp: + src: "{{ item.content }}" + dest: "{{ item.source }}" + mode: "{{ item.mode }}" + sha1: "{{ item.sha1 }}" + with_items: file_data.results + +Distribute a to file many host without compression; Change permissions on dest: + +- hosts: web_servers + tasks: + - name: Pull in web config + bslurp: src="/path/to/file" + register: file_data + run_once: True + - name: Push if changed + bslurp: + src: "{{ file_data.content }}" + dest: "/new/path/to/file" + mode: "0777" + compress: False + sha1: "{{ file_data.sha1 }}" +''' + +import base64 +import hashlib +import os +import sys +import zlib + +def copy_from_host(module): + compress = module.params.get('compress') + src = module.params.get('src') + + if not os.path.exists(src): + module.fail_json(msg="file not found: {}".format(src)) + if not os.access(src, os.R_OK): + module.fail_json(msg="file is not readable: {}".format(src)) + + mode = oct(os.stat(src).st_mode & 0777) + + with open(src, 'rb') as f: + raw_data = f.read() + + sha1 = hashlib.sha1(raw_data).hexdigest() + data = zlib.compress(raw_data) if compress else raw_data + + module.exit_json(content=base64.b64encode(data), sha1=sha1, mode=mode, + source=src) + + +def copy_to_host(module): + compress = module.params.get('compress') + dest = module.params.get('dest') + mode = int(module.params.get('mode'), 0) + sha1 = module.params.get('sha1') + src = module.params.get('src') + + data = base64.b64decode(src) + raw_data = zlib.decompress(data) if compress else data + + if sha1: + if os.path.exists(dest): + if os.access(dest, os.R_OK): + with open(dest, 'rb') as f: + if hashlib.sha1(f.read()).hexdigest() == sha1: + module.exit_json(changed=False) + else: + module.exit_json(failed=True, changed=False, + msg='file is not accessible: {}'.format(dest)) + + if sha1 != hashlib.sha1(raw_data).hexdigest(): + module.exit_json(failed=True, changed=False, + msg='sha1 sum does not match data') + + with os.fdopen(os.open(dest, os.O_WRONLY | os.O_CREAT, mode), 'wb') as f: + f.write(raw_data) + + module.exit_json(changed=True) + +def main(): + module = AnsibleModule( + argument_spec = dict( + compress = dict(default=True, type='bool'), + dest = dict(type='str'), + mode = dict(default='0644', type='str'), + sha1 = dict(default=None, type='str'), + src = dict(required=True, type='str') + ) + ) + + dest = module.params.get('dest') + + try: + if dest: + copy_to_host(module) + else: + copy_from_host(module) + except Exception as e: + module.exit_json(failed=True, changed=True, msg=repr(e)) + +# import module snippets +from ansible.module_utils.basic import * +if __name__ == '__main__': + main() diff --git a/pool/shard002/Python/0025652_persist_info.py b/pool/shard002/Python/0025652_persist_info.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6496c19a39ce6a86c08725131f744a562ff174 --- /dev/null +++ b/pool/shard002/Python/0025652_persist_info.py @@ -0,0 +1,55 @@ +# +# This file is part of Checkbox. +# +# Copyright 2008 Canonical Ltd. +# +# Checkbox 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. +# +# Checkbox 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 Checkbox. If not, see . +# +from checkbox.contrib.persist import Persist + +from checkbox.properties import Path +from checkbox.plugin import Plugin + + +class PersistInfo(Plugin): + + # Filename where to persist information + filename = Path(default="%(checkbox_data)s/plugins.bpickle") + + def register(self, manager): + super(PersistInfo, self).register(manager) + + self.persist = None + + for (rt, rh) in [ + ("begin", self.begin), + ("prompt-begin", self.begin), + ("prompt-job", self.save)]: + self._manager.reactor.call_on(rt, rh, -100) + + # Save persist data last + self._manager.reactor.call_on("stop", self.save, 1000) + + def begin(self, interface=None): + if self.persist is None: + self.persist = Persist(self.filename) + self._manager.reactor.fire("begin-persist", self.persist) + + def save(self, *args): + # Flush data to disk + if self.persist: + self.persist.save() + + +factory = PersistInfo diff --git a/pool/shard002/Python/0025653_session.py b/pool/shard002/Python/0025653_session.py new file mode 100644 index 0000000000000000000000000000000000000000..1f55f729aac15b9674915277125a25a3c470df19 --- /dev/null +++ b/pool/shard002/Python/0025653_session.py @@ -0,0 +1,65 @@ +#!/usr/bin/python + +import cherrypy + +from webserver.alerts import Alerts + + +class Session(): + + def __init__(self, CPSession): + self._session = CPSession + self.alerts = Alerts(CPSession) + self.id = CPSession.id + + def __del__(self): + cherrypy.request.session.save() + + def get(self, *args, **kwargs): + return self._session.get(*args, **kwargs) + + def regenerate(self): + self._session.clear() + self._session.regenerate() + self.id = self._session.id + + def set(self, params): + for key, value in params.iteritems(): + self._session[key] = value + + def unset(self, key): + self._session[key] = None + + def isLoggedIn(self): + user = self._session.get('user') + + # This is certainly not pythonic. + if user: + return True + else: # user is not defined! + return False + + @staticmethod + def restricted(f): + def _checkUser(*args, **kwargs): + if cherrypy.request.session.isLoggedIn(): + return f(*args, **kwargs) + else: + cherrypy.request.session.alerts.error("You are not logged in.") + cherrypy.request.session.set({ + 'origin': cherrypy.lib.httputil.urljoin( + cherrypy.request.script_name, + cherrypy.request.path_info + ) + }) + raise cherrypy.HTTPRedirect("/") + + return _checkUser + + @staticmethod + def handler(): + try: + foo = Session(cherrypy.session) + cherrypy.request.session = foo + except: + pass diff --git a/pool/shard002/Python/0025656_commands.py b/pool/shard002/Python/0025656_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..6394ac040b740e244fa45afcf218ca61707821e8 --- /dev/null +++ b/pool/shard002/Python/0025656_commands.py @@ -0,0 +1,165 @@ +# telepathy-mixer - a MXit connection manager for Telepathy +# +# Copyright (C) 2008 Ralf Kistner +# +# Adapted from telepathy-butterfly, +# Copyright (C) 2006-2007 Ali Sabil +# +# 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 + +import logging +import exceptions + +from mixer.util.decorator import async, logexceptions +from mixer.channel.text import MixerTextChannel +from mixer.channel.multitext import MixerRoomChannel + +from mxit.handles import Mood + +__all__ = ['CommandHandler'] + +logger = logging.getLogger('Mixer.Commands') + +class CommandHandler: + def __init__(self, con): + self.con = con + + def get_buddy(self, channel, args): + if isinstance(channel, MixerTextChannel): + buddy = channel.contact_handle.contact + if buddy and not buddy.is_room(): + return (buddy, args) + if args: + buddy = self.con.mxit.roster.get_buddy(args[0]) + + if not buddy: + buddy = self.con.mxit.roster.find_buddy(args[0]) + + return (buddy, args[1:]) + else: + return (None, args) + + def get_room(self, channel, args): + if isinstance(channel, MixerTextChannel): + buddy = channel.contact_handle.contact + if buddy and buddy.is_room(): + return (buddy, args) + + if args: + room = self.con.mxit.roster.get_room(args[0]) + + if not room: + room = self.con.mxit.roster.find_room(args[0]) + + return (room, args[1:]) + else: + return (None, args) + + def _get_func(self, name): + return getattr(self, name) + + def get_mood(self, text): + if text.isdigit(): + return Mood.byid(int(text)) + else: + return getattr(Mood, text) + + def _handle_command(self, command, channel, *args): + logger.info("COMMAND %s, %s, %s" % (command, channel, args)) + if hasattr(self, command): + f = self._get_func(command) + try: + f(channel, *args) + except Exception, e: + self.help(channel, command) + raise + else: + logger.info("command not found") + + def handle_command(self, channel, message): + args = message.split() + cmd = args[0][1:] + args = args[1:] + + self._handle_command(cmd, channel, *args) + + + def help(self, channel, *args): + if args: + name = args[0] + func = self._get_func(name) + doc = unicode(func.__doc__) + else: + doc = """ Available commands: + /mood - set your mood + /create - create a MultiMX room + /invite - invite a buddy to a MultiMX room + """ + self.con.info(doc, channel) + + def invite(self, channel, *args): + """ Usage: /invite + + Must be called from a room. + + buddy can be either the name or the id of the buddy + """ + room, args = self.get_room(channel, args) + buddy, args = self.get_buddy(None, args) + logger.info("Inviting %s to room %s" % (buddy, room)) + if room and buddy: + self.con.mxit.invite_buddies_room(room, [buddy]) + else: + raise exceptions.Exception("Invalid room or buddy") + + def leave(self, channel, *args): + """ Usage: /leave + + Leaves the room. + + Must be called from a room. + """ + room, args = self.get_room(channel, args) + + if room: + logger.info("Leaving room %s" % (room)) + self.con.mxit.leave_room(room) + else: + raise exceptions.Exception("Invalid room") + + def create(self, channel, *args): + """ Usage: /create + + Create a room with the specified name. + """ + if args: + name = args[0] + + self.con.mxit.create_room(name) + else: + raise exceptions.Exception("Name must be specified") + + def mood(self, channel, *args): + """ Usage: /mood + + moods: none, happy, sad, grumpy, angry, excited, inlove, invincible, hot, sick, sleepy + """ + if args: + name = args[0].upper() + mood = self.get_mood(name) + else: + mood = Mood.NONE + + self.con.mxit.set_mood(mood) \ No newline at end of file diff --git a/pool/shard002/Python/0025671_myState.py b/pool/shard002/Python/0025671_myState.py new file mode 100644 index 0000000000000000000000000000000000000000..63bbb8391b12f0f4e0a4736083cde83947711956 --- /dev/null +++ b/pool/shard002/Python/0025671_myState.py @@ -0,0 +1,71 @@ +# Copyright (C) weslowskij +# +# 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. + +class MyState(object): + def __init__(self,astate): + self.mystate=astate + + def on_enter(self, fromstate): + pass + + def update(self): + pass + + def on_leave(self, tostate): + pass + + +class MyStateController(object): + def __init__(self): + self.mystate=None + #self.mystatestr="undefined" + self.mystates={} + + def add_state(self, astate): + self.mystates[astate.mystate]=astate + #self.mystatestr = str(astate.mystate) + + def change_state(self,newstatestr): + if self.mystates.has_key(newstatestr): + newstate=self.mystates[newstatestr] + """ + if self.mystate == newstate: + return + """ + print "change State " + str(newstatestr) + if self.mystate: + self.mystate.on_leave(newstate) + newstate.back = self.mystate + newstate.on_enter(self.mystate) + self.mystate=newstate + else: + print "State " + str(newstatestr) + " doesnt exists" + #self.mystatestr = str(self.mystate) + + def change_state_back(self): + if self.mystate.back: + newstatestr= self.mystate.back.mystate + if self.mystates.has_key(newstatestr): + newstate=self.mystates[newstatestr] + if self.mystate: + self.mystate.on_leave(newstate) + newstate.on_enter(self.mystate) + self.mystate=newstate + #self.mystatestr = str(self.mystate) + + def update(self): + if self.mystate: + self.mystate.update() \ No newline at end of file diff --git a/pool/shard002/Python/0025672_0065_create_description.py b/pool/shard002/Python/0025672_0065_create_description.py new file mode 100644 index 0000000000000000000000000000000000000000..806f63b8ee2636a9754ecc8a0a1c65b96ed7db42 --- /dev/null +++ b/pool/shard002/Python/0025672_0065_create_description.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('instance', '0064_merge'), + ] + + operations = [ + migrations.AddField( + model_name='mongodbserver', + name='description', + field=models.CharField(blank=True, max_length=250), + ), + migrations.AddField( + model_name='mongodbserver', + name='name', + field=models.CharField(max_length=250, blank=True), + ), + migrations.AddField( + model_name='mysqlserver', + name='description', + field=models.CharField(blank=True, max_length=250), + ), + migrations.AddField( + model_name='mysqlserver', + name='name', + field=models.CharField(max_length=250, blank=True), + ), + ] diff --git a/pool/shard002/Python/0025680_test_hub.py b/pool/shard002/Python/0025680_test_hub.py new file mode 100644 index 0000000000000000000000000000000000000000..ce676708f2d6b2d81269ad1a1bdf4f098c8dd9fb --- /dev/null +++ b/pool/shard002/Python/0025680_test_hub.py @@ -0,0 +1,179 @@ +# pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103 + +from __future__ import absolute_import, division, print_function + +import pytest +from mock import MagicMock + +from ..data import Data +from ..data_collection import DataCollection +from ..exceptions import InvalidSubscriber, InvalidMessage +from ..hub import Hub, HubListener +from ..message import SubsetMessage, Message +from ..subset import Subset + + +class TestHub(object): + + def setup_method(self, method): + self.hub = Hub() + + def get_subscription(self): + msg = Message + handler = MagicMock() + subscriber = MagicMock(spec_set=HubListener) + return msg, handler, subscriber + + def test_subscribe(self): + msg, handler, subscriber = self.get_subscription() + self.hub.subscribe(subscriber, msg, handler) + assert self.hub.is_subscribed(subscriber, msg) + assert self.hub.get_handler(subscriber, msg) == handler + + def test_get_handler(self): + msg, handler, subscriber = self.get_subscription() + self.hub.subscribe(subscriber, msg, handler) + assert self.hub.get_handler(subscriber, msg) == handler + assert self.hub.get_handler(subscriber, None) is None + assert self.hub.get_handler(None, msg) is None + + def test_unsubscribe(self): + msg, handler, subscriber = self.get_subscription() + self.hub.subscribe(subscriber, msg, handler) + self.hub.unsubscribe(subscriber, msg) + + assert not self.hub.is_subscribed(subscriber, msg) + assert self.hub.get_handler(subscriber, msg) is None + + def test_unsubscribe_all(self): + msg, handler, subscriber = self.get_subscription() + msg2 = SubsetMessage + self.hub.subscribe(subscriber, msg, handler) + self.hub.subscribe(subscriber, msg2, handler) + self.hub.unsubscribe_all(subscriber) + assert not self.hub.is_subscribed(subscriber, msg) + assert not self.hub.is_subscribed(subscriber, msg2) + + def test_unsubscribe_specific_to_message(self): + msg, handler, subscriber = self.get_subscription() + msg2 = SubsetMessage + self.hub.subscribe(subscriber, msg, handler) + self.hub.subscribe(subscriber, msg2, handler) + self.hub.unsubscribe(subscriber, msg) + assert not self.hub.is_subscribed(subscriber, msg) + assert self.hub.is_subscribed(subscriber, msg2) + + def test_broadcast(self): + msg, handler, subscriber = self.get_subscription() + self.hub.subscribe(subscriber, msg, handler) + msg_instance = msg("Test") + self.hub.broadcast(msg_instance) + handler.assert_called_once_with(msg_instance) + + def test_unsubscribe_halts_broadcast(self): + msg, handler, subscriber = self.get_subscription() + self.hub.subscribe(subscriber, msg, handler) + self.hub.unsubscribe(subscriber, msg) + msg_instance = msg("Test") + self.hub.broadcast(msg_instance) + assert handler.call_count == 0 + + def test_unsubscribe_spec_setific_to_message(self): + msg, handler, subscriber = self.get_subscription() + msg2 = SubsetMessage + self.hub.subscribe(subscriber, msg2, handler) + msg_instance = msg("Test") + self.hub.broadcast(msg_instance) + assert handler.call_count == 0 + + def test_subscription_catches_message_subclasses(self): + msg, handler, subscriber = self.get_subscription() + msg2 = SubsetMessage + self.hub.subscribe(subscriber, msg, handler) + msg_instance = msg2(MagicMock(spec_set=Subset)) + self.hub.broadcast(msg_instance) + handler.assert_called_once_with(msg_instance) + + def test_handler_ignored_if_subset_handler_present(self): + msg, handler, subscriber = self.get_subscription() + handler2 = MagicMock() + msg2 = SubsetMessage + self.hub.subscribe(subscriber, msg, handler) + self.hub.subscribe(subscriber, msg2, handler2) + msg_instance = SubsetMessage(Subset(None)) + self.hub.broadcast(msg_instance) + handler2.assert_called_once_with(msg_instance) + assert handler.call_count == 0 + + def test_filter(self): + msg, handler, subscriber = self.get_subscription() + filter = lambda x: False + self.hub.subscribe(subscriber, msg, handler) + msg_instance = msg("Test") + self.hub.broadcast(msg) + assert handler.call_count == 0 + + def test_broadcast_sends_to_all_subsribers(self): + msg, handler, subscriber = self.get_subscription() + msg, handler2, subscriber2 = self.get_subscription() + + self.hub.subscribe(subscriber, msg, handler) + self.hub.subscribe(subscriber2, msg, handler2) + msg_instance = msg("Test") + self.hub.broadcast(msg_instance) + handler.assert_called_once_with(msg_instance) + handler2.assert_called_once_with(msg_instance) + + def test_invalid_unsubscribe_ignored(self): + msg, handler, subscriber = self.get_subscription() + self.hub.unsubscribe(handler, subscriber) + + def test_invalid_subscribe(self): + + msg, handler, subscriber = self.get_subscription() + + with pytest.raises(InvalidSubscriber) as exc: + self.hub.subscribe(None, msg, handler) + assert exc.value.args[0].startswith("Subscriber must be a HubListener") + + with pytest.raises(InvalidMessage) as exc: + self.hub.subscribe(subscriber, None, handler) + assert exc.value.args[0].startswith("message class must be " + "a subclass of glue.Message") + + def test_default_handler(self): + msg, handler, subscriber = self.get_subscription() + self.hub.subscribe(subscriber, msg) + msg_instance = msg("Test") + + self.hub.broadcast(msg_instance) + subscriber.notify.assert_called_once_with(msg_instance) + + def test_autosubscribe(self): + l = MagicMock(spec_set=HubListener) + d = MagicMock(spec_set=Data) + s = MagicMock(spec_set=Subset) + dc = MagicMock(spec_set=DataCollection) + hub = Hub(l, d, s, dc) + + l.register_to_hub.assert_called_once_with(hub) + d.register_to_hub.assert_called_once_with(hub) + dc.register_to_hub.assert_called_once_with(hub) + s.register.assert_called_once_with() + + def test_invalid_init(self): + with pytest.raises(TypeError) as exc: + Hub(None) + assert exc.value.args[0] == ("Inputs must be HubListener, data, " + "subset, or data collection objects") + + +class TestHubListener(object): + """This is a dumb test, I know. Fixated on code coverage""" + + def test_unimplemented(self): + hl = HubListener() + with pytest.raises(NotImplementedError): + hl.register_to_hub(None) + with pytest.raises(NotImplementedError): + hl.notify(None) diff --git a/pool/shard002/Python/0025686_cli.py b/pool/shard002/Python/0025686_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..ea0eff7e32263be86bfa42c3775ed5ccc9b2e6c3 --- /dev/null +++ b/pool/shard002/Python/0025686_cli.py @@ -0,0 +1,35 @@ +import argparse +import json + +from aguin import Aguin + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('-k', '--api-key', required=True, type=str, help='Api key') + parser.add_argument('-s', '--api-secret', required=True, type=str, help='Api secret') + parser.add_argument('-ak', '--aes-key', required=True, type=str, help='AES key') + parser.add_argument('-u', '--url', required=True, type=str, help='Url to api') + parser.add_argument('-a', '--action', required=True, type=str, choices=['GET','POST'], help='Indicate if POST or GET') + parser.add_argument('-e', '--entity', required=True, type=str, help='Name of the entity') + parser.add_argument('-d', '--data', type=str, help='Json data to send. If action is post then it is entity data, if get then search criteria') + parser.add_argument('-p', '--pretty', action='store_true', help='Pretty print of the result') + + args = parser.parse_args() + + api = Aguin(args.api_key, args.api_secret, args.aes_key, args.url) + + if args.data: + args.data = json.loads(args.data) + + if args.action == 'GET': + result = api.get(args.entity, criteria=args.data) + elif args.action =='POST': + result = api.post(args.entity, args.data) + + if args.pretty: + print json.dumps(result, sort_keys=True, indent=4) + else: + print json.dumps(result) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/pool/shard002/Python/0025696_process.py b/pool/shard002/Python/0025696_process.py new file mode 100644 index 0000000000000000000000000000000000000000..155074a3ccef54a4d20221e50f3372b850c3fcd9 --- /dev/null +++ b/pool/shard002/Python/0025696_process.py @@ -0,0 +1,61 @@ +from oldowan.mtconvert import seq2sites, sites2seq, str2sites +from oldowan.fasta import fasta +from string import translate +import pandas as pd +import sys +import re + +sys.path.append('../../scripts') +from utils import * + +## load metadata +metadata = pd.read_csv('metadata.csv', index_col=0) +region = range2region(metadata.ix[0, 'SeqRange']) + +ff = fasta('barbieri2012.fasta', 'r') +data = ff.readentries() +ff.close() + +hids = [] +groups = [] +sites = [] +sequences = [] + +for entry in data: + words = entry['name'].split() + if entry['sequence'].count('N') > 10: + print "Too many Ns in %s (%s), skipping" % (words[0], words[1]) + else: + hids.append(words[0]) + groups.append(words[1]) + sites.append(seq2sites(entry['sequence'])) + sequences.append(entry['sequence']) + +# validate +passed_validation = True + +for i in range(len(sites)): + seq1 = sequences[i] + seq2 = translate(sites2seq(sites[i], region), None, '-') + if not seq1 == seq2: + # some sequences have an N in the poly-C region around 309. + if seq1[:305] == seq2[:305] and seq1[-16254:] == seq2[-16254:]: + pass + else: + passed_validation = False + print i, hids[i] + +counter = {} +for k in metadata.index: + counter[k] = 0 + +if passed_validation: + with open('processed.csv', 'w') as f: + for i in range(len(sites)): + hid = hids[i] + key = groups[i] + prefix = metadata.ix[key,'NewPrefix'] + counter[key] += 1 + newid = prefix + str(counter[key]).zfill(3) + mysites = ' '.join([str(x) for x in sites[i]]) + f.write('%s,%s,%s\n' % (newid, hid, mysites)) \ No newline at end of file diff --git a/pool/shard002/Python/0025700_example_multiprocessing.py b/pool/shard002/Python/0025700_example_multiprocessing.py new file mode 100644 index 0000000000000000000000000000000000000000..35c17b5b582c079cef15a6991f23e889ce5561b7 --- /dev/null +++ b/pool/shard002/Python/0025700_example_multiprocessing.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 + + +import multiprocessing +import time + + +def xyz(): + for i in range(10): + print("thread") + time.sleep(1) + + +if __name__ == '__main__': + proc = multiprocessing.Process(target=xyz) + proc.start() + for i in range(10): + print("main") + time.sleep(1) diff --git a/pool/shard002/Python/0025703_types.py b/pool/shard002/Python/0025703_types.py new file mode 100644 index 0000000000000000000000000000000000000000..083452329a345934da7fd0d7e5ae6559b6bfd19d --- /dev/null +++ b/pool/shard002/Python/0025703_types.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2018 Google LLC +# +# 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 +# +# https://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 __future__ import absolute_import +import sys + +from google.api_core.protobuf_helpers import get_messages + +from google.api import http_pb2 +from google.cloud.speech_v1p1beta1.proto import cloud_speech_pb2 +from google.longrunning import operations_pb2 +from google.protobuf import any_pb2 +from google.protobuf import descriptor_pb2 +from google.protobuf import duration_pb2 +from google.protobuf import empty_pb2 +from google.protobuf import timestamp_pb2 +from google.rpc import status_pb2 + +_shared_modules = [ + http_pb2, + operations_pb2, + any_pb2, + descriptor_pb2, + duration_pb2, + empty_pb2, + timestamp_pb2, + status_pb2, +] + +_local_modules = [ + cloud_speech_pb2, +] + +names = [] + +for module in _shared_modules: + for name, message in get_messages(module).items(): + setattr(sys.modules[__name__], name, message) + names.append(name) +for module in _local_modules: + for name, message in get_messages(module).items(): + message.__module__ = 'google.cloud.speech_v1p1beta1.types' + setattr(sys.modules[__name__], name, message) + names.append(name) + +__all__ = tuple(sorted(names)) diff --git a/pool/shard002/Python/0025705_websocket.py b/pool/shard002/Python/0025705_websocket.py new file mode 100644 index 0000000000000000000000000000000000000000..a9be1f2b2f8f3cbd8d632601dbfa613680d5ee67 --- /dev/null +++ b/pool/shard002/Python/0025705_websocket.py @@ -0,0 +1,96 @@ +"""websocket transport""" +import asyncio +from aiohttp import web + +from .base import Transport +from ..exceptions import SessionIsClosed +from ..protocol import STATE_CLOSED, FRAME_CLOSE +from ..protocol import loads, close_frame + + +class WebSocketTransport(Transport): + + @asyncio.coroutine + def server(self, ws, session): + while True: + try: + frame, data = yield from session._wait() + except SessionIsClosed: + break + + ws.send_str(data) + + if frame == FRAME_CLOSE: + try: + yield from ws.close() + finally: + yield from session._remote_closed() + + @asyncio.coroutine + def client(self, ws, session): + while True: + msg = yield from ws.receive() + + if msg.tp == web.MsgType.text: + data = msg.data + if not data: + continue + + if data.startswith('['): + data = data[1:-1] + + try: + text = loads(data) + except Exception as exc: + yield from session._remote_close(exc) + yield from session._remote_closed() + yield from ws.close(message=b'broken json') + break + + yield from session._remote_message(text) + + elif msg.tp == web.MsgType.close: + yield from session._remote_close() + elif msg.tp == web.MsgType.closed: + yield from session._remote_closed() + break + + @asyncio.coroutine + def process(self): + # start websocket connection + ws = self.ws = web.WebSocketResponse() + ws.start(self.request) + + # session was interrupted + if self.session.interrupted: + self.ws.send_str(close_frame(1002, 'Connection interrupted')) + + elif self.session.state == STATE_CLOSED: + self.ws.send_str(close_frame(3000, 'Go away!')) + + else: + try: + yield from self.manager.acquire(self.session) + except: # should use specific exception + self.ws.send_str(close_frame(3000, 'Go away!')) + yield from ws.close() + return ws + + server = asyncio.async(self.server(ws, self.session)) + client = asyncio.async(self.client(ws, self.session)) + try: + yield from asyncio.wait( + (server, client), + return_when=asyncio.FIRST_COMPLETED) + except asyncio.CancelledError: + raise + except Exception as exc: + yield from self.session._remote_close(exc) + finally: + yield from self.manager.release(self.session) + if not server.done(): + server.cancel() + if not client.done(): + client.cancel() + + return ws diff --git a/pool/shard002/Python/0025711_painter.py b/pool/shard002/Python/0025711_painter.py new file mode 100644 index 0000000000000000000000000000000000000000..960cdf1e5b1fcdffc9ddcfe68ce4123c46cc7a9e --- /dev/null +++ b/pool/shard002/Python/0025711_painter.py @@ -0,0 +1,82 @@ +#!/Users/harvey/Projects/face-hack/venv/face/bin/python +# +# The Python Imaging Library +# $Id$ +# +# this demo script illustrates pasting into an already displayed +# photoimage. note that the current version of Tk updates the whole +# image everytime we paste, so to get decent performance, we split +# the image into a set of tiles. +# + +try: + from tkinter import Tk, Canvas, NW +except ImportError: + from Tkinter import Tk, Canvas, NW + +from PIL import Image, ImageTk +import sys + +# +# painter widget + + +class PaintCanvas(Canvas): + def __init__(self, master, image): + Canvas.__init__(self, master, width=image.size[0], height=image.size[1]) + + # fill the canvas + self.tile = {} + self.tilesize = tilesize = 32 + xsize, ysize = image.size + for x in range(0, xsize, tilesize): + for y in range(0, ysize, tilesize): + box = x, y, min(xsize, x+tilesize), min(ysize, y+tilesize) + tile = ImageTk.PhotoImage(image.crop(box)) + self.create_image(x, y, image=tile, anchor=NW) + self.tile[(x, y)] = box, tile + + self.image = image + + self.bind("", self.paint) + + def paint(self, event): + xy = event.x - 10, event.y - 10, event.x + 10, event.y + 10 + im = self.image.crop(xy) + + # process the image in some fashion + im = im.convert("L") + + self.image.paste(im, xy) + self.repair(xy) + + def repair(self, box): + # update canvas + dx = box[0] % self.tilesize + dy = box[1] % self.tilesize + for x in range(box[0]-dx, box[2]+1, self.tilesize): + for y in range(box[1]-dy, box[3]+1, self.tilesize): + try: + xy, tile = self.tile[(x, y)] + tile.paste(self.image.crop(xy)) + except KeyError: + pass # outside the image + self.update_idletasks() + +# +# main + +root = Tk() + +if len(sys.argv) != 2: + print("Usage: painter file") + sys.exit(1) + +im = Image.open(sys.argv[1]) + +if im.mode != "RGB": + im = im.convert("RGB") + +PaintCanvas(root, im).pack() + +root.mainloop() diff --git a/pool/shard002/Python/0025717_test_quotas.py b/pool/shard002/Python/0025717_test_quotas.py new file mode 100644 index 0000000000000000000000000000000000000000..a17eca070a14bea654e7eff64b690b430a6ea4ec --- /dev/null +++ b/pool/shard002/Python/0025717_test_quotas.py @@ -0,0 +1,87 @@ +# Copyright 2013 OpenStack Foundation +# 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 six +from tempest import test +from tempest_lib.common.utils import data_utils + +from neutron.tests.api import base + + +class QuotasTest(base.BaseAdminNetworkTest): + + """ + Tests the following operations in the Neutron API using the REST client for + Neutron: + + list quotas for tenants who have non-default quota values + show quotas for a specified tenant + update quotas for a specified tenant + reset quotas to default values for a specified tenant + + v2.0 of the API is assumed. + It is also assumed that the per-tenant quota extension API is configured + in /etc/neutron/neutron.conf as follows: + + quota_driver = neutron.db.driver.DbQuotaDriver + """ + + @classmethod + def resource_setup(cls): + super(QuotasTest, cls).resource_setup() + if not test.is_extension_enabled('quotas', 'network'): + msg = "quotas extension not enabled." + raise cls.skipException(msg) + + @test.attr(type='gate') + @test.idempotent_id('2390f766-836d-40ef-9aeb-e810d78207fb') + def test_quotas(self): + # Add a tenant to conduct the test + test_tenant = data_utils.rand_name('test_tenant_') + test_description = data_utils.rand_name('desc_') + tenant = self.identity_admin_client.create_tenant( + name=test_tenant, + description=test_description)['tenant'] + tenant_id = tenant['id'] + self.addCleanup(self.identity_admin_client.delete_tenant, tenant_id) + + new_quotas = {'network': 0, 'security_group': 0} + + # Change quotas for tenant + quota_set = self.admin_client.update_quotas(tenant_id, + **new_quotas) + self.addCleanup(self.admin_client.reset_quotas, tenant_id) + for key, value in six.iteritems(new_quotas): + self.assertEqual(value, quota_set[key]) + + # Confirm our tenant is listed among tenants with non default quotas + non_default_quotas = self.admin_client.list_quotas() + found = False + for qs in non_default_quotas['quotas']: + if qs['tenant_id'] == tenant_id: + found = True + self.assertTrue(found) + + # Confirm from API quotas were changed as requested for tenant + quota_set = self.admin_client.show_quotas(tenant_id) + quota_set = quota_set['quota'] + for key, value in six.iteritems(new_quotas): + self.assertEqual(value, quota_set[key]) + + # Reset quotas to default and confirm + self.admin_client.reset_quotas(tenant_id) + non_default_quotas = self.admin_client.list_quotas() + for q in non_default_quotas['quotas']: + self.assertNotEqual(tenant_id, q['tenant_id']) diff --git a/pool/shard002/Python/0025726_clean_fasta.py b/pool/shard002/Python/0025726_clean_fasta.py new file mode 100644 index 0000000000000000000000000000000000000000..f3163ca2b4e6eeb664b495f7bd8a7e9b5bef55d5 --- /dev/null +++ b/pool/shard002/Python/0025726_clean_fasta.py @@ -0,0 +1,29 @@ +import argparse +from Bio import SeqIO +import math + +parser = argparse.ArgumentParser(description="Calculate effective lengths of sequences") +parser.add_argument("fasta_file", type=str, help="fasta file of reference sequences") +parser.add_argument("cleaned_output", type=str, help="cleaned fasta output") +args = parser.parse_args() + +def clean_letter(l): + if l == "A" or l == "a": + return l + elif l == "T" or l == "t": + return l + elif l == "G" or l == "g": + return l + elif l == "C" or l == "c": + return l + else: + return "N" + + +out = open(args.cleaned_output,'w') +handle = open(args.fasta_file,'r') +for record in SeqIO.parse(handle, "fasta"): + out.write(">%s\n"%(record.id)) + out.write("%s\n"%( "".join([clean_letter(l) for l in str(record.seq)]) )) +handle.close() +out.close() diff --git a/pool/shard002/Python/0025728_conftest.py b/pool/shard002/Python/0025728_conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..6a2d11c90646980462c630e59e97007b34e0759e --- /dev/null +++ b/pool/shard002/Python/0025728_conftest.py @@ -0,0 +1,95 @@ +import pytest + +import logging +log = logging.getLogger(__name__) + +INI = 'test.ini' +#INI = 'production.ini' + +from karakara.tests.data.tracks import * +from karakara.tests.data.tracks_random import * +from karakara.tests.data.auth import * + +# Markers ---------------------------------------------------------------------- + +def pytest_addoption(parser): + parser.addoption("--runslow", action="store_true", help="run slow tests") +def pytest_runtest_setup(item): + if 'unimplemented' in item.keywords: #and not item.config.getoption("--runslow"): + pytest.skip('unimplemented functionality') + if 'unfinished' in item.keywords: + pytest.skip('unfinished functionality') + try: + runslow = item.config.getoption("--runslow") + except ValueError: + runslow = False + if 'slow' in item.keywords and not runslow: + pytest.skip("need --runslow option to run") + + logging.basicConfig(level=logging.DEBUG) + +unimplemented = pytest.mark.unimplemented # Server dose not support the functionlity this test is asserting yet +unfinished = pytest.mark.unfinished # The test is unfinished and currently is know to fail +xfail = pytest.mark.xfail +slow = pytest.mark.slow + +# Fixtures --------------------------------------------------------------------- + + +@pytest.fixture(scope="session") +def app_ini(request, ini_file=INI): + """ + Settings object derived from .ini file required to start Pyramid app + """ + from pyramid.paster import get_appsettings + return get_appsettings(ini_file) + + +@pytest.fixture(scope="session") +def app(request, app_ini): + """ + Start KaraKara application + """ + from webtest import TestApp + from karakara import main as karakara_main + + #print('setup WebApp') + app = TestApp(karakara_main({}, **app_ini)) + + from karakara.model.init_data import init_data + init_data() + + def finalizer(): + #print('tearDown WebApp') + pass + request.addfinalizer(finalizer) + + return app + + +@pytest.fixture(scope="session") +def DBSession(request, app): + """ + Aquire DBSession from WebTest App + The WSGI app has already been started, + we can import the session safly knowing it has been setup + """ + from karakara.model import DBSession + return DBSession + + +@pytest.fixture(scope="session") +def commit(request, DBSession): + """ + Save data attached to DBSession + """ + from karakara.model import commit + return commit + + +@pytest.fixture() +def settings(request, app): + """ + Registry settings dictionary used in the running KaraKara app + """ + return app.app.registry.settings diff --git a/pool/shard002/Python/0025733_browser.py b/pool/shard002/Python/0025733_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..2098a681416bec2214fb72fbbe70164fd23f0006 --- /dev/null +++ b/pool/shard002/Python/0025733_browser.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- + +# Copyright(C) 2015 Baptiste Delpey +# +# This file is part of a weboob module. +# +# This weboob module 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 weboob module 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 weboob module. If not, see . + + +from weboob.exceptions import BrowserIncorrectPassword, BrowserPasswordExpired +from weboob.browser import LoginBrowser, URL, need_login +from weboob.browser.switch import SiteSwitch +from weboob.tools.capabilities.bank.transactions import sorted_transactions + +from .pages import LoginPage, ErrorPage, AccountsPage, TransactionsPage, \ + TiCardPage, TiHistoPage, ComingPage, HistoPage, HomePage + + +class BnpcartesentrepriseBrowser(LoginBrowser): + BASEURL = 'https://www.cartesentreprise.bnpparibas.com' + + login = URL('/ce_internet_public/seConnecter.builder.do', LoginPage) + error = URL('.*.seConnecter.event.do', + '.*.compteGestChgPWD.builder.do', + '/ce_internet_prive_ti/compteTituChgPWD.builder.do', + r'/ce_internet_corporate_ti/compteTituChgPWDCorporate.builder.do', + ErrorPage) + home = URL('/ce_internet_prive_ge/accueilInternetGe.builder.do', + '/ce_internet_(prive|corporate)_ti/accueilInternetTi(Corporate)?.builder.do', HomePage) + accounts = URL('/ce_internet_prive_ge/carteAffaireParc.builder.do', + '/ce_internet_prive_ge/carteAffaireParcChange.event.do', + '/ce_internet_prive_ge/pageParcCarteAffaire.event.do', AccountsPage) + coming = URL('/ce_internet_prive_ge/operationEnCours.builder.do', + '/ce_internet_prive_ge/operationEnCours.event.do', ComingPage) + history = URL('/ce_internet_prive_ge/operationHisto.builder.do', + '/ce_internet_prive_ge/operationHisto.event.do', HistoPage) + transactions = URL('ce_internet_prive_ge/operationEnCoursDetail.builder.do.*', + 'ce_internet_prive_ge/pageOperationEnCoursDetail.event.do.*', + 'ce_internet_prive_ge/operationHistoDetail.builder.do.*', + 'ce_internet_prive_ge/pageOperationHistoDetail.event.do.*', + TransactionsPage) + + ti_card = URL('/ce_internet_prive_ti/operationEnCoursDetail.builder.do', + '/ce_internet_(prive|corporate)_ti/operation(Corporate)?EnCoursDetail(Afficher|Appliquer)?.event.do.*', + '/ce_internet_prive_ti/pageOperationEnCoursDetail.event.do.*', TiCardPage) + ti_corporate_card = URL('/ce_internet_corporate_ti/operationCorporateEnCoursDetail.builder.do', TiCardPage) + ti_histo = URL('/ce_internet_prive_ti/operationHistoDetail.builder.do', + '/ce_internet_(prive|corporate)_ti/operation(Corporate)?HistoDetail(Afficher|Appliquer)?.event.do.*', + '/ce_internet_prive_ti/pageOperationHistoDetail.event.do.*', TiHistoPage) + ti_corporate_histo = URL('/ce_internet_corporate_ti/operationCorporateHistoDetail.builder.do', TiHistoPage) + TIMEOUT = 60.0 + + def __init__(self, type, *args, **kwargs): + super(BnpcartesentrepriseBrowser, self).__init__(*args, **kwargs) + self.type = type + self.is_corporate = False + self.transactions_dict = {} + + def do_login(self): + assert isinstance(self.username, basestring) + assert isinstance(self.password, basestring) + self.login.stay_or_go() + assert self.login.is_here() + self.page.login(self.type, self.username, self.password) + if self.error.is_here() or self.page.is_error(): + raise BrowserIncorrectPassword() + if self.type == '2' and self.page.is_corporate(): + raise SiteSwitch('corporate') + # ti corporate and ge corporate are not detected the same way .. + if 'corporate' in self.page.url: + self.is_corporate = True + + def ti_card_go(self): + if self.is_corporate: + self.ti_corporate_card.go() + else: + self.ti_card.go() + + def ti_histo_go(self): + if self.is_corporate: + self.ti_corporate_histo.go() + else: + self.ti_histo.go() + + @need_login + def iter_accounts(self): + if self.type == '1': + self.ti_card_go() + elif self.type == '2': + self.accounts.go() + + if self.error.is_here(): + raise BrowserPasswordExpired() + + if self.type == '1': + for account in self.page.iter_accounts(rib=None): + self.page.expand(account=account) + account.coming = self.page.get_balance() + yield account + if self.type == '2': + for company in self.page.get_companies(): + self.accounts.stay_or_go() + self.page.expand(company=company) + for rib in self.page.get_rib_list(): + self.page.expand(rib=rib, company=company) + + accounts = list(self.page.iter_accounts(rib=rib, company=company)) + ids = {} + prev_rib = None + for account in accounts: + if account.id in ids: + self.logger.warning('duplicate account %r', account.id) + account.id += '_%s' % ''.join(account.label.split()) + + if prev_rib != account._rib: + self.coming.go() + self.page.expand(rib=account._rib, company=account._company) + account.coming = self.page.get_balance(account) + prev_rib = account._rib + + ids[account.id] = account + yield account + + # Could be the very same as non corporate but this shitty website seems + # completely bugged + def get_ti_corporate_transactions(self, account): + if account.id not in self.transactions_dict: + self.transactions_dict[account.id] = [] + self.ti_histo_go() + self.page.expand(self.page.get_periods()[0], account=account, company=account._company) + for tr in sorted_transactions(self.page.get_history()): + self.transactions_dict[account.id].append(tr) + return self.transactions_dict[account.id] + + def get_ti_transactions(self, account): + self.ti_card_go() + self.page.expand(account=account, company=account._company) + for tr in sorted_transactions(self.page.get_history()): + yield tr + self.ti_histo_go() + self.page.expand(self.page.get_periods()[0], account=account, company=account._company) + for period in self.page.get_periods(): + self.page.expand(period, account=account, company=account._company) + for tr in sorted_transactions(self.page.get_history()): + yield tr + + def get_ge_transactions(self, account): + transactions = [] + self.coming.go() + self.page.expand(account=account, rib=account._rib, company=account._company) + link = self.page.get_link(account) + if link: + self.location(link) + transactions += self.page.get_history() + self.history.go() + for period in self.page.get_periods(): + self.page.expand(period, rib=account._rib, company=account._company, account=account) + link = self.page.get_link(account) + if link: + self.location(link) + transactions += self.page.get_history() + self.history.go() + return sorted_transactions(transactions) + + @need_login + def get_transactions(self, account): + if self.type == '1': + if self.is_corporate: + return self.get_ti_corporate_transactions(account) + return self.get_ti_transactions(account) + return self.get_ge_transactions(account) diff --git a/pool/shard002/Python/0025740_test_learning_unit_pedagogy.py b/pool/shard002/Python/0025740_test_learning_unit_pedagogy.py new file mode 100644 index 0000000000000000000000000000000000000000..8712f5359a4d9d7a232d728f7f8f382c0bd43395 --- /dev/null +++ b/pool/shard002/Python/0025740_test_learning_unit_pedagogy.py @@ -0,0 +1,203 @@ +############################################################################## +# +# OSIS stands for Open Student Information System. It's an application +# designed to manage the core business of higher education institutions, +# such as universities, faculties, institutes and professional schools. +# The core business involves the administration of students, teachers, +# courses, programs and so on. +# +# Copyright (C) 2015-2018 Université catholique de Louvain (http://www.uclouvain.be) +# +# 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. +# +# A copy of this license - GNU General Public License - is available +# at the root of the source code of this program. If not, +# see http://www.gnu.org/licenses/. +# +############################################################################## +import uuid +from copy import copy +from unittest.mock import patch + +from django.conf import settings +from django.contrib.auth.models import Permission +from django.test import TestCase + +from base.forms.learning_unit_pedagogy import LearningUnitPedagogyEditForm, TeachingMaterialModelForm +from base.models.enums.learning_unit_year_subtypes import FULL +from base.tests.factories.academic_year import create_current_academic_year +from base.tests.factories.business.learning_units import GenerateAcademicYear +from base.tests.factories.learning_unit_year import LearningUnitYearFactory +from base.tests.factories.person import PersonFactory +from base.tests.factories.teaching_material import TeachingMaterialFactory +from cms.enums import entity_name +from cms.tests.factories.text_label import TextLabelFactory +from cms.tests.factories.translated_text import TranslatedTextFactory +from reference.tests.factories.language import LanguageFactory + + +class LearningUnitPedagogyContextMixin(TestCase): + """"This mixin is used in this test file in order to setup an environment for testing pedagogy""" + def setUp(self): + self.language = LanguageFactory(code="EN") + self.person = PersonFactory() + self.person.user.user_permissions.add(Permission.objects.get(codename="can_edit_learningunit_pedagogy")) + self.current_ac = create_current_academic_year() + self.ac_years_containers = GenerateAcademicYear(start_year=self.current_ac.year + 1, + end_year=self.current_ac.year + 5) + self.current_luy = LearningUnitYearFactory( + learning_container_year__academic_year=self.current_ac, + academic_year=self.current_ac, + acronym="LAGRO1000", + subtype=FULL + ) + self.luys = {self.current_ac.year: self.current_luy} + self.luys.update( + _duplicate_learningunityears(self.current_luy, academic_years=self.ac_years_containers.academic_years) + ) + + +class TestValidation(LearningUnitPedagogyContextMixin): + def setUp(self): + super().setUp() + self.cms_translated_text = TranslatedTextFactory( + entity=entity_name.LEARNING_UNIT_YEAR, + reference=self.luys[self.current_ac.year].id, + language='EN', + text='Text random' + ) + self.valid_form_data = _get_valid_cms_form_data(self.cms_translated_text) + + def test_invalid_form(self): + del self.valid_form_data['cms_id'] + form = LearningUnitPedagogyEditForm(self.valid_form_data) + self.assertFalse(form.is_valid()) + + def test_valid_form(self): + form = LearningUnitPedagogyEditForm(self.valid_form_data) + self.assertEqual(form.errors, {}) + self.assertTrue(form.is_valid()) + + @patch("cms.models.translated_text.update_or_create") + def test_save_without_postponement(self, mock_update_or_create): + """In this test, we ensure that if we modify UE of N or N-... => The postponement is not done for CMS data""" + form = LearningUnitPedagogyEditForm(self.valid_form_data) + self.assertTrue(form.is_valid(), form.errors) + form.save() + mock_update_or_create.assert_called_once_with(entity=self.cms_translated_text.entity, + reference=self.cms_translated_text.reference, + language=self.cms_translated_text.language, + text_label=self.cms_translated_text.text_label, + defaults={'text': self.cms_translated_text.text}) + + @patch("cms.models.translated_text.update_or_create") + def test_save_with_postponement(self, mock_update_or_create): + """In this test, we ensure that if we modify UE of N+1 or N+X => The postponement until the lastest UE""" + luy_in_future = self.luys[self.current_ac.year + 1] + cms_pedagogy_future = TranslatedTextFactory( + entity=entity_name.LEARNING_UNIT_YEAR, + reference=luy_in_future.id, + language='EN', + text='Text in future' + ) + form = LearningUnitPedagogyEditForm(data=_get_valid_cms_form_data(cms_pedagogy_future)) + self.assertTrue(form.is_valid(), form.errors) + form.save() + + # N+1 ===> N+6 + self.assertEqual(mock_update_or_create.call_count, 5) + + +class TestTeachingMaterialForm(LearningUnitPedagogyContextMixin): + @patch('base.models.teaching_material.postpone_teaching_materials', side_effect=lambda *args: None) + def test_save_without_postponement(self, mock_postpone_teaching_materials): + """In this test, we ensure that if we modify UE of N or N-... => The postponement is not done for teaching + materials""" + teaching_material = TeachingMaterialFactory.build(learning_unit_year=self.current_luy) + post_data = _get_valid_teaching_material_form_data(teaching_material) + teaching_material_form = TeachingMaterialModelForm(post_data) + self.assertTrue(teaching_material_form.is_valid(), teaching_material_form.errors) + teaching_material_form.save(learning_unit_year=self.current_luy) + self.assertFalse(mock_postpone_teaching_materials.called) + + @patch('base.models.teaching_material.postpone_teaching_materials', side_effect=lambda *args: None) + def test_save_with_postponement(self, mock_postpone_teaching_materials): + """In this test, we ensure that if we modify UE of N+1 or N+X => The postponement until the lastest UE""" + luy_in_future = self.luys[self.current_ac.year + 1] + teaching_material = TeachingMaterialFactory.build(learning_unit_year=luy_in_future) + post_data = _get_valid_teaching_material_form_data(teaching_material) + teaching_material_form = TeachingMaterialModelForm(post_data) + self.assertTrue(teaching_material_form.is_valid(), teaching_material_form.errors) + teaching_material_form.save(learning_unit_year=luy_in_future) + self.assertTrue(mock_postpone_teaching_materials.called) + + +class TestLearningUnitPedagogyEditForm(LearningUnitPedagogyContextMixin): + @patch("cms.models.translated_text.update_or_create") + def test_save_fr_bibliography_also_updates_en_bibliography(self, mock_update_or_create): + """Ensure that if we modify bibliography in FR => bibliography in EN is updated with same text""" + text_label_bibliography = TextLabelFactory( + entity=entity_name.LEARNING_UNIT_YEAR, + label='bibliography' + ) + cms_translated_text_fr = TranslatedTextFactory( + entity=entity_name.LEARNING_UNIT_YEAR, + reference=self.luys[self.current_ac.year].id, + language='fr-be', + text_label=text_label_bibliography, + text='Some random text' + ) + valid_form_data_fr = _get_valid_cms_form_data(cms_translated_text_fr) + + form = LearningUnitPedagogyEditForm(valid_form_data_fr) + self.assertTrue(form.is_valid(), form.errors) + form.save() + + for language in settings.LANGUAGES: + mock_update_or_create.assert_any_call( + entity=cms_translated_text_fr.entity, + reference=cms_translated_text_fr.reference, + language=language[0], + text_label=cms_translated_text_fr.text_label, + defaults={'text': cms_translated_text_fr.text} + ) + + +def _duplicate_learningunityears(luy_to_duplicate, academic_years): + # Duplicate learning unit year with different academic year + luys = {} + for ac_year in academic_years: + new_luy = copy(luy_to_duplicate) + new_luy.pk = None + new_luy.uuid = uuid.uuid4() + new_luy.academic_year = ac_year + new_luy.save() + luys[ac_year.year] = new_luy + return luys + + +def _get_valid_cms_form_data(cms_translated_text): + """Valid data for form CMS form""" + return { + "trans_text": getattr(cms_translated_text, 'text'), + "cms_id": getattr(cms_translated_text, 'id'), + "reference": getattr(cms_translated_text, 'reference') + } + + +def _get_valid_teaching_material_form_data(teaching_material): + """Valid data for teaching material form""" + data = { + 'title': teaching_material.title, + } + if getattr(teaching_material, 'mandatory', False): + data['mandatory'] = 'on' + return data diff --git a/pool/shard002/Python/0025750_test_bytes_utils.py b/pool/shard002/Python/0025750_test_bytes_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..aed29a6a95f9a7f653ca9eb1dad9521041c3c605 --- /dev/null +++ b/pool/shard002/Python/0025750_test_bytes_utils.py @@ -0,0 +1,122 @@ +import io + +import pytest + +from dask.bytes.utils import read_block, seek_delimiter, infer_storage_options + + +def test_read_block(): + delimiter = b'\n' + data = delimiter.join([b'123', b'456', b'789']) + f = io.BytesIO(data) + + assert read_block(f, 1, 2) == b'23' + assert read_block(f, 0, 1, delimiter=b'\n') == b'123\n' + assert read_block(f, 0, 2, delimiter=b'\n') == b'123\n' + assert read_block(f, 0, 3, delimiter=b'\n') == b'123\n' + assert read_block(f, 0, 5, delimiter=b'\n') == b'123\n456\n' + assert read_block(f, 0, 8, delimiter=b'\n') == b'123\n456\n789' + assert read_block(f, 0, 100, delimiter=b'\n') == b'123\n456\n789' + assert read_block(f, 1, 1, delimiter=b'\n') == b'' + assert read_block(f, 1, 5, delimiter=b'\n') == b'456\n' + assert read_block(f, 1, 8, delimiter=b'\n') == b'456\n789' + + for ols in [[(0, 3), (3, 3), (6, 3), (9, 2)], + [(0, 4), (4, 4), (8, 4)]]: + out = [read_block(f, o, l, b'\n') for o, l in ols] + assert b"".join(filter(None, out)) == data + + +def test_seek_delimiter_endline(): + f = io.BytesIO(b'123\n456\n789') + + # if at zero, stay at zero + seek_delimiter(f, b'\n', 5) + assert f.tell() == 0 + + # choose the first block + for bs in [1, 5, 100]: + f.seek(1) + seek_delimiter(f, b'\n', blocksize=bs) + assert f.tell() == 4 + + # handle long delimiters well, even with short blocksizes + f = io.BytesIO(b'123abc456abc789') + for bs in [1, 2, 3, 4, 5, 6, 10]: + f.seek(1) + seek_delimiter(f, b'abc', blocksize=bs) + assert f.tell() == 6 + + # End at the end + f = io.BytesIO(b'123\n456') + f.seek(5) + seek_delimiter(f, b'\n', 5) + assert f.tell() == 7 + + +def test_infer_storage_options(): + so = infer_storage_options('/mnt/datasets/test.csv') + assert so.pop('protocol') == 'file' + assert so.pop('path') == '/mnt/datasets/test.csv' + assert not so + + assert infer_storage_options('./test.csv')['path'] == './test.csv' + assert infer_storage_options('../test.csv')['path'] == '../test.csv' + + so = infer_storage_options('C:\\test.csv') + assert so.pop('protocol') == 'file' + assert so.pop('path') == 'C:\\test.csv' + assert not so + + assert infer_storage_options('d:\\test.csv')['path'] == 'd:\\test.csv' + assert infer_storage_options('\\test.csv')['path'] == '\\test.csv' + assert infer_storage_options('.\\test.csv')['path'] == '.\\test.csv' + assert infer_storage_options('test.csv')['path'] == 'test.csv' + + so = infer_storage_options( + 'hdfs://username:pwd@Node:123/mnt/datasets/test.csv?q=1#fragm', + inherit_storage_options={'extra': 'value'}) + assert so.pop('protocol') == 'hdfs' + assert so.pop('username') == 'username' + assert so.pop('password') == 'pwd' + assert so.pop('host') == 'Node' + assert so.pop('port') == 123 + assert so.pop('path') == '/mnt/datasets/test.csv' + assert so.pop('url_query') == 'q=1' + assert so.pop('url_fragment') == 'fragm' + assert so.pop('extra') == 'value' + assert not so + + so = infer_storage_options('hdfs://User-name@Node-name.com/mnt/datasets/test.csv') + assert so.pop('username') == 'User-name' + assert so.pop('host') == 'Node-name.com' + + u = 'http://127.0.0.1:8080/test.csv' + assert infer_storage_options(u) == {'protocol': 'http', 'path': u} + + # For s3 and gcs the netloc is actually the bucket name, so we want to + # include it in the path. Test that: + # - Parsing doesn't lowercase the bucket + # - The bucket is included in path + for protocol in ['s3', 'gcs', 'gs']: + options = infer_storage_options('%s://Bucket-name.com/test.csv' % protocol) + assert options['path'] == 'Bucket-name.com/test.csv' + + with pytest.raises(KeyError): + infer_storage_options('file:///bucket/file.csv', {'path': 'collide'}) + with pytest.raises(KeyError): + infer_storage_options('hdfs:///bucket/file.csv', {'protocol': 'collide'}) + + +@pytest.mark.parametrize('urlpath, expected_path', ( + (r'c:\foo\bar', r'c:\foo\bar'), + (r'C:\\foo\bar', r'C:\\foo\bar'), + (r'c:/foo/bar', r'c:/foo/bar'), + (r'file:///c|\foo\bar', r'c:\foo\bar'), + (r'file:///C|/foo/bar', r'C:/foo/bar'), + (r'file:///C:/foo/bar', r'C:/foo/bar'), +)) +def test_infer_storage_options_c(urlpath, expected_path): + so = infer_storage_options(urlpath) + assert so['protocol'] == 'file' + assert so['path'] == expected_path diff --git a/pool/shard002/Python/0025753_admin.py b/pool/shard002/Python/0025753_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..e779f69677c4f5f4d6775f00141e230d150a998d --- /dev/null +++ b/pool/shard002/Python/0025753_admin.py @@ -0,0 +1,29 @@ +from django.conf.urls import url +from django.contrib import admin +from django.db import models +from django.utils.translation import ugettext_lazy + +from apps.costs.admin_views import costs + + +class DummyModel(models.Model): + + class Meta: + verbose_name = ugettext_lazy('Costs') + verbose_name_plural = ugettext_lazy('Costs') + app_label = 'costs' + + +class DummyModelAdmin(admin.ModelAdmin): + model = DummyModel + + def get_urls(self): + view_name = '{}_{}_changelist'.format( + self.model._meta.app_label, self.model._meta.model_name) + return [ + url(r'costs/$', costs, name=view_name), + url(r'costs/(\d+)/(\d+)', costs, name=view_name), + ] + + +admin.site.register(DummyModel, DummyModelAdmin) diff --git a/pool/shard002/Python/0025760_test_console_script.py b/pool/shard002/Python/0025760_test_console_script.py new file mode 100644 index 0000000000000000000000000000000000000000..4a3e5bc8938d0083dbd38477fb03ddd7921ba88b --- /dev/null +++ b/pool/shard002/Python/0025760_test_console_script.py @@ -0,0 +1,29 @@ +import autonetkit.console_script as console_script +import subprocess +import os +import sys +#from cStringIO import StringIO +import shutil +import autonetkit.log as log +import autonetkit + +# stdio redirect from stackoverflow.com/q/2654834 + +#TODO: add feature that reports if only IP addresses have changed: match the diff to an IP regex + +automated = True # whether to open ksdiff, log to file... +if __name__ == "__main__": + automated = False + +dirname, filename = os.path.split(os.path.abspath(__file__)) + +anm = autonetkit.ANM() +input_file = os.path.join(dirname, "small_internet.graphml") +print input_file + +arg_string = "-f %s --diff --render" % input_file +args = console_script.parse_options(arg_string) + +console_script.main(args) + +#TODO: test output works \ No newline at end of file diff --git a/pool/shard002/Python/0025763_views.py b/pool/shard002/Python/0025763_views.py new file mode 100644 index 0000000000000000000000000000000000000000..6d9d6867520cdf81437231fa60891a1fe624044a --- /dev/null +++ b/pool/shard002/Python/0025763_views.py @@ -0,0 +1,277 @@ +import logging + +import copy +import urllib.parse as urlparse + +from django.urls import reverse +from django.http import HttpResponseRedirect, QueryDict +from django.views.generic import View +from django.views.generic.base import ContextMixin +from django.views.generic.base import TemplateResponseMixin +from django.views.generic.edit import FormMixin +from django.utils.translation import gettext + +from erudit.solr.models import get_model_instance +from base.http import JsonAckResponse +from base.http import JsonErrorResponse + +from . import filters, legacy +from .forms import ResultsFilterForm +from .forms import ResultsOptionsForm +from .forms import SearchForm +from .pagination import PaginationOutOfBoundsException +from .saved_searches import SavedSearchList +from .utils import get_search_elements, GET_as_dict + +logger = logging.getLogger(__name__) + + +class AdvancedSearchView(TemplateResponseMixin, FormMixin, View): + """ Displays the search form in order to perform advanced searches for Érudit documents. """ + + form_class = SearchForm + http_method_names = [ + "get", + ] + template_name = "public/search/advanced_search.html" + + def get(self, request, *args, **kwargs): + form = self.get_form() + if request.GET: + form.is_valid() + return self.render_to_response(self.get_context_data(form=form)) + + def get_context_data(self, **kwargs): + context = super(AdvancedSearchView, self).get_context_data(**kwargs) + + # Prepares the saved searches, generates the search elements for each querystring and + # inserts them into the context. + saved_searches = SavedSearchList(self.request) + if saved_searches: + _saved_searches = reversed(sorted(saved_searches, key=lambda s: s["timestamp"])) + sorted_saved_searches = [] + for search in _saved_searches: + new_search = search.copy() + qsdict = QueryDict(new_search["querystring"]) + new_search["elements"] = get_search_elements(qsdict) + sorted_saved_searches.append(new_search) + + context["saved_searches"] = sorted_saved_searches + + return context + + def get_form_kwargs(self): + kwargs = {"initial": self.get_initial(), "prefix": self.get_prefix()} + if self.request.GET: + MULTI = { + "article_types", + "publication_types", + "funds", + "disciplines", + "languages", + "journals", + } + kwargs["initial"].update(GET_as_dict(self.request.GET, MULTI)) + return kwargs + + +class SearchResultsView(TemplateResponseMixin, ContextMixin, View): + """ Display the results associated with a search for Érudit documents. """ + + filter_form_class = ResultsFilterForm + http_method_names = [ + "get", + ] + options_form_class = ResultsOptionsForm + search_form_class = SearchForm + template_name = "public/search/results.html" + + def __init__(self): + super().__init__() + self._search_form = None + + def get(self, request, *args, **kwargs): + # This view works only for GET requests + self.request = copy.copy(self.request) + search_form = self.get_search_form() + options_form = self.get_options_form() + search_form_valid, options_form_valid = search_form.is_valid(), options_form.is_valid() + if search_form_valid and options_form_valid: + return self.forms_valid(search_form, options_form) + else: + return self.forms_invalid(search_form, options_form) + + def get_search_form(self): + """ Returns an instance of the search form to be used in this view. """ + if self._search_form is None: + self._search_form = self.search_form_class(**self.get_search_form_kwargs()) + return self._search_form + + def get_search_form_kwargs(self): + """ Returns the keyword arguments for instantiating the search form. """ + form_kwargs = {} + + if self.request.method == "GET": + form_kwargs.update( + { + "data": self.request.GET, + } + ) + return form_kwargs + + def get_filter_form(self, **kwargs): + """ Returns an instance of the filter form to be used in this view. """ + return self.filter_form_class(**self.get_filter_form_kwargs(**kwargs)) + + def get_filter_form_kwargs(self, **kwargs): + """ Returns the keyword arguments for instantiating the filter form. """ + form_kwargs = {} + form_kwargs.update(kwargs) + + if self.request.method == "GET": + form_kwargs.update( + { + "data": self.request.GET, + } + ) + return form_kwargs + + def get_options_form(self): + """ Returns an instance of the options form to be used in this view. """ + return self.options_form_class(**self.get_options_form_kwargs()) + + def get_options_form_kwargs(self): + """ Returns the keyword arguments for instantiating the options form. """ + form_kwargs = {} + + self.request.GET = legacy.add_correspondences_to_search_query( + self.request, "filter_article_types", self.filter_form_class.article_type_correspondence + ) + + self.request.GET = legacy.add_correspondences_to_search_query( + self.request, "filter_languages", self.filter_form_class.language_code_correspondence + ) + + if self.request.method == "GET": + form_kwargs.update( + { + "data": self.request.GET, + } + ) + return form_kwargs + + def get_context_data(self, **kwargs): + context = super(SearchResultsView, self).get_context_data(**kwargs) + results = context.get("results", None) + + if results: + context["main_qterm"] = self.request.GET.get("basic_search_term", "") + context["start_at"] = (results["pagination"]["current_page"] - 1) * results[ + "pagination" + ]["page_size"] + context["search_elements"] = get_search_elements( + self.request.GET, form=self.get_search_form() + ) + + return context + + def forms_valid(self, search_form, options_form): + # Applies the search engine filter backend in order to get a list of filtered + # EruditDocument localidentifiers, a dictionnary contening the result of aggregations + # that should be embedded in the final response object and a number of hits. + + try: + pagination_info, documents, aggregations_dict = filters.SolrFilter().filter( + self.request + ) + except PaginationOutOfBoundsException: + return HttpResponseRedirect(reverse("public:search:advanced_search")) + + solr_objects = [get_model_instance(document) for document in documents] + results = { + "pagination": pagination_info, + "results": solr_objects, + "aggregations": aggregations_dict, + } + + # Initializes the filters form here in order to display it using choices generated from the + # aggregations embedded in the results. + filter_form = self.get_filter_form(api_results=results) + + return self.render_to_response( + self.get_context_data( + search_form=search_form, + filter_form=filter_form, + options_form=options_form, + results=results, + documents=results.get("results"), + ) + ) + + def forms_invalid(self, search_form, options_form): + GET = self.request.GET + if "basic_search_term" not in GET: + # This is simply a case of typing the /recherche/ url directly. We don't want to log + # those. + pass + elif "basic_search_term" in GET and not GET.get("basic_search_term"): + # This is simply a case of clicking on homepage's search magnifier without a search + # param. We don't want to log those, we just want to silently redirect. + pass + else: + # We have some unhandled form validation here that we'd like to know about. + logger.error( + "search.form.invalid", + extra={ + "stack": True, + "search_form_errors": search_form.errors.as_json(), + "options_form_errors": options_form.errors.as_json(), + }, + ) + return HttpResponseRedirect( + "{}?{}".format(reverse("public:search:advanced_search"), self.request.GET.urlencode()) + ) + + +class SavedSearchAddView(View): + """ Add a search's querystring to the list of saved searches associated to the current user. """ + + http_method_names = [ + "post", + ] + + def post(self, request): + querystring = request.POST.get("querystring", None) + results_count = request.POST.get("results_count", None) + if querystring is None or results_count is None: + return JsonErrorResponse(gettext("Querystring incorrecte")) + try: + urlparse.parse_qsl(querystring, strict_parsing=True) + results_count = int(results_count) + except ValueError: + return JsonErrorResponse(gettext("Querystring incorrecte")) + + # Inserts the search into the saved searches set + searches = SavedSearchList(request) + searches.add(querystring, results_count) + searches.save() + + return JsonAckResponse() + + +class SavedSearchRemoveView(View): + """ Remove a saved search from the list of saved searches associated to the current user. """ + + http_method_names = [ + "post", + ] + + def post(self, request, uuid): + searches = SavedSearchList(request) + try: + searches.remove(uuid) + except ValueError: + return JsonErrorResponse(gettext("Cette recherche n'est pas sauvegardée")) + + searches.save() + return JsonAckResponse() diff --git a/pool/shard002/Python/0025765_poids_carburants_parser.py b/pool/shard002/Python/0025765_poids_carburants_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..284574b9556c852e564b1931dea342a84eb752a6 --- /dev/null +++ b/pool/shard002/Python/0025765_poids_carburants_parser.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +import pandas as pd +import numpy as np + +from ipp_macro_series_parser.config import Config + +parser = Config() + +transports_directory = parser.get('data', 'transports_directory') +g_bilan_circulation = transports_directory + '/Annexes_G_-_Bilan_de_la_circulation.xls' + +def transports_parser(excelfile_name, onglet): + data_frame = pd.read_excel(excelfile_name, sheetname = onglet, skiprows = 2) + data_frame.rename(columns = {'Unnamed: 0': 'index'}, inplace = True) + data_frame = data_frame.dropna(thresh = 3) + data_frame.fillna('-', inplace = True) + return data_frame + + +def transports_parser_categ(excelfile_name, onglet): + data_frame = pd.read_excel(excelfile_name, sheetname = onglet, skiprows = 2) + data_frame.rename(columns = {'Unnamed: 0': 'index'}, inplace = True) + data_frame['categorie'] = np.nan + data_frame.loc[data_frame[2005].isnull(), 'categorie'] = \ + data_frame.loc[data_frame[2005].isnull(), 'index'] + data_frame['categorie'].fillna(method='ffill', inplace = True) + data_frame = data_frame.dropna(thresh = 3) + cols = data_frame.columns.tolist() + cols = cols[-1:] + cols[:-1] + data_frame = data_frame[cols] + return data_frame + + +parc_auto = transports_parser(g_bilan_circulation, 4) # composition moyenne du parc automobile (ess/die) +consommation = transports_parser_categ(g_bilan_circulation, 5) # consommation en L au 100 par type de véhicule (ess/die) diff --git a/pool/shard002/Python/0025768_image.py b/pool/shard002/Python/0025768_image.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b340210e563c1a41ae23af850be3505a2f9982 --- /dev/null +++ b/pool/shard002/Python/0025768_image.py @@ -0,0 +1,124 @@ +# This files defines a class for metadata objects of sentinel images. Large part of the work depends on python readers +# from the tops toolbox. +import os +import warnings +import zipfile +import copy + +from doris.doris_stack.main_code.swath import SwathMeta + + +class ImageMeta(object): + # Object for image files for sentinel data + + def __init__(self, path='' , pol='all' ,swath_no=['1','2','3']): + # Initialize function variables + + # This will contain a list of swath objects + self.swaths = [] + self.pol = pol + self.swath_no = swath_no + + # The following contain the path of xml and data files + self.swaths_xml = [] + self.swaths_data = [] + self.image_kml = '' + + # This variable contains the convex hull of all swaths together + self.metadata = [] + self.coverage = [] + + # The following variables store data on which processing steps are performed and the results of these steps. + self.steps = [] + self.steps_res = [] + + # The following variable is to check the total number of bursts for this image. This is used to remove time + # slots with less bursts. + self.burst_no = 0 + + # Check if the data is unzipped or not. If unzipped run the further initialization. + self.zip_path = '' + self.unzip_path = '' + if path.endswith('.zip'): + self.zip_path = path + else: + self.unzip_path = path + + # orbit information for this image + self.orbit = '' + + ###################################################### + + def init_unzipped(self, unzip_path=''): + # This function creates an image object and searches for available data and xml files. It gives an error when + # either the path does not exist, no data or xml files can be found or the data and xml files do not match. + # It is possible to choose one of the available polarisations or swaths using the pol and swath variables. + xml_dir = os.path.join(self.unzip_path, 'annotation') + xml = [f for f in os.listdir(xml_dir) if os.path.isfile(os.path.join(xml_dir, f))] + + data_dir = os.path.join(self.unzip_path, 'measurement') + data = [f for f in os.listdir(data_dir) if os.path.isfile(os.path.join(data_dir, f))] + + # Select polarisation + if any(s in self.pol for s in ('hh','vv','hv','vh')): + xml = [x for x in xml if x[12:14] in self.pol] + data = [x for x in data if x[12:14] in self.pol] + elif self.pol != 'all': + warnings.warn('Polarisation not recognized, using default (all)') + + # Select swaths + xml = sorted([os.path.join(self.unzip_path,'annotation',x) for x in xml if x[6] in self.swath_no]) + data = sorted([os.path.join(self.unzip_path,'measurement',x) for x in data if x[6] in self.swath_no]) + + # Initialize function values + dat = [os.path.basename(d) for d in data] + self.swaths_xml = [x for x in xml if os.path.basename(x)[:-4] + '.tiff' in dat] + self.swaths_data = data + + # Check if the data is there and if the filenames coincide. + if len(self.swaths_xml) == 0: + warnings.warn('There are no xml files') + + + def unzip(self, unzip_path=''): + # This function unzips the corresponding image, based on some requirements. + # Note that this is a backup function, while most unpacking is done by load_shape_unzip.py + if not os.path.exists(self.path): + try: + zip = zipfile.ZipFile(self.path + '.zip') + path = os.path.abspath(os.path.join(self.path, os.pardir)) + zip.extractall(path) + return True + except: + print('Failed to unpack!') + return False + else: + return True + + def meta_swath(self, precise_folder=''): + # This function reads and stores metadata of different swaths in the swath objects. + orbits = [] + orb_type = '' + + if not self.swaths_data: + self.init_unzipped() + + if not self.swaths: + for i in range(len(self.swaths_data)): + data = self.swaths_data[i] + xml = os.path.join(os.path.dirname(os.path.dirname(data)), 'annotation', os.path.basename(data)[:-5] + '.xml') + + # Initialize swath and load data from xml file + swath = SwathMeta(xml=xml, data=data) + swath.meta_swath() + + # Calculate the orbits for this swath and reuse it for other swaths if it is already calculated + if not orbits or not orb_type: + orbits, orb_type = swath.orbits_swath(precise_folder=precise_folder) + else: + swath.orbits = copy.deepcopy(orbits) + swath.orbit_type = orb_type + + # Define the resdata for the individual burst. And append the swath to the image object. + swath.meta_burst() + self.swaths.append(swath) diff --git a/pool/shard002/Python/0025770_image_provider.py b/pool/shard002/Python/0025770_image_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..87eed5eebd7680e578c822083efb8b9eab16b266 --- /dev/null +++ b/pool/shard002/Python/0025770_image_provider.py @@ -0,0 +1,86 @@ +# Copyright (c) 2016 PaddlePaddle 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. + +import io +import random + +import paddle.utils.image_util as image_util +from paddle.trainer.PyDataProvider2 import * + + +# +# {'img_size': 32, +# 'settings': , +# 'color': True, +# 'mean_img_size': 32, +# 'meta': './data/cifar-out/batches/batches.meta', +# 'num_classes': 10, +# 'file_list': ('./data/cifar-out/batches/train_batch_000',), +# 'use_jpeg': True} +def hook(settings, img_size, mean_img_size, num_classes, color, meta, use_jpeg, + is_train, **kwargs): + settings.mean_img_size = mean_img_size + settings.img_size = img_size + settings.num_classes = num_classes + settings.color = color + settings.is_train = is_train + + if settings.color: + settings.img_raw_size = settings.img_size * settings.img_size * 3 + else: + settings.img_raw_size = settings.img_size * settings.img_size + + settings.meta_path = meta + settings.use_jpeg = use_jpeg + + settings.img_mean = image_util.load_meta(settings.meta_path, + settings.mean_img_size, + settings.img_size, settings.color) + + settings.logger.info('Image size: %s', settings.img_size) + settings.logger.info('Meta path: %s', settings.meta_path) + settings.input_types = [ + dense_vector(settings.img_raw_size), # image feature + integer_value(settings.num_classes) + ] # labels + + settings.logger.info('DataProvider Initialization finished') + + +@provider(init_hook=hook, min_pool_size=0) +def processData(settings, file_list): + """ + The main function for loading data. + Load the batch, iterate all the images and labels in this batch. + file_list: the batch file list. + """ + with open(file_list, 'r') as fdata: + lines = [line.strip() for line in fdata] + random.shuffle(lines) + for file_name in lines: + with io.open(file_name.strip(), 'rb') as file: + data = cPickle.load(file) + indexes = list(range(len(data['images']))) + if settings.is_train: + random.shuffle(indexes) + for i in indexes: + if settings.use_jpeg == 1: + img = image_util.decode_jpeg(data['images'][i]) + else: + img = data['images'][i] + img_feat = image_util.preprocess_img( + img, settings.img_mean, settings.img_size, + settings.is_train, settings.color) + label = data['labels'][i] + yield img_feat.astype('float32'), int(label) diff --git a/pool/shard002/Python/0025774_shp2shps.py b/pool/shard002/Python/0025774_shp2shps.py new file mode 100644 index 0000000000000000000000000000000000000000..fb8368bdf09bb64563fdbcb5c0ad64f77136127a --- /dev/null +++ b/pool/shard002/Python/0025774_shp2shps.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python -u +# -*- coding: utf-8 -*- + +#****************************************************************************** +# shp2shps.py +# --------------------------------------------------------- +# Convert each feature from a layer to reprojected layer with this feature +# More: https://gitlab.com/nextgis_private/ +# +# Usage: +# usage: shp2shps.py [-h] input +# where: +# -h Show this help message and exit +# input Input shapefile name +# Examples: +# python shp2shps.py boundary_145.shp +# +# Copyright (C) 2017 Maxim Dubinin (maxim.dubinin@nextgis.ru) +# Created: 24.10.2017 +# +# This source 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 code 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. +# +# A copy of the GNU General Public License is available on the World Wide Web +# at . You can also obtain it by writing +# to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, +# MA 02111-1307, USA. +# +#****************************************************************************** + +from osgeo import ogr +from osgeo import osr + +import sys +import os +os.environ["SHAPE_ENCODING"] = "UTF-8" +import argparse + +parser = argparse.ArgumentParser() +parser.add_argument('input', help='Input shapefile name') +args = parser.parse_args() + + +def save_shp(in_layer,name,transform,in_feat): + driverName = "ESRI Shapefile" + drv = ogr.GetDriverByName( driverName ) + if drv is None: + print "%s driver not available.\n" % driverName + + f_out = drv.CreateDataSource( "%s.shp" % name ) + if f_out is None: + print "Creation of output file failed.\n" + sys.exit( 1 ) + + out_layer = f_out.CreateLayer( "name", None, ogr.wkbPolygon ) + if out_layer is None: + print "Layer creation failed." + sys.exit( 1 ) + + inLayerDefn = in_layer.GetLayerDefn() + for i in range(0, inLayerDefn.GetFieldCount()): + fieldDefn = inLayerDefn.GetFieldDefn(i) + out_layer.CreateField(fieldDefn) + + geom = f.GetGeometryRef() + geom.Transform(transform) + + feat = ogr.Feature( out_layer.GetLayerDefn() ) + feat.SetGeometry(geom) + + outLayerDefn = out_layer.GetLayerDefn() + for i in range(0, outLayerDefn.GetFieldCount()): + feat.SetField(outLayerDefn.GetFieldDefn(i).GetNameRef(), in_feat.GetField(i)) + + if out_layer.CreateFeature( feat ) != 0: + print "Failed to create feature in shapefile.\n" + sys.exit( 1 ) + + target_crs.MorphToESRI() + file = open('%s.prj' % name.decode('utf-8'), 'w') + file.write(target_crs.ExportToWkt()) + file.close() + + feat.Destroy() + f_out.Destroy() + + +if __name__ == '__main__': + ogrData = ogr.Open(args.input, 0 ) + + if ogrData is None: + print "ERROR: open failed" + sys.exit( 1 ) + + in_layer = ogrData.GetLayer() + if in_layer is None: + print "ERROR: can't access layer" + sys.exit( 1 ) + + print "Feature count", in_layer.GetFeatureCount() + + source_crs = osr.SpatialReference() + source_crs.ImportFromEPSG(4326) + for f in in_layer: + target_crs_num = 32600 + int(f.GetFieldAsString(9)) #last field has UTM zone number + target_crs = osr.SpatialReference() + target_crs.ImportFromEPSG(target_crs_num) + + transform = osr.CoordinateTransformation(source_crs, target_crs) + + + name = f.GetFieldAsString(0) + print name + save_shp(in_layer,name,transform,f) + + ogrData.Destroy() \ No newline at end of file diff --git a/pool/shard002/Python/0025777_meta.py b/pool/shard002/Python/0025777_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..722fd05401d01d0229910729d0b1f9c5b5c9c260 --- /dev/null +++ b/pool/shard002/Python/0025777_meta.py @@ -0,0 +1,117 @@ +# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80: + +# python-quilt - A Python implementation of the quilt patch system +# +# Copyright (C) 2012 - 2017 Björn Ricks +# +# See LICENSE comming with the source of python-quilt for details. + +from __future__ import print_function + +import os +import six +import sys + +import quilt + +from quilt.db import Db, Series + +from quilt.cli.parser import Parser, SubParser, ArgumentsCollectorMetaClass, \ + Argument + +command_map = dict() + + +def register_command(name, command_class): + command_map[name] = command_class + + +def find_command(name): + return command_map.get(name, None) + + +def list_commands(): + return sorted(command_map.items()) + + +class CommandMetaClass(ArgumentsCollectorMetaClass): + + def __new__(meta, name, bases, attrs): + cls = super(CommandMetaClass, meta).__new__(meta, name, bases, attrs) + if cls.name is not None: + register_command(cls.name, cls) + return cls + + +@six.add_metaclass(CommandMetaClass) +class Command(SubParser): + + name = None + help = None + description = None + + def __init__(self): + super(Command, self).__init__(self.name, help=self.help, + description=self.description or + self.help) + self.patches_dir = "patches" + self.pc_dir = ".pc" + + def get_patches_dir(self): + patches_dir = os.environ.get("QUILT_PATCHES") + if not patches_dir: + patches_dir = self.patches_dir + return patches_dir + + def get_pc_dir(self): + pc_dir = os.environ.get("QUILT_PC") + if not pc_dir: + pc_dir = self.pc_dir + return pc_dir + + def get_db(self): + return Db(self.get_pc_dir()) + + def get_series(self): + return Series(self.get_patches_dir()) + + def get_cwd(self): + return os.getcwd() + + def exit_error(self, error, value=1): + print(error, file=sys.stderr) + sys.exit(value) + + def get_defaults(self): + return {"run": self.run} + + def run(options, args): + raise NotImplementedError() + + +class QuiltCli(Parser): + + default_subparsers_kwargs = { + "title": "list of commands", + "dest": "command", + "description": "List of available commands. Use %(prog)s COMMAND " + "--help for more info.", + "help": "Description", + "metavar": "COMMAND", + } + + version = Argument("--version", action="version", + version="%%(prog)s %s" % quilt.__version__) + + def __init__(self, *args, **kwargs): + super(QuiltCli, self).__init__(*args, **kwargs) + + for cmd in list_commands(): + self.add_subparser(cmd[1]()) + + def run(self): + args = self.parse_args() + if args.command: + args.run(args) + else: + self.print_usage() diff --git a/pool/shard002/Python/0025779_urls.py b/pool/shard002/Python/0025779_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..2da6f4ea501b3c08bfee23af627b9748d21c75dc --- /dev/null +++ b/pool/shard002/Python/0025779_urls.py @@ -0,0 +1,20 @@ +from django.conf.urls import url +from esgf import views + +urlpatterns = [ + url(r'^node_search/$', views.node_search), + url(r'^load_facets/$', views.load_facets), + url(r'^logon/$', views.logon), + url(r'^node_list/$', views.node_list), + url(r'^get_user_data$', views.get_user_data), + url(r'^file_upload/$', views.file_upload), + url(r'^get_publish_config/$', views.get_publish_config), + url(r'^get_publish_config_list/$', views.get_publish_config_list), + url(r'^save_publish_config/$', views.save_publish_config), + url(r'^publish/$', views.publish), + url(r'^upload_to_viewer/$', views.upload_to_viewer), + url(r'^get_favorite_plots/$', views.get_favorite_plots), + url(r'^set_favorite_plot/$', views.set_favorite_plot), + url(r'^read_nc/$', views.read_nc), + url(r'^get_data_type_folders/$', views.get_data_type_folders), +] diff --git a/pool/shard002/Python/0025780_low_level_api.py b/pool/shard002/Python/0025780_low_level_api.py new file mode 100644 index 0000000000000000000000000000000000000000..282ae347eba5bb6385c3c325392d6cb802eb7098 --- /dev/null +++ b/pool/shard002/Python/0025780_low_level_api.py @@ -0,0 +1,36 @@ +__author__ = 'sanyi' + + +from ipsetpy import ipset_version, ipset_create_set, ipset_add_entry, ipset_list, ipset_test_entry, \ + ipset_flush_set, ipset_destroy_set + +# getting ipset version banner +print(ipset_version()) + +# creating a set +ipset_create_set('test_set', 'hash:ip', exist=True) + +# adding some entries to the "test_set" +ipset_add_entry('test_set', '192.168.1.101', exist=True) +ipset_add_entry('test_set', '192.168.1.103', exist=True) +ipset_add_entry('test_set', '192.168.2.0/24', exist=True) + +# listing available sets +print(ipset_list()) + + +# check if ip is in set +print(ipset_test_entry('test_set', '192.168.1.1')) + +print(ipset_test_entry('test_set', '192.168.1.101')) + +print(ipset_test_entry('test_set', '192.168.2.21')) + +print(ipset_test_entry('test_set', '192.168.3.21')) + + +# delete entries +ipset_flush_set('test_set') + +# delete set +ipset_destroy_set('test_set') diff --git a/pool/shard002/Python/0025781_import_graaddagen_archive.py b/pool/shard002/Python/0025781_import_graaddagen_archive.py new file mode 100644 index 0000000000000000000000000000000000000000..c5803f8b5808b3e90e1761de5918c07a28cb6084 --- /dev/null +++ b/pool/shard002/Python/0025781_import_graaddagen_archive.py @@ -0,0 +1,32 @@ +from django.core.management.base import BaseCommand, CommandError +import requests +import pandas +import datetime +from degreeday.models import DegreedaySource +from degreeday.models import Degreeday + + +ilist = [ + 'http://www.aardgas.be/sites/default/files/sites/default/files/imce/DJE01new-1.xls', + ] + + +class Command(BaseCommand): + help = 'Import graaddagen from http://www.aardgas.be/nl/particulier/graaddagen' + + def handle(self, *args, **options): + for xls in ilist: + df = pandas.read_excel(xls) + for r in df.iterrows(): + r1 = r[1][0] + r2 = r[1][1] + if isinstance(r1, datetime.datetime): + d = r1.date() + print(d, r2) + dds = DegreedaySource.objects.get(name="aardgas") + print (r2) + dd = Degreeday() + dd.source = dds + dd.date_day = d + dd.value = r2 + dd.save() diff --git a/pool/shard002/Python/0025785_RingedEncoderElement.py b/pool/shard002/Python/0025785_RingedEncoderElement.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c8983a9ef7cac4a468c6cc96134f335157e987 --- /dev/null +++ b/pool/shard002/Python/0025785_RingedEncoderElement.py @@ -0,0 +1,80 @@ +# http://remotescripts.blogspot.com + +# emacs-mode: -*- python-*- +# -*- coding: utf-8 -*- + +from _Framework.EncoderElement import EncoderElement +from _Framework.ButtonElement import ButtonElement +RING_OFF_VALUE = 0 +RING_SIN_VALUE = 1 +RING_VOL_VALUE = 2 +RING_PAN_VALUE = 3 +class RingedEncoderElement(EncoderElement): + """ Class representing a continuous control on the controller enclosed with an LED ring """ + + def __init__(self, msg_type, channel, identifier, map_mode): + EncoderElement.__init__(self, msg_type, channel, identifier, map_mode) + self._ring_mode_button = None + self.set_needs_takeover(False) + + + + + def set_ring_mode_button(self, button): + if not (button == None or isinstance(button, ButtonElement)): + raise AssertionError + force_send = self._ring_mode_button != None and True + self._ring_mode_button.send_value(RING_OFF_VALUE, force_send) + self._ring_mode_button = button + self._update_ring_mode() + + + + def connect_to(self, parameter): + if parameter != self._parameter_to_map_to and not self.is_mapped_manually(): + force_send = True + self._ring_mode_button.send_value(RING_OFF_VALUE, force_send) + EncoderElement.connect_to(self, parameter) + + + + def release_parameter(self): + EncoderElement.release_parameter(self) + self._update_ring_mode() + + + + def install_connections(self, install_translation_callback, install_mapping_callback, install_forwarding_callback): + EncoderElement.install_connections(self, install_translation_callback, install_mapping_callback, install_forwarding_callback) + if not self._is_mapped and self.value_listener_count() == 0: + self._is_being_forwarded = install_forwarding_callback(self) + self._update_ring_mode() + + + + def is_mapped_manually(self): + return not self._is_mapped and not self._is_being_forwarded + + + + def _update_ring_mode(self): + if self._ring_mode_button != None: + force_send = True + if self.is_mapped_manually(): + self._ring_mode_button.send_value(RING_SIN_VALUE, force_send) + elif self._parameter_to_map_to != None: + param = self._parameter_to_map_to + p_range = param.max - param.min + value = (param.value - param.min) / p_range * 127 + self.send_value(int(value), force_send) + if self._parameter_to_map_to.min == -1 * self._parameter_to_map_to.max: + self._ring_mode_button.send_value(RING_PAN_VALUE, force_send) + elif self._parameter_to_map_to.is_quantized: + self._ring_mode_button.send_value(RING_SIN_VALUE, force_send) + else: + self._ring_mode_button.send_value(RING_VOL_VALUE, force_send) + else: + self._ring_mode_button.send_value(RING_OFF_VALUE, force_send) + + + diff --git a/pool/shard002/Python/0025797_utils.py b/pool/shard002/Python/0025797_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7044d1ed3d535b9c5990f93bd790a3760b6d8a8f --- /dev/null +++ b/pool/shard002/Python/0025797_utils.py @@ -0,0 +1,80 @@ +from django.conf import settings +import os +import sys +import logging +from django_extensions.management.signals import pre_command, post_command + +try: + from importlib import import_module +except ImportError: + try: + from django.utils.importlib import import_module + except ImportError: + def import_module(module): + return __import__(module, {}, {}, ['']) + + +def get_project_root(): + """ get the project root directory """ + django_settings_module = os.environ.get('DJANGO_SETTINGS_MODULE') + if not django_settings_module: + module_str = settings.SETTINGS_MODULE + else: + module_str = django_settings_module.split(".")[0] + mod = import_module(module_str) + return os.path.dirname(os.path.abspath(mod.__file__)) + + +def _make_writeable(filename): + """ + Make sure that the file is writeable. Useful if our source is + read-only. + + """ + import stat + if sys.platform.startswith('java'): + # On Jython there is no os.access() + return + if not os.access(filename, os.W_OK): + st = os.stat(filename) + new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR + os.chmod(filename, new_permissions) + + +def setup_logger(logger, stream, filename=None, fmt=None): + """Sets up a logger (if no handlers exist) for console output, + and file 'tee' output if desired.""" + if len(logger.handlers) < 1: + console = logging.StreamHandler(stream) + console.setLevel(logging.DEBUG) + console.setFormatter(logging.Formatter(fmt)) + logger.addHandler(console) + logger.setLevel(logging.DEBUG) + + if filename: + outfile = logging.FileHandler(filename) + outfile.setLevel(logging.INFO) + outfile.setFormatter(logging.Formatter("%(asctime)s " + (fmt if fmt else '%(message)s'))) + logger.addHandler(outfile) + + +class RedirectHandler(logging.Handler): + """Redirect logging sent to one logger (name) to another.""" + def __init__(self, name, level=logging.DEBUG): + # Contemplate feasibility of copying a destination (allow original handler) and redirecting. + logging.Handler.__init__(self, level) + self.name = name + self.logger = logging.getLogger(name) + + def emit(self, record): + self.logger.handle(record) + + +def signalcommand(func): + """A decorator for management command handle defs that sends out a pre/post signal.""" + def inner(self, *args, **kwargs): + pre_command.send(self.__class__, args=args, kwargs=kwargs) + ret = func(self, *args, **kwargs) + post_command.send(self.__class__, args=args, kwargs=kwargs, outcome=ret) + return ret + return inner diff --git a/pool/shard002/Python/0025804_test_rounding.py b/pool/shard002/Python/0025804_test_rounding.py new file mode 100644 index 0000000000000000000000000000000000000000..0a047f9b93f73f17a0f3dd0983e5e1ade603e66b --- /dev/null +++ b/pool/shard002/Python/0025804_test_rounding.py @@ -0,0 +1,36 @@ +import numpy +import pytest + +import chainerx +import chainerx.testing + +from chainerx_tests import dtype_utils +from chainerx_tests import math_utils + + +@chainerx.testing.numpy_chainerx_array_equal() +@pytest.mark.parametrize_device(['native:0', 'cuda:0']) +@pytest.mark.parametrize('input', [ + numpy.asarray(0.5), + numpy.asarray(-1.2), + numpy.asarray(10.9), + numpy.asarray(float('inf')), + numpy.asarray(-float('inf')), + numpy.asarray(float('nan')), + numpy.full((), 2.1), + numpy.full((0,), 2), + numpy.full((2, 3), 2.6), + numpy.full((1, 1), 1.01), + numpy.full((1, 1), 1.99), +]) +@pytest.mark.parametrize('dtypes', math_utils.in_out_dtypes_math_functions) +@pytest.mark.parametrize('func', [ + lambda xp, a: xp.ceil(a), + lambda xp, a: xp.floor(a) +]) +def test_rounding_routines(func, xp, device, input, dtypes): + (in_dtype, ), out_dtype = dtypes + a = xp.array(input.astype(in_dtype)) + a = func(xp, a) + a = dtype_utils.cast_if_numpy_array(xp, a, out_dtype) + return a diff --git a/pool/shard002/Python/0025807_init__.py b/pool/shard002/Python/0025807_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee7f682dcb89f9d35bc41bfed270dc7736f04828 --- /dev/null +++ b/pool/shard002/Python/0025807_init__.py @@ -0,0 +1,214 @@ +"""Ansible integration test infrastructure.""" + +from __future__ import absolute_import, print_function + +import contextlib +import os +import shutil +import tempfile + +from lib.target import ( + analyze_integration_target_dependencies, + walk_integration_targets, +) + +from lib.config import ( + NetworkIntegrationConfig, + PosixIntegrationConfig, + WindowsIntegrationConfig, +) + +from lib.util import ( + ApplicationError, + display, + make_dirs, +) + +from lib.cache import ( + CommonCache, +) + + +def generate_dependency_map(integration_targets): + """ + :type integration_targets: list[IntegrationTarget] + :rtype: dict[str, set[IntegrationTarget]] + """ + targets_dict = dict((target.name, target) for target in integration_targets) + target_dependencies = analyze_integration_target_dependencies(integration_targets) + dependency_map = {} + + invalid_targets = set() + + for dependency, dependents in target_dependencies.items(): + dependency_target = targets_dict.get(dependency) + + if not dependency_target: + invalid_targets.add(dependency) + continue + + for dependent in dependents: + if dependent not in dependency_map: + dependency_map[dependent] = set() + + dependency_map[dependent].add(dependency_target) + + if invalid_targets: + raise ApplicationError('Non-existent target dependencies: %s' % ', '.join(sorted(invalid_targets))) + + return dependency_map + + +def get_files_needed(target_dependencies): + """ + :type target_dependencies: list[IntegrationTarget] + :rtype: list[str] + """ + files_needed = [] + + for target_dependency in target_dependencies: + files_needed += target_dependency.needs_file + + files_needed = sorted(set(files_needed)) + + invalid_paths = [path for path in files_needed if not os.path.isfile(path)] + + if invalid_paths: + raise ApplicationError('Invalid "needs/file/*" aliases:\n%s' % '\n'.join(invalid_paths)) + + return files_needed + + +@contextlib.contextmanager +def integration_test_environment(args, target, inventory_path): + """ + :type args: IntegrationConfig + :type target: IntegrationTarget + :type inventory_path: str + """ + vars_file = 'integration_config.yml' + + if args.no_temp_workdir or 'no/temp_workdir/' in target.aliases: + display.warning('Disabling the temp work dir is a temporary debugging feature that may be removed in the future without notice.') + + integration_dir = 'test/integration' + ansible_config = os.path.join(integration_dir, '%s.cfg' % args.command) + + inventory_name = os.path.relpath(inventory_path, integration_dir) + + if '/' in inventory_name: + inventory_name = inventory_path + + yield IntegrationEnvironment(integration_dir, inventory_name, ansible_config, vars_file) + return + + root_temp_dir = os.path.expanduser('~/.ansible/test/tmp') + + prefix = '%s-' % target.name + suffix = u'-\u00c5\u00d1\u015a\u00cc\u03b2\u0141\u00c8' + + if args.no_temp_unicode or 'no/temp_unicode/' in target.aliases: + display.warning('Disabling unicode in the temp work dir is a temporary debugging feature that may be removed in the future without notice.') + suffix = '-ansible' + + if isinstance('', bytes): + suffix = suffix.encode('utf-8') + + if args.explain: + temp_dir = os.path.join(root_temp_dir, '%stemp%s' % (prefix, suffix)) + else: + make_dirs(root_temp_dir) + temp_dir = tempfile.mkdtemp(prefix=prefix, suffix=suffix, dir=root_temp_dir) + + try: + display.info('Preparing temporary directory: %s' % temp_dir, verbosity=2) + + inventory_names = { + PosixIntegrationConfig: 'inventory', + WindowsIntegrationConfig: 'inventory.winrm', + NetworkIntegrationConfig: 'inventory.networking', + } + + inventory_name = inventory_names[type(args)] + + cache = IntegrationCache(args) + + target_dependencies = sorted([target] + list(cache.dependency_map.get(target.name, set()))) + + files_needed = get_files_needed(target_dependencies) + + integration_dir = os.path.join(temp_dir, 'test/integration') + ansible_config = os.path.join(integration_dir, '%s.cfg' % args.command) + + file_copies = [ + ('test/integration/%s.cfg' % args.command, ansible_config), + ('test/integration/integration_config.yml', os.path.join(integration_dir, vars_file)), + (inventory_path, os.path.join(integration_dir, inventory_name)), + ] + + file_copies += [(path, os.path.join(temp_dir, path)) for path in files_needed] + + directory_copies = [ + (os.path.join('test/integration/targets', target.name), os.path.join(integration_dir, 'targets', target.name)) for target in target_dependencies + ] + + inventory_dir = os.path.dirname(inventory_path) + + host_vars_dir = os.path.join(inventory_dir, 'host_vars') + group_vars_dir = os.path.join(inventory_dir, 'group_vars') + + if os.path.isdir(host_vars_dir): + directory_copies.append((host_vars_dir, os.path.join(integration_dir, os.path.basename(host_vars_dir)))) + + if os.path.isdir(group_vars_dir): + directory_copies.append((group_vars_dir, os.path.join(integration_dir, os.path.basename(group_vars_dir)))) + + directory_copies = sorted(set(directory_copies)) + file_copies = sorted(set(file_copies)) + + if not args.explain: + make_dirs(integration_dir) + + for dir_src, dir_dst in directory_copies: + display.info('Copying %s/ to %s/' % (dir_src, dir_dst), verbosity=2) + + if not args.explain: + shutil.copytree(dir_src, dir_dst, symlinks=True) + + for file_src, file_dst in file_copies: + display.info('Copying %s to %s' % (file_src, file_dst), verbosity=2) + + if not args.explain: + make_dirs(os.path.dirname(file_dst)) + shutil.copy2(file_src, file_dst) + + yield IntegrationEnvironment(integration_dir, inventory_name, ansible_config, vars_file) + finally: + if not args.explain: + shutil.rmtree(temp_dir) + + +class IntegrationEnvironment(object): + """Details about the integration environment.""" + def __init__(self, integration_dir, inventory_path, ansible_config, vars_file): + self.integration_dir = integration_dir + self.inventory_path = inventory_path + self.ansible_config = ansible_config + self.vars_file = vars_file + + +class IntegrationCache(CommonCache): + """Integration cache.""" + @property + def integration_targets(self): + """ + :rtype: list[IntegrationTarget] + """ + return self.get('integration_targets', lambda: list(walk_integration_targets())) + + @property + def dependency_map(self): + """ + :rtype: dict[str, set[IntegrationTarget]] + """ + return self.get('dependency_map', lambda: generate_dependency_map(self.integration_targets)) diff --git a/pool/shard002/Python/0025817_craytoolchain.py b/pool/shard002/Python/0025817_craytoolchain.py new file mode 100644 index 0000000000000000000000000000000000000000..ab66f3bf5b56275433d8dc3aecbbee4871e79c6a --- /dev/null +++ b/pool/shard002/Python/0025817_craytoolchain.py @@ -0,0 +1,77 @@ +## +# Copyright 2015-2017 Ghent University +# +# This file is part of EasyBuild, +# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), +# with support of Ghent University (http://ugent.be/hpc), +# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), +# Flemish Research Foundation (FWO) (http://www.fwo.be/en) +# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). +# +# http://github.com/hpcugent/easybuild +# +# EasyBuild 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 v2. +# +# EasyBuild 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 EasyBuild. If not, see . +## +""" +EasyBuild support for installing Cray toolchains, implemented as an easyblock + +@author: Kenneth Hoste (Ghent University) +@author: Guilherme Peretti Pezzi (CSCS) +@author: Petar Forai (IMP/IMBA) +""" + +from easybuild.easyblocks.generic.bundle import Bundle +from easybuild.tools.build_log import EasyBuildError + + +KNOWN_PRGENVS = ['PrgEnv-cray', 'PrgEnv-gnu', 'PrgEnv-intel', 'PrgEnv-pgi'] + + +class CrayToolchain(Bundle): + """ + Compiler toolchain: generate module file only, nothing to build/install + """ + def make_module_dep(self): + """ + Generate load/swap statements for dependencies in the module file + """ + prgenv_mod = None + + # collect 'swap' statement for dependencies (except PrgEnv) + swap_deps = [] + for dep in self.toolchain.dependencies: + mod_name = dep['full_mod_name'] + # determine versionless module name, e.g. 'fftw/3.3.4.1' => 'fftw' + dep_name = '/'.join(mod_name.split('/')[:-1]) + + if mod_name.startswith('PrgEnv'): + prgenv_mod = mod_name + else: + swap_deps.append(self.module_generator.swap_module(dep_name, mod_name).lstrip()) + + self.log.debug("Swap statements for dependencies of %s: %s", self.full_mod_name, swap_deps) + + if prgenv_mod is None: + raise EasyBuildError("Could not find a PrgEnv-* module listed as dependency: %s", + self.toolchain.dependencies) + + # unload statements for other PrgEnv modules + prgenv_unloads = [''] + for prgenv in [prgenv for prgenv in KNOWN_PRGENVS if not prgenv_mod.startswith(prgenv)]: + prgenv_unloads.append(self.module_generator.unload_module(prgenv).strip()) + + # load statement for selected PrgEnv module (only when not loaded yet) + prgenv_load = self.module_generator.load_module(prgenv_mod, recursive_unload=False) + + txt = '\n'.join(prgenv_unloads + [prgenv_load] + swap_deps) + return txt diff --git a/pool/shard002/Python/0025818_AdcpCodec.py b/pool/shard002/Python/0025818_AdcpCodec.py new file mode 100644 index 0000000000000000000000000000000000000000..ce53e0028c53c5bae92a02ac447117daa03b6183 --- /dev/null +++ b/pool/shard002/Python/0025818_AdcpCodec.py @@ -0,0 +1,77 @@ +import logging +from Codecs.BinaryCodec import BinaryCodec +from Codecs.BinaryCodecUdp import BinaryCodecUdp +from Codecs.WaveForceCodec import WaveForceCodec +from Utilities.events import EventHandler + +logger = logging.getLogger("ADCP Codec") +logger.setLevel(logging.ERROR) +FORMAT = '[%(asctime)-15s][%(levelname)s][%(name)s:%(funcName)s] %(message)s' +logging.basicConfig(format=FORMAT) + + +class AdcpCodec: + """ + ADCP Codec will decode the + ADCP data. There are more than one ADCP format, this will use all the different + codecs to decode the data. + """ + + def __init__(self, is_udp=False, udp_port=55057): + if not is_udp: + self.binary_codec = BinaryCodec() + else: + self.binary_codec = BinaryCodecUdp(udp_port) + self.binary_codec.EnsembleEvent += self.process_ensemble + + # WaveForce codec + self.WaveForceCodec = WaveForceCodec() + self.IsWfcEnabled = False + + # Event to receive the ensembles + self.EnsembleEvent = EventHandler(self) + + def add(self, data): + """ + Add the data to the codecs. + :param data: Raw data to add to the codecs. + """ + self.binary_codec.add(data) + + def enable_waveforce_codec(self, ens_in_burst, path, lat, lon, bin1, bin2, bin3, ps_depth): + """ + Enable the WaveForce codec. This data will be encoded + into the Matlab format. + :param ens_in_burst: Ensembles in a burst. + :param path: Path to record the burst matlab files. + :param lat: Latitude where data was recorded. + :param lon: Longitude where data was recorded. + :param bin1: First bin to measure. + :param bin2: Second bin to measure. + :param bin3: Third bin to measure. + :param ps_depth: Pressure sensor depth. + :return: + """ + + self.WaveForceCodec.init(ens_in_burst, path, lat, lon, bin1, bin2, bin3, ps_depth) + self.IsWfcEnabled = True + + def process_ensemble(self, sender, ens): + """ + Take the ensemble from the codec and pass it to all the subscribers. + If the WaveForce codec is enabled, pass the ensemble to the WaveForce + codec to process. + :param ens: Ensemble data. + """ + logger.debug("Received processed ensemble") + + # If the WaveForce codec is enabled, then pass the ensemble data to the WaveForce codec + if self.IsWfcEnabled: + logger.debug("Send to WaveForce Codec") + self.WaveForceCodec.add(ens) + + # Pass ensemble to all subscribers of the ensemble data. + self.EnsembleEvent(ens) + + + diff --git a/pool/shard002/Python/0025821_commands.py b/pool/shard002/Python/0025821_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..44165c2f8024bd5ecda075b780c516a4ba551775 --- /dev/null +++ b/pool/shard002/Python/0025821_commands.py @@ -0,0 +1,68 @@ +def user_confirm(prompt='Are you sure?'): + while True: + user_input = raw_input('%s [y/N] ' % prompt).lower() + if user_input not in ('y', 'n'): + print 'Unable to recognize input.' + continue + else: + return user_input == 'y' + +def _format_change(change): + return '\n'.join(( + 'ID: %s' % change.id, + 'Name: %s' % getattr(change, 'name', '...'), + 'WIP: %s' % ('Yes' if change.wip else 'No',), + 'Approved: %s' % ('Yes' if change.wip else 'No',), + 'Tags: %s' % (', '.join(change.tags) or '...',), + 'Desc: %s' % getattr(change, 'description', '...'), + '', + )) + + +def list_changes(service, args): + for change in service.list_changes(): + print _format_change(change) + + +def show_change(service, args): + change = service.get_change(args.change_id) + print _format_change(change) + + +def create_change(service, args): + data = {} + for key in 'name', 'description', 'tags': + value = getattr(args, key) + if value is not None: + data[key] = value + change = service.create_change(data) + print 'Created change %s' % change.id + + +def delete_change(service, args): + prompt = 'Are you sure you want to delete change %s?' % args.change_id + if user_confirm(prompt): + change = service.get_change(args.change_id) + service.delete_change(change) + print 'Deleted change change %s' % args.change_id + else: + print 'Ignoring request to delete change %s' % args.change_id + + +def register(subparsers): + subparser = subparsers.add_parser('list') + subparser.set_defaults(func=list_changes) + + subparser = subparsers.add_parser('show') + subparser.set_defaults(func=show_change) + subparser.add_argument('change_id') + + subparser = subparsers.add_parser('create') + subparser.set_defaults(func=create_change) + subparser.add_argument('--name', required=True) + subparser.add_argument('--description') + subparser.add_argument('--tag', dest='tags', action='append') + + subparser = subparsers.add_parser('delete') + subparser.set_defaults(func=delete_change) + subparser.add_argument('change_id') diff --git a/pool/shard002/Python/0025823_urls.py b/pool/shard002/Python/0025823_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..4601a970be237cfcb37cddad61b5195812574b6a --- /dev/null +++ b/pool/shard002/Python/0025823_urls.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +__author__ = 'mateusz' +__date__ = '13.11.14 / 09:09' +__git__ = 'https://github.com/mateuszdargacz' + + +from django.conf.urls import patterns, include, url +from django.conf import settings +from django.views.generic import TemplateView + +urlpatterns = patterns('apps.test_app.views', + # Examples: + url(r'^main/?$', TemplateView.as_view(template_name="test_app/main.html"), name='main'), + # url(r'^{{ project_name }}/', include('{{ project_name }}.foo.urls')), +) + +# Uncomment the next line to serve media files in dev. +# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + +if settings.DEBUG: + import debug_toolbar + urlpatterns += patterns('', + url(r'^__debug__/', include(debug_toolbar.urls)), + ) diff --git a/pool/shard002/Python/0025824_views.py b/pool/shard002/Python/0025824_views.py new file mode 100644 index 0000000000000000000000000000000000000000..a803da2e1fa70c956ad341040ad81b34ef290e5e --- /dev/null +++ b/pool/shard002/Python/0025824_views.py @@ -0,0 +1,137 @@ +from __future__ import absolute_import + +import six +from django import forms +from sentry.auth.view import AuthView, ConfigureView +from sentry.models import AuthIdentity + +from .client import GitHubClient +from .constants import ERR_NO_ORG_ACCESS +from .constants import REQUIRE_VERIFIED_EMAIL +from .constants import ( + ERR_NO_SINGLE_VERIFIED_PRIMARY_EMAIL, + ERR_NO_SINGLE_PRIMARY_EMAIL, + ERR_NO_VERIFIED_PRIMARY_EMAIL, + ERR_NO_PRIMARY_EMAIL, +) + + +def _get_name_from_email(email): + """ + Given an email return a capitalized name. Ex. john.smith@example.com would return John Smith. + """ + name = email.rsplit("@", 1)[0] + name = " ".join([n_part.capitalize() for n_part in name.split(".")]) + return name + + +class FetchUser(AuthView): + def __init__(self, org=None, *args, **kwargs): + self.org = org + super(FetchUser, self).__init__(*args, **kwargs) + + def handle(self, request, helper): + client = GitHubClient(helper.fetch_state("data")["access_token"]) + + if self.org is not None: + if not client.is_org_member(self.org["id"]): + return helper.error(ERR_NO_ORG_ACCESS) + + user = client.get_user() + + if not user.get("email"): + emails = client.get_user_emails() + email = [ + e["email"] + for e in emails + if ((not REQUIRE_VERIFIED_EMAIL) | e["verified"]) and e["primary"] + ] + if len(email) == 0: + if REQUIRE_VERIFIED_EMAIL: + msg = ERR_NO_VERIFIED_PRIMARY_EMAIL + else: + msg = ERR_NO_PRIMARY_EMAIL + return helper.error(msg) + elif len(email) > 1: + if REQUIRE_VERIFIED_EMAIL: + msg = ERR_NO_SINGLE_VERIFIED_PRIMARY_EMAIL + else: + msg = ERR_NO_SINGLE_PRIMARY_EMAIL + return helper.error(msg) + else: + user["email"] = email[0] + + # A user hasn't set their name in their Github profile so it isn't + # populated in the response + if not user.get("name"): + user["name"] = _get_name_from_email(user["email"]) + + helper.bind_state("user", user) + + return helper.next_step() + + +class ConfirmEmailForm(forms.Form): + email = forms.EmailField(label="Email") + + +class ConfirmEmail(AuthView): + def handle(self, request, helper): + user = helper.fetch_state("user") + + # TODO(dcramer): this isnt ideal, but our current flow doesnt really + # support this behavior; + try: + auth_identity = AuthIdentity.objects.select_related("user").get( + auth_provider=helper.auth_provider, ident=user["id"] + ) + except AuthIdentity.DoesNotExist: + pass + else: + user["email"] = auth_identity.user.email + + if user.get("email"): + return helper.next_step() + + form = ConfirmEmailForm(request.POST or None) + if form.is_valid(): + user["email"] = form.cleaned_data["email"] + helper.bind_state("user", user) + return helper.next_step() + + return self.respond("sentry_auth_github/enter-email.html", {"form": form}) + + +class SelectOrganizationForm(forms.Form): + org = forms.ChoiceField(label="Organization") + + def __init__(self, org_list, *args, **kwargs): + super(SelectOrganizationForm, self).__init__(*args, **kwargs) + + self.fields["org"].choices = [(o["id"], o["login"]) for o in org_list] + self.fields["org"].widget.choices = self.fields["org"].choices + + +class SelectOrganization(AuthView): + def __init__(self, *args, **kwargs): + super(SelectOrganization, self).__init__(*args, **kwargs) + + def handle(self, request, helper): + client = GitHubClient(helper.fetch_state("data")["access_token"]) + org_list = client.get_org_list() + + form = SelectOrganizationForm(org_list, request.POST or None) + if form.is_valid(): + org_id = form.cleaned_data["org"] + org = [o for o in org_list if org_id == six.text_type(o["id"])][0] + helper.bind_state("org", org) + return helper.next_step() + + return self.respond( + "sentry_auth_github/select-organization.html", {"form": form, "org_list": org_list} + ) + + +class GitHubConfigureView(ConfigureView): + def dispatch(self, request, organization, auth_provider): + return self.render("sentry_auth_github/configure.html") diff --git a/pool/shard002/Python/0025831_models.py b/pool/shard002/Python/0025831_models.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe3c8b8f56a1d5cf36d504640fd784a2ac55198 --- /dev/null +++ b/pool/shard002/Python/0025831_models.py @@ -0,0 +1,49 @@ +# nnmware(c)2012-2020 + +from __future__ import unicode_literals + +from django.conf import settings +from django.urls import reverse +from django.db import models +from django.utils.translation import gettext as _ + +from nnmware.apps.address.models import Region +from nnmware.core.abstract import Tree, AbstractDate, AbstractName, AbstractIP +from nnmware.core.constants import STATUS_CHOICES, STATUS_DRAFT +from nnmware.core.managers import StatusManager +from nnmware.core.models import LikeMixin + + +class TopicCategory(Tree): + slug_detail = 'topics_category' + + class Meta: + ordering = ['parent__id', 'name'] + verbose_name = _('Topic Category') + verbose_name_plural = _('Topic Categories') + + @property + def obj_active_set(self): + return Topic.objects.filter(category=self) + + +class Topic(AbstractDate, AbstractName, LikeMixin, AbstractIP): + region = models.ForeignKey(Region, verbose_name=_('Region'), blank=True, null=True, related_name="%(class)s_reg", + on_delete=models.PROTECT) + category = models.ForeignKey(TopicCategory, verbose_name=_('Category'), null=True, blank=True, + on_delete=models.PROTECT) + user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('User'), on_delete=models.PROTECT) + status = models.IntegerField(_("Status"), choices=STATUS_CHOICES, default=STATUS_DRAFT) + + objects = StatusManager() + + class Meta: + ordering = ['-created_date', ] + verbose_name = _('Topic') + verbose_name_plural = _('Topics') + + def get_absolute_url(self): + return reverse('topic_detail', args=[self.pk]) + + def get_edit_url(self): + return reverse('topic_edit', args=[self.pk]) diff --git a/pool/shard002/Python/0025837_scroll.py b/pool/shard002/Python/0025837_scroll.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d5423a53d63e8c3049be469ded32c0655e9f05 --- /dev/null +++ b/pool/shard002/Python/0025837_scroll.py @@ -0,0 +1,125 @@ +''' +Scroll effect +============= + +.. versionadded:: 1.7.0 + +Based on the :class:`~kivy.effects.kinetic` effect, the :class:`ScrollEffect` +will limit the movement to bounds determined by its :attr:`~ScrollEffect.min` +and :attr:`~ScrollEffect.max` properties. If the movement exceeds these +bounds, it will calculate the amount of :attr:`~ScrollEffect.overscroll` and +try to return to the value of one of the bounds. + +This is very useful for implementing a scrolling list. We actually use this +class as a base effect for our :class:`~kivy.uix.scrollview.ScrollView` widget. + +''' + + +__all__ = ('ScrollEffect', ) + + +from kivy.effects.kinetic import KineticEffect +from kivy.uix.widget import Widget +from kivy.properties import NumericProperty, ObjectProperty + + +class ScrollEffect(KineticEffect): + '''ScrollEffect class. See the module documentation for more information. + ''' + + drag_threshold = NumericProperty('20sp') + '''Minimum distance to travel before the movement is considered as a drag. + + :attr:`drag_threshold` is a :class:`~kivy.properties.NumericProperty` and + defaults to 20sp. + ''' + + min = NumericProperty(0) + '''Minimum boundary to use for scrolling. + + :attr:`min` is a :class:`~kivy.properties.NumericProperty` and defaults to + 0. + ''' + + max = NumericProperty(0) + '''Maximum boundary to use for scrolling. + + :attr:`max` is a :class:`~kivy.properties.NumericProperty` and defaults to + 0. + ''' + + scroll = NumericProperty(0) + '''Computed value for scrolling. This value is different from + :py:attr:`kivy.effects.kinetic.KineticEffect.value` + in that it will return to one of the min/max bounds. + + :attr:`scroll` is a :class:`~kivy.properties.NumericProperty` and defaults + to 0. + ''' + + overscroll = NumericProperty(0) + '''Computed value when the user over-scrolls i.e. goes out of the bounds. + + :attr:`overscroll` is a :class:`~kivy.properties.NumericProperty` and + defaults to 0. + ''' + + target_widget = ObjectProperty(None, allownone=True, baseclass=Widget) + '''Widget to attach to this effect. Even if this class doesn't make changes + to the `target_widget` by default, subclasses can use it to change the + graphics or apply custom transformations. + + :attr:`target_widget` is a :class:`~kivy.properties.ObjectProperty` and + defaults to None. + ''' + + displacement = NumericProperty(0) + '''Cumulative distance of the movement during the interaction. This is used + to determine if the movement is a drag (more than :attr:`drag_threshold`) + or not. + + :attr:`displacement` is a :class:`~kivy.properties.NumericProperty` and + defaults to 0. + ''' + + def reset(self, pos): + '''(internal) Reset the value and the velocity to the `pos`. + Mostly used when the bounds are checked. + ''' + self.value = pos + self.velocity = 0 + if self.history: + val = self.history[-1][1] + super(ScrollEffect, self).start(val, None) + + def on_value(self, *args): + scroll_min = self.min + scroll_max = self.max + if scroll_min > scroll_max: + scroll_min, scroll_max = scroll_max, scroll_min + if self.value < scroll_min: + self.overscroll = self.value - scroll_min + self.reset(scroll_min) + elif self.value > scroll_max: + self.overscroll = self.value - scroll_max + self.reset(scroll_max) + else: + self.scroll = self.value + + def start(self, val, t=None): + self.is_manual = True + self.displacement = 0 + return super(ScrollEffect, self).start(val, t) + + def update(self, val, t=None): + self.displacement += abs(val - self.history[-1][1]) + return super(ScrollEffect, self).update(val, t) + + def stop(self, val, t=None): + self.is_manual = False + self.displacement += abs(val - self.history[-1][1]) + if self.displacement <= self.drag_threshold: + self.velocity = 0 + return + return super(ScrollEffect, self).stop(val, t) diff --git a/pool/shard002/Python/0025847_decoder.py b/pool/shard002/Python/0025847_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd1e6cddb9d29c5db49535d10f550e5e4fa3f30 --- /dev/null +++ b/pool/shard002/Python/0025847_decoder.py @@ -0,0 +1,104 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Copyright (c) 2007-2013 Parisson +# Copyright (c) 2007 Olivier Guilyardi +# Copyright (c) 2007-2013 Guillaume Pellerin +# Copyright (c) 2010-2013 Paul Brossier +# +# This file is part of TimeSide. + +# 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 . + +# Authors: +# Paul Brossier +# Guillaume Pellerin +# Thomas Fillon + +from __future__ import division + +from timeside.core import Processor, implements, interfacedoc, abstract +from timeside.core.api import IDecoder + + +class Decoder(Processor): + + """General abstract base class for Decoder + """ + implements(IDecoder) + abstract() + + type = 'decoder' + + mimetype = '' + output_samplerate = None + output_channels = None + + def __init__(self, start=0, duration=None): + super(Decoder, self).__init__() + + self.uri_start = float(start) + if duration: + self.uri_duration = float(duration) + else: + self.uri_duration = duration + + if start == 0 and duration is None: + self.is_segment = False + else: + self.is_segment = True + + @interfacedoc + def channels(self): + return self.output_channels + + @interfacedoc + def samplerate(self): + return self.output_samplerate + + @interfacedoc + def blocksize(self): + return self.output_blocksize + + @interfacedoc + def totalframes(self): + return self.input_totalframes + + @interfacedoc + def release(self): + pass + + @interfacedoc + def mediainfo(self): + return dict(uri=self.uri, + duration=self.uri_duration, + start=self.uri_start, + is_segment=self.is_segment, + samplerate=self.input_samplerate, + sha1=self.sha1) + + @property + def sha1(self): + return self._sha1 + + def __del__(self): + self.release() + + @interfacedoc + def encoding(self): + return self.format().split('/')[-1] + + @interfacedoc + def resolution(self): + return self.input_width diff --git a/pool/shard002/Python/0025848_test_utils.py b/pool/shard002/Python/0025848_test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..49cd674bcbe811761e4061ccb6596be14e66c0b4 --- /dev/null +++ b/pool/shard002/Python/0025848_test_utils.py @@ -0,0 +1,47 @@ +try: + import unittest2 as unittest +except ImportError: + import unittest + +import Orange +from Orange import utils + + +class TestUtils(unittest.TestCase): + def test_new_wrappers(self): + class A(Orange.core.OrangeBase): + __new__ = utils._orange__new__(Orange.core.OrangeBase) + + def __call__(self, data): + return data, self.name, self.msg + + msg = "This is a test" + name = "A" + a = A(name=name, msg=msg) + self.assertIsInstance(a, A) + self.assertEqual(a.name, name) + self.assertEqual(a.msg, msg) + + iris = Orange.data.Table("iris") + b, name1, msg1 = A(iris, name=name, msg=msg) + self.assertIs(b, iris) + self.assertEqual(name1, name) + self.assertEqual(msg1, msg) + + class L(Orange.core.Learner): + __new__ = utils._orange__new__(Orange.core.Learner) + + def __call__(self, data, weight=0): + return data, weight, self.msg + + a = L(msg=msg) + self.assertIsInstance(a, L) + self.assertEqual(a.msg, msg) + + b, weight, msg1 = L(iris, 2, msg=msg) + self.assertIs(b, iris) + self.assertEqual(weight, 2) + self.assertEqual(msg1, msg) + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard002/Python/0025854_cms_plugins.py b/pool/shard002/Python/0025854_cms_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..2d75ee9822fa26233a534546789f89016723bbe8 --- /dev/null +++ b/pool/shard002/Python/0025854_cms_plugins.py @@ -0,0 +1,37 @@ +from django.utils.translation import ugettext_lazy as _ +from django.utils.datastructures import SortedDict + +from cms.plugin_base import CMSPluginBase +from cms.plugin_pool import plugin_pool + +from . import utils +from . import models + + +class CMSCompleteSchedulePlugin(CMSPluginBase): + """ + Plugin for rendering the whole conference schedule. + """ + model = models.CompleteSchedulePlugin + name = _('Complete schedule') + render_template = "schedule/plugins/complete.html" + + def render(self, context, instance, placeholder): + schedule = utils.create_schedule() + incl_sections = instance.sections.all() + if not incl_sections: + schedule = schedule + else: + s = SortedDict() + for k, v in schedule.iteritems(): + if k in incl_sections: + s[k] = v + schedule = s + context.update({ + 'instance': instance, + 'schedule': schedule, + 'placeholder': placeholder, + }) + return context + +plugin_pool.register_plugin(CMSCompleteSchedulePlugin) diff --git a/pool/shard002/Python/0025855_map_rms.py b/pool/shard002/Python/0025855_map_rms.py new file mode 100644 index 0000000000000000000000000000000000000000..302cc87dfd6727166a25d9d72e783c2adaeed5e9 --- /dev/null +++ b/pool/shard002/Python/0025855_map_rms.py @@ -0,0 +1,112 @@ +import matplotlib.pyplot as plt +import astropy.units as u +import warnings +import numpy as np +import os + +from astropy.io import fits +import aplpy + +from config import plottingDictionary + +region_list=['L1688', 'B18', 'NGC1333', 'OrionA'] +line_list=['NH3_11','NH3_22','NH3_33','C2S','HC5N','HC7N_21_20','HC7N_22_21'] +label_list=['NH$_3$(1,1)','NH$_3$(2,2)','NH$_3$(3,3)','C$_2$S','HC$_5$N', + 'HC$_7$N (21-20)','HC$_7$N (22-21)'] +extension='DR1_rebase3' +color_table='Blues' +text_color='black' +beam_color='#d95f02' # previously used '#E31A1C' +color_hist='#a6bddb' + +color_hall= ['#a6cee3', '#fdbf6f', '#33a02c', '#b2df8a', '#fb9a99', '#e31a1c', + '#1f78b4'] +# color_hall= ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', +# '#a6761d'] + +bin_size=0.01 # K + +for region_i in region_list: + plot_param=plottingDictionary[region_i]#setup_plot_parameters(region=region_i) + fig_hall=plt.figure(figsize=(6,6)) + ax_hall = fig_hall.add_subplot(111) + v_hall_max=np.max(plot_param['rms_max']) + v_hall_min=np.min(plot_param['rms_min']) + nbin_hall=int(np.ceil( np.abs(v_hall_max-v_hall_min)/ bin_size)) + for i in range(len(line_list)): + line_i=line_list[i] + label_i=label_list[i] + file_rms='{0}/{0}_{1}_{2}_rms_QA_trim.fits'.format(region_i,line_i,extension) + v_min=plot_param['rms_min'][i] + v_max=plot_param['rms_max'][i] + if os.path.isfile(file_rms): + fig=aplpy.FITSFigure(file_rms, hdu=0, figsize=(plot_param['size_x'], plot_param['size_y']) ) + fig.show_colorscale( cmap=color_table,vmin=v_min, vmax=v_max) + fig.set_nan_color('0.9') + # + # Ticks + fig.ticks.set_color(text_color) + fig.tick_labels.set_xformat('hh:mm:ss') + # Add beam + fig.add_beam() + fig.beam.set_color(beam_color) + fig.beam.set_corner(plot_param['beam_pos']) + # Scale bar + # magic line of code to obtain scale in arcsec obtained from + # http://www.astropy.org/astropy-tutorials/Quantities.html + ang_sep = (plot_param['scalebar_size'].to(u.au)/plot_param['distance']).to(u.arcsec, equivalencies=u.dimensionless_angles()) + fig.add_scalebar(ang_sep.to(u.degree)) + fig.scalebar.set_corner(plot_param['scalebar_pos']) + fig.scalebar.set(color=text_color) + fig.scalebar.set_label('{0:4.2f}'.format(plot_param['scalebar_size'])) + # Labels + fig.add_label(plot_param['label_xpos'], plot_param['label_ypos'], + '{0}\n{1}'.format(region_i,label_i), + relative=True, color=text_color, + horizontalalignment=plot_param['label_align']) + # add colorbar + fig.add_colorbar() + fig.colorbar.set_width(0.15) + fig.colorbar.show( box_orientation='horizontal', width=0.1, pad=0.0, + location='top', axis_label_text='(K)') + # fig.set_system_latex(True) + fig.save( 'figures/{0}_{1}_{2}_rms_map.pdf'.format(region_i,line_i,extension),adjust_bbox=True)#, bbox_inches='tight') + fig.close() + + data, hd=fits.getdata(file_rms, header=True) + fig=plt.figure(figsize=(6,6)) + ax = fig.add_subplot(111) + # the histogram of the data + nbin=int(np.ceil( np.abs(v_max-v_min)/ bin_size)) + myarray=data[np.isfinite(data)] + weights = np.ones_like(myarray)/float(len(myarray)) + n, bins, patches = ax.hist( myarray, weights=weights, bins=nbin, + facecolor=color_hist, range=(v_min,v_max), + histtype='stepfilled') + ax.set_xlabel('rms (K)') + ax.set_ylabel('Fraction of Pixels') + ax.text(0.9, 0.9, '{0}\n{1}'.format(region_i,label_i), + horizontalalignment='right', + verticalalignment='top', + transform=ax.transAxes) + ax.set_xlim(xmin=v_min,xmax=v_max) + fig.savefig('figures/{0}_{1}_{2}_rms_hist.pdf'.format(region_i,line_i,extension),adjust_bbox=True) + # now do the histogram of all lines together + hist, binEdges = np.histogram( myarray, weights=weights, bins=nbin_hall, + range=(v_hall_min,v_hall_max)) + binCenters = 0.5*(binEdges[1:]+binEdges[:-1]) + ax_hall.plot( binCenters, hist, drawstyle='steps-mid',label=label_i,color=color_hall[i]) + else: + print('File {0} not found'.format(file_rms)) + # after for loop is finished then close things + ax_hall.set_xlabel('rms (K)') + ax_hall.set_ylabel('Fraction of Pixels') + ax_hall.set_xlim(xmin=v_hall_min,xmax=v_hall_max) + leg=ax_hall.legend(frameon=False, loc=1, title=region_i, handlelength=0) + leg_text=leg.get_texts() + for index in range(len(leg_text)): + plt.setp( leg_text[index], color=color_hall[index] ) + for item in leg.legendHandles: + item.set_visible(False) + fig_hall.savefig('figures/{0}_all_{1}_rms_hist.pdf'.format(region_i,extension),adjust_bbox=True) + plt.close('all') diff --git a/pool/shard002/Python/0025861_converter.py b/pool/shard002/Python/0025861_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..6d94829f2eea343c1e860e66dc2ae742f4e78900 --- /dev/null +++ b/pool/shard002/Python/0025861_converter.py @@ -0,0 +1,39 @@ +# (C) 2009 copyright by Peter Bouda +# -*- coding: utf-8 -*- +""" +A class to convert Elan's .eaf files to other formats. +""" +__author__ = 'Peter Bouda' +__version__= '0.1.1' + +import os +from lxml import etree +from StringIO import StringIO + +class Callable: + def __init__(self, anycallable): + self.__call__ = anycallable + +class Convert(object): + def __init__(self): + pass + + def toAg(text): + """ + Convert an Elan XML string to a Annotation Graph XML string. + Call this as a static function: + + ag_xml = pyannotation.elan.converter.Convert.toAg(elan_xml) + + """ + xsl_path = os.path.join(os.path.dirname(__file__), '..', 'xsl', 'elan2ag.xsl') + xslt_doc = etree.parse(xsl_path) + transform = etree.XSLT(xslt_doc) + document = etree.parse(StringIO(text.encode('utf-8'))) + result = transform(document) + result = str(result) + result = result.decode('utf-8') + return result + + toAg = Callable(toAg) + diff --git a/pool/shard002/Python/0025862_test_bom.py b/pool/shard002/Python/0025862_test_bom.py new file mode 100644 index 0000000000000000000000000000000000000000..4e520ef233785fe96dc9caecabaeb29f51905ed0 --- /dev/null +++ b/pool/shard002/Python/0025862_test_bom.py @@ -0,0 +1,51 @@ +# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors +# License: GNU General Public License v3. See license.txt + + +from __future__ import unicode_literals +import unittest +import frappe +from frappe.utils import cstr + +test_records = frappe.get_test_records('BOM') + +class TestBOM(unittest.TestCase): + def test_get_items(self): + from erpnext.manufacturing.doctype.bom.bom import get_bom_items_as_dict + items_dict = get_bom_items_as_dict(bom=get_default_bom(), company="_Test Company", qty=1, fetch_exploded=0) + self.assertTrue(test_records[2]["items"][0]["item_code"] in items_dict) + self.assertTrue(test_records[2]["items"][1]["item_code"] in items_dict) + self.assertEquals(len(items_dict.values()), 2) + + def test_get_items_exploded(self): + from erpnext.manufacturing.doctype.bom.bom import get_bom_items_as_dict + items_dict = get_bom_items_as_dict(bom=get_default_bom(), company="_Test Company", qty=1, fetch_exploded=1) + self.assertTrue(test_records[2]["items"][0]["item_code"] in items_dict) + self.assertFalse(test_records[2]["items"][1]["item_code"] in items_dict) + self.assertTrue(test_records[0]["items"][0]["item_code"] in items_dict) + self.assertTrue(test_records[0]["items"][1]["item_code"] in items_dict) + self.assertEquals(len(items_dict.values()), 3) + + def test_get_items_list(self): + from erpnext.manufacturing.doctype.bom.bom import get_bom_items + self.assertEquals(len(get_bom_items(bom=get_default_bom(), company="_Test Company")), 3) + + def test_default_bom(self): + def _get_default_bom_in_item(): + return cstr(frappe.db.get_value("Item", "_Test FG Item 2", "default_bom")) + + bom = frappe.get_doc("BOM", {"item":"_Test FG Item 2", "is_default": 1}) + self.assertEqual(_get_default_bom_in_item(), bom.name) + + bom.is_active = 0 + bom.save() + self.assertEqual(_get_default_bom_in_item(), "") + + bom.is_active = 1 + bom.is_default=1 + bom.save() + + self.assertTrue(_get_default_bom_in_item(), bom.name) + +def get_default_bom(item_code="_Test FG Item 2"): + return frappe.db.get_value("BOM", {"item": item_code, "is_active": 1, "is_default": 1}) diff --git a/pool/shard002/Python/0025865_account_forms.py b/pool/shard002/Python/0025865_account_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..31d81019448356549739c8a90d3c6f3c72c5837b --- /dev/null +++ b/pool/shard002/Python/0025865_account_forms.py @@ -0,0 +1,128 @@ +from django import forms +from django.db import models +from django.forms import widgets +from django.forms import fields +from django.utils.translation import ugettext as _ +from django.contrib.auth import authenticate + +from twistranet.twistapp.lib import permissions +from twistranet.twistapp.forms.widgets import ResourceWidget +from twistranet.twistapp.models import UserAccount, Account +from twistranet.twistapp.forms.base_forms import BaseForm +from twistranet.tagging.fields import TagsFormField +from twistranet.tagging.models import Tag + +class UserAccountForm(BaseForm): + """ + User account edition. + """ + title = fields.CharField( + label = _("Your name"), + help_text = _("Enter your full name (eg. Firstname Lastname) as you want it to be displayed to other users."), + ) + + description = fields.CharField( + label = _("About you"), + help_text = _("Present yourself in a few lines. What are you working on? What do you like besides work?"), + widget = widgets.Textarea(), + ) + + tags = TagsFormField( + label = _("Keywords about you"), + help_text = _("Enter what you do, what you like, ..."), + required = False, + queryset = Tag.objects.all(), + ) + + class Meta: + model = UserAccount + fields = ('title', 'description', 'tags', 'picture', ) + widgets = { + "picture": ResourceWidget(), + } + +class UserAccountCreationForm(forms.Form): + """ + User Creation form. + We add a few things to make this shiny. + """ + first_name = forms.CharField( + max_length = 40, + label = _("First name"), + ) + last_name = forms.CharField( + max_length = 40, + label = _("Last name"), + ) + username = forms.CharField( + label = _("Login name"), + max_length = 30 + ) + email = forms.EmailField(max_length = 40) + password = forms.CharField( + widget = widgets.PasswordInput(), + label = _("Choose your password"), + ) + password_confirm = forms.CharField( + widget = widgets.PasswordInput(), + label = _("Confirm your password"), + ) + class Meta: + pass + +class UserInviteForm(forms.Form): + """ + User account creation. + """ + email = forms.EmailField() + make_admin = forms.BooleanField( + required = False, + label = _("Invite as an administrator?") + ) + invite_message = forms.CharField( + required = False, + widget = widgets.Textarea(), + label = _("Invitation message"), + help_text = _("If given, this text will be added to the user when sending the invitation."), + ) + + class Meta: + pass + +class ChangePasswordForm(forms.Form): + """ + Password reset form. + """ + password = forms.CharField( + label = _("Enter your current password"), + widget=forms.PasswordInput, + ) + new_password = forms.CharField( + label = _("Enter your new password"), + widget=forms.PasswordInput, + ) + confirm = forms.CharField( + label = _("Confirm your new password"), + help_text = _("Enter the same password as above, for verification."), + widget=forms.PasswordInput, + ) + + def clean_password(self,): + # Double check username according to currently logged-in user + username = Account.objects._getAuthenticatedAccount().user.username + password = self.cleaned_data.get('password') + if password: + user_cache = authenticate(username=username, password=password) + if user_cache is None: + raise forms.ValidationError(_("Invalid password.")) + elif not user_cache.is_active: + raise RuntimeError("Inactive account! Should never reach there.") + else: + return "(valid)" # Avoid propagating the clean password... + + def clean_confirm(self,): + password = self.cleaned_data.get("new_password", "") + confirm = self.cleaned_data["confirm"] + if password != confirm: + raise forms.ValidationError(_("The two password fields didn't match.")) + return confirm diff --git a/pool/shard002/Python/0025875_0001_initial.py b/pool/shard002/Python/0025875_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..0a9f96d9f114667c7c905a903f53756d137b65ad --- /dev/null +++ b/pool/shard002/Python/0025875_0001_initial.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.6 on 2017-10-31 18:42 +from __future__ import unicode_literals + +from django.db import migrations, models +import uuid + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Whoosis', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('name', models.CharField(max_length=32)), + ('date_created', models.DateTimeField(auto_now_add=True)), + ('date_modified', models.DateTimeField(auto_now=True)), + ], + ), + ] diff --git a/pool/shard002/Python/0025886_Shelf.py b/pool/shard002/Python/0025886_Shelf.py new file mode 100644 index 0000000000000000000000000000000000000000..3939d8d9a86fa527069d3e5b34ac1410b31a90b7 --- /dev/null +++ b/pool/shard002/Python/0025886_Shelf.py @@ -0,0 +1,33 @@ +# encoding: utf8 + + +# noinspection PyPep8Naming +from SmallScrewdriver import Point, Size, Rect + + +class Shelf(Rect): + def __init__(self, max_size, origin=Point()): + Rect.__init__(self, origin, Size()) + self.maxSize = max_size + self.images = [] + + def addImage(self, image): + """ + Добавить изображение на полку + :param image: добавляемое изображение + :return: True если изображение может быть добавлено + False если не может + """ + free_size = Size(self.maxSize.width - self.size.width, self.maxSize.height) + image_size = Size(image.crop.size.height, image.crop.size.width) if image.rotated else image.crop.size + if image_size < free_size: # >= image_size + + image.origin = Point(self.size.width, self.origin.y) + self.images.append(image) + + self.size.width += image_size.width + if image_size.height > self.size.height: + self.size.height += image_size.height + return True + else: + return False diff --git a/pool/shard002/Python/0025889_mac.py b/pool/shard002/Python/0025889_mac.py new file mode 100644 index 0000000000000000000000000000000000000000..279594795648da0ef48ab1b19c4235867182039b --- /dev/null +++ b/pool/shard002/Python/0025889_mac.py @@ -0,0 +1,266 @@ +#Copyright 2013 Paul Barton +# +#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 time +import Quartz +from AppKit import NSSystemDefined, NSEvent +from .base import PyKeyboardMeta, PyKeyboardEventMeta + +# Taken from events.h +# /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h +character_translate_table = { + 'a': 0x00, + 's': 0x01, + 'd': 0x02, + 'f': 0x03, + 'h': 0x04, + 'g': 0x05, + 'z': 0x06, + 'x': 0x07, + 'c': 0x08, + 'v': 0x09, + 'b': 0x0b, + 'q': 0x0c, + 'w': 0x0d, + 'e': 0x0e, + 'r': 0x0f, + 'y': 0x10, + 't': 0x11, + '1': 0x12, + '2': 0x13, + '3': 0x14, + '4': 0x15, + '6': 0x16, + '5': 0x17, + '=': 0x18, + '9': 0x19, + '7': 0x1a, + '-': 0x1b, + '8': 0x1c, + '0': 0x1d, + ']': 0x1e, + 'o': 0x1f, + 'u': 0x20, + '[': 0x21, + 'i': 0x22, + 'p': 0x23, + 'l': 0x25, + 'j': 0x26, + '\'': 0x27, + 'k': 0x28, + ';': 0x29, + '\\': 0x2a, + ',': 0x2b, + '/': 0x2c, + 'n': 0x2d, + 'm': 0x2e, + '.': 0x2f, + '`': 0x32, + ' ': 0x31, + '\r': 0x24, + '\t': 0x30, + '\n': 0x24, + 'return' : 0x24, + 'tab' : 0x30, + 'space' : 0x31, + 'delete' : 0x33, + 'escape' : 0x35, + 'command' : 0x37, + 'shift' : 0x38, + 'capslock' : 0x39, + 'option' : 0x3A, + 'alternate' : 0x3A, + 'control' : 0x3B, + 'rightshift' : 0x3C, + 'rightoption' : 0x3D, + 'rightcontrol' : 0x3E, + 'function' : 0x3F, +} + +#inverse of character_translate_table for key code to name lookups +key_code_translate_table = dict((key_code, key_name) for key_name, key_code in character_translate_table.items()) + +# Taken from ev_keymap.h +# http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h +special_key_translate_table = { + 'KEYTYPE_SOUND_UP': 0, + 'KEYTYPE_SOUND_DOWN': 1, + 'KEYTYPE_BRIGHTNESS_UP': 2, + 'KEYTYPE_BRIGHTNESS_DOWN': 3, + 'KEYTYPE_CAPS_LOCK': 4, + 'KEYTYPE_HELP': 5, + 'POWER_KEY': 6, + 'KEYTYPE_MUTE': 7, + 'UP_ARROW_KEY': 8, + 'DOWN_ARROW_KEY': 9, + 'KEYTYPE_NUM_LOCK': 10, + 'KEYTYPE_CONTRAST_UP': 11, + 'KEYTYPE_CONTRAST_DOWN': 12, + 'KEYTYPE_LAUNCH_PANEL': 13, + 'KEYTYPE_EJECT': 14, + 'KEYTYPE_VIDMIRROR': 15, + 'KEYTYPE_PLAY': 16, + 'KEYTYPE_NEXT': 17, + 'KEYTYPE_PREVIOUS': 18, + 'KEYTYPE_FAST': 19, + 'KEYTYPE_REWIND': 20, + 'KEYTYPE_ILLUMINATION_UP': 21, + 'KEYTYPE_ILLUMINATION_DOWN': 22, + 'KEYTYPE_ILLUMINATION_TOGGLE': 23 +} + +class PyKeyboard(PyKeyboardMeta): + + def __init__(self): + self.shift_key = 'shift' + self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False} + + def press_key(self, key): + if key.title() in self.modifier_table: + self.modifier_table.update({key.title():True}) + + if key in special_key_translate_table: + self._press_special_key(key, True) + else: + self._press_normal_key(key, True) + + def release_key(self, key): + # remove the key + if key.title() in self.modifier_table: + self.modifier_table.update({key.title():False}) + + if key in special_key_translate_table: + self._press_special_key(key, False) + else: + self._press_normal_key(key, False) + + def special_key_assignment(self): + self.volume_mute_key = 'KEYTYPE_MUTE' + self.volume_down_key = 'KEYTYPE_SOUND_DOWN' + self.volume_up_key = 'KEYTYPE_SOUND_UP' + self.media_play_pause_key = 'KEYTYPE_PLAY' + + # Doesn't work :( + # self.media_next_track_key = 'KEYTYPE_NEXT' + # self.media_prev_track_key = 'KEYTYPE_PREVIOUS' + + def _press_normal_key(self, key, down): + try: + key_code = character_translate_table[key.lower()] + # kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift + event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down) + mkeyStr = '' + for mkey in self.modifier_table: + if self.modifier_table[mkey]: + if len(mkeyStr)>1: + mkeyStr = mkeyStr+' ^ ' + mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey + if len(mkeyStr)>1: + eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')') + Quartz.CGEventPost(Quartz.kCGHIDEventTap, event) + if key.lower() == "shift": + time.sleep(.1) + + except KeyError: + raise RuntimeError("Key {} not implemented.".format(key)) + + def _press_special_key(self, key, down): + """ Helper method for special keys. + + Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac + """ + key_code = special_key_translate_table[key] + + ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( + NSSystemDefined, # type + (0,0), # location + 0xa00 if down else 0xb00, # flags + 0, # timestamp + 0, # window + 0, # ctx + 8, # subtype + (key_code << 16) | ((0xa if down else 0xb) << 8), # data1 + -1 # data2 + ) + + Quartz.CGEventPost(0, ev.CGEvent()) + +class PyKeyboardEvent(PyKeyboardEventMeta): + def __init__(self,diagnostic=False): + self.diagnostic = diagnostic + PyKeyboardEventMeta.__init__(self) + + def run(self): + tap = Quartz.CGEventTapCreate( + Quartz.kCGSessionEventTap, + Quartz.kCGHeadInsertEventTap, + Quartz.kCGEventTapOptionDefault, + Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) | + Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp), + self.handler, + None) + + loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0) + self.loop = Quartz.CFRunLoopGetCurrent() + Quartz.CFRunLoopAddSource(self.loop, loopsource, Quartz.kCFRunLoopDefaultMode) + Quartz.CGEventTapEnable(tap, True) + + while self.state: + Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False) + + def escape(self, key): + return key_code_translate_table[key] == 'escape' + + def stop(self): + """Stop listening for keyboard input events.""" + Quartz.CFRunLoopStop(self.loop) + self.state = False + + def _diagnostic(self,key,event): + print('\n---Keyboard Event Diagnostic---') + #print('MessageName:', event.MessageName) + #print('Message:', event.Message) + #print('Time:', event.Time) + #print('Window:', event.Window) + #print('WindowName:', event.WindowName) + #print('Ascii:', event.Ascii, ',', chr(event.Ascii)) + print('Key:',key_code_translate_table[key]) + print('Key Code:',key) + #print('KeyID:', event.KeyID) + #print('ScanCode:', event.ScanCode) + #print('Extended:', event.Extended) + #print('Injected:', event.Injected) + #print('Alt', event.Alt) + #print('Transition', event.Transition) + print('---') + + def handler(self, proxy, type, event, refcon): + key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode) + if self.escape(key): # A chance to escape + self.stop() + + if self.diagnostic: + self._diagnostic(key,event) + + if type == Quartz.kCGEventKeyDown: + self.key_press(key) + + elif type == Quartz.kCGEventKeyUp: + self.key_release(key) + + if self.capture: + Quartz.CGEventSetType(event, Quartz.kCGEventNull) + + return event diff --git a/pool/shard002/Python/0025894_cursor_response.py b/pool/shard002/Python/0025894_cursor_response.py new file mode 100644 index 0000000000000000000000000000000000000000..028df64649db297dd5e2e8c8798fd64f3046351b --- /dev/null +++ b/pool/shard002/Python/0025894_cursor_response.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python +# encoding: utf-8 + +# Copyright (C) Alibaba Cloud Computing +# All rights reserved. + +from .util import Util +from .logresponse import LogResponse + + +class GetCursorResponse(LogResponse): + """ The response of the get_cursor API from log. + + :type header: dict + :param header: ListShardResponse HTTP response header + + :type resp: dict + :param resp: the HTTP response body + """ + + def __init__(self, resp, header): + LogResponse.__init__(self, header, resp) + self.cursor = Util.convert_unicode_to_str(resp["cursor"]) + + def get_cursor(self): + """ + + :return: + """ + return self.cursor + + def log_print(self): + print('GetCursorResponse') + print('headers:', self.get_all_headers()) + print('cursor:', self.cursor) diff --git a/pool/shard002/Python/0025902_setup.py b/pool/shard002/Python/0025902_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d19d9bda65b4fa5777b4ce2877c0feb698d4d811 --- /dev/null +++ b/pool/shard002/Python/0025902_setup.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 + +from __future__ import print_function +import ast +import os +import setuptools +import sys + +os.chdir(os.path.dirname(os.path.abspath(__file__))) + +if sys.version_info[0] != 3: + print("Only Python 3 is supported!") + sys.exit(1) + + +def read_requirements(path="requirements.txt"): + fullpath = os.path.join(os.path.dirname(__file__), path) + with open(fullpath, "r") as f: + lines = f.readlines() + lines = [l.strip() for l in lines if l] + return [l for l in lines if l] + + +def get_version(path="russell/__version__.py"): + with open(path) as fh: + for line in fh: + if line.startswith("__version__ ="): + return ast.literal_eval(line[14:]) + + +setuptools.setup( + name="russell", + packages=["russell"], + version=get_version(), + license="GPL-3.0", + description="A static HTML blog generator.", + author="Andreas Lutro", + author_email="anlutro@gmail.com", + url="https://github.com/anlutro/russell", + keywords=["blog", "static", "html", "generator"], + classifiers=[], + install_requires=read_requirements(), + entry_points={ + "console_scripts": ["russell=russell.cli:main"], + }, +) diff --git a/pool/shard002/Python/0025905_engine.py b/pool/shard002/Python/0025905_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..ba633f19aaa202623587b7fe92f01147f6460e2b --- /dev/null +++ b/pool/shard002/Python/0025905_engine.py @@ -0,0 +1,18 @@ +from sqlalchemy.orm import sessionmaker +from sqlalchemy import create_engine + +import os +import toml + +def build_engine(): + conf = load_configs() + return create_engine('mysql+pymysql://%s:%s@%s/%s' % (conf["username"], + conf["password"], conf["host"], conf["database"])) + +def load_configs(config_file="config/database.toml"): + config_file = os.path.dirname(os.path.realpath(__file__)) + "/" + config_file + with open(config_file) as f: + return toml.loads(f.read()) + +def session(): + return sessionmaker(bind=build_engine())() diff --git a/pool/shard002/Python/0025907_pyedit_create_lines_on_commas.py b/pool/shard002/Python/0025907_pyedit_create_lines_on_commas.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc4e4df44fe1119f6d1953e78a6afc805ed5bcb --- /dev/null +++ b/pool/shard002/Python/0025907_pyedit_create_lines_on_commas.py @@ -0,0 +1,51 @@ +#=============================================================================== +# Pydev Extensions in Jython code protocol +#=============================================================================== +if False: + from org.python.pydev.editor import PyEdit #@UnresolvedImport + cmd = 'command string' + editor = PyEdit + systemGlobals = {} + + + +if cmd == 'onCreateActions': + # interface: PyEdit object: this is the actual editor that we will act upon + assert editor is not None + + CreateLinesOnCommas = systemGlobals.get('CreateLinesOnCommas') + if CreateLinesOnCommas is None: + Action = editor.getActionClass() #from org.eclipse.jface.action import Action #@UnresolvedImport + + class CreateLinesOnCommas(Action): + ''' Split a line in its commas. + ''' + + def __init__(self, editor): + self.editor = editor + + def run(self): + editor = self.editor + from split_text_in_commas import SplitTextInCommas + sel = editor.createPySelection() + txt = sel.getSelectedText() + delimiter = sel.getEndLineDelim() + indent = sel.getIndentationFromLine() + + splitted = SplitTextInCommas(txt) + + doc = sel.getDoc() + sel = sel.getTextSelection() + doc.replace(sel.getOffset(), sel.getLength(), (delimiter + indent).join([x.strip() + ', ' for x in splitted])) + + systemGlobals['CreateLinesOnCommas'] = CreateLinesOnCommas + + # Change these constants if the default does not suit your needs + ACTIVATION_STRING = 'sl' + WAIT_FOR_ENTER = False + + # Register the extension as an ActionListener. + editor.addOfflineActionListener(ACTIVATION_STRING, CreateLinesOnCommas(editor), \ + 'Create new lines in commas', \ + WAIT_FOR_ENTER) + diff --git a/pool/shard002/Python/0025909_mockup.py b/pool/shard002/Python/0025909_mockup.py new file mode 100644 index 0000000000000000000000000000000000000000..554df069121db7469cfafeaad2417d502aa5f753 --- /dev/null +++ b/pool/shard002/Python/0025909_mockup.py @@ -0,0 +1,75 @@ +# coding: utf8 +import json +import os + +from unittest.mock import Mock + +from requests import Session, Response + +SERVER = "https://my.test.server.com" +RESPONSE_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "responses") + + +def mockup_server(): + return SERVER + + +def request_mockup(*args, **kwargs): + method = kwargs["method"] + url = kwargs["url"] + if not url.startswith(SERVER + "/"): + raise ValueError("URL [{}] does not start with [{}/].".format(url, SERVER)) + parts = url[len(SERVER) + 1 :].split("?") + url = parts[0] + response_key = parts[1] if len(parts) > 1 else None + if kwargs["data"] is not None: + response_key = str(kwargs["data"]) + + response = Response() + response.url = kwargs["url"] + + response_file = os.path.join(RESPONSE_ROOT, url, method) + try: + with open(response_file, encoding="utf-8") as f: + data = {"responses": {}, "__builtins__": {}, "true": True, "false": False, "null": None} + exec(f.read(), data) + data = data["responses"][response_key] + if type(data) is dict: + if "status_code" in data: + response.status_code = data.pop("status_code") + else: + response.status_code = 200 + + # Extend the links with the server + for item in [None, "owner", "project", "workspace"]: + # Use values of paged response + for elem in data["values"] if "values" in data else [data]: + cur_dict = elem if item is None else elem.get(item, {}) + if "links" in cur_dict: + for link in cur_dict["links"].values(): + for ld in link if type(link) is list else [link]: + ld["href"] = "{}/{}".format(SERVER, ld["href"]) + if "next" in data: + data["next"] = "{}/{}".format(SERVER, data["next"]) + + response.encoding = "utf-8" + response._content = bytes(json.dumps(data), response.encoding) + else: + response.status_code = 200 + response._content = data + except FileNotFoundError: + response.encoding = "utf-8" + response._content = b"{}" + response.status_code = 404 # Not found + response.reason = "No stub defined [{}]".format(response_file) + except KeyError: + response.encoding = "utf-8" + response._content = b"{}" + response.status_code = 404 # Not found + response.reason = "No stub defined for key [{}] in [{}]".format(response_key, response_file) + + return response + + +Session.request = Mock() +Session.request.side_effect = request_mockup diff --git a/pool/shard002/Python/0025917_server.py b/pool/shard002/Python/0025917_server.py new file mode 100644 index 0000000000000000000000000000000000000000..666e68c15d5c12f73b422ec6478bf833cfa38a7e --- /dev/null +++ b/pool/shard002/Python/0025917_server.py @@ -0,0 +1,102 @@ +import cherrypy +from domain_discovery_API.server import Page +#import domain_discovery_api.* as dd_api +from ConfigParser import ConfigParser +import json +import os +from threading import Lock +import urlparse +from domain_discovery_API.models.domain_discovery_model import DomainModel +from domain_discovery_API.models.crawler_model import CrawlerModel +from domain_discovery_API.models.RadvizModel import RadvizModel + +class DDTServer(Page): + @staticmethod + def getConfig(): + # Parses file to prevent cherrypy from restarting when config.conf changes: after each request + # it restarts saying config.conf changed, when it did not. + config = ConfigParser() + config.read(os.path.join(os.path.dirname(__file__), "config.conf")) + + configMap = {} + for section in config.sections(): + configMap[section] = {} + for option in config.options(section): + # Handles specific integer entries. + val = config.get(section, option) + if option == "server.socket_port" or option == "server.thread_pool": + val = int(val) + configMap[section][option] = val + + return configMap + + # Default constructor reading app config file. + def __init__(self): + path = os.path.dirname(os.path.realpath(__file__)) + self._ddtModel = DomainModel(path) + self._crawlerModel = CrawlerModel(path) + self._ddtModel.setCrawlerModel(self._crawlerModel) + self._radvizModel = RadvizModel(path) + models = {"domain": self._ddtModel, "crawler": self._crawlerModel, "radviz": self._radvizModel} + super(DDTServer, self).__init__(models, path) + + # Access to seed crawler vis. + @cherrypy.expose + def seedcrawler(self): + # TODO Use SeedCrawlerModelAdapter self._crawler = SeedCrawlerModelAdapter() + return open(os.path.join(self._HTML_DIR, u"index.html")) + + @cherrypy.expose + def release(self): + return open(os.path.join(self._HTML_DIR, u"release.html")) + + @cherrypy.expose + def index(self): + return self.seedcrawler() + + # Submits a web query for a list of terms, e.g. 'ebola disease' + # @cherrypy.expose + # def queryWeb(self, terms, session): + # print "\n\n\n QUERY WEB IN REACT" + # session = json.loads(session) + # cherrypy.response.headers["Content-Type"] = "text/plain;" + # # for res in self._model.queryWeb(terms, 20, session=session): + # # print "\n\n\n SERVER QUERY WEB\n",res,"\n\n\n" + + # return self._model.queryWeb(terms, 20, session=session) + # queryWeb._cp_config ={'response.stream':True} + + @cherrypy.expose + def thing(self): + cherrypy.response.headers['Content-Type'] = 'text/plain' + # if not authorized(): + # raise cherrypy.NotFound() + def content(): + print "\n\n\nRUNNING CONTENT\n\n\n" + yield json.dumps({"first":"Hello"}) + yield json.dumps({"first":"World"}) + return content() + thing._cp_config = {'response.stream': True} + +if __name__ == "__main__": + server = DDTServer() + + # CherryPy always starts with app.root when trying to map request URIs + # to objects, so we need to mount a request handler root. A request + # to "/" will be mapped to HelloWorld().index(). + app = cherrypy.quickstart(server, config=DDTServer.getConfig()) + cherrypy.config.update(server.config) + #app = cherrypy.tree.mount(page, "/", page.config) + + #if hasattr(cherrypy.engine, "signal_handler"): + # cherrypy.engine.signal_handler.subscribe() + #if hasattr(cherrypy.engine, "console_control_handler"): + # cherrypy.engine.console_control_handler.subscribe() + #cherrypy.engine.start() + #cherrypy.engine.block() + +else: + server = DDTServer() + # This branch is for the test suite; you can ignore it. + config = DDTServer.getConfig() + app = cherrypy.tree.mount(server, config=config) diff --git a/pool/shard002/Python/0025923_chooseMTModel.py b/pool/shard002/Python/0025923_chooseMTModel.py new file mode 100644 index 0000000000000000000000000000000000000000..5702216b8b625936fdd2c718f9eceb6b7f37688a --- /dev/null +++ b/pool/shard002/Python/0025923_chooseMTModel.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- + +""" +Module implementing ChooseMTModelDialog. +""" + +import sys + +from PyQt4.QtCore import ( + pyqtSignature, + QObject, + SIGNAL, + ) +from PyQt4.QtGui import QDialog +from PyQt4.QtSql import QSqlQueryModel + +from Ui_chooseMTModel import Ui_Dialog +from util import doAlert + + +class ChooseMTModelDialog(QDialog, Ui_Dialog): + """ + Class documentation goes here. + """ + def __init__(self, parent=None, datamodel=None): + """ + Constructor + """ + QDialog.__init__(self, parent) + self.setupUi(self) + self.model = QSqlQueryModel() + self.selTableView.setModel(self.model) + self.database = datamodel.getQSqlDatabase() + self.updateModel() + self.selTableView.hideColumn(0) + self.selTableView.hideColumn(5) + self.selTableView.hideColumn(6) + # Change status and keep the column. + QObject.connect( + datamodel, SIGNAL("modelInstalled()"), + self.on_datamodel_modelInstalled) + + def updateModel(self): + self.model.setQuery( + 'SELECT ID, name, srclang, trglang, status, path, mosesini ' + 'FROM models ' + 'WHERE status = "READY" AND deleted != "True"', + self.database) + + def on_datamodel_recordUpdated(self, bRecord): + """Deal with the selection changed problem.""" + try: + if bRecord: + current = self.selTableView.currentIndex() + if current and current.row() != -1: + self.curSelection = current.row() + else: + self.curSelection = None + else: + if self.curSelection is not None: + self.selTableView.selectRow(self.curSelection) + except Exception as e: + print >> sys.stderr, str(e) + + def on_datamodel_modelInstalled(self): + self.updateModel() + + @pyqtSignature("") + def on_buttonBox_accepted(self): + """ + Slot documentation goes here. + """ + current = self.selTableView.currentIndex() + if not current: + doAlert("Please choose a model to start.") + return + record = self.model.record(current.row()) + self.ID = record.value("ID").toString() + self.modelName = record.value("name").toString() + self.srcLang = record.value('srclang').toString() + self.trgLang = record.value('trglang').toString() + self.path = record.value("path").toString() + self.mosesini = record.value("mosesini").toString() + self.accept() diff --git a/pool/shard002/Python/0025927_backend.py b/pool/shard002/Python/0025927_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..afdc20f91f2d8f8add0080bb078f9ed488ced5f7 --- /dev/null +++ b/pool/shard002/Python/0025927_backend.py @@ -0,0 +1,138 @@ +import os + +from ajenti.com import * +from ajenti.utils import * + + +def is_installed(): + return os.path.exists('/etc/samba/') + +def restart(): + shell('service smbd restart') + shell('service samba restart') # older samba packages + + +class SambaConfig(Plugin): + shares = {} + general = {} + users = {} + + general_defaults = { + 'server string': '', + 'workgroup': 'WORKGROUP', + 'interfaces': '', + 'socket options': 'TCP_NODELAY', + 'password server': '', + 'security': 'user' + } + + defaults = { + 'available': 'yes', + 'browseable': 'yes', + 'valid users': '', + 'path': '/dev/null', + 'read only': 'yes', + 'guest ok': 'yes', + 'guest only': 'no' + } + + editable = { + 'Account Flags': '-c', + 'User SID': '-U', + 'Primary Group SID': '-G', + 'Full Name': '-f', + 'Home Directory': '-h', + 'HomeDir Drive': '-D', + 'Logon Script': '-S', + 'Profile Path': '-p', + 'Kickoff time': '-K' + } + + fields = [] + + def load(self): + self.shares = {} + ss = open('/etc/samba/smb.conf', 'r').read().split('\n') + cs = '' + for s in ss: + s = s.strip() + try: + if s[0] != '#' and s[0] != ';': + if s[0] == '[': + cs = s[1:-1] + self.shares[cs] = self.new_share() if cs != 'global' else self.general_defaults.copy() + else: + s = s.split('=') + self.shares[cs][s[0].strip()] = s[1].strip() + except: + pass + + self.general = self.shares['global'] + self.shares.pop('global') + + self.users = {} + ss = [s.split(',')[0].split(':')[0] for s in shell('pdbedit -L').split('\n')] + for s in ss: + if s != '': + x = shell('pdbedit -L -v -u ' + s).split('\n') + self.users[s] = {} + self.fields = [] + for l in x: + try: + self.users[s][l.split(':')[0]] = l.split(':')[1].strip() + self.fields.append(l.split(':')[0]) + except: + pass + + + def save(self): + with open('/etc/samba/smb.conf', 'w') as f: + f.write('[global]\n') + for k in self.general: + if not k in self.general_defaults or \ + self.general[k] != self.general_defaults[k]: + f.write('\t%s = %s\n' % (k,self.general[k])) + for s in self.shares: + f.write('\n[%s]\n' % s) + for k in self.shares[s]: + if not k in self.defaults or self.shares[s][k] != self.defaults[k]: + f.write('\t%s = %s\n' % (k,self.shares[s][k])) + + def modify_user(self, u, p, v): + shell('pdbedit -r -u %s %s "%s"' % (u,self.editable[p],v)) + + def del_user(self, u): + shell('pdbedit -x -u ' + u) + + def add_user(self, u): + with open('/tmp/pdbeditnn', 'w') as f: + f.write('\n\n\n') + shell('pdbedit -a -t -u ' + u + ' < /tmp/pdbeditnn') + os.unlink('/tmp/pdbeditnn') + + def get_shares(self): + return self.shares.keys() + + def new_share(self): + return self.defaults.copy() + + def set_param(self, share, param, value): + if share == 'general': + self.general[param] = value + else: + self.shares[share][param] = value + + def set_param_from_vars(self, share, param, vars): + if share == 'general': + value = vars.getvalue(param, self.general_defaults[param]) + else: + value = vars.getvalue(param, self.defaults[param]) + self.set_param(share, param, value) + + def set_param_from_vars_yn(self, share, param, vars): + if share == 'general': + value = 'yes' if vars.getvalue(param, self.general_defaults[param]) == '1' else 'no' + else: + value = 'yes' if vars.getvalue(param, self.defaults[param]) == '1' else 'no' + self.set_param(share, param, value) + diff --git a/pool/shard002/Python/0025931_ShareplaceCom.py b/pool/shard002/Python/0025931_ShareplaceCom.py new file mode 100644 index 0000000000000000000000000000000000000000..cfc2807f9c2407fac4caf841afc8dc28c471a968 --- /dev/null +++ b/pool/shard002/Python/0025931_ShareplaceCom.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- + +import re +import urllib +from module.plugins.Hoster import Hoster + + +class ShareplaceCom(Hoster): + __name__ = "ShareplaceCom" + __type__ = "hoster" + __pattern__ = r'(http://)?(?:www\.)?shareplace\.(com|org)/\?[a-zA-Z0-9]+' + __version__ = "0.11" + __description__ = """Shareplace.com hoster plugin""" + __author_name__ = "ACCakut" + __author_mail__ = None + + def process(self, pyfile): + self.pyfile = pyfile + self.prepare() + self.download(self.get_file_url()) + + def prepare(self): + if not self.file_exists(): + self.offline() + + self.pyfile.name = self.get_file_name() + + wait_time = self.get_waiting_time() + self.setWait(wait_time) + self.logDebug("%s: Waiting %d seconds." % (self.__name__, wait_time)) + self.wait() + + def get_waiting_time(self): + if not self.html: + self.download_html() + + #var zzipitime = 15; + m = re.search(r'var zzipitime = (\d+);', self.html) + if m: + sec = int(m.group(1)) + else: + sec = 0 + + return sec + + def download_html(self): + url = re.sub("shareplace.com\/\?", "shareplace.com//index1.php/?a=", self.pyfile.url) + self.html = self.load(url, decode=True) + + def get_file_url(self): + """ returns the absolute downloadable filepath + """ + url = re.search(r"var beer = '(.*?)';", self.html) + if url: + url = url.group(1) + url = urllib.unquote( + url.replace("http://http:/", "").replace("vvvvvvvvv", "").replace("lllllllll", "").replace( + "teletubbies", "")) + self.logDebug("URL: %s" % url) + return url + else: + self.fail("absolute filepath could not be found. offline? ") + + def get_file_name(self): + if not self.html: + self.download_html() + + return re.search("\s*(.*?)\s*", self.html).group(1) + + def file_exists(self): + """ returns True or False + """ + if not self.html: + self.download_html() + + if re.search(r"HTTP Status 404", self.html) is not None: + return False + else: + return True diff --git a/pool/shard002/Python/0025935_Get_Congressional_Records_py2.py b/pool/shard002/Python/0025935_Get_Congressional_Records_py2.py new file mode 100644 index 0000000000000000000000000000000000000000..802721de84577c3c55a01c8452b18ab7d76b34ec --- /dev/null +++ b/pool/shard002/Python/0025935_Get_Congressional_Records_py2.py @@ -0,0 +1,178 @@ +################################## +### ### +### Joshua G. Mausolf ### +### Department of Sociology ### +### University of Chicago ### +### ### +################################## + +# Dependencies +################################## +""" +------------------------------------------------------------------------ +Notes: This Package Requires several dependencies +- Anaconda Distribution of Python 2 +- wget: + - Download the wget program zipfile: + https://pypi.python.org/pypi/wget + + - Through your command line terminal, navigate to the folder + and in your terminal execute "python setup.py install" +------------------------------------------------------------------------ +""" + + +def getURL(date): + """Prints Congressional Record URL (of PDF record) for a given date.""" + base_url = "https://www.gpo.gov/fdsys/pkg/CREC-"+date+"/pdf/CREC-"+date+".pdf" + print base_url + + +def getfullURL(date): + """Returns Congressional Record URL (of PDF record) for a given date.""" + base_url = "https://www.gpo.gov/fdsys/pkg/CREC-"+date+"/pdf/CREC-"+date+".pdf" + return base_url + + +def getdates(yr1=2009, yr2=2016, month1=1, month2=12, day1=1, day2=31): + """Returns a list of all possible dates as a set of tuples: + E.G. date1 = (2009, 01, 01) or datex = (2011, 12, 06) + The form is therefore a [(yyyy, mm, dd), ... (yyyy, mm, dd)] + + This function is set up to return all possible dates between 01/01/2009 and 12/31/2016. + + It can be modified to provide expanded dates if need be. + + Note that while this creates dates that do not exist, the end result + is simply an invalid url link, which is handled in subsequent functions.""" + + import itertools + + years = ['2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016'] + months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] + days = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'] + + + index_yr1 = yr1-2009 + index_yr2 = yr2-2009 + index_mo1 = month1-1 + index_mo2 = month2-1 + index_dy1 = day1-1 + index_dy2 = day2-1 + + req_years = years[index_yr1:index_yr2+1] + req_months = months[index_mo1:index_mo2+1] + req_days = days[index_dy1:index_dy2+1] + + dates = (list(itertools.product(req_years, req_months, req_days))) + return dates + + +def getcongressURLs(): + """This function returns a list of urls for the congressional records between 2009 and 2016.""" + + dates = getdates() + + f = open('congressional_records_URLs2.csv', 'w') + try: + for dt in range(0, len(dates)): + date = str(dates[dt]).replace("'", "").replace(",", "-").replace(" ", "").replace("(", "").replace(")", "") + full_url = getfullURL(date) + f.write(u'%s\n' % (full_url)) + finally: + f.close() + + + +def get_congressional_records(): + """This function retrieves the congressional records for the possible dates between 2009 and 2016. + + It writes urls where exceptions occur to a seperate spreadsheet. + Note that pages where no congressional record exists yield a 404 page for the Congressional record + website. As such, the wget function downloads the html code for that page, saving it based + on the url as a pdf: + + "https://www.gpo.gov/fdsys/pkg/CREC-"+date+"/pdf/CREC-"+date+".pdf" + + As a result, these pages are all identical and have a size of approximately 5618 bytes. + A subsequent bash script filters these false hits out based on these parameters. + + Note that the congressional record site will block your bot from downloading the page + if the time clock is too fast. + + For example, time.sleep(0.5) quickly locks up. The current set time time.sleep(5.5) + has run in testing without issue. Experiment at your own risk. + + """ + + import sys, csv, time, os, subprocess, wget, signal + + sys.path.append('../Python_Scripts/') + sys.path.append('..') + + ## Add Functions for Timeout and Signal ## + class TimeoutException(Exception): + pass + + def timeout_handler(signum, frame): + raise TimeoutException + + signal.signal(signal.SIGALRM, timeout_handler) + + + ## Setup Directory and Dates ## + try: + os.mkdir("Congressional_Records") + except: + pass + + os.chdir("Congressional_Records") + + dates = getdates() + + ## Begin Congressional Record Collection ## + try: + for dt in range(0, len(dates)): + date = str(dates[dt]).replace("'", "").replace(",", "-").replace(" ", "").replace("(", "").replace(")", "") + url = str(getfullURL(date)) + print "Downloading congressional record for date: ", date + + signal.alarm(30) + try: + filename = wget.download(url) + print "\n" + time.sleep(5.5) + except TimeoutException: + print "Timeout exception" + f = open('congressional_records_timeout_exception_URLs.csv', 'a') + try: + f.write(u'%s\n' % (url)) + finally: + f.close() + continue + + except: + time.sleep(5.5) + print "No congression record found, date: ", date + f = open('congressional_records_no_record_exception_URLs.csv', 'a') + try: + f.write(u'%s\n' % (url)) + finally: + f.close() + pass + + + except: + print "An unexpected error occurred." + f = open('congressional_records__unexpected_exception_URLs.csv', 'a') + try: + f.write(u'%s\n' % (url)) + finally: + f.close() + pass + +##Run Get Congressional Records +get_congressional_records() + + + diff --git a/pool/shard002/Python/0025938_encode-n-ary-tree-to-binary-tree.py b/pool/shard002/Python/0025938_encode-n-ary-tree-to-binary-tree.py new file mode 100644 index 0000000000000000000000000000000000000000..c0842bbee13439616b4422e0f4adc5fe758f4b11 --- /dev/null +++ b/pool/shard002/Python/0025938_encode-n-ary-tree-to-binary-tree.py @@ -0,0 +1,69 @@ +# Time: O(n) +# Space: O(h) + +# Definition for a Node. +class Node(object): + def __init__(self, val, children): + self.val = val + self.children = children + + +# Definition for a binary tree node. +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + + +class Codec: + + def encode(self, root): + """Encodes an n-ary tree to a binary tree. + + :type root: Node + :rtype: TreeNode + """ + def encodeHelper(root, parent, index): + if not root: + return None + node = TreeNode(root.val); + if index+1 < len(parent.children): + node.left = encodeHelper(parent.children[index+1], parent, index+1) + if root.children: + node.right = encodeHelper(root.children[0], root, 0); + return node + + if not root: + return None + node = TreeNode(root.val); + if root.children: + node.right = encodeHelper(root.children[0], root, 0) + return node + + def decode(self, data): + """Decodes your binary tree to an n-ary tree. + + :type data: TreeNode + :rtype: Node + """ + def decodeHelper(root, parent): + if not root: + return + children = [] + node = Node(root.val, children) + decodeHelper(root.right, node) + parent.children.append(node) + decodeHelper(root.left, parent) + + if not data: + return None + children = [] + node = Node(data.val, children) + decodeHelper(data.right, node) + return node + + +# Your Codec object will be instantiated and called as such: +# codec = Codec() +# codec.decode(codec.encode(root)) diff --git a/pool/shard002/Python/0025943_models.py b/pool/shard002/Python/0025943_models.py new file mode 100644 index 0000000000000000000000000000000000000000..62ae2ee073daab28a801e2dde56e2800bbff9155 --- /dev/null +++ b/pool/shard002/Python/0025943_models.py @@ -0,0 +1,93 @@ +# coding=utf-8 +"""Models for user map.""" +from django.core.urlresolvers import reverse +import logging +from django.contrib.gis.db import models + +logger = logging.getLogger(__name__) + + +class ApprovedEntryManager(models.Manager): + """Custom entry manager that shows only approved records.""" + + def get_query_set(self): + """Query set generator""" + return super( + ApprovedEntryManager, self).get_query_set().filter( + approved=True) + + +class UnapprovedEntryManager(models.Manager): + """Custom entry manager that shows only unapproved records.""" + + def get_query_set(self): + """Query set generator""" + return super( + UnapprovedEntryManager, self).get_query_set().filter( + approved=False) + + +class Role(models.Model): + """Role for users e.g. developer, trainer, user.""" + name = models.CharField( + help_text='How would you define your participation?', + max_length=255, + null=False, + blank=False, + unique=True) + sort_number = models.IntegerField( + help_text='Sorting order for role in role list.', + null=True, + blank=True) + + +class UserPoint(models.Model): + """An entry is the basic unit of a changelog.""" + name = models.CharField( + help_text='Title for this change note.', + max_length=255, + null=False, + blank=False, + unique=True) + + email = models.EmailField( + help_text='Describe the new feature. Markdown is supported.', + null=False, + blank=False, + unique=True) + + website = models.URLField( + help_text='Optional link to your personal or organisation web site.', + null=True, + blank=True) + + point = models.PointField( + help_text='Where are you?', + max_length=255, + null=False, + blank=False) + role = models.ForeignKey(Role) + email_updates = models.BooleanField( + help_text='Tick this to receive occasional news email messages.' + ) + approved = models.BooleanField( + help_text='Whether this user has approved their entry by email.' + ) + objects = models.GeoManager() + approved_objects = ApprovedEntryManager() + unapproved_objects = UnapprovedEntryManager() + + # noinspection PyClassicStyleClass + class Meta: + """Meta options for the version class.""" + app_label = 'user_map' + + def __unicode__(self): + return u'%s' % self.name + + def get_absolute_url(self): + """URL that can be used to access the edit form for the user. + """ + return reverse('user', kwargs={ + 'uid': self.uid, + }) diff --git a/pool/shard002/Python/0025948_test_decoder.py b/pool/shard002/Python/0025948_test_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..8c9cc7e46029e6efed0b89a553fdcb313a86d246 --- /dev/null +++ b/pool/shard002/Python/0025948_test_decoder.py @@ -0,0 +1,180 @@ +from unittest import TestCase + +from ruuvitag_sensor.decoder import get_decoder, parse_mac, UrlDecoder, Df3Decoder, Df5Decoder + +# pylint: disable=line-too-long + + +class TestDecoder(TestCase): + + def test_getcorrectdecoder(self): + dec = get_decoder(2) + self.assertIsInstance(dec, UrlDecoder) + dec = get_decoder(3) + self.assertIsInstance(dec, Df3Decoder) + + def test_decode_is_valid(self): + decoder = UrlDecoder() + data = decoder.decode_data('AjwYAMFc') + + self.assertEqual(data['temperature'], 24) + self.assertEqual(data['pressure'], 995) + self.assertEqual(data['humidity'], 30) + self.assertEqual(data['identifier'], None) + + def test_decode_is_valid_case2(self): + decoder = UrlDecoder() + data = decoder.decode_data('AjgbAMFc') + + self.assertEqual(data['temperature'], 27) + self.assertEqual(data['pressure'], 995) + self.assertEqual(data['humidity'], 28) + self.assertEqual(data['identifier'], None) + + def test_decode_is_valid_weatherstation_2017_04_12(self): + decoder = UrlDecoder() + data = decoder.decode_data('AjUX1MAw0') + + self.assertEqual(data['temperature'], 25.12) + self.assertEqual(data['pressure'], 992.0) + self.assertEqual(data['humidity'], 26.5) + self.assertEqual(data['identifier'], '0') + + def test_df3decode_is_valid(self): + decoder = Df3Decoder() + data = decoder.decode_data('03291A1ECE1EFC18F94202CA0B5300000000BB') + + self.assertEqual(data['temperature'], 26.3) + self.assertEqual(data['pressure'], 1027.66) + self.assertEqual(data['humidity'], 20.5) + self.assertEqual(data['battery'], 2899) + self.assertNotEqual(data['acceleration'], 0) + self.assertEqual(data['acceleration_x'], -1000) + self.assertNotEqual(data['acceleration_y'], 0) + self.assertNotEqual(data['acceleration_z'], 0) + + data = decoder.decode_data('03291A1ECE1EFC18F94202CA0B53BB') + self.assertEqual(data['temperature'], 26.3) + self.assertEqual(data['pressure'], 1027.66) + self.assertEqual(data['humidity'], 20.5) + self.assertEqual(data['battery'], 2899) + self.assertNotEqual(data['acceleration'], 0) + self.assertEqual(data['acceleration_x'], -1000) + self.assertNotEqual(data['acceleration_y'], 0) + self.assertNotEqual(data['acceleration_z'], 0) + + def test_df3decode_is_valid_notNone(self): + test_cases = [ + '1502010611FF990403411540C84AFC72FE2FFFC50B89C6', + '1502010611FF990403411544C850FC72FE2FFFC60B89B9', + '1502010611FF990403411540C855FC72FE2FFFC30B83C7', + '1502010611FF990403411539C842FC72FE2FFFC60B89C5', + '1502010611FF990403421534C813FC72FE2FFFC50B8FD5', + '1502010611FF990403441536C810FC72FE2FFFC70B83C7', + ] + decoder = Df3Decoder() + for x in test_cases: + data = decoder.decode_data(x) + self.assertIsNotNone(data) + + def test_df3decode_is_valid_max_values(self): + decoder = Df3Decoder() + humidity = 'C8' + temp = '7F63' + pressure = 'FFFF' + accX = '03E8' + accY = '03E8' + accZ = '03E8' + batt = 'FFFF' + data = decoder.decode_data( + '03{humidity}{temp}{pressure}{accX}{accY}{accZ}{batt}00000000BB'.format( + humidity=humidity, + temp=temp, + pressure=pressure, + accX=accX, + accY=accY, + accZ=accZ, + batt=batt)) + + self.assertEqual(data['temperature'], 127.99) + self.assertEqual(data['pressure'], 1155.35) + self.assertEqual(data['humidity'], 100.0) + self.assertEqual(data['battery'], 65535) + self.assertEqual(data['acceleration_x'], 1000) + self.assertEqual(data['acceleration_y'], 1000) + self.assertEqual(data['acceleration_z'], 1000) + self.assertNotEqual(data['acceleration'], 0) + + def test_df3decode_is_valid_min_values(self): + decoder = Df3Decoder() + humidity = '00' + temp = 'FF63' + pressure = '0000' + accX = 'FC18' + accY = 'FC18' + accZ = 'FC18' + batt = '0000' + data = decoder.decode_data( + '03{humidity}{temp}{pressure}{accX}{accY}{accZ}{batt}00000000BB'.format( + humidity=humidity, + temp=temp, + pressure=pressure, + accX=accX, + accY=accY, + accZ=accZ, + batt=batt)) + + self.assertEqual(data['temperature'], -127.99) + self.assertEqual(data['pressure'], 500.0) + self.assertEqual(data['humidity'], 0.0) + self.assertEqual(data['battery'], 0) + self.assertEqual(data['acceleration_x'], -1000) + self.assertEqual(data['acceleration_y'], -1000) + self.assertEqual(data['acceleration_z'], -1000) + self.assertNotEqual(data['acceleration'], 0) + + def test_df5decode_is_valid(self): + decoder = Df5Decoder() + data_format = '05' + temp = '12FC' + humidity = '5394' + pressure = 'C37C' + accX = '0004' + accY = 'FFFC' + accZ = '040C' + power_info = 'AC36' + movement_counter = '42' + measurement_sequence = '00CD' + mac = 'CBB8334C884F' + data = decoder.decode_data( + '{format}{temp}{humidity}{pressure}{accX}{accY}{accZ}{power_info}{movement_counter}{measurement_sequence}{mac}'.format( + format=data_format, + humidity=humidity, + temp=temp, + pressure=pressure, + accX=accX, + accY=accY, + accZ=accZ, + power_info=power_info, + movement_counter=movement_counter, + measurement_sequence=measurement_sequence, + mac=mac)) + + self.assertEqual(data['temperature'], 24.30) + self.assertEqual(data['humidity'], 53.49) + self.assertEqual(data['pressure'], 1000.44) + self.assertEqual(data['acceleration_x'], 4) + self.assertEqual(data['acceleration_y'], -4) + self.assertEqual(data['acceleration_z'], 1036) + self.assertEqual(data['tx_power'], 4) + self.assertEqual(data['battery'], 2977) + self.assertEqual(data['movement_counter'], 66) + self.assertEqual(data['measurement_sequence_number'], 205) + self.assertEqual(data['mac'], 'cbb8334c884f') + + def test_parse_df5_mac(self): + mac_payload = 'e62eb92e73e5' + mac = 'E6:2E:B9:2E:73:E5' + + parsed = parse_mac(5, mac_payload) + self.assertEqual(parsed, mac) diff --git a/pool/shard002/Python/0025961_0016_auto_20170601_1412.py b/pool/shard002/Python/0025961_0016_auto_20170601_1412.py new file mode 100644 index 0000000000000000000000000000000000000000..dc381c669f837b2ed1f29b241147ae3710830bca --- /dev/null +++ b/pool/shard002/Python/0025961_0016_auto_20170601_1412.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.6 on 2017-06-01 11:12 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('website', '0015_auto_20170601_1411'), + ] + + operations = [ + migrations.AddField( + model_name='github_user', + name='number_all_repos', + field=models.IntegerField(default=0), + preserve_default=False, + ), + migrations.AddField( + model_name='github_user', + name='number_repos1', + field=models.IntegerField(default=0), + preserve_default=False, + ), + migrations.AddField( + model_name='github_user', + name='number_repos2', + field=models.IntegerField(default=0), + preserve_default=False, + ), + migrations.AddField( + model_name='github_user', + name='number_repos3', + field=models.IntegerField(default=0), + preserve_default=False, + ), + migrations.AddField( + model_name='github_user', + name='technology1', + field=models.CharField(default='', max_length=50), + preserve_default=False, + ), + migrations.AddField( + model_name='github_user', + name='technology2', + field=models.CharField(default='', max_length=50), + preserve_default=False, + ), + migrations.AddField( + model_name='github_user', + name='technology3', + field=models.CharField(default='', max_length=50), + preserve_default=False, + ), + ] diff --git a/pool/shard002/Python/0025966_depmgr.py b/pool/shard002/Python/0025966_depmgr.py new file mode 100644 index 0000000000000000000000000000000000000000..dbae899d6bbc519eb44d34c6c2b82203faf02ff5 --- /dev/null +++ b/pool/shard002/Python/0025966_depmgr.py @@ -0,0 +1,278 @@ +# This file is part of Checkbox. +# +# Copyright 2012 Canonical Ltd. +# Written by: +# Zygmunt Krynicki +# +# Checkbox 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. +# +# Checkbox 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 Checkbox. If not, see . + +""" +plainbox.impl.depmgr +==================== + +Internal implementation of plainbox + + * THIS MODULE DOES NOT HAVE STABLE PUBLIC API * +""" + +from abc import ABCMeta +from abc import abstractproperty +from itertools import chain +from itertools import repeat +from logging import getLogger + + +logger = getLogger("plainbox.depmgr") + + +class DependencyError(Exception, metaclass=ABCMeta): + """ + Exception raised when a dependency error is detected + """ + + @abstractproperty + def affected_job(self): + """ + JobDefinition instance that is affected by the dependency error. + """ + + +class DependencyCycleError(DependencyError): + """ + Exception raised when a cyclic dependency is detected + """ + + def __init__(self, job_list): + """ + Initialize with a list of jobs that form a dependency loop. + + The dependencies satisfy the given expression: + + job_list[n - 1] depends-on job_list[n] + + The error exists because job_list[0] is job_list[-1]. + Each item is a JobDefinition instance. + """ + assert len(job_list) > 1 + assert job_list[0] is job_list[-1] + self.job_list = job_list + + @property + def affected_job(self): + return self.job_list[0] + + def __str__(self): + return "dependency cycle detected: {}".format( + " -> ".join([job.name for job in self.job_list])) + + def __repr__(self): + return "<{} job_list:{!r}>".format( + self.__class__.__name__, self.job_list) + + +class DependencyMissingError(DependencyError): + """ + Exception raised when a job has unsatisfied dependency + """ + + DEP_TYPE_RESOURCE = "resource" + DEP_TYPE_DIRECT = "direct" + + def __init__(self, job, missing_job_name, dep_type): + self.job = job + self.missing_job_name = missing_job_name + self.dep_type = dep_type + + @property + def affected_job(self): + return self.job + + def __str__(self): + return "missing dependency: {!r} ({})".format( + self.missing_job_name, self.dep_type) + + def __repr__(self): + return "<{} job:{!r} missing_job_name:{!r} dep_type:{!r}>".format( + self.__class__.__name__, + self.job, self.missing_job_name, self.dep_type) + + +class DependencyDuplicateError(DependencyError): + """ + Exception raised when two jobs have identical name + """ + + def __init__(self, job, duplicate_job): + assert job.name == duplicate_job.name + self.job = job + self.duplicate_job = duplicate_job + + @property + def affected_job(self): + return self.job + + def __str__(self): + return "duplicate job name: {!r}".format(self.affected_job.name) + + def __repr__(self): + return "<{} job:{!r} duplicate_job:{!r}>".format( + self.__class__.__name__, self.job, self.duplicate_job) + + +class DependencySolver: + """ + Dependency solver for Jobs + + Uses a simple depth-first search to discover the sequence of jobs that can + run. Use the resolve_dependencies() class method to get the solution. + """ + + # Node colors: + # + # white nodes have not been visited yet + # gray nodes are currently being visited and are incomplete + # black nodes have been visited and are complete + COLOR_WHITE, COLOR_GRAY, COLOR_BLACK = range(3) + + @classmethod + def resolve_dependencies(cls, job_list, visit_list=None): + """ + Solve the dependency graph expressed as a list of job definitions. The + visit_list, if specified, allows to consider only a part of the graph + while still having access and knowledge of all jobs. + + Returns the solution (a list of jobs to execute in order) + + raises DependencyCycleError if a cyclic dependency is present. + + raises DependencyMissingErorr if a required job does not exist. + """ + return cls(job_list)._solve(visit_list) + + def __init__(self, job_list): + """ + Instantiate a new dependency solver with the specified list of jobs + """ + # Remember the jobs that were passed + self._job_list = job_list + # Build a map of jobs (by name) + self._job_map = self._get_job_map(job_list) + # Job colors, maps from job.name to COLOR_xxx + self._job_color_map = {job.name: self.COLOR_WHITE for job in job_list} + # The computed solution, made out of job instances. This is not + # necessarily the only solution but the algorithm computes the same + # value each time, given the same input. + self._solution = [] + + def _solve(self, visit_list=None): + """ + Internal method of DependencySolver. + + Solves the dependency graph and returns the solution. + + Calls _visit() on each of the initial nodes/jobs + """ + # Visit the visit list + logger.debug("Starting solve") + if visit_list is None: + visit_list = self._job_list + for job in visit_list: + self._visit(job) + logger.debug("Done solving") + # Return the solution + return self._solution + + def _visit(self, job, trail=None): + """ + Internal method of DependencySolver + + Called each time a node is visited. Nodes already seen in _visited are + skipped. Attempts to enumerate all dependencies (both direct and + resource) and resolve them. Missing jobs cause DependencyMissingError + to be raised. Calls _visit recursively on all dependencies. + """ + color = self._job_color_map[job.name] + logger.debug("Visiting job %s (color %s)", job, color) + if color == self.COLOR_WHITE: + # This node has not been visited yet. Let's mark it as GRAY (being + # visited) and iterate through the list of dependencies + self._job_color_map[job.name] = self.COLOR_GRAY + # If the trail was not specified start a trail for this node + if trail is None: + trail = [job] + # Visit each dependency + for dep_type, job_name in self._get_dependency_set(job): + logger.debug("Found dependency %s: %s", dep_type, job_name) + # Dependency is just a name, we need to resolve it + # to a job instance. This can fail (missing dependencies) + # so let's guard against that. + try: + next_job = self._job_map[job_name] + except KeyError: + raise DependencyMissingError(job, job_name, dep_type) + else: + # For each dependency that we visit let's reuse the trail + # to give proper error messages if a dependency loop exists + logger.debug("Visiting dependency: %r", next_job) + # Update the trail as we visit that node + trail.append(next_job) + self._visit(next_job, trail) + trail.pop() + # We've visited (recursively) all dependencies of this node, + # let's color it black and append it to the solution list. + logger.debug("Appending %r to solution", job) + self._job_color_map[job.name] = self.COLOR_BLACK + self._solution.append(job) + elif color == self.COLOR_GRAY: + # This node is not fully traced yet but has been visited already + # so we've found a dependency loop. We need to cut the initial + # part of the trail so that we only report the part that actually + # forms a loop + raise DependencyCycleError(trail[trail.index(job):]) + else: + assert color == self.COLOR_BLACK + # This node has been visited and is fully traced. + # We can just skip it and go back + + @staticmethod + def _get_job_map(job_list): + """ + Internal method of DependencySolver. + + Computes a map of job.name => job + Raises DependencyDuplicateError if a collision is found + """ + job_map = {} + for job in job_list: + if job.name in job_map: + raise DependencyDuplicateError(job_map[job.name], job) + else: + job_map[job.name] = job + return job_map + + @staticmethod + def _get_dependency_set(job): + """ + Internal method of DependencySolver + + Returns a set of pairs (dep_type, job_name) that describe all + dependencies of the specified job. The first element in the pair, + dep_type, is either DEP_TYPE_DIRECT or DEP_TYPE_RESOURCE. The second + element is the name of the job. + """ + direct = DependencyMissingError.DEP_TYPE_DIRECT + resource = DependencyMissingError.DEP_TYPE_RESOURCE + return set(chain( + zip(repeat(direct), job.get_direct_dependencies()), + zip(repeat(resource), job.get_resource_dependencies()))) diff --git a/pool/shard002/Python/0025969_TimelineEvent.py b/pool/shard002/Python/0025969_TimelineEvent.py new file mode 100644 index 0000000000000000000000000000000000000000..2607da9835b5ed04ffcb1f71f36e26e8ce03fba4 --- /dev/null +++ b/pool/shard002/Python/0025969_TimelineEvent.py @@ -0,0 +1,167 @@ +############################ Copyrights and license ############################ +# # +# Copyright 2019 Nick Campbell # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub 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. # +# # +# PyGithub 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 PyGithub. If not, see . # +# # +################################################################################ + +import github.GithubObject +import github.NamedUser +import github.TimelineEventSource + + +class TimelineEvent(github.GithubObject.NonCompletableGithubObject): + """ + This class represents IssueTimelineEvents. The reference can be found here https://developer.github.com/v3/issues/timeline/ + """ + + def __repr__(self): + return self.get__repr__({"id": self._id.value}) + + @property + def actor(self): + """ + :type: :class:`github.NamedUser.NamedUser` + """ + return self._actor.value + + @property + def commit_id(self): + """ + :type: string + """ + return self._commit_id.value + + @property + def created_at(self): + """ + :type: datetime.datetime + """ + return self._created_at.value + + @property + def event(self): + """ + :type: string + """ + return self._event.value + + @property + def id(self): + """ + :type: integer + """ + return self._id.value + + @property + def node_id(self): + """ + :type: string + """ + return self._node_id.value + + @property + def commit_url(self): + """ + :type: string + """ + return self._commit_url.value + + @property + def source(self): + """ + :type: :class:`github.TimelineEventSource.TimelineEventSource` + """ + # only available on `cross-referenced` events. + if ( + self.event == "cross-referenced" + and self._source is not github.GithubObject.NotSet + ): + return self._source.value + return None + + @property + def body(self): + """ + :type string + """ + if self.event == "commented" and self._body is not github.GithubObject.NotSet: + return self._body.value + return None + + @property + def author_association(self): + """ + :type string + """ + if ( + self.event == "commented" + and self._author_association is not github.GithubObject.NotSet + ): + return self._author_association.value + return None + + @property + def url(self): + """ + :type: string + """ + return self._url.value + + def _initAttributes(self): + self._actor = github.GithubObject.NotSet + self._commit_id = github.GithubObject.NotSet + self._created_at = github.GithubObject.NotSet + self._event = github.GithubObject.NotSet + self._id = github.GithubObject.NotSet + self._node_id = github.GithubObject.NotSet + self._commit_url = github.GithubObject.NotSet + self._source = github.GithubObject.NotSet + self._body = github.GithubObject.NotSet + self._author_association = github.GithubObject.NotSet + self._url = github.GithubObject.NotSet + + def _useAttributes(self, attributes): + if "actor" in attributes: # pragma no branch + self._actor = self._makeClassAttribute( + github.NamedUser.NamedUser, attributes["actor"] + ) + if "commit_id" in attributes: # pragma no branch + self._commit_id = self._makeStringAttribute(attributes["commit_id"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "event" in attributes: # pragma no branch + self._event = self._makeStringAttribute(attributes["event"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "commit_url" in attributes: # pragma no branch + self._commit_url = self._makeStringAttribute(attributes["commit_url"]) + if "source" in attributes: # pragma no branch + self._source = self._makeClassAttribute( + github.TimelineEventSource.TimelineEventSource, attributes["source"] + ) + if "body" in attributes: # pragma no branch + self._body = self._makeStringAttribute(attributes["body"]) + if "author_association" in attributes: # pragma no branch + self._author_association = self._makeStringAttribute( + attributes["author_association"] + ) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/pool/shard002/Python/0025971_player.py b/pool/shard002/Python/0025971_player.py new file mode 100644 index 0000000000000000000000000000000000000000..2d22b022cc737c7078ac3d669c158824d8454147 --- /dev/null +++ b/pool/shard002/Python/0025971_player.py @@ -0,0 +1,85 @@ +import pygame as pg +from src.game import Sprite, GameObject +from src.physics import Body, Vector + +class Player(GameObject): + def __init__(self, pos): + self.sprites = { + "down": Sprite("assets/static_face_1.png", size=(80,80)), + "up": Sprite("assets/static_back_1.png", size=(80,80)), + "left": Sprite("assets/static_left.png", size=(80,80)), + "right": Sprite("assets/static_right.png", size=(80,80)), + # "idle_left": Sprite("assets/idle_left.png"), + # "idle_up": Sprite("assets/idle_up.png"), + # "idle_right": Sprite("assets/idle_right.png"), + # "move_down": Sprite("assets/move_down.png"), + # "move_left": Sprite("assets/move_left.png"), + # "move_up": Sprite("assets/move_up.png"), + # "move_right": Sprite("assets/move_right.png"), + # "attack_down": Sprite("assets/attack_down.png"), + # "attack_left": Sprite("assets/attack_left.png"), + # "attack_up": Sprite("assets/attack_up.png"), + # "attack_right": Sprite("assets/attack_right.png"), + } + + self.draw_offset = Vector(-40,-40) + + self.current_sprite = self.sprites["down"] + self.body = Body(10, p=pos) + self.on_ground = True + self.contor = 0 + self.fire_delay = 30 + + def update(self, keys): + if self.body.p.y > 500.0: + self.body.p.y = 500.0 + self.body.v.y = 0.0 + self.on_ground = True + self.contor += 1 + + if keys[pg.K_a]: + self.current_sprite = self.sprites["left"] + self.body.p += Vector(-4,0) + if keys[pg.K_d]: + self.current_sprite = self.sprites["right"] + self.body.p += Vector(4,0) + if keys[pg.K_w]: + self.current_sprite = self.sprites["up"] + self.body.p += Vector(0,-4) + if keys[pg.K_s]: + self.current_sprite = self.sprites["down"] + self.body.p += Vector(0,4) + if keys[pg.K_LEFT]: + if(self.contor > self.fire_delay): + from src import main + from src.objects import Projectile + main.GAME.objects.append(Projectile(self.body.p, Vector(-1,0))) + self.contor = 0 + self.current_sprite = self.sprites["left"] + elif keys[pg.K_RIGHT]: + if(self.contor > self.fire_delay): + from src import main + from src.objects import Projectile + main.GAME.objects.append(Projectile(self.body.p, Vector(1,0))) + self.contor = 0 + self.current_sprite = self.sprites["right"] + elif keys[pg.K_UP]: + if(self.contor > self.fire_delay): + from src import main + from src.objects import Projectile + main.GAME.objects.append(Projectile(self.body.p, Vector(0,-1))) + self.contor = 0 + self.current_sprite = self.sprites["up"] + elif keys[pg.K_DOWN]: + if(self.contor > self.fire_delay): + from src import main + from src.objects import Projectile + main.GAME.objects.append(Projectile(self.body.p, Vector(0,1))) + self.contor = 0 + self.current_sprite = self.sprites["down"] + + def draw(self, display): + self.current_sprite.draw(display, self.body.p + self.draw_offset) + + def remove(self): + pass \ No newline at end of file diff --git a/pool/shard002/Python/0025972_rest_client.py b/pool/shard002/Python/0025972_rest_client.py new file mode 100644 index 0000000000000000000000000000000000000000..d3c8a9488321e03e2a882a880065da44d4d45fe7 --- /dev/null +++ b/pool/shard002/Python/0025972_rest_client.py @@ -0,0 +1,24 @@ +import requests +import getpass +import httplib + +class APIError(Exception): + pass +def main(): + proxies = { + 'http': 'http://137.121.61.4:3128', + 'https': 'http://137.121.1.26:3128', + } + + #user = raw_input("User ?") + #password = getpass.getpass() + resp = requests.get('https://onomap-gs.noise-planet.org/geoserver/rest', + proxies=proxies) + #data = open("wps/UploadZip.groovy").read(), auth=(user, password), + #proxies=proxies) + if resp.status_code != 200: + # This means something went wrong. + raise Exception(httplib.responses[resp.status_code]) + for todo_item in resp.json(): + print('{} {}'.format(todo_item['id'], todo_item['summary'])) +main() \ No newline at end of file diff --git a/pool/shard002/Python/0025981_test_create_snapshot.py b/pool/shard002/Python/0025981_test_create_snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..7c40fa15fd86916cd537f4abf3c30cacc5066c71 --- /dev/null +++ b/pool/shard002/Python/0025981_test_create_snapshot.py @@ -0,0 +1,116 @@ +# Copyright (c) 2013 - 2015 EMC Corporation. +# 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 json + +from six.moves import urllib + +from cinder import context +from cinder import db +from cinder import exception +from cinder.tests.unit import fake_snapshot +from cinder.tests.unit import fake_volume +from cinder.tests.unit.volume.drivers.emc import scaleio +from cinder.tests.unit.volume.drivers.emc.scaleio import mocks + + +class TestCreateSnapShot(scaleio.TestScaleIODriver): + """Test cases for ``ScaleIODriver.create_snapshot()``""" + def return_fake_volume(self, ctx, id): + return self.fake_volume + + def setUp(self): + """Setup a test case environment. + + Creates fake volume and snapshot objects and sets up the required + API responses. + """ + super(TestCreateSnapShot, self).setUp() + ctx = context.RequestContext('fake', 'fake', auth_token=True) + + self.fake_volume = fake_volume.fake_volume_obj( + ctx, **{'provider_id': 'fake_pid'}) + + self.snapshot = fake_snapshot.fake_snapshot_obj( + ctx, **{'volume': self.fake_volume}) + + self.mock_object(db.sqlalchemy.api, 'volume_get', + self.return_fake_volume) + + snap_vol_id = self.snapshot.volume_id + self.volume_name_2x_enc = urllib.parse.quote( + urllib.parse.quote(self.driver._id_to_base64(snap_vol_id)) + ) + self.snapshot_name_2x_enc = urllib.parse.quote( + urllib.parse.quote(self.driver._id_to_base64(self.snapshot.id)) + ) + + self.snapshot_reply = json.dumps( + { + 'volumeIdList': ['cloned'], + 'snapshotGroupId': 'cloned_snapshot' + } + ) + + self.HTTPS_MOCK_RESPONSES = { + self.RESPONSE_MODE.Valid: { + 'types/Volume/instances/getByName::' + + self.volume_name_2x_enc: '"{}"'.format( + self.snapshot.volume_id + ), + 'instances/System/action/snapshotVolumes': + self.snapshot_reply, + 'types/Volume/instances/getByName::' + + self.snapshot_name_2x_enc: self.snapshot.id, + }, + self.RESPONSE_MODE.BadStatus: { + 'types/Volume/instances/getByName::' + + self.volume_name_2x_enc: self.BAD_STATUS_RESPONSE, + 'types/Volume/instances/getByName::' + + self.snapshot_name_2x_enc: self.BAD_STATUS_RESPONSE, + 'instances/System/action/snapshotVolumes': + self.BAD_STATUS_RESPONSE, + }, + self.RESPONSE_MODE.Invalid: { + 'types/Volume/instances/getByName::' + + self.volume_name_2x_enc: None, + 'instances/System/action/snapshotVolumes': + mocks.MockHTTPSResponse( + { + 'errorCode': 400, + 'message': 'Invalid Volume Snapshot Test' + }, 400 + ), + }, + } + + def test_bad_login(self): + self.set_https_response_mode(self.RESPONSE_MODE.BadStatus) + self.assertRaises( + exception.VolumeBackendAPIException, + self.driver.create_snapshot, + self.snapshot + ) + + def test_invalid_volume(self): + self.set_https_response_mode(self.RESPONSE_MODE.Invalid) + self.assertRaises( + exception.VolumeBackendAPIException, + self.driver.create_snapshot, + self.snapshot + ) + + def test_create_snapshot(self): + self.set_https_response_mode(self.RESPONSE_MODE.Valid) + self.driver.create_snapshot(self.snapshot) diff --git a/pool/shard002/Python/0025983_cnos_command.py b/pool/shard002/Python/0025983_cnos_command.py new file mode 100644 index 0000000000000000000000000000000000000000..9cb65fa44c5e07330e6aa5e7fe20a54cba452afc --- /dev/null +++ b/pool/shard002/Python/0025983_cnos_command.py @@ -0,0 +1,160 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2017 Lenovo, Inc. +# +# This file is part of Ansible +# +# Ansible 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. +# +# Ansible 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 Ansible. If not, see . +# +# Module to send CLI commands to Lenovo Switches +# Lenovo Networking +# +# + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community'} + + +DOCUMENTATION = ''' +--- +module: cnos_command +author: "Dave Kasberg (@dkasberg)" +short_description: Execute a single command on devices running Lenovo CNOS +description: + - This module allows you to modify the switch running configuration. It provides a way to + execute a single CNOS command on a switch by evaluating the current running configuration + and executing the command only if the specific setting has not been already configured. + The CNOS command is passed as an argument of the method. + This module uses SSH to manage network device configuration. + The results of the operation will be placed in a directory named 'results' + that must be created by the user in their local directory to where the playbook is run. + For more information about this module from Lenovo and customizing it usage for your + use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_command.html) +version_added: "2.3" +extends_documentation_fragment: cnos +options: + clicommand: + description: + - This specifies the CLI command as an attribute to this method. The command is + passed using double quotes. The variables can be placed directly on to the CLI + commands or can be invoked from the vars directory. + required: true + default: Null +''' +EXAMPLES = ''' +Tasks : The following are examples of using the module cnos_command. These are written in the main.yml file of the tasks directory. +--- +- name: Test Command + cnos_command: + host: "{{ inventory_hostname }}" + username: "{{ hostvars[inventory_hostname]['username'] }}" + password: "{{ hostvars[inventory_hostname]['password'] }}" + enablePassword: "{{ hostvars[inventory_hostname]['enablePassword'] }}" + deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}" + outputfile: "./results/test_command_{{ inventory_hostname }}_output.txt" + clicommand: "display users" + +''' +RETURN = ''' +msg: + description: Success or failure message + returned: always + type: string + sample: "Command Applied" +''' + + +import sys +import paramiko +import time +import argparse +import socket +import array +import json +import time +import re +try: + from ansible.module_utils import cnos + HAS_LIB = True +except: + HAS_LIB = False +from ansible.module_utils.basic import AnsibleModule +from collections import defaultdict + + +def main(): + module = AnsibleModule( + argument_spec=dict( + clicommand=dict(required=True), + outputfile=dict(required=True), + host=dict(required=True), + deviceType=dict(required=True), + username=dict(required=True), + password=dict(required=True, no_log=True), + enablePassword=dict(required=False, no_log=True),), + supports_check_mode=False) + + username = module.params['username'] + password = module.params['password'] + enablePassword = module.params['enablePassword'] + cliCommand = module.params['clicommand'] + deviceType = module.params['deviceType'] + outputfile = module.params['outputfile'] + hostIP = module.params['host'] + output = "" + + # Create instance of SSHClient object + remote_conn_pre = paramiko.SSHClient() + + # Automatically add untrusted hosts (make sure okay for security policy in your environment) + remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + + # initiate SSH connection with the switch + remote_conn_pre.connect(hostIP, username=username, password=password) + time.sleep(2) + + # Use invoke_shell to establish an 'interactive session' + remote_conn = remote_conn_pre.invoke_shell() + time.sleep(2) + + # Enable and enter configure terminal then send command + output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn) + + output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) + + # Make terminal length = 0 + output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn) + + # Go to config mode + output = output + cnos.waitForDeviceResponse("configure d\n", "(config)#", 2, remote_conn) + + # Send the CLi command + output = output + cnos.waitForDeviceResponse(cliCommand + "\n", "(config)#", 2, remote_conn) + + # Save it into the file + file = open(outputfile, "a") + file.write(output) + file.close() + + # Logic to check when changes occur or not + errorMsg = cnos.checkOutputForError(output) + if(errorMsg is None): + module.exit_json(changed=True, msg="CLI command executed and results saved in file ") + else: + module.fail_json(msg=errorMsg) + +if __name__ == '__main__': + main() diff --git a/pool/shard002/Python/0025986_adapters.py b/pool/shard002/Python/0025986_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..818997cc94a5f7aac45266293510d267ec3bebad --- /dev/null +++ b/pool/shard002/Python/0025986_adapters.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (c) 2013-2016, OVH SAS. +# 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 OVH SAS 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 OVH SAS 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 OVH SAS AND 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. + +""" +Djehouty intends to be a set of logging formatters and handlers to easily +send log entries. +""" + +import logging + +class LTSVLoggerAdapter(logging.LoggerAdapter): + """LTSVLoggerAdapter""" + def __init__(self, logger): + logging.LoggerAdapter.__init__(self, logger, {}) + + def process(self, msg, kwargs): + """process""" + new_kwargs = {} + for attr in ('exc_info', 'extra'): + if attr in kwargs: + new_kwargs[attr] = kwargs.pop(attr) + + new_msg = '{0}\t{1}'.format( + msg, "\t".join(['%s:%s' %i for i in kwargs.items()]) + ) + + return new_msg, new_kwargs diff --git a/pool/shard002/Python/0025987_views.py b/pool/shard002/Python/0025987_views.py new file mode 100644 index 0000000000000000000000000000000000000000..7445b013fd6a71c076600ecc4c436c42314348d4 --- /dev/null +++ b/pool/shard002/Python/0025987_views.py @@ -0,0 +1,36 @@ +from django.http import HttpResponseRedirect +from django.shortcuts import render_to_response, HttpResponse +from django.template import RequestContext +from models import Car, Street +from scripts import simulation + + +def home(request): + if request.method == 'POST': + return HttpResponseRedirect('/') + else: + pass + if request.GET.get('start-button'): + print 'aaaaaaaaaa' + simulation.start() + elif request.GET.get('stop-button'): + simulation.stop() + return render_to_response('base.html', {'cars': Car.objects.all(), 'streets': Street.objects.all()}, + context_instance=RequestContext(request)) + + +def update(request): + tmp = Car.objects.all() + cars = '' + for car in tmp: + cars += str(car.Longitude) + ',' + cars += str(car.Latitude) + '|' + return HttpResponse(cars[:-1]) + + +def street(request): + tmp = Street.objects.all() + streets = '' + for stret in tmp: + streets += str(stret) + ',' + str(stret.IsOpen) + '|' + return HttpResponse(streets[:-1]) diff --git a/pool/shard002/Python/0025988_random_color_squares.py b/pool/shard002/Python/0025988_random_color_squares.py new file mode 100644 index 0000000000000000000000000000000000000000..ff4b6068ae9f6fa69ebecebd5bf1c1b5ed9ed557 --- /dev/null +++ b/pool/shard002/Python/0025988_random_color_squares.py @@ -0,0 +1,22 @@ +import turtle +import random +t = turtle.Pen() + +def square(x, y, size): + t.penup() + t.setpos(x,y) + t.pendown() + t.begin_fill() + for counter in range(0,4): + t.forward(size) + t.right(90) + t.end_fill() + +square(25,25,100) +square(0,50,50) +for i in range(0,10000): + t.color(random.random(),random.random(),random.random()) + x = random.randint(-200,200) + y = random.randint(-200,200) + size = random.randint(10,500) + square(x,y,size) diff --git a/pool/shard002/Python/0025992_cat_tests.py b/pool/shard002/Python/0025992_cat_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..d3bee9835c09b43647d626e627ec7ac346a882c4 --- /dev/null +++ b/pool/shard002/Python/0025992_cat_tests.py @@ -0,0 +1,30 @@ +""" +This script concatenates .check files and prints the output to stdout. The .check file locations +are read from the arguments. + +The reason it's required is that all #include directives need to be at the beginning of the file. +""" + +import sys + +def main(): + includes = set() + lines = [] + + for file_path in sys.argv[1:]: + with open(file_path) as check_file: + for line in check_file: + if line.strip().startswith("#include"): + include = line.strip().replace("#include", "").strip() + includes.add(include) + else: + lines.append(line.rstrip()) + + for include in includes: + print("#include {0}".format(include)) + for line in lines: + print(line) + +if __name__ == "__main__": + main() + diff --git a/pool/shard002/Python/0026001_Processes.py b/pool/shard002/Python/0026001_Processes.py new file mode 100644 index 0000000000000000000000000000000000000000..e30ac75ecbfbef8496010d09a5be15624868baea --- /dev/null +++ b/pool/shard002/Python/0026001_Processes.py @@ -0,0 +1,174 @@ +############################################################################## +# +# Copyright (C) Zenoss, Inc. 2013, all rights reserved. +# +# This content is made available according to terms specified in +# License.zenoss under the directory where your Zenoss product is installed. +# +############################################################################## + +''' +Windows Running Processes + +Models running processes by querying Win32_Process and +Win32_PerfFormattedData_PerfProc_Process via WMI. +''' + +import re + +from itertools import ifilter, imap + +from Products.ZenModel import OSProcess +from Products.ZenModel.Device import Device +from Products.ZenUtils.Utils import prepId + +from ZenPacks.zenoss.Microsoft.Windows.modeler.WinRMPlugin import WinRMPlugin +from ZenPacks.zenoss.Microsoft.Windows.utils import ( + get_processNameAndArgs, + get_processText, + save + ) + +try: + # Introduced in Zenoss 4.2 2013-10-15 RPS. + from Products.ZenModel.OSProcessMatcher import buildObjectMapData +except ImportError: + def buildObjectMapData(processClassMatchData, lines): + raise Exception("buildObjectMapData does not exist on this Zenoss") + return [] + + +if hasattr(Device, 'osProcessClassMatchData'): + # Introduced in Zenoss 4.2 2013-10-15 RPS. + PROXY_MATCH_PROPERTY = 'osProcessClassMatchData' +else: + # Older property. + PROXY_MATCH_PROPERTY = 'getOSProcessMatchers' + + +class Processes(WinRMPlugin): + compname = 'os' + relname = 'processes' + modname = 'ZenPacks.zenoss.Microsoft.Windows.OSProcess' + + deviceProperties = WinRMPlugin.deviceProperties + ( + PROXY_MATCH_PROPERTY, + ) + + queries = { + 'Win32_Process': "SELECT Name, ExecutablePath, CommandLine FROM Win32_Process", + 'Win32_PerfFormattedData_PerfProc_Process': "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process", + } + + @save + def process(self, device, results, log): + log.info( + "Modeler %s processing data for device %s", + self.name(), device.id) + + rm = self.relMap() + + # Get process ObjectMap instances. + if hasattr(device, 'osProcessClassMatchData'): + oms = self.new_process(device, results, log) + else: + oms = self.old_process(device, results, log) + + # Determine if WorkingSetPrivate is supported. + try: + perfproc = results.get('Win32_PerfFormattedData_PerfProc_Process', (None,))[0] + supports_WorkingSetPrivate = hasattr(perfproc, 'WorkingSetPrivate') + except IndexError: + supports_WorkingSetPrivate = False + + for om in oms: + om.supports_WorkingSetPrivate = supports_WorkingSetPrivate + rm.append(om) + + return rm + + def new_process(self, device, results, log): + ''' + Model processes according to new style. + + Handles style introduced by Zenoss 4.2 2013-10-15 RPS. + ''' + processes = ifilter(bool, imap(get_processText, results.values()[0])) + oms = imap( + self.objectMap, + buildObjectMapData(device.osProcessClassMatchData, processes)) + + for om in oms: + yield om + + def old_process(self, device, results, log): + ''' + Model processes according to old style. + + Handles Zenoss 4.1 and Zenoss 4.2 prior to the 2013-10-15 RPS. + ''' + self.compile_regexes(device, log) + + seen = set() + + for item in results.values()[0]: + procName, parameters = get_processNameAndArgs(item) + processText = get_processText(item) + + for matcher in device.getOSProcessMatchers: + if hasattr(OSProcess.OSProcess, 'matchRegex'): + match = OSProcess.OSProcess.matchRegex( + matcher['regex'], + matcher['excludeRegex'], + processText) + else: + match = matcher['regex'].search(processText) + + if not match: + continue + + if hasattr(OSProcess.OSProcess, 'generateId'): + process_id = OSProcess.OSProcess.generateId( + matcher['regex'], + matcher['getPrimaryUrlPath'], + processText) + else: + process_id = prepId(OSProcess.getProcessIdentifier( + procName, + None if matcher['ignoreParameters'] else parameters)) + + if process_id in seen: + continue + + seen.add(process_id) + + data = { + 'id': process_id, + 'procName': procName, + 'parameters': parameters, + 'setOSProcessClass': matcher['getPrimaryDmdId'], + } + + if hasattr(OSProcess.OSProcess, 'processText'): + data['processText'] = processText + + yield self.objectMap(data) + + def compile_regexes(self, device, log): + for matcher in device.getOSProcessMatchers: + try: + matcher['regex'] = re.compile(matcher['regex']) + except Exception: + log.warning( + "Invalid process regex '%s' -- ignoring", + matcher['regex']) + + if 'excludeRegex' in matcher: + try: + matcher['excludeRegex'] = re.compile( + matcher['excludeRegex']) + + except Exception: + log.warning( + "Invalid process exclude regex '%s' -- ignoring", + matcher['excludeRegex']) diff --git a/pool/shard002/Python/0026010_urls.py b/pool/shard002/Python/0026010_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..b60f52dae134e430e18e323a1d6539758d359c13 --- /dev/null +++ b/pool/shard002/Python/0026010_urls.py @@ -0,0 +1,34 @@ +from django.conf.urls import patterns, include, url +from django.contrib import admin + +from NewRaPo.settings import base as settings +from NewRaPo.sitemaps import BlogSitemap, KnowSitemap + + +sitemaps = { + 'blog': BlogSitemap, + # 'static': StaticViewSitemap, + 'knowledge': KnowSitemap +} + + +urlpatterns = patterns('', + # Examples: + # url(r'^$', 'NewRaPo.views.home', name='home'), + # url(r'^blog/', include('blog.urls')), + + url(r'^admin/', include(admin.site.urls)), + url(r'^', include('app.myblog.urls')), + url(r'^blog_admin/', include('app.blog_admin.urls')), + url(r'^lab/', include('app.blog_lab.urls')), + # url(r'404', 'app.myblog.views.not_found'), + # url(r'500', 'app.myblog.views.server_error'), + (r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}), + url(r'^css/(?P.*)$', 'django.views.static.serve', {'document_root': settings.CSS_DIR}), + url(r'^js/(?P.*)$', 'django.views.static.serve', {'document_root': settings.JS_DIR}), + url(r'^img/(?P.*)$', 'django.views.static.serve', {'document_root': settings.IMG_DIR}), + url(r'^fonts/(?P.*)$', 'django.views.static.serve', {'document_root': settings.FONTS_DIR}), + url(r'^verify/(?P.*)$', 'django.views.static.serve', {'document_root': settings.VERIFY_DIR}), + url(r'^file/(?P.*)$', 'django.views.static.serve', {'document_root': settings.FILE_DIR}), + url(r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DIR}), +) diff --git a/pool/shard002/Python/0026014_verify_filelist.py b/pool/shard002/Python/0026014_verify_filelist.py new file mode 100644 index 0000000000000000000000000000000000000000..b97e4205ec685329bca0ae63a997b738ffc8cc8c --- /dev/null +++ b/pool/shard002/Python/0026014_verify_filelist.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python +# 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 optparse +import os +import re +import sys + +from build_paths import SDK_SRC_DIR + +# Add SDK make tools scripts to the python path. +sys.path.append(os.path.join(SDK_SRC_DIR, 'tools')) + +import getos + +VALID_PLATFORMS = ['linux', 'mac', 'win'] + +class ParseException(Exception): + def __init__(self, filename, line, message): + Exception.__init__(self) + self.filename = filename + self.line = line + self.message = message + + def __str__(self): + return '%s:%d: %s' % (self.filename, self.line, self.message) + + +class VerifyException(Exception): + pass + +class Rules(object): + def __init__(self, platform, filename, contents=None): + self.glob_prefixes = [] + self.exact_filenames = set() + self.filename = filename + self.platform = platform + self.exe_ext = '.exe' if platform == 'win' else '' + + if platform not in VALID_PLATFORMS: + raise ParseException(self.filename, 1, 'Unknown platform %s' % platform) + + if not contents: + with open(filename) as f: + contents = f.read() + + for line_no, rule in enumerate(contents.split('\n')): + rule = rule.strip() + if rule: + self.ParsePattern(line_no + 1, rule) + + def ParsePattern(self, line_no, pattern): + match = re.match(r'^\[([^\]]*)\](.*)$', pattern) + if match: + # platform-specific pattern + platforms = match.group(1).split(',') + unknown_platforms = set(platforms) - set(VALID_PLATFORMS) + if unknown_platforms: + msg = 'Unknown platform(s) %s.' % ( + ', '.join('"%s"' % platform for platform in unknown_platforms)) + raise ParseException(self.filename, line_no, msg) + if self.platform not in platforms: + return + + # If this platform is included, strip the [...] part. + pattern = match.group(2) + + pattern = pattern.replace('${PLATFORM}', self.platform) + pattern = pattern.replace('${EXE_EXT}', self.exe_ext) + + if '*' in pattern: + # glob pattern + # We only support * at the end. + if pattern.find('*') != len(pattern) - 1: + msg = '* is only allowed at the end of the line.' + raise ParseException(self.filename, line_no, msg) + + # Remove the * + pattern = pattern[:-1] + self.glob_prefixes.append(pattern) + else: + self.exact_filenames.add(pattern) + + def VerifyDirectoryList(self, directory_list): + exact_filenames_used = set() + glob_prefixes_used = set() + expected_globs = set() + expected_filenames = set() + unexpected_filenames = set() + + for filename in directory_list: + if os.path.sep != '/': + filename = filename.replace(os.path.sep, '/') + if filename in self.exact_filenames: + exact_filenames_used.add(filename) + continue + + # glob pattern + found_prefix = False + for prefix in self.glob_prefixes: + if filename.startswith(prefix): + glob_prefixes_used.add(prefix) + found_prefix = True + break + + if not found_prefix: + unexpected_filenames.add(filename) + + if len(exact_filenames_used) != len(self.exact_filenames): + # We looped through the directory list, so if the lengths are unequal, it + # must be that we expected something that isn't there. + expected_filenames = self.exact_filenames - exact_filenames_used + + if len(glob_prefixes_used) != self.glob_prefixes: + expected_globs = set(self.glob_prefixes) - glob_prefixes_used + + if expected_filenames or unexpected_filenames or expected_globs: + msg = '' + if unexpected_filenames: + msg += '>>> Unexpected filenames: <<<\n%s\n' % ( + '\n'.join(sorted(unexpected_filenames))) + if expected_filenames: + msg += '>>> Expected filenames: <<<\n%s\n' % ( + '\n'.join(sorted(expected_filenames))) + if expected_globs: + msg += '>>> Expected 1+ files in these directories: <<< \n%s\n' % ( + '\n'.join(sorted(expected_globs))) + raise VerifyException(msg) + + +def GetDirectoryList(directory_path): + result = [] + for root, _, files in os.walk(directory_path): + rel_root = os.path.relpath(root, directory_path) + if rel_root == '.': + rel_root = '' + for base_name in files: + result.append(os.path.join(rel_root, base_name)) + return result + + +def Verify(platform, rule_path, directory_path): + rules = Rules(platform, rule_path) + directory_list = GetDirectoryList(directory_path) + rules.VerifyDirectoryList(directory_list) + + +def main(args): + parser = optparse.OptionParser(usage='%prog ') + parser.add_option('-p', '--platform', + help='Test with this platform, instead of the system\'s platform') + options, args = parser.parse_args(args) + if len(args) != 2: + parser.error('Expected rule file and directory.') + + rule_path, directory_path = args + if options.platform: + if options.platform not in VALID_PLATFORMS: + parser.error('Unknown platform: %s' % options.platform) + platform = options.platform + else: + platform = getos.GetPlatform() + + try: + return Verify(platform, rule_path, directory_path) + except ParseException, e: + print >> sys.stderr, 'Error parsing rules:\n', e + return 1 + except VerifyException, e: + print >> sys.stderr, 'Error verifying file list:\n', e + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/pool/shard002/Python/0026015_RawSerialize.py b/pool/shard002/Python/0026015_RawSerialize.py new file mode 100644 index 0000000000000000000000000000000000000000..557cfbb65408c3f844fc952749ede6c06e0cc339 --- /dev/null +++ b/pool/shard002/Python/0026015_RawSerialize.py @@ -0,0 +1,41 @@ +import json +import logging + +logger = logging.getLogger(__name__) + +class RawSerialize(): + + def __init__(self): + pass + + def serialize(self, content_obj): + ''' + encode content_obj to string. + for example: + content_obj = {'a':'apple','b':'banana'} + encode to string, return the string. + ''' + msg = json.dumps(content_obj,ensure_ascii=False) + return msg + + def unserialize(self, content_str): + ''' + decode it to json object, then renturn object. + ''' + msg = content_str + try: + obj = json.loads(msg) + except Exception, e: + logger.info(e) + obj = {} + return obj + +if __name__ == '__main__': + s = RawSerialize() + a = {'a':'apple','b':'banana'} + print a + b = s.serialize(a) + print b + c = s.unserialize(b) + print c + diff --git a/pool/shard002/Python/0026016_update_cloudflare.py b/pool/shard002/Python/0026016_update_cloudflare.py new file mode 100644 index 0000000000000000000000000000000000000000..7da48135b1555b4576426d726f49909f5f7e5b6b --- /dev/null +++ b/pool/shard002/Python/0026016_update_cloudflare.py @@ -0,0 +1,96 @@ +from fcntl import ioctl +from socket import AF_INET, SOCK_DGRAM, inet_ntoa, socket +from struct import pack +from pathlib import Path +from pprint import pprint + +from requests import Session +from requests.adapters import DEFAULT_POOLSIZE +from yaml import load, BaseLoader + + +def api(endpoint): + return 'https://api.cloudflare.com/client/v4{}'.format(endpoint) + + +def main(): + interface_ips = {} + + with ( + Path(__file__).resolve().parent / 'config.yaml' + ).open('r') as r: + update_list = load(r, Loader=BaseLoader) + + for user in update_list: + session = Session() + session.headers.update( + { + 'Authorization': 'Bearer {}'.format(user['token']), + 'DNT': '1', + } + ) + for target in user['targets']: + internal = 'internal' not in target.keys() or bool(int(target['internal'])) + target_interface = target['interface'] if internal else target['interface'] + '_internal' + if (target_interface not in interface_ips.keys()): + s = socket(AF_INET, SOCK_DGRAM) + internal_ip = inet_ntoa( + ioctl( + s.fileno(), + 0x8915, # SIOCGIFADDR + pack('256s', bytes(target['interface'][:15], 'utf-8')), + )[20:24] + ) + if internal: + interface_ips[target_interface] = internal_ip + else: + bound_sess = Session() + bound_sess.get_adapter('https://').init_poolmanager( + connections=DEFAULT_POOLSIZE, + maxsize=DEFAULT_POOLSIZE, + source_address=(internal_ip, 0), + ) + interface_ips[target_interface] = bound_sess.get('https://api.ipify.org/').text + myip = interface_ips[target_interface] + endpoint = api( + '/zones/{zone_id}/dns_records/{id}'.format( + zone_id=target['zone_id'], + id=target['id'] + ) + ) + record = session.get(endpoint).json()['result'] + if record['type'] != 'A': + print( + 'zone_id {}, id {} ({} {}) is not an A record; ' + 'not doing anything.'.format( + record['zone_id'], + record['id'], + record['type'], + record['name'] + ) + ) + continue + result = session.put( + endpoint, + json={ + 'type': 'A', + 'name': record['name'], + 'content': myip + } + ).json() + if result['success']: + record = result['result'] + print( + 'Successfully updated {} to {}'.format( + record['name'], myip + ) + ) + else: + print( + 'An error occurred while updating {}: ' + 'Please see below for details.\n'.format(record['name']) + ) + pprint(result) + +if __name__ == '__main__': + main() diff --git a/pool/shard002/Python/0026020_misc.py b/pool/shard002/Python/0026020_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6faa1c52bd0d48f1f89372f229e0e1735f1d32 --- /dev/null +++ b/pool/shard002/Python/0026020_misc.py @@ -0,0 +1,75 @@ +import logging + +from patroni.exceptions import PostgresException + +logger = logging.getLogger(__name__) + + +def postgres_version_to_int(pg_version): + """Convert the server_version to integer + + >>> postgres_version_to_int('9.5.3') + 90503 + >>> postgres_version_to_int('9.3.13') + 90313 + >>> postgres_version_to_int('10.1') + 100001 + >>> postgres_version_to_int('10') # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + PostgresException: 'Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: 10' + >>> postgres_version_to_int('9.6') # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + PostgresException: 'Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: 9.6' + >>> postgres_version_to_int('a.b.c') # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + PostgresException: 'Invalid PostgreSQL version: a.b.c' + """ + + try: + components = list(map(int, pg_version.split('.'))) + except ValueError: + raise PostgresException('Invalid PostgreSQL version: {0}'.format(pg_version)) + + if len(components) < 2 or len(components) == 2 and components[0] < 10 or len(components) > 3: + raise PostgresException('Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: {0}'.format(pg_version)) + + if len(components) == 2: + # new style version numbers, i.e. 10.1 becomes 100001 + components.insert(1, 0) + + return int(''.join('{0:02d}'.format(c) for c in components)) + + +def postgres_major_version_to_int(pg_version): + """ + >>> postgres_major_version_to_int('10') + 100000 + >>> postgres_major_version_to_int('9.6') + 90600 + """ + return postgres_version_to_int(pg_version + '.0') + + +def parse_lsn(lsn): + t = lsn.split('/') + return int(t[0], 16) * 0x100000000 + int(t[1], 16) + + +def parse_history(data): + for line in data.split('\n'): + values = line.strip().split('\t') + if len(values) == 3: + try: + values[0] = int(values[0]) + values[1] = parse_lsn(values[1]) + yield values + except (IndexError, ValueError): + logger.exception('Exception when parsing timeline history line "%s"', values) + + +def format_lsn(lsn, full=False): + template = '{0:X}/{1:08X}' if full else '{0:X}/{1:X}' + return template.format(lsn >> 32, lsn & 0xFFFFFFFF) diff --git a/pool/shard002/Python/0026035_interface_zmq.py b/pool/shard002/Python/0026035_interface_zmq.py new file mode 100644 index 0000000000000000000000000000000000000000..def71c5f0f6de23c522dfae6c875bdf9e47a3d8a --- /dev/null +++ b/pool/shard002/Python/0026035_interface_zmq.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +# Copyright (c) 2015-2017 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +"""Test the ZMQ notification interface.""" +import struct + +from test_framework.test_framework import ( + BitcoinTestFramework, skip_if_no_bitcoind_zmq, skip_if_no_py3_zmq) +from test_framework.mininode import CTransaction +from test_framework.util import (assert_equal, + bytes_to_hex_str, + hash256, + ) +from io import BytesIO + +class ZMQSubscriber: + def __init__(self, socket, topic): + self.sequence = 0 + self.socket = socket + self.topic = topic + + import zmq + self.socket.setsockopt(zmq.SUBSCRIBE, self.topic) + + def receive(self): + topic, body, seq = self.socket.recv_multipart() + # Topic should match the subscriber topic. + assert_equal(topic, self.topic) + # Sequence should be incremental. + assert_equal(struct.unpack(' col_i else None) + + del data[array_column] + + data.to_csv(args.dst, index=False) diff --git a/pool/shard002/Python/0026048_id_.py b/pool/shard002/Python/0026048_id_.py new file mode 100644 index 0000000000000000000000000000000000000000..e7caed7e17705b105d679f6f4fd3bb5475ba73cb --- /dev/null +++ b/pool/shard002/Python/0026048_id_.py @@ -0,0 +1,109 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# vim: ts=4:sw=4:et: + +__doc__ = """ A class for an identifier parsed by the preprocessor. +It contains it's name, arguments and macro value. +""" + +import sys +import copy + +from typing import Optional + +from .macrocall import MacroCall +from src.api.debug import __DEBUG__ +from .output import CURRENT_FILE +import src.zxbpp.prepro as prepro + +DEBUG_LEVEL = 3 # Which -d level is required to show debug info + + +class ID: + """This class represents an identifier. It stores a string + (the ID name and value by default). + """ + + __slots__ = "name", "value", "lineno", "fname", "args", "evaluating" + + def __init__(self, id_: str, args=None, value=None, lineno: int = None, fname: str = None): + if fname is None: + fname = CURRENT_FILE[-1] + + if value is None: + value = [id_] + + if not isinstance(value, list): + value = [value] + + self.name: str = id_ + self.value: list = value + self.lineno: Optional[int] = lineno # line number at which de ID was defined + self.fname: str = fname # file name in which the ID was defined + self.args = args + self.evaluating = False + + @property + def hasArgs(self) -> bool: + return self.args is not None + + def __str__(self): + return self.name + + @staticmethod + def __dumptable(table: "prepro.DefinesTable") -> None: + """Dumps table on screen for debugging purposes""" + for k, v in table.table.items(): + sys.stdout.write("{0}\t<--- {1} {2}".format(k, v, type(v))) + if isinstance(v, ID): + sys.stdout.write(" {0}".format(v.value)), + sys.stdout.write("\n") + + def __call__(self, table, macro: MacroCall) -> str: + __DEBUG__("evaluating id '%s'" % self.name, DEBUG_LEVEL) + if self.value is None: + __DEBUG__("undefined (null) value. BUG?", DEBUG_LEVEL) + return "" + + if self.evaluating: + result = self.name + if self.hasArgs: + result += "(" + result += ", ".join( + table[arg.name](table, self) if isinstance(arg, ID) else str(arg) for arg in self.args + ) + result += ")" + return result + + self.evaluating = True + + result = "" + for token in self.value: + __DEBUG__("evaluating token '%s'" % str(token), DEBUG_LEVEL) + if isinstance(token, MacroCall): + if isinstance(token.id_, MacroCall): + token.id_ = token.id_(table) + __DEBUG__("token '%s'(%s) is a MacroCall" % (token.id_, str(token)), DEBUG_LEVEL) + if table.defined(token.id_): + tmp = table[token.id_] + __DEBUG__("'%s' is defined in the symbol table as '%s'" % (token.id_, tmp.name), DEBUG_LEVEL) + + if isinstance(tmp, ID) and not tmp.hasArgs: + __DEBUG__("'%s' is an ID" % tmp.name, DEBUG_LEVEL) + token = copy.deepcopy(token) + token.id_ = tmp(table, macro) + __DEBUG__("'%s' is the new id" % token.id_, DEBUG_LEVEL) + + __DEBUG__("executing MacroCall '%s'" % token.id_, DEBUG_LEVEL) + tmp = token(table) + else: + if isinstance(token, ID): + __DEBUG__("token '%s' is an ID" % token.name, DEBUG_LEVEL) + token = token(table, macro) + tmp = token + + __DEBUG__("token got value '%s'" % tmp, DEBUG_LEVEL) + result += tmp + + self.evaluating = False + return result diff --git a/pool/shard002/Python/0026049_0001_initial.py b/pool/shard002/Python/0026049_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..29c8d311b5498b9bcc1061b834b39bc007e4755f --- /dev/null +++ b/pool/shard002/Python/0026049_0001_initial.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('cms', '__first__'), + ] + + operations = [ + migrations.CreateModel( + name='Table', + fields=[ + ('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cms.CMSPlugin')), + ('name', models.CharField(max_length=256, verbose_name='name')), + ('headers_top', models.PositiveSmallIntegerField(default=1, verbose_name='top')), + ('headers_left', models.PositiveSmallIntegerField(default=0, verbose_name='left')), + ('headers_bottom', models.PositiveSmallIntegerField(default=0, verbose_name='bottom')), + ('table_data', models.TextField(verbose_name='table data')), + ], + options={ + 'abstract': False, + }, + bases=('cms.cmsplugin',), + ), + ] diff --git a/pool/shard002/Python/0026053_alert.py b/pool/shard002/Python/0026053_alert.py new file mode 100644 index 0000000000000000000000000000000000000000..7a9a3ee252acf1163df03e51b83b9b3b945b7a14 --- /dev/null +++ b/pool/shard002/Python/0026053_alert.py @@ -0,0 +1,139 @@ + +import json +import socket +import logging +import time +import os +import smtplib +from datetime import datetime +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText + +from config import HealthCheckConfig +from config import gethtmltemplatedir +from config import getconfigpath +from messages import MessageDatabase +from output import full_status_html + +def send(config,messagesdb): + log = logging.getLogger('alert.send()') + summary={} + messages_to_send=None + summary=messagesdb.summary() + log.debug("%s" % summary) + if 'ALL' == config.report_type.upper(): + log.debug("Sending all messages") + messages_to_send=dict(messagesdb) + elif 'ALERT' == config.report_type.upper(): + log.debug("Sending only alerts") + alertcount,messages_to_send=messagesdb.getAlerts(alert_lifetime=config.alert_lifetime) + log.info("Number of Alerts Found: %s" % alertcount) + + if messages_to_send: + #convert messages into HTML using jinja2 + log.debug(json.dumps(messages_to_send,indent=4)) + email_html=full_status_html(gethtmltemplatedir(),summary,messages_to_send) + email(config,email_html) + else: + log.debug("No messages found") + + + +def email(config,content): + log = logging.getLogger('Healthcheck.sendemail()') + if config.email_enabled: + curr_time=time.time() + log.debug("Sending Email at %s " % str(datetime.now())) + try: + # Create message container - the correct MIME type is multipart/alternative. + log = logging.getLogger('alert.email()') + msg = MIMEMultipart('alternative') + msg['Subject'] = config.email_subject + msg['From'] = config.smtp_sender + msg['To'] = ", ".join(config.smtp_receiver) + html_content="" + + + html_content = content + + part1 = MIMEText(html_content, 'html') + + # Attach parts into message container. + # According to RFC 2046, the last part of a multipart message, in this case + # the HTML message, is best and preferred. + msg.attach(part1) + + # Send the message via local SMTP server. + #s = smtplib.SMTP('smtp.gmail.com',465) + conn = smtplib.SMTP(config.smtp_host,config.smtp_port, timeout=30) + #conn.starttls() + #user,password = ('Demo','Test') + #conn.login(user,password) + + # sendmail function takes 3 arguments: sender's address, recipient's address + # and message to send - here it is sent as one string. + conn.sendmail(config.smtp_sender, config.smtp_receiver, msg.as_string()) + log.info("Alert email sent at %s " % str(datetime.now())) + conn.quit() + except (socket.error,socket.gaierror,smtplib.SMTPException) as e: + log.error("Failed to send email: %s" % str(e)) + #log.exception(e) + else: + log.debug("Email feature disabled in config file") + log.debug("set email_enabled to yes in config file") + + +if __name__ == '__main__': + myjson={"testserver": { + "SASStudio": { + "available": False, + "return_code": 300, + "last_checked": "2017-06-05 11:56:42.181631", + "service_id": "3e460a2bbbe7f0f29b13c7d910959fd3", + "message": "[Errno 8] nodename nor servname provided, or not known", + "type": "webapp", + "group":"SAS Web applications" + }, + "SASStudio2": { + "available": True, + "return_code": 300, + "last_checked": "2017-06-05 11:56:42.181631", + "service_id": "3e460a2bbbe7f0f29b13c7d910959fd3", + "message": "[Errno 8] nodename nor servname provided, or not known", + "type": "webapp" + } + + }, + "testserver3": { + "SASStudio": { + "available": False, + "return_code": 300, + "last_checked": "2017-06-05 11:56:42.181631", + "service_id": "3e460a2bbbe7f0f29b13c7d910959fd3", + "message": "[Errno 8] nodename nor servname provided, or not known", + "type": "webapp" + }, + "SASStudio2": { + "available": True, + "return_code": 300, + "last_checked": "2017-06-05 11:56:42.181631", + "service_id": "3e460a2bbbe7f0f29b13c7d910959fd3", + "message": "[Errno 8] nodename nor servname provided, or not known", + "type": "webapp", + "environment":"unknown" + } + + } + } + + try: + #from healthchecklogging import initializeLogging + #initializeLogging(default_level=logging.DEBUG) + config=HealthCheckConfig(getconfigpath()) + logging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') + cls3=MessageDatabase() + cls3.add(myjson) + except ValueError as e: + print "cls3 not created: %s" % e + else: + send(config,cls3) diff --git a/pool/shard002/Python/0026056_random_seed_test.py b/pool/shard002/Python/0026056_random_seed_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0046420468398ec8e2ccd11d2cb5b9474648e593 --- /dev/null +++ b/pool/shard002/Python/0026056_random_seed_test.py @@ -0,0 +1,21 @@ +import tensorflow as tf +tf.set_random_seed(1337) +a = tf.random_uniform([1]) +b = tf.random_uniform([1]) + +# Repeatedly running this block with the same graph will generate different +# sequences of 'a' and 'b'. +print("Session 1") +with tf.Session() as sess1: + print(sess1.run(a)) # generates 'A1' + print(sess1.run(a)) # generates 'A2' + print(sess1.run(b)) # generates 'B1' + print(sess1.run(b)) # generates 'B2' + +print("Session 2") +with tf.Session() as sess2: + print(sess2.run(a)) # generates 'A1' + print(sess2.run(a)) # generates 'A2' + print(sess2.run(b)) # generates 'B1' + print(sess2.run(b)) # generates 'B2' + diff --git a/pool/shard002/Python/0026059_CaliopeWebSocketAPI_test.py b/pool/shard002/Python/0026059_CaliopeWebSocketAPI_test.py new file mode 100644 index 0000000000000000000000000000000000000000..590dc57de8bb88de5aea459dd3cf52357a13f2bd --- /dev/null +++ b/pool/shard002/Python/0026059_CaliopeWebSocketAPI_test.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- +""" +@authors: Sebastián Ortiz V. neoecos@gmail.com + +SIIM Server is the web server of SIIM's Framework +Copyright (C) 2013 Infometrika Ltda + + 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 . +""" + +import unittest +import hashlib + +#gevent +from gevent.pywsgi import WSGIServer +from geventwebsocket.handler import WebSocketHandler + +#tinyrpc +from tinyrpc.protocols.jsonrpc import JSONRPCProtocol +from tinyrpc.client import RPCClient, RPCError +from tinyrpc.transports.http import HttpWebSocketClientTransport + +#neo4j +from py2neo import neo4j + +#flask +from flask import (Flask) + +#simplekv +import redis +from simplekv.memory.redisstore import RedisStore + +from cid import caliope_server +from cid.utils.DefaultDatabase import DefaultDatabase + + + +class CaliopeServerTestCase(unittest.TestCase): + def setUp(self): + caliope_server.app.config['TESTING'] = True + caliope_server.init_flask_app() + caliope_server.configure_server_and_app("../../conf/test_caliope_server.json") + caliope_server.configure_logger("../../conf/tests_logger.json") + caliope_server.register_modules() + caliope_server.app.storekv = RedisStore(redis.StrictRedis()) + self.http_server = WSGIServer((caliope_server.app.config['address'], + caliope_server.app.config['port']), + caliope_server.app, + handler_class=WebSocketHandler) # @IgnorePep8 + self.http_server.start() + self.create_default_database() + + def tearDown(self): + """Get rid of the database again after each test.""" + if self.rpc_client: + self.rpc_client.transport.close() + self.http_server.stop() + self.http_server = None + caliope_server.app = Flask('caliope_server') + #:Delete database + neo4j.GraphDatabaseService().clear() + + + def create_default_database(self): + DefaultDatabase().test_defaultUserGroupOne() + + + def login(self, username, password): + self.rpc_client = RPCClient(JSONRPCProtocol(), + HttpWebSocketClientTransport('ws://localhost:9001/api/ws')) + self.loginManager = self.rpc_client.get_proxy("login.") + hashed_password = hashlib.sha256(password).hexdigest() + return self.loginManager.authenticate(username=username, + password=hashed_password) + + def logout(self, uuid): + if self.loginManager is None: + return + return self.loginManager.logout(uuid=uuid) + + + def test_login(self): + rv = self.login(u'user', u'123') + expected = \ + {u'first_name': {u'value': u'User'}, + u'last_name': {u'value': u'Test'}, + u'image': {u'data': None}, + u'user': {u'value': u'user'}, + u'login': True, + } + self.assertDictContainsSubset(expected, rv) + self.assertIn("session_uuid", rv) + self.assertIn("user_uuid", rv) + + + def test_logout(self): + uuid = self.login(u'user', u'123')['user_uuid']['value'] + rv = self.logout(uuid=uuid) + self.assertIn('logout', rv) + self.assertTrue(rv['logout']) + self.assertIn('uuid', rv) + self.assertEqual(uuid, rv['uuid']) + + def test_accounts_get_public_info(self): + users = [self.login(u'user', u'123')['user_uuid']['value']] + accounts_proxy = self.rpc_client.get_proxy(prefix="accounts.") + info = accounts_proxy.getPublicInfo(users) + assert len(info) == 1 + assert 'uuid' in info[0] + for user in users: + info_uuid = info[0]['uuid']['value'] + assert user == info_uuid + + + + def test_projects_create(self): + user = self.login(u'user', u'123') + projects_proxy = self.rpc_client.get_proxy(prefix="project.") + model = projects_proxy.getModel() + data = {"name": "PROYECTO 305", + "general_location": "

ASDASDASD

", + "locality": "suba", + "project_type": "py_gr_escala", + "profit_center": "ASDASDADS", + "areas": [{"tipo": "A1", "valor": "121"}, {"tipo": "A2", "valor": "13"}], + "uuid": model['data']['uuid']['value'] + } + #: TODO Check for real asserts + try: + rv = projects_proxy.create(data=data) + assert True + except BaseException: + assert False + + def test_form_find(self): + user = self.login(u'user', u'123') + projects_proxy = self.rpc_client.get_proxy(prefix="project.") + rv = projects_proxy.getAll() + self.assertIsNotNone(rv) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard002/Python/0026060_template_engine.py b/pool/shard002/Python/0026060_template_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..0e76506886b0dc0dda799c80cfe0bdab94813c9d --- /dev/null +++ b/pool/shard002/Python/0026060_template_engine.py @@ -0,0 +1,34 @@ +# Component that parses template and returns list of blocks +# and allows you to put data into each block + +import re + +class TemplateEngine(object): + def __init__(self, template): + self.template = template + self.__parse_for_blocks() + + def __parse_for_blocks(self): + self.blocks = set(re.findall("\\{%\s*(.*?)\s*%\\}", self.template)) + + def replace(self, **kwargs): + if len(kwargs) == 0: + return -1 + for key in kwargs: + if key not in self.blocks: + return -2 + + # modified_txt not in init because we need text to be updated + # as we go along. Each replacement needs to modify template + # not the modified txt + modified_txt = self.template[:] + + for k, v in kwargs.iteritems(): + modified_txt = re.sub("\\{%%\s+(%s)\s+%%\\}" % (k), v, modified_txt) + + return modified_txt + + + + + diff --git a/pool/shard002/Python/0026065_swerv_config_gen.py b/pool/shard002/Python/0026065_swerv_config_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..074d291e04271c2743b610dde1218d1caf683843 --- /dev/null +++ b/pool/shard002/Python/0026065_swerv_config_gen.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +from fusesoc.capi2.generator import Generator +import os +import subprocess +import sys + +class SwervConfigGenerator(Generator): + def run(self): + script_root = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..')) + files = [ + {"common_defines.vh" : { + "copyto" : "config/common_defines.vh", + "file_type" : "systemVerilogSource"}}, + {"el2_pdef.vh" : { + "copyto" : "config/el2_pdef.vh", + "file_type" : "systemVerilogSource"}}, + {"el2_param.vh" : { + "is_include_file" : True, + "file_type" : "systemVerilogSource"}}, + {"pic_map_auto.h" : { + "is_include_file" : True, + "file_type" : "systemVerilogSource"}}] + + env = os.environ.copy() + env['RV_ROOT'] = script_root + env['BUILD_PATH'] = os.getcwd() + args = ['configs/swerv.config'] + self.config.get('args', []) + + rc = subprocess.call(args, cwd=script_root, env=env, stdout=subprocess.DEVNULL) + if rc: + exit(1) + filenames = [] + for f in files: + for k in f: + filenames.append(k) + + self.add_files(files) + +g = SwervConfigGenerator() +g.run() +g.write() diff --git a/pool/shard002/Python/0026072_2.3_Example_a_Handwriting_Recognition_System.py b/pool/shard002/Python/0026072_2.3_Example_a_Handwriting_Recognition_System.py new file mode 100644 index 0000000000000000000000000000000000000000..efd99be21d75152389b81d7198c4559890006fb7 --- /dev/null +++ b/pool/shard002/Python/0026072_2.3_Example_a_Handwriting_Recognition_System.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Part 1 - Chapter 2.3 - 4 - Example: a Handwriting Recognition System + + +print("*************************************\n Machine Learning In Action - Code\n") +print(" Part : 1 - Classification") +print(" Chapter : 2.3 - Example: a Handwriting Recognition System") +print(" Index : 4\n") +print(" Page : 28\n") +print(" By : Troy Lewis\n*************************************\n\n") + +print("=====================================\nStep 01: Import kNN.py and test img2vector\n") +import kNN +test_vector = kNN.img2vector('digits/test_digits/0_13.txt') +print "array1 = " +print test_vector[0, 0:32] +print "array2 = " +print test_vector[0, 32:64] + +print("=====================================\nStep 02: Test the classifier\n") +print "run the classifier: " +kNN.handwriting_test() diff --git a/pool/shard002/Python/0026077_views.py b/pool/shard002/Python/0026077_views.py new file mode 100644 index 0000000000000000000000000000000000000000..d75c2b979f6354761c8513ce9521e935bd666822 --- /dev/null +++ b/pool/shard002/Python/0026077_views.py @@ -0,0 +1,68 @@ +from rest_framework import generics, permissions +from foodtrucks.models import Foodtruck, Comment +from foodtrucks.serializers import FoodtruckSerializer, CommentSerializer +from foodtrucks.permissions import IsOwnerOrReadOnly +from django.shortcuts import get_object_or_404 + + +class FoodtruckList(generics.ListCreateAPIView): + permission_classes = ( + permissions.IsAuthenticatedOrReadOnly, + IsOwnerOrReadOnly, + ) + queryset = Foodtruck.objects.all() + serializer_class = FoodtruckSerializer + + def get_object(self): + queryset = self.get_queryset() + obj = get_object_or_404( + queryset, + pk=self.kwargs['pk'], + ) + self.check_object_permissions(self.request, obj) + return obj + + def perform_create(self, serializer): + serializer.save(owner=self.request.user) + + +class FoodtruckDetail(generics.RetrieveUpdateDestroyAPIView): + permission_classes = ( + permissions.IsAuthenticatedOrReadOnly, + IsOwnerOrReadOnly, + ) + queryset = Foodtruck.objects.all() + serializer_class = FoodtruckSerializer + + def get_object(self): + queryset = self.get_queryset() + obj = get_object_or_404( + queryset, + pk=self.kwargs['pk'], + ) + self.check_object_permissions(self.request, obj) + return obj + + +class CommentList(generics.ListCreateAPIView): + permission_classes = ( + permissions.IsAuthenticatedOrReadOnly, + ) + serializer_class = CommentSerializer + + def perform_create(self, serializer): + current_foodtruck = Foodtruck.objects.get(pk=self.kwargs['pk']) + serializer.save(user=self.request.user, foodtruck=current_foodtruck) + + def dispatch(self, request, *args, **kwargs): + self.queryset = Comment.objects.filter(foodtruck=self.kwargs['pk']) + return super(CommentList, self).dispatch(request, *args, **kwargs) + + def get_object(self): + queryset = self.get_queryset() + obj = get_object_or_404( + queryset, + pk=self.kwargs['pk'], + ) + self.check_object_permissions(self.request, obj) + return obj diff --git a/pool/shard002/Python/0026078_cursor.py b/pool/shard002/Python/0026078_cursor.py new file mode 100644 index 0000000000000000000000000000000000000000..0264fa1b8f686b17cde6e48895ce552c1711cca9 --- /dev/null +++ b/pool/shard002/Python/0026078_cursor.py @@ -0,0 +1,37 @@ +### +# Tests the driver cursor API +### + +import unittest +from os import getenv +from sys import path, argv +path.append("../../drivers/python") + +import rethinkdb as r + +num_rows = int(argv[2]) +port = int(argv[1]) + +class TestCursor(unittest.TestCase): + + def setUp(self): + c = r.connect(port=port) + tbl = r.table('test') + self.cur = tbl.run(c) + + def test_type(self): + self.assertEqual(type(self.cur), r.Cursor) + + def test_count(self): + i = 0 + for row in self.cur: + i += 1 + + self.assertEqual(i, num_rows) + +if __name__ == '__main__': + print "Testing cursor for %d rows" % num_rows + suite = unittest.TestSuite() + loader = unittest.TestLoader() + suite.addTest(loader.loadTestsFromTestCase(TestCursor)) + unittest.TextTestRunner(verbosity=2).run(suite) diff --git a/pool/shard002/Python/0026090_utils.py b/pool/shard002/Python/0026090_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2504c135006c9be78f95e87001ce3c760dd8b66f --- /dev/null +++ b/pool/shard002/Python/0026090_utils.py @@ -0,0 +1,26 @@ +import posixpath + +try: + from urllib.parse import urlsplit, urlunsplit +except ImportError: + from urlparse import urlsplit, urlunsplit + + +def url_join(base, *args): + """ + Helper function to join an arbitrary number of url segments together. + """ + scheme, netloc, path, query, fragment = urlsplit(base) + path = path if len(path) else "/" + path = posixpath.join(path, *[('%s' % x) for x in args]) + return urlunsplit([scheme, netloc, path, query, fragment]) + + +def iterator(d): + """ + Helper to get and a proper dict iterator with Py2k and Py3k + """ + try: + return d.iteritems() + except AttributeError: + return d.items() diff --git a/pool/shard002/Python/0026091_init__.py b/pool/shard002/Python/0026091_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..164a2d5767dcf844b2bf571894bfd7d90559f10d --- /dev/null +++ b/pool/shard002/Python/0026091_init__.py @@ -0,0 +1,129 @@ +""" +A module that represent a WS Service that will start a WS server +""" + +from twisted.application import internet, service +from twisted.internet import ssl +from autobahn.twisted.websocket import listenWS + +from zope.interface import classImplementsOnly +from zope.component import adapts +from zope.component import getGlobalSiteManager + +from NetCatKS.NetCAT.api.interfaces.autobahn.services import IDefaultWSService +from NetCatKS.NetCAT.api.interfaces.autobahn.factories import IDefaultWSFactory +from NetCatKS.Logger import Logger + + +__author__ = 'dimd' + + +class DefaultWSService(service.Service): + """ + Provides functionality for starting default TCP Server as single app or as part of many services + """ + adapts(IDefaultWSFactory) + + def __init__(self, factory): + """ + + :param factory: + :type IDefaultFactory + + """ + + self.factory = factory + + self.__logger = Logger() + + self.listener = None + + if self.factory.ws_protocol == 'wss': + + self.__ssl_context = ssl.DefaultOpenSSLContextFactory( + self.factory.crt_keys.get('key'), + self.factory.crt_keys.get('crt') + ) + + self.setName(self.factory.name) + + if self.factory.belong_to is False: + + self.__application = service.Application(self.factory.name, uid=1000, gid=1000) + self.service_collection = service.IServiceCollection(self.__application) + + else: + + self.service_collection = self.factory.belong_to + + def startService(self): + + """ + Starting a TCP server and put to the right service collection + + :return: + """ + if self.factory.ws_protocol == 'ws': + + factory = self.factory.ws_server_factory(self.factory.url) + factory.protocol = self.factory.ws_msg_protocol + factory.name = self.factory.name + + self.factory.ws_server_factory = factory + + internet.TCPServer( + self.factory.port, + factory, + 50 + ).setServiceParent(self.service_collection) + + else: + + factory = self.factory.ws_server_factory(self.factory.url) + + factory.protocol = self.factory.ws_msg_protocol + + factory.startFactory() + + self.factory.ws_server_factory = factory + + self.listener = listenWS(self.factory.ws_server_factory, self.__ssl_context) + + if self.factory.belong_to is False: + + return self.__application + + def start(self): + + """ + A public start method + + :return: service_application + """ + self.setServiceParent(self.service_collection) + + if self.factory.belong_to is False: + return self.__application + + def stopService(self): + + """ + A stop service method + + :return: void + """ + self.factory.ws_server_factory.stopFactory() + + # if is not meaning wss server + if self.listener is not None: + self.listener.stopListening() + +classImplementsOnly(DefaultWSService, IDefaultWSService) + +gsm = getGlobalSiteManager() +gsm.registerAdapter(DefaultWSService) + + +__all__ = [ + 'DefaultWSService' +] diff --git a/pool/shard002/Python/0026093_ScriptExcept.py b/pool/shard002/Python/0026093_ScriptExcept.py new file mode 100644 index 0000000000000000000000000000000000000000..4d1991ee2ad156d844cab714d8e494e1aabd3ff7 --- /dev/null +++ b/pool/shard002/Python/0026093_ScriptExcept.py @@ -0,0 +1,218 @@ +#!/usr/bin/python +# coding: utf-8 -*- + +# Version 1.92 - ScriptRt message converted in utf-8 if necessary +# Version 1.95 - Version alignment + +########################################################################### +# SYSTEM LIBS ############################################################# +########################################################################### + +import os +import sys + +########################################################################### +# APPLICATION LIBS ######################################################## +########################################################################### + +# import path +sys.path.append(os.getenv("PYLIB")) + +########################################################################### +# ENUMS ################################################################### +########################################################################### + +ok_e, warning_e, error_e = range(3) + +########################################################################### +# EXCEPTIONS ############################################################## +########################################################################### + +class ScriptRt(Exception) : + """ + general purpose runtime errors + """ + + # ---- ctors ---- + + def __init__( + self, + reason_s) : + """ + ctor + @param reason_s : exception description + """ + + if isinstance(reason_s, unicode) : + reason_s = reason_s.encode("utf-8") + # ---- super ---- + + Exception.__init__( + self) + + # ---- data ---- + + # error description + self._reason_s = "" + + # ---- code ---- + + self._reason_s = reason_s + + def __str__( + self) : + """ + operator const char*() + """ + return(self._reason_s) + +class ScriptIo(ScriptRt) : + """ + operating system error + """ + + # ---- ctors ---- + + def __init__( + self, + reason_s, + errno) : + """ + ctor + @param reason_s : exception description + @param errno : error number + """ + + # ---- super ---- + + ScriptRt.__init__( + self, + reason_s) + + # ---- data ---- + + self._errno = errno + + def __str__( + self) : + """ + operator const char*() + """ + return("Echec(errno=%d): %s\n%s" % + (self._errno, os.strerror(self._errno), self._reason_s)) + +class ScriptSg(ScriptRt) : + """ + signal error + """ + + # ---- ctors ---- + + def __init__( + self, + signum, + reason_s) : + """ + ctor + @param signum : signal number + @param reason_s : exception description + """ + + # ---- super ---- + + ScriptRt.__init__( + self, + reason_s) + + # ---- data ---- + + # caught signal number + self._signum = signum + + # ---- code ---- + + self._signum = signum + + def __str__( + self) : + """ + operator const char*() + """ + return("Echec(signal=%d): %s" % (self._signum, self._reason_s)) + +class ScriptDbg(Exception) : + """ + debug purpose runtime errors (not catched) + """ + + # ---- ctors ---- + + def __init__( + self, + reason_s) : + """ + ctor + @param reason_s : exception description + """ + + # ---- super ---- + + Exception.__init__( + self) + + # ---- data ---- + + # error description + self._reason_s = "" + + # ---- code ---- + + self._reason_s = reason_s + + def __str__( + self) : + """ + operator const char*() + """ + return(self._reason_s) + + +class ScriptCancel(Exception) : + """ + general purpose runtime errors + """ + + # ---- ctors ---- + + def __init__( + self, + reason_s) : + """ + ctor + @param reason_s : exception description + """ + + # ---- super ---- + + Exception.__init__( + self) + + # ---- data ---- + + # error description + self._reason_s = "" + + # ---- code ---- + + self._reason_s = reason_s + + def __str__( + self) : + """ + operator const char*() + """ + return(self._reason_s) + + +# eof + diff --git a/pool/shard002/Python/0026095_high_level.py b/pool/shard002/Python/0026095_high_level.py new file mode 100644 index 0000000000000000000000000000000000000000..702cd574c292e6bf8809576bb276bd73d809247b --- /dev/null +++ b/pool/shard002/Python/0026095_high_level.py @@ -0,0 +1,88 @@ +# -*- coding: utf-8 -*- + +# Copyright © 2012 Petter Reinholdtsen +# +# 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. + +from decimal import Decimal +from functools import partial +import datetime + +import mexbtcapi +from mexbtcapi import concepts +from mexbtcapi.concepts.currencies import BTC, USD +from mexbtcapi.concepts.currency import Amount, ExchangeRate +from mexbtcapi.concepts.market import Market as BaseMarket, PassiveParticipant, Order + +import urllib +import urllib2 +import sys +import json + +try: + from bitstamp import client +except ImportError: + print "Couldn't find module bitstamp. Download and install from:" + print "https://github.com/kmadac/bitstamp-python-client.git" + sys.exit(1) + +MARKET_NAME= "Bitstamp" +_URL = "https://www.bitstamp.net/api/" + +class BitStampTicker( concepts.market.Ticker): + TIME_PERIOD= 24*60*60 + +class BitstampMarket(BaseMarket): + def __init__( self, currency, currency2 = BTC): + mexbtcapi.concepts.market.Market.__init__(self, MARKET_NAME, currency, BTC) + if currency != USD: + raise Exception("Currency not supported on Bitstamp: " + currency) + self.xchg_factory = partial(ExchangeRate, BTC, USD) + self.public_api = client.public() + + def getTicker(self): + url = _URL + "ticker" + data = self.public_api.ticker() + for x,y in [('bid','buy'),('ask','sell')]: + data[y]= data[x] + fields= list(BitStampTicker.RATE_FIELDS) + fields.remove('average') #not present on Bitstamp API + data2 = dict( [ (x, self.xchg_factory(data[x])) for x in fields] ) + data2['time']= datetime.datetime.now() + return BitStampTicker( market=self, **data2 ) + + def getDepth(self): + data = self.public_api.order_book() + #print data + ret = {} + for typ in ('bids', 'asks'): + depth = [] + ret[typ]=depth + for o in data[typ]: + rate = Decimal(o[0]) + amount = Decimal(o[1]) + from_amount = Amount(rate * amount, USD) + price = self.xchg_factory(rate) + order_type = (typ == 'bids' and Order.BID) or Order.ASK + depth.append(Order(self, None, order_type, from_amount, price)) + return ret + diff --git a/pool/shard002/Python/0026096_misc.py b/pool/shard002/Python/0026096_misc.py new file mode 100644 index 0000000000000000000000000000000000000000..078675a3c0556ef1881c478899e5b3677dbd8502 --- /dev/null +++ b/pool/shard002/Python/0026096_misc.py @@ -0,0 +1,30 @@ +import json +import requests +from lib.parser import PostbackError + +def result_dump(result_list, file): + ''' + Dump the list into a file, separated by \n + ''' + for i in result_list: + if i[0] > 99: + return None + with open(file, 'w') as f: + json.dump(result_list, f) + +def manual_rate(stdout_info, allow_sp=False): + # Print the stdout_info to screen for manual rating + # 0 = no good (0), 1 = good (100), 5 = not sure (50) + m_rate = None + # If allow sp: "?" will be decode as -99 for special action + if allow_sp: + score_dict = {'0': 0, '1': 100, '5': 50, '?': -99} + else: + score_dict = {'0': 0, '1': 100, '5': 50} + while m_rate not in score_dict: + print(stdout_info) + m_rate = input('Rate ==> ') + if m_rate in score_dict: + return score_dict[m_rate] + else: + print('!!! Invalid score !!!') \ No newline at end of file diff --git a/pool/shard002/Python/0026097_views.py b/pool/shard002/Python/0026097_views.py new file mode 100644 index 0000000000000000000000000000000000000000..270dab6e340cebdb38c1d93ed33f0ac50a7f1fc9 --- /dev/null +++ b/pool/shard002/Python/0026097_views.py @@ -0,0 +1,182 @@ +try: + from urllib import quote_plus #python 2 +except: + pass + +try: + from urllib.parse import quote_plus #python 3 +except: + pass + +from django.contrib.auth import get_user_model +from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger +from django.contrib.auth.mixins import LoginRequiredMixin +from django.utils import timezone +from django.shortcuts import render, get_object_or_404 +from django.contrib.contenttypes.models import ContentType +from django.http import HttpResponseRedirect, Http404 +from django.urls import reverse_lazy +from django.views.generic import ( + FormView, + ListView, + DetailView, + CreateView, + UpdateView, + DeleteView, +) + +from comments.models import Comment +from comments.forms import CommentForm +from .models import Post +from .forms import PostForm +from tags.models import Tag + +User = get_user_model() + +# Create your views here. +class PostListView(ListView): + model = Post + + def get_context_data(self, **kwargs): + context = super(PostListView, self).get_context_data(**kwargs) + paginator = Paginator(context['post_list'], 10) + + page = self.request.GET.get('page') + try: + context['post_list'] = paginator.page(page) + except PageNotAnInteger: + # If page is not an integer, deliver first page. + context['post_list'] = paginator.page(1) + except EmptyPage: + # If page is out of range (e.g. 9999), deliver last page of results. + context['post_list'] = paginator.page(paginator.num_pages) + + user_list = User.objects.all() + context['user_list'] = user_list + context['paginator'] = paginator + + tag_list = Tag.objects.all() + if not self.request.user.is_superuser: + tag_list = Tag.objects.all().exclude(tag='hango') + + tag_list = sorted(tag_list, key=lambda x: x.post_set.count(), reverse=True) + context['tag_list'] = tag_list[:10] + + return context + + def get_queryset(self): + instances = super().get_queryset() + if not self.request.user.is_superuser: + instances = instances.exclude(tags__tag='hango') + return instances + +class PostCreateView(FormView): + + template_name = 'posts/post_form.html' + model = Post + form_class = PostForm + success_url = reverse_lazy("posts:list") + # fields = ['title', 'content', 'publish', 'language'] + + def dispatch(self, request, *args, **kwargs): + if not self.request.user.is_authenticated: + raise Http404 + return super(PostCreateView, self).dispatch(request, *args, **kwargs) + + def form_valid(self, form): + post = form.save() + form_valid = super(PostCreateView, self).form_valid(form) + if form.cleaned_data["tag"]: + new_tag, created = Tag.objects.get_or_create(tag=form.cleaned_data["tag"]) + else: + new_tag, created = Tag.objects.get_or_create(tag="blog") + post.tags.add(new_tag) + return form_valid + +class PostDetailView(DetailView): + model = Post + + def get_context_data(self, **kwargs): + context = super(PostDetailView, self).get_context_data(**kwargs) + return context + +def post_detail(request, slug=None): + instance = get_object_or_404(Post, slug=slug) + # if instance.publish > timezone.now().date() or instance.draft: + # if not request.user.is_staff or not request.user.is_superuser: + # raise Http404 + # share_string = quote_plus(instance.content) + + initial_data = { + "content_type": instance.get_content_type, + "object_id": instance.id + } + form = CommentForm(request.POST or None, initial=initial_data) + if form.is_valid() and request.user.is_authenticated(): + c_type = form.cleaned_data.get("content_type") + content_type = ContentType.objects.get(model=c_type) + obj_id = form.cleaned_data.get('object_id') + content_data = form.cleaned_data.get("content") + parent_obj = None + try: + parent_id = int(request.POST.get("parent_id")) + except: + parent_id = None + + if parent_id: + parent_qs = Comment.objects.filter(id=parent_id) + if parent_qs.exists() and parent_qs.count() == 1: + parent_obj = parent_qs.first() + + + new_comment, created = Comment.objects.get_or_create( + user = request.user, + content_type= content_type, + object_id = obj_id, + content = content_data, + parent = parent_obj, + ) + return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) + + comments = instance.comments + context = { + "title": instance.title, + "object": instance, + # "share_string": share_string, + "comments": comments, + "comment_form":form, + } + return render(request, "posts/post_detail.html", context) + +class PostUpdateView(LoginRequiredMixin, UpdateView): + template_name = 'posts/post_form.html' + model = Post + form_class = PostForm + success_url = reverse_lazy("posts:list") + + def dispatch(self, request, *args, **kwargs): + instance = self.get_object() + if not self.request.user.is_superuser: + if instance.user != self.request.user: + raise Http404 + return super(PostUpdateView, self).dispatch(request, *args, **kwargs) + + def form_valid(self, form): + post = form.save() + form_valid = super(PostUpdateView, self).form_valid(form) + if form.cleaned_data["tag"]: + new_tag, created = Tag.objects.get_or_create(tag=form.cleaned_data["tag"]) + else: + new_tag, created = Tag.objects.get_or_create(tag="blog") + post.tags.add(new_tag) + return form_valid + +class PostDeleteView(DeleteView): + model = Post + success_url = reverse_lazy("posts:list") + + def dispatch(self, request, *args, **kwargs): + instance = self.get_object() + if instance.user != self.request.user: + raise Http404 + return super(PostDeleteView, self).dispatch(request, *args, **kwargs) \ No newline at end of file diff --git a/pool/shard002/Python/0026099_sharedboard_server.py b/pool/shard002/Python/0026099_sharedboard_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7d61b3cbb12f0b7375ac65d0a91e1243ddfc38df --- /dev/null +++ b/pool/shard002/Python/0026099_sharedboard_server.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Shared Board is a simple shared board,It was made for fun and for testing twistedmatrix + +(C) Copyright 2006 Francisco Jose Moreno Llorca + +Shared Board 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. + +Shared Board 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 Shared Board. If not, see . +""" + +"""Shared Board + +Basic shared board server. +""" + +#serialize objects +import pickle +from pickle import UnpicklingError +import os +#modules for twisted +from twisted.internet.protocol import Factory +from twisted.internet.protocol import Protocol +from twisted.internet import reactor + +#global constants +ARCHIVO_LOG = 'sb_server.log' # path to log file +CREDENTIALS = 'cred.ini' # path to cred.ini +DATA = 'data_s/' # data folder + +#logging engine +from twisted.python import log +log.startLogging(open(ARCHIVO_LOG,'a')) + +#ldap authentication +import ldap +servidor_auth = 'ldapserver:389' + +def cadenaLdap(usuario): + """Return the identification string in LDAP from the value + in the field sAMAccountName + + """ + try: + l = ldap.open(servidor_auth) + l.protocol_version = ldap.VERSION3 + except ldap.LDAPError, e: + log.msg(e) + #first login and then search + try: + arch = open(CREDENTIALS,'r') + leido = arch.read() + lineas = leido.split('\n') + arch.close() + print lineas + except: + log.msg("error opening credentials file") + l.simple_bind_s(lineas[0],lineas[1]) + baseDN = lineas[2] + searchScope = ldap.SCOPE_SUBTREE + retrieveAttributes = None + try: + searchFilter = "cn=%s*%s*" % (usuario.split('.')[0],usuario.split('.')[1]) + ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes) + while 1: + result_type, result_data = l.result(ldap_result_id, 0) + if (result_data == []): + break + else: + if result_type == ldap.RES_SEARCH_ENTRY: + log.msg(result_data[0][0]) + return result_data[0][0] + except: + log.msg('Error authenticating against LDAP') + +def autentico(usuario, password): + """ + this function return True if the password identify to the user + False in other cases + """ + log.msg("Auth in progress......") + try: + log.msg("-------------------------- "+usuario) + l = ldap.open(servidor_auth) + l.simple_bind_s(cadenaLdap(usuario),password) + log.msg("%s Authentication ok" % (usuario)) + return True + except: + log.msg('Error authenticating against LDAP') + return False + +# actions: +NULA = '0' +RECT = '1' +CIRC = '2' +IMG = '3' +CHAR = '4' +LINE = '5' +BORR = '6' + +# magic numbers +AUTH = '1368' +WELCOME = '2461' +DRAW = '028h' +SEPARADOR = 'd2h9' +DESHACER = '0zk<' +REHACER = 'm18s' +ALDIA = '15vu' +IMAGEN = 'm238' +IMG_SEP = '##17' + +class Packo(Protocol): + """Packo protocol + Define the behaviour of the connection protocol. + """ + usuario = "" + password = "" + + def dataReceived(self, data): + """manage the data entry + """ + if data[:4] == AUTH: + self.usuario = data[4:].split(';')[0] + self.password = data[4:].split(';')[1] + if autentico(self.usuario,self.password) == False: + self.transport.write(AUTH+"DENIED") + else: + self.transport.write(AUTH+"ACCEPT") + elif data[:4] == DRAW: + par = data[4:].split(SEPARADOR) + if par[0] == IMG: + try: + nom = str(len(os.listdir(DATA))+1) + deser = pickle.loads(par[10]) + archivo = open(DATA+nom,'w+') + archivo.write(deser) + archivo.close() + log.msg("Image saved") + par[10] = nom + comando = SEPARADOR.join(par) + comando = DRAW+comando + self.factory.historico.append(comando) + for c in self.factory.clients: + c.mensaje(comando) + except UnpicklingError,e: + log.msg('Error saving image: %s' %(e)) + del self.factory.deshecho + self.factory.deshecho = [] + elif par[0]== BORR: + log.msg(par[10]) + self.factory.deshecho.append(self.factory.historico[int(par[10])]) + del self.factory.historico[int(par[10])] + for c in self.factory.clients: + c.mensaje(data) + else: + self.factory.datos = data + self.factory.historico.append(data) + for c in self.factory.clients: + c.mensaje(data) + del self.factory.deshecho + self.factory.deshecho = [] + elif data[:4] == DESHACER: + if len(self.factory.historico) > 0: + self.factory.deshecho.append(self.factory.historico.pop()) + for c in self.factory.clients: + c.mensaje(data) + elif data[:4] == REHACER: + if len(self.factory.deshecho) > 0: + mandar = self.factory.deshecho.pop() + self.factory.historico.append(mandar) + for c in self.factory.clients: + c.mensaje(mandar) + elif data[:4] == ALDIA: + historia = pickle.dumps(self.factory.historico) + self.mensaje(ALDIA+historia) + elif data[:4] == IMAGEN: + archivo = open(DATA+data[4:],'r') + im = pickle.dumps(archivo.read()) + self.mensaje(IMAGEN+data[4:]+IMG_SEP+im) + archivo.close() + print "Image served: "+data[4:] + + def connectionMade(self): + """Add to a list the clients connections. + """ + self.factory.clients.append(self) + self.transport.write(WELCOME) + + def connectionLost(self,reason): + """remove the connection from the list + and send a message to other clients + """ + + self.factory.clients.remove(self) + + def mensaje(self, datos): + """send a message + """ + self.transport.write(datos) + +factory = Factory() +factory.protocol = Packo +factory.clients = [] +factory.historico = [] +factory.deshecho = [] + +reactor.listenTCP(8011, factory) +reactor.run() \ No newline at end of file diff --git a/pool/shard002/Python/0026103_statHWE.py b/pool/shard002/Python/0026103_statHWE.py new file mode 100644 index 0000000000000000000000000000000000000000..8751338d91b2b3f9d90c97333e5907469a5f3637 --- /dev/null +++ b/pool/shard002/Python/0026103_statHWE.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python + +# +# $File: statHWE.py $ +# +# This file is part of simuPOP, a forward-time population genetics +# simulation environment. Please visit http://simupop.sourceforge.net +# for details. +# +# Copyright (C) 2004 - 2010 Bo Peng (bpeng@mdanderson.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 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 . +# + +# This script is an example in the simuPOP user's guide. Please refer to +# the user's guide (http://simupop.sourceforge.net/manual) for a detailed +# description of this example. +# + +import simuPOP as sim +pop = sim.Population([1000], loci=1) +pop.setVirtualSplitter(sim.ProportionSplitter([0.4, 0.4, 0.2])) +pop.evolve( + initOps=[ + sim.InitSex(), + sim.InitGenotype(genotype=[0,0], subPops=[(0,0)]), + sim.InitGenotype(genotype=[0,1], subPops=[(0,1)]), + sim.InitGenotype(genotype=[1,1], subPops=[(0,2)]), + ], + preOps=[ + sim.Stat(HWE=0, genoFreq=0), + sim.PyEval(r'"HWE p-value: %.5f (AA: %.2f, Aa: %.2f, aa: %.2f)\n" % (HWE[0], ' + 'genoFreq[0][(0,0)], genoFreq[0][(0,1)] + genoFreq[0][(1,0)], genoFreq[0][(1,1)])'), + ], + matingScheme=sim.RandomMating(), + postOps=[ + sim.Stat(HWE=0, genoFreq=0), + sim.PyEval(r'"HWE p-value: %.5f (AA: %.2f, Aa: %.2f, aa: %.2f)\n" % (HWE[0], ' + 'genoFreq[0][(0,0)], genoFreq[0][(0,1)] + genoFreq[0][(1,0)], genoFreq[0][(1,1)])'), + ], + gen = 1 +) + diff --git a/pool/shard002/Python/0026113_test_data_upload_settings.py b/pool/shard002/Python/0026113_test_data_upload_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..8855e13336eb22abd4307298c5da63d8bf7d6eb8 --- /dev/null +++ b/pool/shard002/Python/0026113_test_data_upload_settings.py @@ -0,0 +1,186 @@ +from io import BytesIO + +from django.core.exceptions import RequestDataTooBig, TooManyFieldsSent +from django.core.handlers.wsgi import WSGIRequest +from django.test import SimpleTestCase +from django.test.client import FakePayload + +TOO_MANY_FIELDS_MSG = 'The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS.' +TOO_MUCH_DATA_MSG = 'Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.' + + +class DataUploadMaxMemorySizeFormPostTests(SimpleTestCase): + def setUp(self): + payload = FakePayload('a=1&a=2;a=3\r\n') + self.request = WSGIRequest({ + 'REQUEST_METHOD': 'POST', + 'CONTENT_TYPE': 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH': len(payload), + 'wsgi.input': payload, + }) + + def test_size_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=12): + with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG): + self.request._load_post_and_files() + + def test_size_not_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=13): + self.request._load_post_and_files() + + def test_no_limit(self): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=None): + self.request._load_post_and_files() + + +class DataUploadMaxMemorySizeMultipartPostTests(SimpleTestCase): + def setUp(self): + payload = FakePayload("\r\n".join([ + '--boundary', + 'Content-Disposition: form-data; name="name"', + '', + 'value', + '--boundary--' + '' + ])) + self.request = WSGIRequest({ + 'REQUEST_METHOD': 'POST', + 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', + 'CONTENT_LENGTH': len(payload), + 'wsgi.input': payload, + }) + + def test_size_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=10): + with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG): + self.request._load_post_and_files() + + def test_size_not_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=11): + self.request._load_post_and_files() + + def test_no_limit(self): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=None): + self.request._load_post_and_files() + + def test_file_passes(self): + payload = FakePayload("\r\n".join([ + '--boundary', + 'Content-Disposition: form-data; name="file1"; filename="test.file"', + '', + 'value', + '--boundary--' + '' + ])) + request = WSGIRequest({ + 'REQUEST_METHOD': 'POST', + 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', + 'CONTENT_LENGTH': len(payload), + 'wsgi.input': payload, + }) + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=1): + request._load_post_and_files() + self.assertIn('file1', request.FILES, "Upload file not present") + + +class DataUploadMaxMemorySizeGetTests(SimpleTestCase): + def setUp(self): + self.request = WSGIRequest({ + 'REQUEST_METHOD': 'GET', + 'wsgi.input': BytesIO(b''), + 'CONTENT_LENGTH': 3, + }) + + def test_data_upload_max_memory_size_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=2): + with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG): + self.request.body + + def test_size_not_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=3): + self.request.body + + def test_no_limit(self): + with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=None): + self.request.body + + +class DataUploadMaxNumberOfFieldsGet(SimpleTestCase): + + def test_get_max_fields_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=1): + with self.assertRaisesMessage(TooManyFieldsSent, TOO_MANY_FIELDS_MSG): + request = WSGIRequest({ + 'REQUEST_METHOD': 'GET', + 'wsgi.input': BytesIO(b''), + 'QUERY_STRING': 'a=1&a=2;a=3', + }) + request.GET['a'] + + def test_get_max_fields_not_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=3): + request = WSGIRequest({ + 'REQUEST_METHOD': 'GET', + 'wsgi.input': BytesIO(b''), + 'QUERY_STRING': 'a=1&a=2;a=3', + }) + request.GET['a'] + + +class DataUploadMaxNumberOfFieldsMultipartPost(SimpleTestCase): + def setUp(self): + payload = FakePayload("\r\n".join([ + '--boundary', + 'Content-Disposition: form-data; name="name1"', + '', + 'value1', + '--boundary', + 'Content-Disposition: form-data; name="name2"', + '', + 'value2', + '--boundary--' + '' + ])) + self.request = WSGIRequest({ + 'REQUEST_METHOD': 'POST', + 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', + 'CONTENT_LENGTH': len(payload), + 'wsgi.input': payload, + }) + + def test_number_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=1): + with self.assertRaisesMessage(TooManyFieldsSent, TOO_MANY_FIELDS_MSG): + self.request._load_post_and_files() + + def test_number_not_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=2): + self.request._load_post_and_files() + + def test_no_limit(self): + with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=None): + self.request._load_post_and_files() + + +class DataUploadMaxNumberOfFieldsFormPost(SimpleTestCase): + def setUp(self): + payload = FakePayload("\r\n".join(['a=1&a=2;a=3', ''])) + self.request = WSGIRequest({ + 'REQUEST_METHOD': 'POST', + 'CONTENT_TYPE': 'application/x-www-form-urlencoded', + 'CONTENT_LENGTH': len(payload), + 'wsgi.input': payload, + }) + + def test_number_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=2): + with self.assertRaisesMessage(TooManyFieldsSent, TOO_MANY_FIELDS_MSG): + self.request._load_post_and_files() + + def test_number_not_exceeded(self): + with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=3): + self.request._load_post_and_files() + + def test_no_limit(self): + with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=None): + self.request._load_post_and_files() diff --git a/pool/shard002/Python/0026114_fedex_interface.py b/pool/shard002/Python/0026114_fedex_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..6a26f0d02e4aae6a24b5c276e890e6749f5b6f31 --- /dev/null +++ b/pool/shard002/Python/0026114_fedex_interface.py @@ -0,0 +1,242 @@ + +from fedex.config import FedexConfig +from fedex.base_service import FedexError +from fedex.services.track_service import FedexTrackRequest, FedexInvalidTrackingNumber + +from ..data import TrackingInfo +from ..service import BaseInterface, TrackFailed, InvalidTrackingNumber + + +class FedexInterface(BaseInterface): + + + def identify(self, num): + return num.isdigit() and (len(num) in (12, 15, 20, 22)) + + def track(self, tracking_number): + if not self.validate(tracking_number): + raise InvalidTrackingNumber() + + track = FedexTrackRequest(self._get_cfg()) + + track.TrackPackageIdentifier.Type = 'TRACKING_NUMBER_OR_DOORTAG' + track.TrackPackageIdentifier.Value = tracking_number + track.IncludeDetailedScans = True + + # Fires off the request, sets the 'response' attribute on the object. + try: + track.send_request() + except FedexInvalidTrackingNumber as e: + raise InvalidTrackingNumber(e) + except FedexError as e: + raise TrackFailed(e) + + # TODO: I haven't actually seen an unsuccessful query yet + if track.response.HighestSeverity != "SUCCESS": + raise TrackFailed("%d: %s" % ( + track.response.Notifications[0].Code, + track.response.Notifications[0].LocalizedMessage + )) + + return self._parse_response(track.response.TrackDetails[0], tracking_number) + + + def url(self, tracking_number): + return ('http://www.fedex.com/Tracking?tracknumbers=%s' % tracking_number) + + + def _parse_response(self, rsp, tracking_number): + """Parse the track response and return a TrackingInfo object""" + + # test status code, return actual delivery time if package + # was delivered, otherwise estimated target time + if rsp.StatusCode == 'DL': + delivery_date = rsp.ActualDeliveryTimestamp + + # this may not be present + try: + delivery_detail = rsp.Events[0].StatusExceptionDescription + except AttributeError: + delivery_detail = None + + last_update = delivery_date + location = ','.join(( + rsp.ActualDeliveryAddress.City, + rsp.ActualDeliveryAddress.StateOrProvinceCode, + rsp.ActualDeliveryAddress.CountryCode, + )) + + else: + delivery_detail = None + try: + delivery_date = rsp.EstimatedDeliveryTimestamp + except AttributeError: + delivery_date = None + last_update = rsp.Events[0].Timestamp + location = self._getTrackingLocation(rsp.Events[0]) + + + # a new tracking info object + trackinfo = TrackingInfo( + tracking_number = tracking_number, + last_update = last_update, + status = rsp.StatusDescription, + location = location, + delivery_date = delivery_date, + delivery_detail = delivery_detail, + service = rsp.ServiceType, + ) + + # now add the events + for e in rsp.Events: + trackinfo.addEvent( + location = self._getTrackingLocation(e), + date = e.Timestamp, + detail = e.EventDescription, + ) + + return trackinfo + + + def _getTrackingLocation(self, e): + """Returns a nicely formatted location for a given event""" + try: + return ','.join(( + e.Address.City, + e.Address.StateOrProvinceCode, + e.Address.CountryCode, + )) + except: + return None + + + def _get_cfg(self): + """Makes and returns a FedexConfig object from the packagetrack + configuration. Caches it, so it doesn't create each time.""" + + # got one cached, so just return it + if self.cfg: + return self.cfg + + self.cfg = FedexConfig( + key = self.config.get('FedEx', 'key'), + password = self.config.get('FedEx', 'password'), + account_number = self.config.get('FedEx', 'account_number'), + meter_number = self.config.get('FedEx', 'meter_number'), + use_test_server = False, + express_region_code = 'US', + ) + + # these are optional, and afaik, not really used for tracking + # at all, but you can still set them, so.... + if self.config.has_option('FedEx', 'express_region_code'): + self.cfg.express_region_code = self.config.get('FedEx', 'express_region_code') + + if self.config.has_option('FedEx', 'integrator_id'): + self.cfg.integrator_id = self.config.get('FedEx', 'integrator_id') + + if self.testing or self.config.has_option('FedEx', 'use_test_server'): + self.cfg.use_test_server = self.config.getboolean('FedEx', 'use_test_server') + + return self.cfg + + + def validate(self, tnum): + """Validate the tracking number""" + + if len(tnum) == 12: + return self._validate_express(tnum) + + elif (len(tnum) == 15): + return self._validate_ground96(tnum) + + elif (len(tnum) == 22) and tnum.startswith('96'): + return self._validate_ground96(tnum) + + elif (len(tnum) == 20) and tnum.startswith('00'): + return self._validate_ssc18(tnum) + + return False + + + def _validate_ground96(self, tracking_number): + """Validates ground code 128 ("96") bar codes + + 15-digit form: + + 019343586678996 + shipper ID: ------- + package ID: ------- + checksum: - + + 22-digit form: + 9611020019343586678996 + UCC/EAN id: -- + SCNC: -- + class of svc: -- + shipper ID: ------- + package ID: ------- + checksum: - + + """ + + rev = tracking_number[::-1] + + eventotal = 0 + oddtotal = 0 + for i in range(1, 15): + if i % 2: + eventotal += int(rev[i]) + else: + oddtotal += int(rev[i]) + + check = 10 - ((eventotal * 3 + oddtotal) % 10) + + # compare with the checksum digit, which is the last digit + return check == int(tracking_number[-1:]) + + def _validate_ssc18(self, tracking_number): + """Validates SSC18 tracking numbers""" + + rev = tracking_number[::-1] + + eventotal = 0 + oddtotal = 0 + for i in range(1, 19): + if i % 2: + eventotal += int(rev[i]) + else: + oddtotal += int(rev[i]) + + check = 10 - ((eventotal * 3 + oddtotal) % 10) + + # compare with the checksum digit, which is the last digit + return check == int(tracking_number[-1:]) + + + def _validate_express(self, tracking_number): + """Validates Express tracking numbers""" + + basenum = tracking_number[0:10] + + sums = [] + mult = 1 + total = 0 + for digit in basenum[::-1]: + sums.append(int(digit) * mult) + total = total + (int(digit) * mult) + + if mult == 1: + mult = 3 + if mult == 3: + mult = 7 + if mult == 7: + mult = 1 + + check = total % 11 + if check == 10: + check = 0 + + # compare with the checksum digit, which is the last digit + return check == int(tracking_number[-1:]) + diff --git a/pool/shard002/Python/0026116_views.py b/pool/shard002/Python/0026116_views.py new file mode 100644 index 0000000000000000000000000000000000000000..afb3a9ab00af435b8765d3d7b4749364a20665e0 --- /dev/null +++ b/pool/shard002/Python/0026116_views.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- +from django.db.models import Min +from django.views.generic import ( + ListView, + DetailView, +) +from django.contrib.auth.models import User +from django.shortcuts import get_object_or_404 + +from webapp.models import Menu +from .models import ( + SwimTest, + Record, +) +from .forms import ( + SwimTestSearchForm, +) + +class CurrentMenuMixin(object): + """ Adds the current menu object to the context data. """ + def get_context_data(self, **kwargs): + context = super(CurrentMenuMixin, self).get_context_data(**kwargs) + context['current_menu'] = get_object_or_404(Menu, slug='zwemtest') + return context + + +class SwimTestList(CurrentMenuMixin, ListView): + model = SwimTest + + def get_queryset(self, **kwargs): + """ Filters the queryset with the search values. """ + queryset = super(SwimTestList, self).get_queryset() + user = self.request.GET.get("user") + if user: + queryset = queryset.filter(record__user=user) + return queryset + + def get_context_data(self, **kwargs): + """ Adds the search form to context data. """ + context = super(SwimTestList, self).get_context_data(**kwargs) + initial_data = self.request.GET + context['form'] = SwimTestSearchForm(initial=initial_data) + return context + + +class SwimTestDetail(CurrentMenuMixin, DetailView): + model = SwimTest + + +class UserList(CurrentMenuMixin, ListView): + model = User + template_name = 'swimtest/user_list.html' + + def get_queryset(self, **kwargs): + queryset = super(UserList, self).get_queryset() + queryset = queryset.order_by('username').exclude(record__isnull=True) + return queryset + + +class UserDetail(CurrentMenuMixin, DetailView): + model = User + template_name = 'swimtest/user_detail.html' + + +class BestTimeList(CurrentMenuMixin, ListView): + model = Record + template_name = 'swimtest/best_time_list.html' + + def get_queryset(self, **kwargs): + queryset = super(BestTimeList, self).get_queryset()\ + .order_by('user', 'time_500').distinct('user') + ids = [obj.id for obj in queryset] + queryset = self.model.objects.filter(pk__in=ids)\ + .select_related('user', 'swim_test').order_by('time_500') + return queryset diff --git a/pool/shard002/Python/0026126_l_bp_tests.py b/pool/shard002/Python/0026126_l_bp_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..eaa3cf3dda90baa40e2e66f75287ef909878b666 --- /dev/null +++ b/pool/shard002/Python/0026126_l_bp_tests.py @@ -0,0 +1,52 @@ +from unittest import TestCase, main +from svtools.l_bp import * + +class Test_l_bp(TestCase): + def test_find_all(self): + test_string = 'ABBA' + sub_string = 'A' + + result = [ x for x in find_all(test_string, sub_string) ] + self.assertEqual(result, [0,3]) + + def test_to_map(self): + string = 'NS=3;AF=0.5;DB' + expected = { 'NS' : '3', 'AF' : '0.5', 'DB' : None } + result = to_map(string) + self.assertEqual(result, expected) + + def test_split_v(self): + info_bnd_map = { + 'SVTYPE' : 'BND', + 'STRANDS' : '-+', + 'CIPOS' : '-100,10', + 'CIEND' : '-10,400', + 'END' : '1100' + } + + var1 = '1 1000 2345 N ]2:1100]N 0 . SVTYPE=BND;STRANDS=-+;CIPOS=-100,10;CIEND=-10,400' + self.assertEqual(split_v(var1), ['BND', '1', '2', '-+', 900, 1010, 1090, 1500, info_bnd_map]) + + var2 = '1 1000 2345 N [2:1100[N 0 . SVTYPE=BND;STRANDS=-+;CIPOS=-100,10;CIEND=-10,400' + self.assertEqual(split_v(var2), ['BND', '1', '2', '-+', 900, 1010, 1090, 1500, info_bnd_map]) + + var3 = '1 1000 2345 N 0 . SVTYPE=DEL;STRANDS=+-;END=1100;CIPOS=-100,10;CIEND=-10,400' + info_bnd_map['SVTYPE'] = 'DEL' + info_bnd_map['STRANDS'] = '+-' + self.assertEqual(split_v(var3), ['DEL', '1', '1', '+-', 900, 1010, 1090, 1500, info_bnd_map]) + + def test_trim(self): + self.assertEqual(trim([0, 0, 2, 3, 5, 0, 0, 0]), [2, 3]) + self.assertEqual(trim([0, 0, 2, 3, 5]), [2, 0]) + self.assertEqual(trim([2, 3, 5, 0, 0, 0]), [0, 3]) + self.assertEqual(trim([2, 3, 5]), [0, 0]) + + def test_align_intervals(self): + interval1 = [0, 4, [0.2, 0.2, 0.2, 0.2, 0.2]] + interval2 = [1, 5, [0.2, 0.2, 0.2, 0.2, 0.2]] + self.assertEqual(align_intervals([interval1, interval2]), [0, 5, [[0.2, 0.2, 0.2, 0.2, 0.2, 0], [0, 0.2, 0.2, 0.2, 0.2, 0.2]]]) + + +if __name__ == "__main__": + main() + diff --git a/pool/shard002/Python/0026130_Worker.py b/pool/shard002/Python/0026130_Worker.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9488ac2c6e9cccd37acfc90e9f4fe231a094f5 --- /dev/null +++ b/pool/shard002/Python/0026130_Worker.py @@ -0,0 +1,66 @@ +import numpy as np + +# The worker class is a member of the trainer class, the trainer can have multiple workers +class Worker(): + def __init__(self, settings, sess, number, trainerNumber, network, queues, coord): + self.localAC = network + self.name = 'worker{}'.format(number) + self.number = number + self.settings = settings + self.trainerQueue = queues["trainer"] + self.trainerNumber = trainerNumber + self.coord = coord + self.sess = sess + self.playerActionQueue = queues["playerAction"] + self.game = None + self.playerActionQueue.put({"WindowSettings": True if self.name == "worker0" else False, + "worker": number}) + + self.episodeInProgress = True + self.values = [] + + def work(self, gameData): + gameData # Get data from the game + if gameData[0] == "CurrentFrame": # Process the next action based on frame + frame = gameData[1] + feedDict = {self.localAC.frame: [frame]} + actionDist, value = self.sess.run([self.localAC.logits, + self.localAC.value], + feed_dict=feedDict) + action = np.random.choice(actionDist[0], p=actionDist[0]) + action = np.argmax(actionDist==action) + + self.playerActionQueue.put(action) + self.values.append(value[0,0]) + + elif gameData[0] == "Bootstrap": # Bootstrap from bootstrap data + print("{} is bootstrapping!".format(self.name)) + episodeData = gameData[1] + bootstrapValues = self.values[0:len(episodeData)] + self.values = self.values[len(episodeData)::] + workerData = {"episodeData": episodeData, + "values": bootstrapValues, + "bootStrapValue": self.values[0], + "score": 0, + "worker": self.number, + "trainer": self.trainerNumber} + self.trainerQueue.put(workerData) + + elif gameData[0] == "EpisodeData": # Episode is finished, perform training and logging + episodeData = gameData[1] + score = gameData[2] + workerData = {"episodeData": episodeData, + "values": self.values, + "bootStrapValue": 0, + "score": score, + "worker": self.number, + "trainer": self.trainerNumber} + self.trainerQueue.put(workerData) + self.values = [] + + elif gameData[0] == "Game closed!": # Game has been closed + print("{}s game closed, saving and quitting program!".format(self.name)) + self.coord.request_stop() + + else: + print("Invalid game data! got: {}".format(gameData[0])) \ No newline at end of file diff --git a/pool/shard002/Python/0026131_delta_e_itp.py b/pool/shard002/Python/0026131_delta_e_itp.py new file mode 100644 index 0000000000000000000000000000000000000000..fb8086b031f48a75d49f1276af09acfbe0332186 --- /dev/null +++ b/pool/shard002/Python/0026131_delta_e_itp.py @@ -0,0 +1,28 @@ +""" +Delta E ITP. + +https://kb.portrait.com/help/ictcp-color-difference-metric +""" +from ..distance import DeltaE +import math +from .. import util +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: # pragma: no cover + from ..color import Color + + +class DEITP(DeltaE): + """Delta E ITP class.""" + + NAME = "itp" + + @classmethod + def distance(cls, color: 'Color', sample: 'Color', scalar: float = 720, **kwargs: Any) -> float: + """Delta E ITP color distance formula.""" + + i1, t1, p1 = util.no_nans(color.convert('ictcp').coords()) + i2, t2, p2 = util.no_nans(sample.convert('ictcp').coords()) + + # Equation (1) + return scalar * math.sqrt((i1 - i2) ** 2 + 0.25 * (t1 - t2) ** 2 + (p1 - p2) ** 2) diff --git a/pool/shard002/Python/0026136_AvatarHandle.py b/pool/shard002/Python/0026136_AvatarHandle.py new file mode 100644 index 0000000000000000000000000000000000000000..211122c39ebd3c165ee06303eb57a4ea07517601 --- /dev/null +++ b/pool/shard002/Python/0026136_AvatarHandle.py @@ -0,0 +1,24 @@ + + +class AvatarHandle: + dclassName = 'AvatarHandle' + + def getName(self): + if __dev__: + pass + return '' + + def isOnline(self): + if __dev__: + pass + return False + + def isUnderstandable(self): + if __dev__: + pass + return True + + def setTalkWhisper(self, fromAV, fromAC, avatarName, chat, mods, flags): + newText, scrubbed = localAvatar.scrubTalk(chat, mods) + base.talkAssistant.receiveWhisperTalk(fromAV, avatarName, fromAC, None, self.avatarId, self.getName(), newText, scrubbed) + return diff --git a/pool/shard002/Python/0026140_wizutils.py b/pool/shard002/Python/0026140_wizutils.py new file mode 100644 index 0000000000000000000000000000000000000000..54b51b30bb070d1462b530e3aafb5daba4e65245 --- /dev/null +++ b/pool/shard002/Python/0026140_wizutils.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- + +import os, sys +from PyQt5.QtWidgets import (QWizard, QMessageBox) +from PyQt5.QtGui import QPixmap +from PyQt5.QtCore import pyqtSlot, Qt + +try: + import odmltables + + have_odmltables = True +except: + have_odmltables = False + +from .settings import Settings + + +class OdmltablesWizard(QWizard): + def __init__(self, wizname, parent=None): + super(OdmltablesWizard, self).__init__(parent) + + self.wizname = wizname + self.settingsfile = os.path.join(os.path.expanduser("~"), + '.odmltables', + wizname.replace(' ', '').lower() + '.conf') + + # initialize settings + self.settings = Settings(self.settingsfile) + + # setting starting page of wizard + # self.setStartId(0) + + self.setOption(self.IndependentPages, False) + + # images won't show in Windows 7 if style not set + self.setWizardStyle(self.ModernStyle) + self.setOption(self.HaveHelpButton, True) + logo_filename = "odMLtables_100x100.png" + logo_dirs = [os.path.join(os.path.dirname(__file__), '..', '..', 'logo'), + os.path.join(sys.prefix, 'share/pixmaps')] + for logo_dir in logo_dirs: + filepath = os.path.join(logo_dir, logo_filename) + if os.path.exists(filepath): + self.setPixmap(QWizard.LogoPixmap, QPixmap(filepath)) + + # set up help messages + self._lastHelpMsg = '' + self._helpMsgs = self._createHelpMsgs() + self.helpRequested.connect(self._showHelp) + + self.setWindowTitle(self.tr(wizname)) + + def _createHelpMsgs(self): + raise NotImplementedError() + + @pyqtSlot() + def _showHelp(self): + # get the help message for the current page + msg = self._helpMsgs[self.currentId()] + # # if same as last message, display alternate message + # if msg == self._lastHelpMsg: + # msg = self._helpMsgs[self.NUM_PAGES + 1] + + doc_link = "

For detailed information about odMLtables refer to the " \ + "odMLtables " \ + "documentation.

" + + msgBox = QMessageBox() + msgBox.setWindowTitle("Help") + msgBox.setTextFormat(Qt.RichText) + msgBox.setText(msg + doc_link) + msgBox.exec_() + + # QMessageBox.information(self, + # self.tr(self.wizname), + # msg) + # self._lastHelpMsg = msg + + +def get_graphic_path(): + if have_odmltables: + data_path = os.path.join(os.path.dirname(odmltables.__file__), + 'gui', + 'graphics') + return data_path diff --git a/pool/shard002/Python/0026143_plot_mod-traveltime-2d.py b/pool/shard002/Python/0026143_plot_mod-traveltime-2d.py new file mode 100644 index 0000000000000000000000000000000000000000..86d23cb46e2a27086efc973ca1bbe83854599880 --- /dev/null +++ b/pool/shard002/Python/0026143_plot_mod-traveltime-2d.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# encoding: utf-8 + +r""" +Traveltime in 2D +---------------- +""" + +import numpy as np + +import pygimli as pg + +import pygimli.meshtools as mt +from pygimli.physics.traveltime import Refraction + +# Create geometry definition for the modelling domain +world = mt.createWorld(start=[-20, 0], end=[20, -16], layers=[-2, -8], + worldMarker=False) + +# Create a mesh from the geometry definition +mesh = mt.createMesh(world, quality=33, area=0.1, smooth=[1, 10]) + +pg.show(mesh, mesh.cellMarker(), label='marker') + +scheme = pg.physics.traveltime.createRAData(np.linspace(-15., 15., 31)) + +ra = Refraction() + +data = ra.simulate(mesh, np.array(mesh.cellMarker())*1000, + scheme, noiseLevel=0.01, noiseAbs=1e-5, verbose=1) +ra.showVA(data) +ra.showData(data) + +pg.wait() diff --git a/pool/shard002/Python/0026144_cmd.py b/pool/shard002/Python/0026144_cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..3276a8e40f5698bad23593b29b159abb086d2d76 --- /dev/null +++ b/pool/shard002/Python/0026144_cmd.py @@ -0,0 +1,76 @@ +"""Command line utility for mat4py. + +Provides a routine for converting Matlab MAT-files to/from JSON files. + +Call + + python -m mat4py.cmd -h + +to get help with command line usage. +""" + +import argparse +import json +import os + +from mat4py import loadmat, savemat + + +def main(): + # + # get arguments and invoke the conversion routines + # + + parser = argparse.ArgumentParser( + description='Convert Matlab ' + 'MAT-files to JSON formated text files, and the other way around.') + + parser.add_argument( + 'file', nargs='+', + help='path to a Matlab MAT-file or a JSON file') + parser.add_argument( + '--remove-input', action='store_const', const=True, + default=False, help='remove input file after conversion') + parser.add_argument( + '-f', '--force', action='store_const', const=True, + default=False, help='overwrite existing files when converting') + args = parser.parse_args() + + for path in args.file: + spl = os.path.splitext(path) + ext = spl[1].lower() + + if ext == '.mat': + dest = spl[0] + '.json' + try: + if os.path.exists(dest) and not args.force: + raise Exception('File {} already exists.'.format(dest)) + data = loadmat(path) + with open(dest, 'w') as fp: + json.dump(data, fp) + if args.remove_input: + os.remove(path) + except Exception as e: + print('Error: {}'.format(e)) + exit(1) + + elif ext == '.json': + dest = spl[0] + '.mat' + try: + if os.path.exists(dest) and not args.force: + raise Exception('File {} already exists.'.format(dest)) + with open(path) as fp: + data = json.load(fp) + savemat(dest, data) + if args.remove_input: + os.remove(path) + except RuntimeError as e: + print('Error: {}'.format(e)) + exit(1) + else: + print('Unsupported file extension on file: {0}'.format(path)) + exit(1) + + +if __name__ == '__main__': + main() diff --git a/pool/shard002/Python/0026147_fibonacci.py b/pool/shard002/Python/0026147_fibonacci.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c487ddbb061fe7701baffbd8021a14d62882d5 --- /dev/null +++ b/pool/shard002/Python/0026147_fibonacci.py @@ -0,0 +1,48 @@ +""" +Fibonacci numbers function. +""" + +# Copyright 2014 The University of Edinburgh. +# +# 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 sys + +def fibonacci(n): + """ + Calculate the Fibonacci number of the given integer. + @param n If n <= 0 then 0 is assumed. + @return fibonacci number. + """ + if n <= 0: + return 0 + elif n == 1: + return 1 + else: + return fibonacci(n - 1) + fibonacci(n - 2) + +def print_usage(): + """ Print usage information. """ + print("Usage: python fibonacci.py N") + print(" where N >= 0") + +if __name__ == '__main__': + if (len(sys.argv) < 2): + print_usage() + exit(1) + n = int(sys.argv[1]) + if (n < 0): + print_usage() + exit(2) + fib = fibonacci(n) + print("fibonacci(%d) = %d" % (n, fib)) diff --git a/pool/shard002/Python/0026149_problem2.py b/pool/shard002/Python/0026149_problem2.py new file mode 100644 index 0000000000000000000000000000000000000000..49a0f4a5ebdf1d35d6bdd30a25e47ba63134d538 --- /dev/null +++ b/pool/shard002/Python/0026149_problem2.py @@ -0,0 +1,20 @@ +# Krystal Kwan +# 2/14/2016 +# Print a rectangle according to the user's output + +while True: + print "This program will print a rectangle according to your input:" + print "What is the height?" + h = int(raw_input("> ")) + print "What is the length?" + l = int(raw_input("> ")) + for a in range(0,h): + for b in range(0,l): + print "*", + print + print "Do you want to continue (y/n)?" + ans = str(raw_input("> ")) + if ans == "y": + continue + else: + break diff --git a/pool/shard002/Python/0026152_CheckSum.py b/pool/shard002/Python/0026152_CheckSum.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9e90f783767f837182057dbb32530911d362c4 --- /dev/null +++ b/pool/shard002/Python/0026152_CheckSum.py @@ -0,0 +1,143 @@ +# Copyright 2002 by Yves Bastide and Brad Chapman. +# Copyright 2007 by Sebastian Bassi +# All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +"""Functions to calculate assorted sequence checksums.""" + +# crc32, crc64, gcg, and seguid +# crc64 is adapted from BioPerl + +from __future__ import print_function + +from binascii import crc32 as _crc32 +from Bio._py3k import _as_bytes + +__docformat__ = "restructuredtext en" + + +def crc32(seq): + """Returns the crc32 checksum for a sequence (string or Seq object).""" + # NOTE - On Python 2 returns a signed int, on Python 3 it is unsigned + # Docs suggest should use crc32(x) & 0xffffffff for consistency. + # TODO - Should we return crc32(x) & 0xffffffff here? + try: + # Assume its a Seq object + return _crc32(_as_bytes(str(seq))) + except AttributeError: + # Assume its a string/unicode + return _crc32(_as_bytes(seq)) + + +def _init_table_h(): + _table_h = [] + for i in range(256): + l = i + part_h = 0 + for j in range(8): + rflag = l & 1 + l >>= 1 + if part_h & 1: + l |= (1 << 31) + part_h >>= 1 + if rflag: + part_h ^= 0xd8000000 + _table_h.append(part_h) + return _table_h + +# Initialisation +_table_h = _init_table_h() + + +def crc64(s): + """Returns the crc64 checksum for a sequence (string or Seq object).""" + crcl = 0 + crch = 0 + for c in s: + shr = (crch & 0xFF) << 24 + temp1h = crch >> 8 + temp1l = (crcl >> 8) | shr + idx = (crcl ^ ord(c)) & 0xFF + crch = temp1h ^ _table_h[idx] + crcl = temp1l + + return "CRC-%08X%08X" % (crch, crcl) + + +def gcg(seq): + """Returns the GCG checksum (int) for a sequence (string or Seq object). + + Given a nucleotide or amino-acid secuence (or any string), + returns the GCG checksum (int). Checksum used by GCG program. + seq type = str. + + Based on BioPerl GCG_checksum. Adapted by Sebastian Bassi + with the help of John Lenton, Pablo Ziliani, and Gabriel Genellina. + + All sequences are converted to uppercase. + """ + try: + # Assume its a Seq object + seq = str(seq) + except AttributeError: + # Assume its a string + pass + index = checksum = 0 + for char in seq: + index += 1 + checksum += index * ord(char.upper()) + if index == 57: + index = 0 + return checksum % 10000 + + +def seguid(seq): + """Returns the SEGUID (string) for a sequence (string or Seq object). + + Given a nucleotide or amino-acid secuence (or any string), + returns the SEGUID string (A SEquence Globally Unique IDentifier). + seq type = str. + + For more information about SEGUID, see: + http://bioinformatics.anl.gov/seguid/ + DOI: 10.1002/pmic.200600032 + """ + import hashlib + import base64 + m = hashlib.sha1() + try: + # Assume it's a Seq object + seq = str(seq) + except AttributeError: + # Assume it's a string + pass + m.update(_as_bytes(seq.upper())) + try: + # For Python 3+ + return base64.encodebytes(m.digest()).decode().replace("\n", "").rstrip("=") + except AttributeError: + pass + # For all other Pythons + return base64.b64encode(m.digest()).rstrip("=") + + +if __name__ == "__main__": + print("Quick self test") + + str_light_chain_one = "QSALTQPASVSGSPGQSITISCTGTSSDVGSYNLVSWYQQHPGK" \ + + "APKLMIYEGSKRPSGVSNRFSGSKSGNTASLTISGLQAEDEADY" \ + + "YCSSYAGSSTLVFGGGTKLTVL" + + str_light_chain_two = "QSALTQPASVSGSPGQSITISCTGTSSDVGSYNLVSWYQQHPGK" \ + + "APKLMIYEGSKRPSGVSNRFSGSKSGNTASLTISGLQAEDEADY" \ + + "YCCSYAGSSTWVFGGGTKLTVL" + + assert crc64(str_light_chain_one) == crc64(str_light_chain_two) + assert 'CRC-44CAAD88706CC153' == crc64(str_light_chain_one) + + assert 'BpBeDdcNUYNsdk46JoJdw7Pd3BI' == seguid(str_light_chain_one) + assert 'X5XEaayob1nZLOc7eVT9qyczarY' == seguid(str_light_chain_two) + + print("Done") diff --git a/pool/shard002/Python/0026153_0002_auto_20160815_1814.py b/pool/shard002/Python/0026153_0002_auto_20160815_1814.py new file mode 100644 index 0000000000000000000000000000000000000000..bb597fe3da5123d0be40c5e3ded468cdebcc967a --- /dev/null +++ b/pool/shard002/Python/0026153_0002_auto_20160815_1814.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import migrations, models +import DrydenMusicApp.models +from django.utils.timezone import utc +import storages.backends.s3boto +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('DrydenMusicApp', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='music', + name='added', + field=models.DateTimeField(default=datetime.datetime(2016, 8, 15, 18, 14, 43, 265487, tzinfo=utc), auto_now_add=True), + preserve_default=False, + ), + migrations.AddField( + model_name='music', + name='first_line', + field=models.CharField(max_length=200, blank=True), + ), + migrations.AddField( + model_name='music', + name='title', + field=models.CharField(max_length=200, blank=True), + ), + migrations.AlterField( + model_name='music', + name='music_file', + field=models.FileField(null=True, upload_to=DrydenMusicApp.models.data_file_path, storage=storages.backends.s3boto.S3BotoStorage(acl='private', location='music_files'), blank=True), + ), + ] diff --git a/pool/shard002/Python/0026155_dfs.py b/pool/shard002/Python/0026155_dfs.py new file mode 100644 index 0000000000000000000000000000000000000000..879edae61783b5d770b493ed8cd66e713eccdd63 --- /dev/null +++ b/pool/shard002/Python/0026155_dfs.py @@ -0,0 +1,104 @@ +import decimal + +class Coord: + def __init__(self, lat, lon): + self.lat = lat + self.lon = lon + +class Way: + def __init__(self, source, target): + self.source = source + self.target = target + + +f = open('nodes', 'r') +lat = None +nodes = [] +for line in f: + loaded = decimal.Decimal(line) + if lat is None: + lat = loaded + else: + nodes.append(Coord(lat, loaded)) + lat = None +f.close() + +f = open('ways', 'r') +source = None +ways = [] +for line in f: + loaded = int(line) + if source is None: + source = loaded + else: + ways.append(Way(source, loaded)) + source = None +f.close() + +before = """ + + + + Leaflet Quick Start Guide Example + + + + + + + + +
+ + + + + +""" +print before +way = ways[80] +print "[" + str(nodes[way.source].lat) + ", " + str(nodes[way.source].lon) + "]," +print "[" + str(nodes[way.target].lat) + ", " + str(nodes[way.target].lon) + "]" +""" [51.509, -0.08], + [51.503, -0.06], + [51.51, -0.047] +""" +print after \ No newline at end of file diff --git a/pool/shard002/Python/0026157_main.py b/pool/shard002/Python/0026157_main.py new file mode 100644 index 0000000000000000000000000000000000000000..202609d9740464d9ef7d1c06a08a6193a15fc6d0 --- /dev/null +++ b/pool/shard002/Python/0026157_main.py @@ -0,0 +1,38 @@ +class AccountSqlite: + def get_password(self, id): + account = { + 'kent': 'abcd', + 'alex': 'xyz' + } + try: + password = account[id] + except: + password = None + return password + + +class Hash: + def get_hash(self, password): + return 'abcd' if password == '123' else None + +class MobileManager: + def send_text(self, user, msg): + print '{0} sent a message: {1}'.format(user, msg) + + +class ValidateAccount: + def __init__(self, account_db, passwd_hash, mobile_manager): + self.account_db = account_db + self.passwd_hash = passwd_hash + self.mobile_manager = mobile_manager + + def check_account(self, id, password): + password_by_id = self.account_db.get_password(id) + password_by_hash = self.passwd_hash.get_hash(password) + if password_by_id == password_by_hash: + self.mobile_manager.send_text(id, 'Account Valid') # send sms + return True + else: + self.mobile_manager.send_text(id, 'Account Not Valid') # send sms + return False + \ No newline at end of file diff --git a/pool/shard002/Python/0026158_test_signal_handlers.py b/pool/shard002/Python/0026158_test_signal_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..138927acfaf811255af73c064ff1d20b7e175f50 --- /dev/null +++ b/pool/shard002/Python/0026158_test_signal_handlers.py @@ -0,0 +1,82 @@ +from django.db import transaction +from django.test import TransactionTestCase, override_settings + +from wagtail.core.models import Collection +from wagtail.images import get_image_model, signal_handlers +from wagtail.images.tests.utils import get_test_image_file + + +class TestFilesDeletedForDefaultModels(TransactionTestCase): + """ + Because we expect file deletion to only happen once a transaction is + successfully committed, we must run these tests using TransactionTestCase + per the following documentation: + + Django's TestCase class wraps each test in a transaction and rolls back that + transaction after each test, in order to provide test isolation. This means + that no transaction is ever actually committed, thus your on_commit() + callbacks will never be run. If you need to test the results of an + on_commit() callback, use a TransactionTestCase instead. + https://docs.djangoproject.com/en/1.10/topics/db/transactions/#use-in-tests + """ + + def setUp(self): + # Required to create root collection because the TransactionTestCase + # does not make initial data loaded in migrations available and + # serialized_rollback=True causes other problems in the test suite. + # ref: https://docs.djangoproject.com/en/1.10/topics/testing/overview/#rollback-emulation + Collection.objects.get_or_create( + name="Root", + path="0001", + depth=1, + numchild=0, + ) + + def test_image_file_deleted_oncommit(self): + with transaction.atomic(): + image = get_image_model().objects.create( + title="Test Image", file=get_test_image_file() + ) + filename = image.file.name + self.assertTrue(image.file.storage.exists(filename)) + image.delete() + self.assertTrue(image.file.storage.exists(filename)) + self.assertFalse(image.file.storage.exists(filename)) + + def test_rendition_file_deleted_oncommit(self): + with transaction.atomic(): + image = get_image_model().objects.create( + title="Test Image", file=get_test_image_file() + ) + rendition = image.get_rendition("original") + filename = rendition.file.name + self.assertTrue(rendition.file.storage.exists(filename)) + rendition.delete() + self.assertTrue(rendition.file.storage.exists(filename)) + self.assertFalse(rendition.file.storage.exists(filename)) + + +@override_settings(WAGTAILIMAGES_IMAGE_MODEL="tests.CustomImage") +class TestFilesDeletedForCustomModels(TestFilesDeletedForDefaultModels): + def setUp(self): + # Required to create root collection because the TransactionTestCase + # does not make initial data loaded in migrations available and + # serialized_rollback=True causes other problems in the test suite. + # ref: https://docs.djangoproject.com/en/1.10/topics/testing/overview/#rollback-emulation + Collection.objects.get_or_create( + name="Root", + path="0001", + depth=1, + numchild=0, + ) + + #: Sadly signal receivers only get connected when starting django. + #: We will re-attach them here to mimic the django startup behavior + #: and get the signals connected to our custom model.. + signal_handlers.register_signal_handlers() + + def test_image_model(self): + cls = get_image_model() + self.assertEqual( + "%s.%s" % (cls._meta.app_label, cls.__name__), "tests.CustomImage" + ) diff --git a/pool/shard002/Python/0026160_admin.py b/pool/shard002/Python/0026160_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..19b6730a2bb1594829a8b4c935b70a200e3666e3 --- /dev/null +++ b/pool/shard002/Python/0026160_admin.py @@ -0,0 +1,147 @@ +from django.contrib.admin.options import ModelAdmin, csrf_protect_m +from django.contrib.admin.views.main import ChangeList +from django.db import transaction +from django.utils.translation import ugettext_lazy as _ + + +def textual(title, ordering_field=None): + """ + Fallbacks textual field to '---' instead of (None) in admin. + + Sets proper title using ``title`` and if specified also ``admin_order_field`` + using ``ordering_field`` attribute. + """ + def decorator(func): + def wraps(self, obj): + result = func(self, obj) + return result if result else u'---' + + wraps.short_description = title + wraps.allow_tags = True + + if ordering_field: + wraps.admin_order_field = ordering_field + + return wraps + return decorator + + +class BorisChangeList(ChangeList): + """Change list_display with respect to request.""" + + remove_in_popup = ('actions_display',) + + def __init__(self, request, *args, **kwargs): + super(BorisChangeList, self).__init__(request, *args, **kwargs) + + # Display different buttons based on whether we render a pop-up window. + if 'pop' in request.GET: + if isinstance(self.list_display, tuple): + self.list_display = list(self.list_display) + self.list_display.insert(0, 'select_link') + self.list_display = filter(lambda x: x not in self.remove_in_popup, + self.list_display) + + +class BorisBaseAdmin(ModelAdmin): + """ + Adds ``list_actions`` to simplify addition of actions to changelist rows. + """ + list_actions = ('change_button',) + + def __init__(self, *args, **kwargs): + self.list_display += ('actions_display',) + super(BorisBaseAdmin, self).__init__(*args, **kwargs) + + def get_changelist(self, request, **kwargs): + return BorisChangeList + + def actions_display(self, obj): + return ''.join(getattr(self, a)(obj) for a in self.list_actions) + actions_display.allow_tags = True + actions_display.short_description = _(u'Akce') + + def change_button(self, obj): + return u'%s' % ( + obj.get_admin_url(), _('upravit')) + + def select_link(self, obj): + return u'%s' % ( + '%s/' % obj.pk, obj.pk, _('vybrat')) + select_link.allow_tags = True + select_link.short_description = '' + + def show_save(self, obj): + if not obj or not obj.pk: + return True + return False + + def show_save_as_new(self, obj): + return False + + def show_save_and_continue(self, obj): + return True + + def show_save_and_add_another(self, obj): + return False + + def force_show_delete(self, obj): + return False + + def button_captions(self, obj): + """ + Specify various button captions. + + Override to change the captions. The default values are in the + templates/admin/submit_line.html template. Below dictionary serves + to document all possible captions. + + """ + return { + 'BO_SAVE_CAPTION': '', + 'BO_SAVE_AS_NEW_CAPTION': '', + 'BO_SAVE_AND_CONT_CAPTION': '', + 'BO_SAVE_AND_ADD_ANOTHER_CAPTION': '', + 'BO_DELETE_CAPTION': '', + } + + @csrf_protect_m + @transaction.atomic + def change_view(self, request, object_id, extra_context=None): + obj = self.get_object(request, object_id) + buttons_context = { + 'BO_SHOW_SAVE': self.show_save(obj), + 'BO_SHOW_SAVE_AS_NEW': self.show_save_as_new(obj), + 'BO_SHOW_SAVE_AND_CONT': self.show_save_and_continue(obj), + 'BO_SHOW_SAVE_AND_ADD_ANOTHER': self.show_save_and_add_another(obj), + 'BO_FORCE_SHOW_DELETE': self.force_show_delete(obj), + } + buttons_context.update(self.button_captions(obj)) + if extra_context is not None: + extra_context.update(buttons_context) + else: + extra_context = buttons_context + return super(BorisBaseAdmin, self).change_view(request, object_id, extra_context=extra_context) + + @csrf_protect_m + @transaction.atomic + def add_view(self, request, form_url='', extra_context=None): + empty_obj = self.model() + buttons_context = { + 'BO_SHOW_SAVE': self.show_save(empty_obj), + 'BO_SHOW_SAVE_AS_NEW': self.show_save_as_new(empty_obj), + 'BO_SHOW_SAVE_AND_CONT': self.show_save_and_continue(empty_obj), + 'BO_SHOW_SAVE_AND_ADD_ANOTHER': self.show_save_and_add_another( + empty_obj), + 'BO_FORCE_SHOW_DELETE': self.force_show_delete(empty_obj) + } + buttons_context.update(self.button_captions(empty_obj)) + if extra_context is not None: + extra_context.update(buttons_context) + else: + extra_context = buttons_context + return super(BorisBaseAdmin, self).add_view(request, form_url, extra_context=extra_context) diff --git a/pool/shard002/Python/0026163_handlers.py b/pool/shard002/Python/0026163_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..8d7bdd149a5d2a10d72f8c170f39d431e2aabcc3 --- /dev/null +++ b/pool/shard002/Python/0026163_handlers.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- + +import re +from django.db.models import get_model +from django.conf import settings +from transifex.projects.signals import project_created, project_deleted +from transifex.projects.models import Project + +def outsource_to_mozilla(sender, **kwargs): + """ + Outsources translation of the newborn project to general Mozilla project + """ + try: + mozilla = Project.objects.get(slug='mozilla') + sender.outsource = mozilla + sender.save() + except Project.DoesNotExist: + pass + +def connect(): + project_created.connect(outsource_to_mozilla) diff --git a/pool/shard002/Python/0026164_Question_0006_ZigZag_Conversion.py b/pool/shard002/Python/0026164_Question_0006_ZigZag_Conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..963e8f3f9ae56d43d8e1917ea6db917243faebcf --- /dev/null +++ b/pool/shard002/Python/0026164_Question_0006_ZigZag_Conversion.py @@ -0,0 +1,23 @@ +#!/usr/bin/python +# coding: utf-8 + +class Solution(object): + def convert(self, s, numRows): + """ + :type s: str + :type numRows: int + :rtype: str + """ + if numRows < 2: + return s + res = [] + lag = 2 * (numRows - 1) + num = len(s) + for i in range(numRows): + for j in range(i, num, lag): + res.append(s[j]) + if i > 0 and i < numRows - 1: + n = j + lag - 2 * i + if n < num: + res.append(s[n]) + return "".join(res) diff --git a/pool/shard002/Python/0026168_crack_8_3.py b/pool/shard002/Python/0026168_crack_8_3.py new file mode 100644 index 0000000000000000000000000000000000000000..317d1060ef0c11f0a480b9e4f1ad6e3ed6e3eba9 --- /dev/null +++ b/pool/shard002/Python/0026168_crack_8_3.py @@ -0,0 +1,21 @@ +import copy + +def subset(sets): + if len(sets) > 1: + sub = subset(sets[1:]) + temp = copy.deepcopy(sub) + for s in sub: + t = s[:] + t.append(sets[0]) + temp.append(t) + sub = copy.deepcopy(temp) + return sub + elif len(sets) == 1: + sub = [] + sub.append([]) + sub.append(sets) + return sub + +if __name__ == '__main__': + test = [1,2,3,4] + print subset(test) \ No newline at end of file diff --git a/pool/shard002/Python/0026170_XenAPIDomain.py b/pool/shard002/Python/0026170_XenAPIDomain.py new file mode 100644 index 0000000000000000000000000000000000000000..1ca2307c27749da5585818698ef70c840b5ab730 --- /dev/null +++ b/pool/shard002/Python/0026170_XenAPIDomain.py @@ -0,0 +1,183 @@ +#!/usr/bin/python +""" + Copyright (C) International Business Machines Corp., 2005 + Author: Stefan Berger + + Based on XenDomain.py by Dan Smith + + 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; under 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. + + 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 sys +from XmTestLib import * +from types import DictType + + +class XenAPIConfig: + """An object to help create a VM configuration usable via Xen-API""" + def __init__(self): + self.opts = {} + #Array to translate old option to new ones + self.opttrlate = { 'name' : 'name_label' , + 'memory' : [ 'memory_static_max' , + 'memory_static_min' , + 'memory_dynamic_min', + 'memory_dynamic_max' ], + 'kernel' : 'PV_kernel', + 'ramdisk': 'PV_ramdisk', + 'root' : 'PV_args', + 'extra' : 'PV_args' } + + def setOpt(self, name, value): + """Set an option in the config""" + if name == "memory": + value <<= 20 + if name == "root": + value = "root=" + value + if name in self.opttrlate.keys(): + _name = self.opttrlate[name] + else: + _name = name + + if isinstance(_name, list): + for _n in _name: + self.opts[_n] = value + else: + if not self.opts.get(_name) or \ + not _name in [ "PV_args" ]: + self.opts[_name] = value + else: + self.opts[_name] += " " + value + + def getOpt(self, name): + """Return the value of a config option""" + if name in self.opts.keys(): + return self.opts[name] + else: + return None + + def setOpts(self, opts): + """Batch-set options from a dictionary""" + for k, v in opts.items(): + self.setOpt(k, v) + + def getOpts(self): + return self.opts + + +class XenAPIDomain(XenDomain): + + def __init__(self, name=None, config=None): + if name: + self.name = name + else: + self.name = getUniqueName() + + self.config = config + self.console = None + self.netEnv = "bridge" + + self.session = xapi.connect() + try: + self.vm_uuid = self.session.xenapi.VM.create(self.config.getOpts()) + addXAPIDomain(self.vm_uuid) + except: + raise DomainError("Could not create VM config file for " + "managed domain.") + + #Only support PV for now. + self.type = "PV" + + def start(self, noConsole=False, startpaused=False): + #start the VM + session = self.session + if self.vm_uuid: + try: + session.xenapi.VM.start(self.vm_uuid, startpaused) + except: + raise DomainError("Could not start domain") + else: + raise DomainError("VM has no UUID - does VM config exist?") + + if startpaused: + return + + if self.getDomainType() == "HVM": + waitForBoot() + + if self.console and noConsole == True: + self.closeConsole() + + elif self.console and noConsole == False: + return self.console + + elif not self.console and noConsole == False: + return self.getConsole() + + def stop(self): + if self.vm_uuid: + self.session.xenapi.VM.hard_shutdown(self.vm_uuid) + else: + raise DomainError("VM has no UUID - does VM config exist?") + + def destroy(self): + #Stop VM first. + self.stop() + if self.vm_uuid: + self.session.xenapi.VM.destroy(self.vm_uuid) + delXAPIDomain(self.vm_uuid) + else: + raise DomainError("VM has no UUID - does VM config exist?") + + def get_uuid(self): + return self.vm_uuid + + def newDevice(self, Device, *args): + raise DomainError("No support for newDevice().") + + def removeDevice(self, id): + raise DomainError("No support for removeDevice().") + + def removeAllDevices(self, id): + raise DomainError("No support for removeAllDevices().") + + def isRunning(self): + return isDomainRunning(self.name) + + def getDevice(self, id): + raise DomainError("No support for getDevice().") + + +class XmTestAPIDomain(XenAPIDomain): + + """Create a new managed xm-test domain + @param name: The requested domain name + @param extraConfig: Additional configuration options + @param baseConfig: The initial configuration defaults to use + """ + def __init__(self, name=None, extraConfig=None, + baseConfig=arch.configDefaults): + config = XenAPIConfig() + config.setOpts(baseConfig) + if extraConfig: + config.setOpts(extraConfig) + + if name: + config.setOpt("name_label", name) + elif not config.getOpt("name_label"): + config.setOpt("name_label", getUniqueName()) + + XenAPIDomain.__init__(self, config.getOpt("name_label"), + config=config) diff --git a/pool/shard002/Python/0026172_test_cases.py b/pool/shard002/Python/0026172_test_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..b1b0ed5187d5ed06d6bc0cbfc000e7121d9ad150 --- /dev/null +++ b/pool/shard002/Python/0026172_test_cases.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- + +from django.core.management import call_command +from django.test import TestCase + +import supervisor.xmlrpc +import xmlrpclib + + +class CeleryMonTestCase(TestCase): + def test_a_is_down(self): + server = xmlrpclib.ServerProxy( + 'http://127.0.0.1', + transport=supervisor.xmlrpc.SupervisorTransport( + None, None, 'unix:///var/run/supervisor.sock') + ) + + self.assertEquals( + server.supervisor.getProcessInfo('default').get('state'), 20) + self.assertEquals( + server.supervisor.getProcessInfo('mail').get('state'), 20) + + server.supervisor.stopProcess('default') + + self.assertEquals( + server.supervisor.getProcessInfo('default').get('state'), 0) + self.assertEquals( + server.supervisor.getProcessInfo('mail').get('state'), 20) + + call_command('check_celery_state') + + self.assertEquals( + server.supervisor.getProcessInfo('default').get('state'), 20) + self.assertEquals( + server.supervisor.getProcessInfo('mail').get('state'), 20) diff --git a/pool/shard002/Python/0026183_services.py b/pool/shard002/Python/0026183_services.py new file mode 100644 index 0000000000000000000000000000000000000000..ffbd4ebb532f5fb63579b1a86cd4f3805908b09f --- /dev/null +++ b/pool/shard002/Python/0026183_services.py @@ -0,0 +1,68 @@ +# Copyright (C) 2010-2014 GRNET S.A. +# +# 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 copy import deepcopy +from synnefo.lib import join_urls +from urlparse import urlparse + + +def fill_endpoints(services, base_url): + for name, service in services.iteritems(): + prefix = service['prefix'] + endpoints = service['endpoints'] + for endpoint in endpoints: + version = endpoint['versionId'] + publicURL = endpoint['publicURL'] + if publicURL is not None: + continue + + publicURL = join_urls(base_url, prefix, version).rstrip('/') + endpoint['publicURL'] = publicURL + + +def filter_public(services): + public_services = {} + for name, service in services.iteritems(): + if service.get('public', False): + public_services[name] = deepcopy(service) + return public_services + + +def get_public_endpoint(services, service_type, version=None): + found_endpoints = {} + for service_name, service in services.iteritems(): + if service_type != service['type']: + continue + + for endpoint in service['endpoints']: + endpoint_version = endpoint['versionId'] + if version is not None: + if version != endpoint_version: + continue + found_endpoints[endpoint_version] = endpoint + + if not found_endpoints: + m = "No endpoint found for service type '{0}'".format(service_type) + if version is not None: + m += " and version '{0}'".format(version) + raise ValueError(m) + + selected = sorted(found_endpoints.keys())[-1] + return found_endpoints[selected]['publicURL'] + + +def get_service_path(services, service_type, version=None): + service_url = get_public_endpoint(services, service_type, version=version) + return urlparse(service_url).path.rstrip('/') diff --git a/pool/shard002/Python/0026185_package.py b/pool/shard002/Python/0026185_package.py new file mode 100644 index 0000000000000000000000000000000000000000..c339abf1f038c36b2a2035651bf279931cfe0bf9 --- /dev/null +++ b/pool/shard002/Python/0026185_package.py @@ -0,0 +1,37 @@ +# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other +# Spack Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) + +from spack import * + + +class Lis(AutotoolsPackage): + """Lis (Library of Iterative Solvers for linear systems, + pronounced [lis]) is a parallel software library for + solving discretized linear equations and eigenvalue + problems that arise in the numerical solution of partial + differential equations using iterative methods.""" + + homepage = "https://www.ssisc.org/lis/index.en.html" + url = "https://www.ssisc.org/lis/dl/lis-2.0.27.zip" + + version('2.0.27', sha256='85f32f4abbc94d1b40b22c10b915170271b19822b6aa6939b1cb295f6e455237') + + variant('mpi', default=False, description='Build with MPI library') + variant('omp', default=False, description='Build with openMP library') + variant('f90', default=False, description='enable FORTRAN 90 compatible interfaces') + + depends_on('mpi', when='+mpi') + + def configure_args(self): + config_args = [] + config_args.extend(self.enable_or_disable('mpi')) + config_args.extend(self.enable_or_disable('omp')) + config_args.extend(self.enable_or_disable('f90')) + + if self.spec.satisfies('%fj'): + config_args.append('CLIBS=-lm') + config_args.append('FCLDFLAGS=-mlcmain=main') + + return config_args diff --git a/pool/shard002/Python/0026201_import_existing_files.py b/pool/shard002/Python/0026201_import_existing_files.py new file mode 100644 index 0000000000000000000000000000000000000000..83e8c69009c94aa136e7521485cd82a07f3c7f1e --- /dev/null +++ b/pool/shard002/Python/0026201_import_existing_files.py @@ -0,0 +1,76 @@ +import os +import re + +from filer.models import File, Image, Folder +from filer_addons.filer_utils.management.commands.subcommands.base import SubcommandsCommand + + +def is_image(filename): + name, ext = os.path.splitext(filename) + if ext.lower()[1:] in ['jpg', 'jpeg', 'gif', 'png', 'tif', 'tiff']: + return True + + +# TODO: via setting +file_exclude_pattern = r'(_fb_thumb\.)|(_fancybox_thumb\.)|(_home_image\.)|(_left_col_small\.)' \ + r'|(_partner\.)|(_people\.)|(_small\.)|(_thumbnail\.)' +file_exclude_pattern = r'_q85' + +folder_exclude_pattern = r'(_big)|(_thumb)' + + +class ImportExistingFilesCommand(SubcommandsCommand): + help_string = "Import existing files not currently in filer db, but on " \ + "filesystem. Must use --force, if you have existing files" \ + "in your database" + command_name = 'import_existing_files' + + def add_arguments(self, parser): + parser.add_argument( + '--force', + action='store_true', + dest='force', + default=False, + help='Force import, with existing content in database.', + ) + + def handle(self, *args, **options): + print(File.objects.count()) + if not options.get('force', False) and File.objects.count(): + raise Exception('Must use --force, you have existing files in db!') + + from filer import settings as filer_settings + self.storage_public = filer_settings.FILER_PUBLICMEDIA_STORAGE + self.prefix_public = filer_settings.FILER_STORAGES['public']['main']['UPLOAD_TO_PREFIX'] + + def walk(absdir, reldir, db_folder): + print("walk %s" % db_folder) + storage = self.storage_public + child_dirs, files = storage.listdir(absdir) + for filename in files: + matches = [] + if file_exclude_pattern: + matches = re.findall(file_exclude_pattern, filename) + if not len(matches): + filename_with_relpath = os.path.join(reldir, filename) + # media_root = os.path.join(self.storage_public.location) + # filename_with_abspath = os.path.join(media_root, filename_with_relpath) + # django_file = DjangoFile(open(filename_with_abspath, 'rb'), name=filename) + file_cls = File + if is_image(filename): + file_cls = Image + file_cls.objects.create( + original_filename=filename, + folder=db_folder, + file=filename_with_relpath, + is_public=True, + ) + for child in child_dirs: + kwargs = {} + if db_folder: + kwargs['parent'] = db_folder + new_folder, created = Folder.objects.get_or_create(name=child, **kwargs) + walk(os.path.join(absdir, child), os.path.join(reldir, child), new_folder) + + public_path = os.path.join(self.storage_public.location, self.prefix_public) + walk(public_path, self.prefix_public, None) diff --git a/pool/shard002/Python/0026205_rule3_1.py b/pool/shard002/Python/0026205_rule3_1.py new file mode 100644 index 0000000000000000000000000000000000000000..7bdde203a48d7d09556d35b4b44e99537158a439 --- /dev/null +++ b/pool/shard002/Python/0026205_rule3_1.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- + +from rules.rule import * + +class Rule(KLCRule): + """ + Create the methods check and fix to use with the kicad lib files. + """ + def __init__(self, component): + super(Rule, self).__init__(component, 'Rule 3.1', 'Using a 100mils grid, pin ends and origin must lie on grid nodes (IEC-60617).') + + def check(self): + """ + Proceeds the checking of the rule. + The following variables will be accessible after checking: + * violating_pins + """ + self.violating_pins = [] + for pin in self.component.pins: + posx = int(pin['posx']) + posy = int(pin['posy']) + if (posx % 100) != 0 or (posy % 100) != 0: + self.violating_pins.append(pin) + self.verboseOut(Verbosity.HIGH, Severity.ERROR, 'pin: {0} ({1}), {2}'.format(pin['name'], pin['num'], positionFormater(pin))) + + return True if len(self.violating_pins) > 0 else False + + def fix(self): + """ + Proceeds the fixing of the rule, if possible. + """ + self.verboseOut(Verbosity.NORMAL, Severity.INFO, "FIX: not yet supported" ) + # TODO diff --git a/pool/shard002/Python/0026206_Estimation-labeled-l5.py b/pool/shard002/Python/0026206_Estimation-labeled-l5.py new file mode 100644 index 0000000000000000000000000000000000000000..401e66c5df7bb8801ac04fc62eaf9e80ceb9aa64 --- /dev/null +++ b/pool/shard002/Python/0026206_Estimation-labeled-l5.py @@ -0,0 +1,83 @@ +# Copyright (C) 2017 Zhixian MA + +import sys +import os +import pickle +import numpy as np + +import utils +import ConvNet +import ConvAE_FT + +def pos_to_line(label_pos): + return np.max(label_pos,axis=1) + +def main(argv): + + # folder for saving + subfold = argv[1] + if not os.path.exists(subfold): + os.mkdir(subfold) + # load data + fname = '../LRG-fits/data/lrg_171020/sample-LRG-120-120-10-c3.pkl' + with open(fname, 'rb') as fp: + datadict = pickle.load(fp) + X_raw = datadict['data'] + + # Reshape and generate train and test dataset + rs = 120 + # normalization and whitening + ''' + with open("../nets/norm_params.pkl", 'rb') as fp: + normparam = pickle.load(fp) + X_max = normparam["X_max"] + X_min = normparam["X_min"] + X_mean = normparam["X_mean"] + + X_train_pre = X_raw + X_train_pre = (X_train_pre - X_min) / (X_max - X_min) + X_in = X_train_pre.reshape(-1,rs,rs,1) + X_mean = np.mean(X_train_pre) + X_w = X_in - X_mean # Whitening? + ''' + X_w = X_raw.reshape(-1,rs,rs,1).astype('float32') + + numclass = 2 + encode_nodes = 64 + cnn = ConvNet.ConvNet(input_shape=X_w.shape, + kernel_size=[3,3,3,3,3], + kernel_num = [8,8,16,32,32], + fc_nodes=[], encode_nodes=encode_nodes, + padding=('SAME','SAME'), + stride=(2,2), + numclass = numclass, + sess = None, + name = None) + cnn.cae_build() + cnn.cnn_build(learning_rate=0.001) # In order to init the weights + + + foldname = "{0}/net_l5_140".format(subfold) + name = "net_l5.pkl" + cnn.sess, cnn.name = utils.load_net(os.path.join(foldname, name)) + + # estimate + label, label_pos = cnn.cnn_predict(img=X_w) + label_new_pos = pos_to_line(label_pos) + + # save result + savefold = "{0}/est_labeled".format(subfold) + if not os.path.exists(savefold): + os.mkdir(savefold) + savepath = "est_l5.pkl" + savedict = {"label_raw": np.array(datadict['type']), + "z": np.array(datadict['redshift']), + "snvss": np.array(datadict['snvss']), + "name": np.array(datadict['name']), + "label_est": label, + "label_pos": label_new_pos} + with open(os.path.join(savefold,savepath), 'wb') as fp: + pickle.dump(savedict, fp) + +if __name__ == "__main__": + main(sys.argv) diff --git a/pool/shard002/Python/0026216_dfu.py b/pool/shard002/Python/0026216_dfu.py new file mode 100644 index 0000000000000000000000000000000000000000..6d8fc154ec1fced559f578d61ecf02848a2080f8 --- /dev/null +++ b/pool/shard002/Python/0026216_dfu.py @@ -0,0 +1,59 @@ +from __future__ import print_function +from __future__ import absolute_import +from __future__ import unicode_literals +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import object +import os +import esptool +import urllib.request + +from .consts import IotsaError, VERBOSE + +class DFU(object): + """Handle Resetting flash and uploading initial binary over Serial connection (or USB)""" + def __init__(self, port=None): + self.port = port + + def _run(self, cmd, args=[], nostub=False): + """Run a single esptool command""" + command = ["--after", "no_reset"] + if self.port: + command += ["--port", self.port] + if nostub: + command += ["--no-stub"] + command += [cmd] + command += args + try: + esptool.main(command) + except esptool.FatalError as e: + raise IotsaError(str(e)) + + def dfuWait(self): + """Test to see whether a board in programmable mode is connected""" + try: + self._run("chip_id", nostub=True) + except IotsaError: + print("** To use DFU mode on a iotsa device:") + print(" 1. Connect iotsa device to serial using FTDI232 or similar interface") + print(" 2. Ensure iotsa device is powered through normal power supply") + print(" 3. Press-and-hold PRG button while pressing RST button") + raise + + def dfuClear(self): + """Erase flash""" + self.dfuWait() + self._run("erase_flash") + + def dfuRun(self): + """Run program stored in iotsa flash memory""" + self.dfuWait() + self._run("run", nostub=True) + + def dfuLoad(self, filename): + """Load a new program into iotsa flash memory""" + self.dfuWait() + if not os.path.exists(filename): + filename, _ = urllib.request.urlretrieve(filename) + self._run("write_flash", args=["0", filename]) diff --git a/pool/shard002/Python/0026218_promisc_kernel.py b/pool/shard002/Python/0026218_promisc_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..10ed43e9777f4f073858ce017810049732a6ffc5 --- /dev/null +++ b/pool/shard002/Python/0026218_promisc_kernel.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python + +# 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/. +# Copyright (c) 2014 Mozilla Corporation +# +# This code alerts on every successfully opened session on any of the host from a given list + +from lib.alerttask import AlertTask +from mozdef_util.query_models import SearchQuery, TermMatch, QueryStringMatch, PhraseMatch + + +class PromiscKernel(AlertTask): + def main(self): + + search_query = SearchQuery(minutes=2) + + search_query.add_must([ + TermMatch('category', 'syslog'), + PhraseMatch('summary', 'promiscuous'), + PhraseMatch('summary', 'entered') + ]) + + search_query.add_must_not([ + QueryStringMatch('summary: veth*'), + ]) + + self.filtersManual(search_query) + self.searchEventsAggregated('hostname', samplesLimit=10) + self.walkAggregations(threshold=1) + + def onAggregation(self, aggreg): + category = 'promisc' + severity = 'WARNING' + tags = ['promisc', 'kernel'] + + summary = 'Promiscuous mode enabled on {1} [{0}]'.format(aggreg['count'], aggreg['value']) + + return self.createAlertDict(summary, category, tags, aggreg['events'], severity) diff --git a/pool/shard002/Python/0026222_corrector.py b/pool/shard002/Python/0026222_corrector.py new file mode 100644 index 0000000000000000000000000000000000000000..1fd87307395a7799ff02a3a96db0170c529a45cf --- /dev/null +++ b/pool/shard002/Python/0026222_corrector.py @@ -0,0 +1,76 @@ +#coding=utf-8 +from __future__ import unicode_literals + +import re +import os + +from bwikibot.cli import get_wiki, action +from bwikibot.ui import print_diff, ask_y_n +from bwikibot.utils import ON_2 + +if ON_2: + from codecs import open + + +@action('spell') +def spell(*page_name): + ''' Make autocorrection with dictionary ''' + wiki = get_wiki() + + page = wiki.page(' '.join(page_name)) + text = page.read() + if not page.exists(): + print('Page "%s" not exists!' % page.title) + return + correction = correct(text) + + if correction == text: + print('Текст в порядку') + return + + print_diff(text, correction) + if ask_y_n('Здійснити виправлення?'): + print('Виправляємо') + page.write(correction, 'автовиправлення по словнику') + + +def here(filename): + return os.path.join(os.path.dirname(__file__), filename) + +class Corrector: + def __init__(self): + self.substitutions = [] + + with open(here('genitive_a_u.txt'), encoding='utf-8') as f: + self.load_genitive_a_u(f) + + def load_genitive_a_u(self, f): + for word in f: + word = word.strip() + if word.endswith('а'): + err_end = 'у' + elif word.endswith('у'): + err_end = 'а' + else: + print('Слово "%s" має помилкове закінчення' % word) + continue + + self.substitutions.append(( + word[:-1] + err_end + r'\b', + word + )) + + word = word.capitalize() + self.substitutions.append(( + word[:-1] + err_end + r'\b', + word + )) + + def correct(self, text): + for subst in self.substitutions: + text = re.sub(subst[0], subst[1], text, flags=re.U) + return text + + __call__ = correct # shortcut for main action of this class + +correct = Corrector() diff --git a/pool/shard002/Python/0026223_init__.py b/pool/shard002/Python/0026223_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..01a52ef633784f198959569e1dbad8db7f493159 --- /dev/null +++ b/pool/shard002/Python/0026223_init__.py @@ -0,0 +1,223 @@ +# Copyright 2014-2015 ARM Limited +# +# 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. +# + + +# pylint: disable=E1101 +import os +import re +import time + +import pexpect + +from wlauto import BigLittleDevice, Parameter +from wlauto.exceptions import DeviceError +from wlauto.utils.serial_port import open_serial_connection, pulse_dtr +from wlauto.utils.android import adb_connect, adb_disconnect, adb_list_devices +from wlauto.utils.uefi import UefiMenu, UefiConfig +from wlauto.utils.uboot import UbootMenu + + +AUTOSTART_MESSAGE = 'Press Enter to stop auto boot...' + + +class Juno(BigLittleDevice): + + name = 'juno' + description = """ + ARM Juno next generation big.LITTLE development platform. + """ + + capabilities = ['reset_power'] + + has_gpu = True + + core_modules = [ + 'vexpress', + ] + + parameters = [ + Parameter('retries', kind=int, default=2, + description="""Specifies the number of times the device will attempt to recover + (normally, with a hard reset) if it detects that something went wrong."""), + + Parameter('microsd_mount_point', default='/media/JUNO', + description='Location at which the device\'s MicroSD card will be mounted.'), + Parameter('port', default='/dev/ttyS0', description='Serial port on which the device is connected.'), + Parameter('baudrate', kind=int, default=115200, description='Serial connection baud.'), + Parameter('timeout', kind=int, default=300, description='Serial connection timeout.'), + Parameter('core_names', default=['a53', 'a53', 'a53', 'a53', 'a57', 'a57'], override=True), + Parameter('core_clusters', default=[0, 0, 0, 0, 1, 1], override=True), + + Parameter('bootloader', default='uefi', allowed_values=['uefi', 'u-boot'], + description="""Bootloader used on the device."""), + Parameter('actually_disconnect', kind=bool, default=False, + description=""" + Actually perfom "adb disconnect" on closing the connection to the device. + """), + + # VExpress flasher expects a device to have these: + Parameter('uefi_entry', default='WA', + description='The name of the entry to use (will be created if does not exist).'), + Parameter('uefi_config', kind=UefiConfig, + description='''Specifies the configuration for the UEFI entry for his device. In an + entry specified by ``uefi_entry`` parameter doesn't exist in UEFI menu, + it will be created using this config. This configuration will also be + used, when flashing new images.''', + default={ + 'image_name': 'Image', + 'image_args': None, # populated from bootargs if not specified + 'fdt_support': True, + } + ), + Parameter('bootargs', default='console=ttyAMA0,115200 earlyprintk=pl011,0x7ff80000 ' + 'verbose debug init=/init root=/dev/sda1 rw ip=dhcp ' + 'rootwait video=DVI-D-1:1920x1080R@60', + description='''Default boot arguments to use when boot_arguments were not.'''), + ] + + short_delay = 1 + firmware_prompt = 'Cmd>' + + def validate(self): + if not self.uefi_config.image_args: + self.uefi_config.image_args = self.bootargs + + def boot(self, hard=False, **kwargs): + if kwargs: + self.bootargs = kwargs # pylint: disable=attribute-defined-outside-init + if hard: + self.logger.debug('Performing a hard reset.') + self.hard_reset() + else: + self.logger.debug('Resetting the device.') + self.reset() + if self.bootloader == 'uefi': + self._boot_via_uefi() + else: + self._boot_via_uboot(bootargs=self.bootargs) + + def _boot_via_uboot(self, **kwargs): + if not kwargs: + # Standard linaro configuration will proceed directly to the kernel + return + with open_serial_connection(port=self.port, + baudrate=self.baudrate, + timeout=self.timeout, + init_dtr=0) as target: + menu = UbootMenu(target) + self.logger.debug('Waiting for U-Boot prompt...') + menu.open(timeout=120) + for var, value in kwargs.iteritems(): + menu.setenv(var, value) + menu.boot() + + def _boot_via_uefi(self): + with open_serial_connection(port=self.port, + baudrate=self.baudrate, + timeout=self.timeout, + init_dtr=0) as target: + menu = UefiMenu(target) + self.logger.debug('Waiting for UEFI menu...') + menu.open(timeout=120) + try: + menu.select(self.uefi_entry) + except LookupError: + self.logger.debug('{} UEFI entry not found.'.format(self.uefi_entry)) + self.logger.debug('Attempting to create one using default flasher configuration.') + menu.create_entry(self.uefi_entry, self.uefi_config) + menu.select(self.uefi_entry) + self.logger.debug('Waiting for the Android prompt.') + target.expect(self.android_prompt, timeout=self.timeout) + + def connect(self): + if not self._is_ready: + if not self.adb_name: # pylint: disable=E0203 + with open_serial_connection(timeout=self.timeout, + port=self.port, + baudrate=self.baudrate, + init_dtr=0) as target: + target.sendline('') + self.logger.debug('Waiting for the Android prompt.') + target.expect(self.android_prompt) + + self.logger.debug('Waiting for IP address...') + wait_start_time = time.time() + while True: + target.sendline('ip addr list eth0') + time.sleep(1) + try: + target.expect('inet ([1-9]\d*.\d+.\d+.\d+)', timeout=10) + self.adb_name = target.match.group(1) + ':5555' # pylint: disable=W0201 + break + except pexpect.TIMEOUT: + pass # We have our own timeout -- see below. + if (time.time() - wait_start_time) > self.ready_timeout: + raise DeviceError('Could not acquire IP address.') + + if self.adb_name in adb_list_devices(): + adb_disconnect(self.adb_name) + adb_connect(self.adb_name, timeout=self.timeout) + super(Juno, self).connect() # wait for boot to complete etc. + self._is_ready = True + + def disconnect(self): + if self._is_ready: + super(Juno, self).disconnect() + if self.actually_disconnect: + adb_disconnect(self.adb_name) + self._is_ready = False + + def reset(self): + # Currently, reboot is not working in Android on Juno, so + # perfrom a ahard reset instead + self.hard_reset() + + def hard_reset(self): + self.disconnect() + self.adb_name = None # Force re-acquire IP address on reboot. pylint: disable=attribute-defined-outside-init + with open_serial_connection(port=self.port, + baudrate=self.baudrate, + timeout=300, + init_dtr=0, + get_conn=True) as (target, conn): + pulse_dtr(conn, state=True, duration=0.1) # TRM specifies a pulse of >=100ms + + i = target.expect([AUTOSTART_MESSAGE, self.firmware_prompt]) + if i: + self.logger.debug('Saw firmware prompt.') + time.sleep(self.short_delay) + target.sendline('reboot') + else: + self.logger.debug('Saw auto boot message.') + + def wait_for_microsd_mount_point(self, target, timeout=100): + attempts = 1 + self.retries + if os.path.exists(os.path.join(self.microsd_mount_point, 'config.txt')): + return + + self.logger.debug('Waiting for VExpress MicroSD to mount...') + for i in xrange(attempts): + if i: # Do not reboot on the first attempt. + target.sendline('reboot') + for _ in xrange(timeout): + time.sleep(self.short_delay) + if os.path.exists(os.path.join(self.microsd_mount_point, 'config.txt')): + return + raise DeviceError('Did not detect MicroSD mount on {}'.format(self.microsd_mount_point)) + + def get_android_id(self): + # Android ID currenlty not set properly in Juno Android builds. + return 'abad1deadeadbeef' + diff --git a/pool/shard002/Python/0026226_dr.py b/pool/shard002/Python/0026226_dr.py new file mode 100644 index 0000000000000000000000000000000000000000..34a04bcc103842dadc23299da4080be138292190 --- /dev/null +++ b/pool/shard002/Python/0026226_dr.py @@ -0,0 +1,14 @@ +from pcs import usage +from pcs.cli import dr +from pcs.cli.common.routing import create_router + +dr_cmd = create_router( + { + "help": lambda lib, argv, modifiers: print(usage.dr(argv)), + "config": dr.config, + "destroy": dr.destroy, + "set-recovery-site": dr.set_recovery_site, + "status": dr.status, + }, + ["dr"], +) diff --git a/pool/shard002/Python/0026227_freeze_graph.py b/pool/shard002/Python/0026227_freeze_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a456833987aaebb236e9eaf12533557ce803dd --- /dev/null +++ b/pool/shard002/Python/0026227_freeze_graph.py @@ -0,0 +1,135 @@ +# 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. +# ============================================================================== +"""Converts checkpoint variables into Const ops in a standalone GraphDef file. + +This script is designed to take a GraphDef proto, a SaverDef proto, and a set of +variable values stored in a checkpoint file, and output a GraphDef with all of +the variable ops converted into const ops containing the values of the +variables. + +It's useful to do this when we need to load a single file in C++, especially in +environments like mobile or embedded where we may not have access to the +RestoreTensor ops and file loading calls that they rely on. + +An example of command-line usage is: +bazel build tensorflow/python/tools:freeze_graph && \ +bazel-bin/tensorflow/python/tools/freeze_graph \ +--input_graph=some_graph_def.pb \ +--input_checkpoint=model.ckpt-8361242 \ +--output_graph=/tmp/frozen_graph.pb --output_node_names=softmax + +You can also look at freeze_graph_test.py for an example of how to use it. + +""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import tensorflow as tf + +from google.protobuf import text_format +from tensorflow.python.framework import graph_util + + +FLAGS = tf.app.flags.FLAGS + +tf.app.flags.DEFINE_string("input_graph", "", + """TensorFlow 'GraphDef' file to load.""") +tf.app.flags.DEFINE_string("input_saver", "", + """TensorFlow saver file to load.""") +tf.app.flags.DEFINE_string("input_checkpoint", "", + """TensorFlow variables file to load.""") +tf.app.flags.DEFINE_string("output_graph", "", + """Output 'GraphDef' file name.""") +tf.app.flags.DEFINE_boolean("input_binary", False, + """Whether the input files are in binary format.""") +tf.app.flags.DEFINE_string("output_node_names", "", + """The name of the output nodes, comma separated.""") +tf.app.flags.DEFINE_string("restore_op_name", "save/restore_all", + """The name of the master restore operator.""") +tf.app.flags.DEFINE_string("filename_tensor_name", "save/Const:0", + """The name of the tensor holding the save path.""") +tf.app.flags.DEFINE_boolean("clear_devices", True, + """Whether to remove device specifications.""") +tf.app.flags.DEFINE_string("initializer_nodes", "", "comma separated list of " + "initializer nodes to run before freezing.") + + +def freeze_graph(input_graph, input_saver, input_binary, input_checkpoint, + output_node_names, restore_op_name, filename_tensor_name, + output_graph, clear_devices, initializer_nodes): + """Converts all variables in a graph and checkpoint into constants.""" + + if not tf.gfile.Exists(input_graph): + print("Input graph file '" + input_graph + "' does not exist!") + return -1 + + if input_saver and not tf.gfile.Exists(input_saver): + print("Input saver file '" + input_saver + "' does not exist!") + return -1 + + # 'input_checkpoint' may be a prefix if we're using Saver V2 format + if not tf.train.checkpoint_exists(input_checkpoint): + print("Input checkpoint '" + input_checkpoint + "' doesn't exist!") + return -1 + + if not output_node_names: + print("You need to supply the name of a node to --output_node_names.") + return -1 + + input_graph_def = tf.GraphDef() + mode = "rb" if input_binary else "r" + with tf.gfile.FastGFile(input_graph, mode) as f: + if input_binary: + input_graph_def.ParseFromString(f.read()) + else: + text_format.Merge(f.read().decode("utf-8"), input_graph_def) + # Remove all the explicit device specifications for this node. This helps to + # make the graph more portable. + if clear_devices: + for node in input_graph_def.node: + node.device = "" + _ = tf.import_graph_def(input_graph_def, name="") + + with tf.Session() as sess: + if input_saver: + with tf.gfile.FastGFile(input_saver, mode) as f: + saver_def = tf.train.SaverDef() + if input_binary: + saver_def.ParseFromString(f.read()) + else: + text_format.Merge(f.read(), saver_def) + saver = tf.train.Saver(saver_def=saver_def) + saver.restore(sess, input_checkpoint) + else: + sess.run([restore_op_name], {filename_tensor_name: input_checkpoint}) + if initializer_nodes: + sess.run(initializer_nodes) + output_graph_def = graph_util.convert_variables_to_constants( + sess, input_graph_def, output_node_names.split(",")) + + with tf.gfile.GFile(output_graph, "wb") as f: + f.write(output_graph_def.SerializeToString()) + print("%d ops in the final graph." % len(output_graph_def.node)) + + +def main(unused_args): + freeze_graph(FLAGS.input_graph, FLAGS.input_saver, FLAGS.input_binary, + FLAGS.input_checkpoint, FLAGS.output_node_names, + FLAGS.restore_op_name, FLAGS.filename_tensor_name, + FLAGS.output_graph, FLAGS.clear_devices, FLAGS.initializer_nodes) + +if __name__ == "__main__": + tf.app.run() diff --git a/pool/shard002/Python/0026229_test_index.py b/pool/shard002/Python/0026229_test_index.py new file mode 100644 index 0000000000000000000000000000000000000000..c5351c2b101796adf81c5d92f4b4e9f27903b80e --- /dev/null +++ b/pool/shard002/Python/0026229_test_index.py @@ -0,0 +1,94 @@ +import unittest +import numpy as np + +from numcube import Index + + +class IndexTests(unittest.TestCase): + + def test_create_index(self): + a = Index("A", [10, 20, 30]) + self.assertEqual(a.name, "A") + self.assertEqual(len(a), 3) + + a = Index("Dim", ["a", "b", "c", "d"]) + self.assertEqual(a.name, "Dim") + self.assertEqual(len(a), 4) + + # duplicate values + self.assertRaises(ValueError, Index, "A", ["a", "b", "a"]) + self.assertRaises(ValueError, Index, "A", [0, 1, 1]) + + # invalid Index name + self.assertRaises(TypeError, Index, 1, [1, 2, 3]) + + def test_index_take(self): + a = Index("A", ["a", "b", "c", "d"]) + self.assertEqual(a.take([0, 2]).name, "A") # keep name + self.assertTrue(np.array_equal(a.take([0, 2]).values, ["a", "c"])) + self.assertTrue(np.array_equal(a.take([2, 0]).values, ["c", "a"])) + self.assertRaises(ValueError, a.take, [0, 2, 0]) # duplicate values in Index + + def test_compress(self): + a = Index("A", ["a", "b", "c", "d"]) + selector = [True, False, True, False] + b = a.compress(selector) + c = a[np.array(selector)] + self.assertTrue(np.array_equal(b.values, c.values)) + self.assertEqual(a.name, b.name) # keep name + self.assertTrue(np.array_equal(b.values, a.values.compress(selector))) + + def test_writeable(self): + # once index has been created, its values cannot be changed in order not to break lookup function + a = Index("A", [10, 20, 30]) + self.assertRaises(ValueError, a.values.__setitem__, 0, 40) + self.assertRaises(ValueError, a.values.sort) + + def test_indexof(self): + a = Index("A", [10, 20, 30]) + b = Index("Dim", ["ab", "bc", "cd", "de"]) + + # a single value + self.assertEqual(a.indexof(10), 0) + self.assertEqual(b.indexof("cd"), 2) + self.assertEqual(b.indexof(["cd"]), 2) + + # multiple values + self.assertTrue(np.array_equal(a.indexof([10, 30]), [0, 2])) + self.assertTrue(np.array_equal(b.indexof(["de", "cd"]), [3, 2])) + + # non-existent value raises KeyError (similar to dictionary lookup) + self.assertRaises(KeyError, a.indexof, 0) + self.assertRaises(KeyError, b.indexof, "ef") + self.assertRaises(KeyError, b.indexof, None) + self.assertRaises(KeyError, a.indexof, [0, 1]) + self.assertRaises(KeyError, b.indexof, ["de", "ef"]) + + def test_operator_in(self): + a = Index("A", [10, 20, 30]) + b = Index("B", ["ab", "bc", "cd", "de"]) + + self.assertTrue(20 in a) + self.assertFalse(40 in a) + self.assertTrue("bc" in b) + self.assertFalse("ef" in b) + + # unlike Index.contains() operator 'in' cannot work with multiple values + #self.assertRaises(TypeError, a, __contains__, [0, 10]) + #self.assertRaises(TypeError, a, __contains__, (0, 10)) + + def test_contains(self): + a = Index("A", [10, 20, 30]) + b = Index("B", ["ab", "bc", "cd", "de"]) + + # a single value (in this case, operator 'in' is preferred) + self.assertTrue(a.contains(20)) + self.assertFalse(a.contains(40)) + self.assertTrue(b.contains("bc")) + self.assertFalse(b.contains("ef")) + + # multiple values returns one-dimensional numpy array of logical values + self.assertTrue(np.array_equal(a.contains([0, 10, 20, 40]), [False, True, True, False])) + self.assertTrue(np.array_equal(b.contains(["ab"]), [True])) + self.assertTrue(np.array_equal(b.contains(["ab", "ef", "bc"]), [True, False, True])) + self.assertTrue(np.array_equal(b.contains(("ab", "ef", "bc")), [True, False, True])) diff --git a/pool/shard002/Python/0026230_config.py b/pool/shard002/Python/0026230_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f13808d7e6de3762f6bad1625f474a165165ad0e --- /dev/null +++ b/pool/shard002/Python/0026230_config.py @@ -0,0 +1,26 @@ +""" +Created on September 18, 2015 + +@author: oleg-toporkov +""" +import ConfigParser +import os +import selenium.webdriver as webdriver + + +class Config(object): + """ + Config class for storing values from config.ini and browser types. + """ + browser_types = \ + dict(chrome=webdriver.Chrome, firefox=webdriver.Firefox, ie=webdriver.Ie, phantomjs=webdriver.PhantomJS) + config = ConfigParser.ConfigParser() + config.read('config.ini') + + BROWSER = config.get('SELENIUM', 'Browser').lower() + HIGHLIGHT = config.getboolean('SELENIUM', 'Highlight') + REUSE = config.getboolean('SELENIUM', 'Reuse') + + APP_URL = config.get('APPLICATION', 'URL') + + LOG_DIR = os.path.abspath('logs') diff --git a/pool/shard002/Python/0026231_status.py b/pool/shard002/Python/0026231_status.py new file mode 100644 index 0000000000000000000000000000000000000000..5c2ff31a7687b53bd2061f11bd9a0e115ae26f14 --- /dev/null +++ b/pool/shard002/Python/0026231_status.py @@ -0,0 +1,240 @@ +"""status.py - Statusbar for main window.""" + +import gtk + +from mcomix import i18n +from mcomix import constants +from mcomix.preferences import prefs + +class Statusbar(gtk.EventBox): + + SPACING = 5 + + def __init__(self): + super(Statusbar, self).__init__() + + self._loading = True + + # Status text, page number, file number, resolution, path, filename + self.status = gtk.Statusbar() + self.add(self.status) + + # Create popup menu for enabling/disabling status boxes. + self.ui_manager = gtk.UIManager() + self.tooltipstatus = TooltipStatusHelper(self.ui_manager, self.status) + ui_description = """ + + + + + + + + + + """ + self.ui_manager.add_ui_from_string(ui_description) + + actiongroup = gtk.ActionGroup('mcomix-statusbar') + actiongroup.add_toggle_actions([ + ('pagenumber', None, _('Show page numbers'), None, None, + self.toggle_status_visibility), + ('filenumber', None, _('Show file numbers'), None, None, + self.toggle_status_visibility), + ('resolution', None, _('Show resolution'), None, None, + self.toggle_status_visibility), + ('rootpath', None, _('Show path'), None, None, + self.toggle_status_visibility), + ('filename', None, _('Show filename'), None, None, + self.toggle_status_visibility)]) + self.ui_manager.insert_action_group(actiongroup, 0) + + # Hook mouse release event + self.connect('button-release-event', self._button_released) + self.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK) + + # Default status information + self._page_info = '' + self._file_info = '' + self._resolution = '' + self._root = '' + self._filename = '' + self._update_sensitivity() + self.show_all() + + self._loading = False + + def set_message(self, message): + """Set a specific message (such as an error message) on the statusbar, + replacing whatever was there earlier. + """ + self.status.pop(0) + self.status.push(0, " " * Statusbar.SPACING + message) + + def set_page_number(self, page, total, this_screen): + """Update the page number.""" + page_info = "" + for i in range(this_screen): + page_info += '%d' % (page + i) + if i < this_screen - 1: + page_info +=',' + page_info += ' / %d' % total + self._page_info = page_info + + def get_page_number(self): + """Returns the bar's page information.""" + return self._page_info + + def set_file_number(self, fileno, total): + """Updates the file number (i.e. number of current file/total + files loaded).""" + if total > 0: + self._file_info = '(%d / %d)' % (fileno, total) + else: + self._file_info = '' + + def get_file_number(self): + """ Returns the bar's file information.""" + return self._file_info + + def set_resolution(self, dimensions): # 2D only + """Update the resolution data. + + Takes an iterable of tuples, (x, y, scale), describing the original + resolution of an image as well as the currently displayed scale. + """ + resolution = "" + for i in range(len(dimensions)): + d = dimensions[i] + resolution += '%dx%d (%.1f%%)' % (d[0], d[1], d[2] * 100.0) + if i < len(dimensions) - 1: + resolution += ', ' + self._resolution = resolution + + def set_root(self, root): + """Set the name of the root (directory or archive).""" + self._root = i18n.to_unicode(root) + + def set_filename(self, filename): + """Update the filename.""" + self._filename = i18n.to_unicode(filename) + + def update(self): + """Set the statusbar to display the current state.""" + + space = " " * Statusbar.SPACING + text = (space + "|" + space).join(self._get_status_text()) + self.status.pop(0) + self.status.push(0, space + text) + + def push(self, context_id, message): + """ Compatibility with gtk.Statusbar. """ + assert context_id >= 0 + self.status.push(context_id + 1, message) + + def pop(self, context_id): + """ Compatibility with gtk.Statusbar. """ + assert context_id >= 0 + self.status.pop(context_id + 1) + + def _get_status_text(self): + """ Returns an array of text fields that should be displayed. """ + fields = [] + + if prefs['statusbar fields'] & constants.STATUS_PAGE: + fields.append(self._page_info) + if prefs['statusbar fields'] & constants.STATUS_FILENUMBER: + fields.append(self._file_info) + if prefs['statusbar fields'] & constants.STATUS_RESOLUTION: + fields.append(self._resolution) + if prefs['statusbar fields'] & constants.STATUS_PATH: + fields.append(self._root) + if prefs['statusbar fields'] & constants.STATUS_FILENAME: + fields.append(self._filename) + + return fields + + def toggle_status_visibility(self, action, *args): + """ Called when status entries visibility is to be changed. """ + + # Ignore events as long as control is still loading. + if self._loading: + return + + actionname = action.get_name() + if actionname == 'pagenumber': + bit = constants.STATUS_PAGE + elif actionname == 'resolution': + bit = constants.STATUS_RESOLUTION + elif actionname == 'rootpath': + bit = constants.STATUS_PATH + elif actionname == 'filename': + bit = constants.STATUS_FILENAME + elif actionname == 'filenumber': + bit = constants.STATUS_FILENUMBER + + if action.get_active(): + prefs['statusbar fields'] |= bit + else: + prefs['statusbar fields'] &= ~bit + + self.update() + self._update_sensitivity() + + def _button_released(self, widget, event, *args): + """ Triggered when a mouse button is released to open the context + menu. """ + if event.button == 3: + self.ui_manager.get_widget('/Statusbar').popup(None, None, None, + event.button, event.time) + + def _update_sensitivity(self): + """ Updates the action menu's sensitivity based on user preferences. """ + + page_visible = prefs['statusbar fields'] & constants.STATUS_PAGE + fileno_visible = prefs['statusbar fields'] & constants.STATUS_FILENUMBER + resolution_visible = prefs['statusbar fields'] & constants.STATUS_RESOLUTION + path_visible = prefs['statusbar fields'] & constants.STATUS_PATH + filename_visible = prefs['statusbar fields'] & constants.STATUS_FILENAME + + for name, visible in (('pagenumber', page_visible), + ('filenumber', fileno_visible), + ('resolution', resolution_visible), + ('rootpath', path_visible), + ('filename', filename_visible)): + action = self.ui_manager.get_action('/Statusbar/' + name) + action.set_active(visible) + + +class TooltipStatusHelper(object): + """ Attaches to a L{gtk.UIManager} to provide statusbar tooltips when + selecting menu items. """ + + def __init__(self, uimanager, statusbar): + self._statusbar = statusbar + + uimanager.connect('connect-proxy', self._on_connect_proxy) + uimanager.connect('disconnect-proxy', self._on_disconnect_proxy) + + def _on_connect_proxy(self, uimgr, action, widget): + """ Connects the widget's selection handlers to the status bar update. + """ + tooltip = action.get_property('tooltip') + if isinstance(widget, gtk.MenuItem) and tooltip: + cid = widget.connect('select', self._on_item_select, tooltip) + cid2 = widget.connect('deselect', self._on_item_deselect) + setattr(widget, 'app::connect-ids', (cid, cid2)) + + def _on_disconnect_proxy(self, uimgr, action, widget): + """ Disconnects the widget's selection handlers. """ + cids = getattr(widget, 'app::connect-ids', ()) + for cid in cids: + widget.disconnect(cid) + + def _on_item_select(self, menuitem, tooltip): + self._statusbar.push(0, " " * Statusbar.SPACING + tooltip) + + def _on_item_deselect(self, menuitem): + self._statusbar.pop(0) + +# vim: expandtab:sw=4:ts=4 diff --git a/pool/shard002/Python/0026233_sensor.py b/pool/shard002/Python/0026233_sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..2edaa3cf933ebd7e32277380d359fa3c201868c0 --- /dev/null +++ b/pool/shard002/Python/0026233_sensor.py @@ -0,0 +1,144 @@ +"""Sensor for Spot Crime.""" + +from collections import defaultdict +from datetime import timedelta +import logging + +import spotcrime +import voluptuous as vol + +from homeassistant.components.sensor import PLATFORM_SCHEMA +from homeassistant.const import ( + ATTR_ATTRIBUTION, + ATTR_LATITUDE, + ATTR_LONGITUDE, + CONF_API_KEY, + CONF_EXCLUDE, + CONF_INCLUDE, + CONF_LATITUDE, + CONF_LONGITUDE, + CONF_NAME, + CONF_RADIUS, +) +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.entity import Entity +from homeassistant.util import slugify + +_LOGGER = logging.getLogger(__name__) + +CONF_DAYS = "days" +DEFAULT_DAYS = 1 +NAME = "spotcrime" + +EVENT_INCIDENT = f"{NAME}_incident" + +SCAN_INTERVAL = timedelta(minutes=30) + +PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( + { + vol.Required(CONF_NAME): cv.string, + vol.Required(CONF_RADIUS): vol.Coerce(float), + vol.Required(CONF_API_KEY): cv.string, + vol.Inclusive(CONF_LATITUDE, "coordinates"): cv.latitude, + vol.Inclusive(CONF_LONGITUDE, "coordinates"): cv.longitude, + vol.Optional(CONF_DAYS, default=DEFAULT_DAYS): cv.positive_int, + vol.Optional(CONF_INCLUDE): vol.All(cv.ensure_list, [cv.string]), + vol.Optional(CONF_EXCLUDE): vol.All(cv.ensure_list, [cv.string]), + } +) + + +def setup_platform(hass, config, add_entities, discovery_info=None): + """Set up the Crime Reports platform.""" + latitude = config.get(CONF_LATITUDE, hass.config.latitude) + longitude = config.get(CONF_LONGITUDE, hass.config.longitude) + name = config[CONF_NAME] + radius = config[CONF_RADIUS] + api_key = config[CONF_API_KEY] + days = config.get(CONF_DAYS) + include = config.get(CONF_INCLUDE) + exclude = config.get(CONF_EXCLUDE) + + add_entities( + [ + SpotCrimeSensor( + name, latitude, longitude, radius, include, exclude, api_key, days + ) + ], + True, + ) + + +class SpotCrimeSensor(Entity): + """Representation of a Spot Crime Sensor.""" + + def __init__( + self, name, latitude, longitude, radius, include, exclude, api_key, days + ): + """Initialize the Spot Crime sensor.""" + + self._name = name + self._include = include + self._exclude = exclude + self.api_key = api_key + self.days = days + self._spotcrime = spotcrime.SpotCrime( + (latitude, longitude), + radius, + self._include, + self._exclude, + self.api_key, + self.days, + ) + self._attributes = None + self._state = None + self._previous_incidents = set() + self._attributes = {ATTR_ATTRIBUTION: spotcrime.ATTRIBUTION} + + @property + def name(self): + """Return the name of the sensor.""" + return self._name + + @property + def state(self): + """Return the state of the sensor.""" + return self._state + + @property + def device_state_attributes(self): + """Return the state attributes.""" + return self._attributes + + def _incident_event(self, incident): + data = { + "type": incident.get("type"), + "timestamp": incident.get("timestamp"), + "address": incident.get("location"), + } + if incident.get("coordinates"): + data.update( + { + ATTR_LATITUDE: incident.get("lat"), + ATTR_LONGITUDE: incident.get("lon"), + } + ) + self.hass.bus.fire(EVENT_INCIDENT, data) + + def update(self): + """Update device state.""" + incident_counts = defaultdict(int) + incidents = self._spotcrime.get_incidents() + if len(incidents) < len(self._previous_incidents): + self._previous_incidents = set() + for incident in incidents: + incident_type = slugify(incident.get("type")) + incident_counts[incident_type] += 1 + if ( + self._previous_incidents + and incident.get("id") not in self._previous_incidents + ): + self._incident_event(incident) + self._previous_incidents.add(incident.get("id")) + self._attributes.update(incident_counts) + self._state = len(incidents) diff --git a/pool/shard002/Python/0026235_forms.py b/pool/shard002/Python/0026235_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..d31d360cc807e3a41953d8fa5c5e1a9bed86bc40 --- /dev/null +++ b/pool/shard002/Python/0026235_forms.py @@ -0,0 +1,17 @@ +from django import forms + +from .models import Quote + + +class QuoteForm(forms.ModelForm): + author_field = forms.CharField(label='Author', required=False) + + class Meta: + model = Quote + exclude = ('user', 'metadata', 'author', 'star_count') + + def __init__(self, *args, **kwargs): + super(QuoteForm, self).__init__(*args, **kwargs) + for label, field in self.fields.items(): + field.widget.attrs['placeholder'] = field.help_text + field.help_text = None diff --git a/pool/shard002/Python/0026237_data.py b/pool/shard002/Python/0026237_data.py new file mode 100644 index 0000000000000000000000000000000000000000..47211ad5addce57b520ab0804ac18a36f4612291 --- /dev/null +++ b/pool/shard002/Python/0026237_data.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python + +""" +Author: Dan Salo +Initial Commit: 12/5/2016 +Purpose: Class for MNIST +Adapted from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/learn/python/learn/datasets/mnist.py +""" + +from .base import Data +from shutil import copyfile +import numpy as np +import os +import gzip +import urllib.request + + +class Mnist(Data): + def __init__(self, flags): + super().__init__(flags) + + def load_data(self, test_percent=0.15): + one_hot = True + validation_size = 5000 + + SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/' + TRAIN_IMAGES = 'train-images-idx3-ubyte.gz' + TRAIN_LABELS = 'train-labels-idx1-ubyte.gz' + TEST_IMAGES = 't10k-images-idx3-ubyte.gz' + TEST_LABELS = 't10k-labels-idx1-ubyte.gz' + + local_file = self.maybe_download(TRAIN_IMAGES, self.flags['data_directory'], SOURCE_URL + TRAIN_IMAGES) + with open(local_file, 'rb') as f: + train_images = self.extract_images(f) + + local_file = self.maybe_download(TRAIN_LABELS, self.flags['data_directory'], SOURCE_URL + TRAIN_LABELS) + with open(local_file, 'rb') as f: + train_labels = self.extract_labels(f, one_hot=one_hot) + + local_file = self.maybe_download(TEST_IMAGES, self.flags['data_directory'], SOURCE_URL + TEST_IMAGES) + with open(local_file, 'rb') as f: + test_images = self.extract_images(f) + + local_file = self.maybe_download(TEST_LABELS, self.flags['data_directory'], SOURCE_URL + TEST_LABELS) + with open(local_file, 'rb') as f: + test_labels = self.extract_labels(f, one_hot=one_hot) + + if not 0 <= validation_size <= len(train_labels): + raise ValueError( + 'Validation size should be between 0 and {}. Received: {}.'.format(len(train_labels), validation_size)) + return train_images, train_labels, test_images, test_labels + + def maybe_download(self, filename, work_directory, source_url): + """Download the data from source url, unless it's already here. + Args: + filename: string, name of the file in the directory. + work_directory: string, path to working directory. + source_url: url to download from if file doesn't exist. + Returns: + Path to resulting file. + """ + if not os.path.exists(work_directory): + os.makedirs(work_directory) + filepath = os.path.join(work_directory, filename) + if not os.path.exists(filepath): + temp_file_name, _ = urllib.request.urlretrieve(source_url) + copyfile(temp_file_name, filepath) + print('Successfully downloaded', filename) + return filepath + + def extract_images(self, f): + """Extract the images into a 4D uint8 numpy array [index, y, x, depth]. + Args: + f: A file object that can be passed into a gzip reader. + Returns: + data: A 4D unit8 numpy array [index, y, x, depth]. + Raises: + ValueError: If the bytestream does not start with 2051. + """ + print('Extracting', f.name) + with gzip.GzipFile(fileobj=f) as bytestream: + magic = self._read32(bytestream) + if magic != 2051: + raise ValueError('Invalid magic number %d in MNIST image file: %s' % + (magic, f.name)) + num_images = self._read32(bytestream) + rows = self._read32(bytestream) + cols = self._read32(bytestream) + buf = bytestream.read(rows * cols * num_images) + data = np.frombuffer(buf, dtype=np.uint8) + data = data.reshape(num_images, rows, cols, 1) + return data + + def extract_labels(self, f, one_hot=False, num_classes=10): + """Extract the labels into a 1D uint8 numpy array [index]. + Args: + f: A file object that can be passed into a gzip reader. + one_hot: Does one hot encoding for the result. + num_classes: Number of classes for the one hot encoding. + Returns: + labels: a 1D unit8 numpy array. + Raises: + ValueError: If the bystream doesn't start with 2049. + """ + print('Extracting', f.name) + with gzip.GzipFile(fileobj=f) as bytestream: + magic = self._read32(bytestream) + if magic != 2049: + raise ValueError('Invalid magic number %d in MNIST label file: %s' % + (magic, f.name)) + num_items = self._read32(bytestream) + buf = bytestream.read(num_items) + labels = np.frombuffer(buf, dtype=np.uint8) + if one_hot: + return self.dense_to_one_hot(labels, num_classes) + return labels + + @staticmethod + def dense_to_one_hot(labels_dense, num_classes): + """Convert class labels from scalars to one-hot vectors.""" + num_labels = labels_dense.shape[0] + index_offset = np.arange(num_labels) * num_classes + labels_one_hot = np.zeros((num_labels, num_classes)) + labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 + return labels_one_hot + + @staticmethod + def _read32(bytestream): + dt = np.dtype(np.uint32).newbyteorder('>') + return np.frombuffer(bytestream.read(4), dtype=dt)[0] diff --git a/pool/shard002/Python/0026242_status.py b/pool/shard002/Python/0026242_status.py new file mode 100644 index 0000000000000000000000000000000000000000..da8ebacf26a8e901bed6c494de0c9a3921d1b0ba --- /dev/null +++ b/pool/shard002/Python/0026242_status.py @@ -0,0 +1,102 @@ +# Copyright 2022 UW-IT, University of Washington +# SPDX-License-Identifier: Apache-2.0 + +from django.conf import settings +from django.shortcuts import render +from django.views.decorators.cache import never_cache +from django.utils import timezone +from uw_saml.decorators import group_required +from uw_sws.models import Term +from course_grader.models import SubmittedGradeRoster, GradeImport +from course_grader.dao.term import ( + term_from_param, current_term, current_datetime) +from datetime import datetime, timedelta +from logging import getLogger +import json + +logger = getLogger(__name__) + + +@group_required(settings.GRADEPAGE_SUPPORT_GROUP) +@never_cache +def status(request): + try: + curr_term = current_term() + except Exception as ex: + logger.error("GET current term failed: {}".format(ex)) + raise + + term_id = request.GET.get("term", "").strip() + try: + selected_term = term_from_param(term_id) + except Exception as ex: + selected_term = curr_term + + graderosters = SubmittedGradeRoster.objects.get_status_by_term( + selected_term) + + grade_imports = GradeImport.objects.get_import_sources_by_term( + selected_term) + + if selected_term.quarter == Term.SUMMER: + grading_period_open = selected_term.aterm_grading_period_open + else: + grading_period_open = selected_term.grading_period_open + + start_date = timezone.make_aware(grading_period_open, + timezone.get_default_timezone()) + end_date = timezone.make_aware(selected_term.grade_submission_deadline, + timezone.get_default_timezone()) + epoch = timezone.make_aware(datetime(1970, 1, 1), + timezone.get_default_timezone()) + + chart_data = { + "submissions": { + "plot_lines": [], + "grading_period_open": get_total_milliseconds(start_date - epoch), + "data": [] + }, + "grade_imports": { + "catalyst": [], + "canvas": [], + "csv": [], + } + } + + while start_date < end_date: + if start_date.strftime("%a") == "Mon": + chart_data["submissions"]["plot_lines"].append({ + "value": get_total_milliseconds(start_date - epoch), + "color": "#707070", + "width": 1, + "dashStyle": "ShortDot" + }) + start_date = start_date + timedelta(days=1) + + for index, graderoster in enumerate(graderosters): + chart_data["submissions"]["data"].append([ + get_total_milliseconds(graderoster["submitted_date"] - epoch), + index + 1 + ]) + + for grade_import in grade_imports: + chart_data["grade_imports"][grade_import["source"]].append([ + get_total_milliseconds(grade_import["imported_date"] - epoch), + len(chart_data["grade_imports"][grade_import["source"]]) + 1 + ]) + + params = { + "graderosters": graderosters, + "selected_year": selected_term.year, + "selected_quarter": selected_term.get_quarter_display(), + "grading_period_open": grading_period_open, + "grade_submission_deadline": selected_term.grade_submission_deadline, + "current_datetime": current_datetime(), + "chart_data": json.dumps(chart_data), + "term_id": term_id + } + return render(request, "support/status.html", params) + + +def get_total_milliseconds(td): + return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e3 diff --git a/pool/shard002/Python/0026246_test_deposit_validators.py b/pool/shard002/Python/0026246_test_deposit_validators.py new file mode 100644 index 0000000000000000000000000000000000000000..ba120606522b2f46d707b3f747dfa66975098573 --- /dev/null +++ b/pool/shard002/Python/0026246_test_deposit_validators.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# +# This file is part of Invenio. +# Copyright (C) 2015 CERN. +# +# Invenio 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. +# +# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., +# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + +"""Unit tests for deposit module validators.""" + +from invenio.testsuite import InvenioTestCase, make_test_suite, run_test_suite + +from wtforms.validators import ValidationError + + +class Field(object): + + def __init__(self, old_doi, new_doi): + self.object_data = old_doi + self.data = new_doi + + +class Form(object): + pass + + +LOCAL_DOI_PREFIX = "10.5072" +REMOTE_DOI_PREFIX = "10.7777" + + +class MintedDOIValidatorTest(InvenioTestCase): + """Test MitedDOIValidator.""" + + def test_doi_new(self): + from invenio.modules.deposit.validation_utils import MintedDOIValidator + + validator = MintedDOIValidator() + field = Field("", LOCAL_DOI_PREFIX + "/test.77777") + field2 = Field("", REMOTE_DOI_PREFIX + "/test.77777") + form = Form() + + self.assertIsNone(validator(form, field)) + self.assertIsNone(validator(form, field2)) + + def test_matching_doi(self): + from invenio.modules.deposit.validation_utils import MintedDOIValidator + + validator = MintedDOIValidator() + field = Field( + LOCAL_DOI_PREFIX + "/test.77777", + LOCAL_DOI_PREFIX + "/test.77777") + field2 = Field( + REMOTE_DOI_PREFIX + "/test.77777", + REMOTE_DOI_PREFIX + "/test.77777") + form = Form() + + self.assertIsNone(validator(form, field)) + self.assertIsNone(validator(form, field2)) + + def test__different_doi_(self): + from invenio.modules.deposit.validation_utils import MintedDOIValidator + + validator = MintedDOIValidator() + field = Field( + LOCAL_DOI_PREFIX + "/test.12345", + LOCAL_DOI_PREFIX + "/test.77777") + field2 = Field( + REMOTE_DOI_PREFIX + "/test.12345", + REMOTE_DOI_PREFIX + "/test.77777") + form = Form() + + with self.assertRaises(ValidationError): + validator(form, field) + with self.assertRaises(ValidationError): + validator(form, field2) + + +TEST_SUITE = make_test_suite(MintedDOIValidatorTest) + +if __name__ == "__main__": + run_test_suite(TEST_SUITE) diff --git a/pool/shard002/Python/0026247_test_eq.py b/pool/shard002/Python/0026247_test_eq.py new file mode 100644 index 0000000000000000000000000000000000000000..9064dea7e0485d3132a4360b268ac2be6bf4b5b1 --- /dev/null +++ b/pool/shard002/Python/0026247_test_eq.py @@ -0,0 +1,29 @@ +from littlepython.ast import Var, Block, If, ControlBlock, Int +from tests import t + + +def test_ast_eq_dif_types(): + assert Int(t("1")) != Var(t("1")) + + +def test_ast_eq_same_type_diff_attr(): + c1 = Int(t("1")) + c2 = Int(t("1")) + c2.left = "bla" + assert c1 != c2 + + +def test_ast_eq_same_type_same_attr_diff_value(): + c1 = Int(t("1")) + c2 = Int(t("1")) + c1.left = "bla" + c2.left = "bla1" + assert c1 != c2 + + +def test_if_eq_diff_type(): + assert If([], Block()) != Var(t("1")) + + +def test_control_block_eq_diff_type(): + assert ControlBlock([If([], Block())]) != Var(t("1")) diff --git a/pool/shard002/Python/0026255_bipartition.py b/pool/shard002/Python/0026255_bipartition.py new file mode 100644 index 0000000000000000000000000000000000000000..4277fa4b34a7d31480431a8e50f5a6c06a112fa6 --- /dev/null +++ b/pool/shard002/Python/0026255_bipartition.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +from functools import partial, total_ordering +from typing import Callable, Optional, Sequence + +import attr +import funcy as fn +from lazytree import LazyTree + +from monotone_bipartition import hausdorff as mbph +from monotone_bipartition import rectangles # unit_rec +from monotone_bipartition import refine as mbpr # bounding_box +from monotone_bipartition import search as mdts # binsearch +from monotone_bipartition.rectangles import Rec + + +Point = Sequence[float] +Threshold = Callable[[Point], bool] +FindIntersectScheme = Callable[[Rec, Threshold], Point] +BoundaryPointOracle = Callable[[Rec], Point] + + +@attr.s +@total_ordering +class BiPartition: + tree: LazyTree = attr.ib() + + @property + def dim(self): + return len(self.tree.view()) + + def approx(self, tol=1e-4): + recs = self.tree \ + .prune(isleaf=lambda r: r.shortest_edge <= tol) \ + .leaves() + + return list(recs) + + def dist(self, other, tol=1e-4) -> rectangles.Interval: + approxes = mbph.gen_dists(self, other) + within_tol = (i for i in approxes if i.radius < tol) + return fn.first(within_tol) + + def label(self, point) -> bool: + # TODO: Should support either finite precision or max depth. + domain = rectangles.unit_rec(self.dim) + + def above(rec): + return point in domain.forward_cone(rec.bot) and \ + point not in domain.backward_cone(rec.top) + + def below(rec): + return point not in domain.forward_cone(rec.bot) and \ + point in domain.backward_cone(rec.top) + + def not_inside(rec): + return point not in domain.forward_cone(rec.bot) or \ + point not in domain.backward_cone(rec.top) + + recs = self.tree.prune(isleaf=not_inside).bfs() + for rec in recs: + if above(rec): + return True + + if not not_inside(rec): + if all(x == 0 for x in rec.diag): # point rec. + return True + elif below(rec): + return all(x == 0 for x in rec.bot) + + raise RuntimeError("Point outside domain?!?!?!") + + def __le__(self, other): + raise NotImplementedError + + def project(self, point_or_ordering, *, + lexicographic=False, tol=1e-4, percent=False): + """ + If lexicographic is False, then returns an approximation + to the *unique* point that intersect the threshold + boundary AND the line intersecting the origin and the + user defined point. + + If lexicographic is True, then returns an approximation to the + minimum point on the threshold boundary that is minimum in the + ordering provided. The ordering is given as a list of pairs: + `(index, minimize)`. The index is minimized if `minimize` is + true, and maximized otherwise. For example, `[(1, False), (0, + True)]` encodes maximizing along axis 1 of the unit box and + then minimizing along axis 0. + """ + if lexicographic: + assert not percent + return mdts.lexicographic_opt(self.label, point_or_ordering, tol) + + point = point_or_ordering + return mdts.line_intersect(self.label, point, tol, percent=percent) + + @staticmethod + def from_bound_point_oracle( + oracle: BoundaryPointOracle, domain: Rec, *, memoize: bool = True + ) -> BiPartition: + refine = partial(mbpr.refine, diagsearch=oracle) + if memoize: + refine = fn.memoize()(refine) + + return BiPartition(LazyTree(root=domain, child_map=refine)) + + +def from_threshold(func, + dim: int, + *, + memoize_nodes: bool = True, + find_intersect: FindIntersectScheme = mdts.binsearch, + bounding_box: Optional[Rec] = None) -> BiPartition: + + if bounding_box is None: + bounding_box = mbpr.bounding_box( + oracle=func, + domain=rectangles.unit_rec(dim), + find_intersect=find_intersect + ) + + diagsearch = partial(find_intersect, oracle=func) + + return BiPartition.from_bound_point_oracle( + oracle=diagsearch, + domain=bounding_box, + memoize=memoize_nodes, + ) diff --git a/pool/shard002/Python/0026257_mockengine.py b/pool/shard002/Python/0026257_mockengine.py new file mode 100644 index 0000000000000000000000000000000000000000..24fe5facaa8c3c61bc96242b282cadd28da213d6 --- /dev/null +++ b/pool/shard002/Python/0026257_mockengine.py @@ -0,0 +1,100 @@ +""" +Simple in-memory Engine mock. + +""" +from microcosm_dynamodb.errors import ModelNotFoundError + + +class MockQuery: + def __init__(self, engine, model_class): + self._engine = engine + self._model_class = model_class + self._criterion = None + self._limit = None + + @property + def instances(self): + return self._engine.models[self._model_class] + + @instances.setter + def instances(self, value): + self._engine.models[self._model_class] = value + + def filter(self, *criterion): + self._criterion = criterion + return self + + def limit(self, limit): + self._limit = limit + return self + + def check_criterion(self, instance): + # XXX criterion checking is not implemented + return True + + def all(self): + return list(self.gen()) + + def delete(self): + keep = [] + count = 0 + for instance in self.instances: + if self.check_criterion(instance): + count += 1 + else: + keep += instance + self.instances = keep + return count + + def gen(self): + count = 0 + for id, instance in self.instances.items(): + if not self.check_criterion(instance): + continue + yield instance + count += 1 + if count == self._limit: + break + + def one(self): + for instance in self.gen(): + return instance + raise ModelNotFoundError + + +class MockEngine: + def __init__(self, namespace): + self.namespace = namespace + self.region = None + self.models = {} + + def connect_to_region(self, region): + self.region = region + + def register(self, model): + self.models.setdefault(model, {}) + + def delete_schema(self): + pass + + def create_schema(self): + pass + + def save(self, instance): + self.models[instance.__class__][instance.id] = instance + + def scan(self, model_class): + return self.query(model_class) + + def sync(self, instance): + if instance.id in self.models[instance.__class__]: + self.save(instance) + else: + raise ModelNotFoundError + + def query(self, model_class): + return MockQuery(self, model_class) + + def get(self, model_class, **identifiers): + # XXX identifier lookup is not fully featured + return self.models[model_class][identifiers["id"]] diff --git a/pool/shard002/Python/0026259_content.py b/pool/shard002/Python/0026259_content.py new file mode 100644 index 0000000000000000000000000000000000000000..a4cea57c09befa4e6e753ecb78b0723fc45879be --- /dev/null +++ b/pool/shard002/Python/0026259_content.py @@ -0,0 +1,278 @@ +import json + +from sqlalchemy.orm import sessionmaker, scoped_session + +from atod.db import engine +from atod import files +# db models +from atod.db_models.hero import HeroModel +from atod.db_models.ability import AbilityModel +from atod.db_models.ability_specs import AbilitySpecsModel +from atod.db_models.ability_texts import AbilityTextsModel +# utils +from atod.utils import txt2json, json2rows, abilities +from . import schemas + +session = scoped_session(sessionmaker(bind=engine)) + + +def add_heroes(npc_heroes: str, patch: str): + ''' Unite everything that is needed to add heroes to the db table. + + That method does: parses `raw_file` to json, extracts information from + json according to heroes table schema, adds heroes to the table. + + Args: + npc_heroes: full path to the npc_heroes.txt file. + patch: version of the game from which info was taken. + ''' + heroes_file = npc_heroes + + heroes_dict = txt2json.to_json(heroes_file) + + rows = json2rows.heroes_to_rows(heroes_dict, + schemas.get_heroes_columns()) + + for row in rows: + row['patch'] = patch + hero = HeroModel(row) + session.add(hero) + + session.commit() + + +def add_abilities_specs(npc_abilties: str, patch: str): + ''' Fills table with the data from cleaned npc_abilities file. + + Args: + npc_abilties: full path to the npc_abilities.txt file. + patch: version of the game from which info was taken. + + ''' + + parsed = txt2json.to_json(npc_abilties) + clean = abilities.get_cleaned_abilities(parsed) + + schema = schemas.get_abilities_specs_columns() + + with open(files.CONVERTER_FILE, 'r') as fp: + converter = json.load(fp) + + for skill, description in clean.items(): + try: + hero, skill_name = json2rows.parse_skill_name(skill) + # if skill name cannot be parsed + except ValueError: + continue + + for row in json2rows.ability_to_row(description, schema): + row['HeroID'] = converter[hero] + row['name'] = skill_name + row['pk'] = str(row['ID']) + '.' + str(row['lvl']) + row['patch'] = patch + + skill = AbilitySpecsModel(row) + session.add(skill) + + session.commit() + + +def add_abilities(labels: str, patch: str): + ''' Fills abilities table. + + Args: + labels: full path to the labeled_abilities.json file + patch: version of the data + ''' + + with open(labels, 'r') as fp: + skills = json.load(fp) + + with open(files.CONVERTER_FILE, 'r') as fp: + converter = json.load(fp) + + for skill, description in skills.items(): + if 'special' in skill: + continue + + # get skill and hero names + try: + hero, skill_name = json2rows.parse_skill_name(skill) + except ValueError: + continue + + # for marked abilities + if 'labels' in description: + row = json2rows.binarize_labels(description['labels'], + schemas.LABELS) + # for unmarked abilities + else: + row = {k: 0 for k in schemas.LABELS} + + row['HeroID'] = converter[hero] + row['name'] = skill_name + row['ID'] = description['ID'] + row['patch'] = patch + + skill = AbilityModel(row) + session.add(skill) + + session.commit() + + +def add_abilities_texts(dota_english: str, patch): + ''' Fills abilities_texts table. + + Notes: + This function need AbilitiesTable to be created for current + version. I will fix it in future versions. + + Args: + dota_english: full path to the dota_english.txt file. + patch: version of the game from which info was taken. + ''' + + for specification in get_abilities_texts(dota_english): + # if specification is empty + if not specification: + continue + + specification['patch'] = patch + texts = AbilityTextsModel(specification) + session.add(texts) + + session.commit() + + +''' Functions below are doing utils of abilities texts and the reason + they are here is because they need filled database tables (heroes and + abilities). +''' +def group_abilities_texts(texts): + ''' Groups the information in dota_english by ability. + + Args: + texts (dict): *parsed* dota_english.txt + + Returns: + desc_by_ability (dict): {: } + ''' + + desc_by_ability = dict() + keys = sorted(texts) + ability = ' ' + + for key in keys: + if ability in key: + desc_by_ability[ability][key[len(ability) + 1:]] = texts[key] + else: + ability = key + desc_by_ability[ability] = dict() + desc_by_ability[ability]['name'] = texts[ability] + + return desc_by_ability + + +def get_abilities_texts(dota_english: str): + ''' Produces ready to use dictionaries to create AbilityTextsModel object. + + Yields: + dict: containing all the needed keys or empty if texts can not be + sorted + ''' + + texts_file = dota_english + # parse texts file and take only texts from it + parsed_texts = txt2json.to_json(texts_file)['lang']['Tokens'] + # group texts by ability + grouped_texts = group_abilities_texts(parsed_texts) + + # for all keys in grouped_texts + prefix = 'DOTA_Tooltip_ability_' + for key in list(grouped_texts): + if not key.startswith(prefix): + del grouped_texts[key] + continue + + # this is a tuple + parsed_name = json2rows.parse_skill_name(key[len(prefix):]) + + # there are 2 independent `if` statements to call parse_skill_name() + # one time and only if it is needed + + # if the name cann't be parsed + if len(parsed_name) < 2: + del grouped_texts[key] + continue + # if the name can be split to the hero name and skill name -- change + # original uppercase name to in-game style: all lower case with under + # instead of space + else: + grouped_texts[key]['name'] = parsed_name[1] + sorted_ = sort_texts(grouped_texts[key]) + id_ = get_id_from_in_game_name(parsed_name[0], parsed_name[1]) + if sorted_ and id_ is not None: + sorted_['ID'] = id_ + yield sorted_ + else: + yield {} + + +def sort_texts(unsorted): + ''' Creates a dictionary that fits AbilityTextsModel init method. + + Args: + unsorted (dict): all fields in dota_english file for an ability. + + Returns: + dict: where keys are columns in AbilityTextsModel + ''' + + # description is the most important text, so if ability doesn't contain + # one it wouldn't be added in db + if 'Description' not in unsorted: + return {} + + sorted_ = dict() + sorted_['name'] = unsorted['name'] + sorted_['description'] = unsorted['Description'] + sorted_['lore'] = unsorted['Lore'] if 'Lore' in unsorted else '' + + sorted_['notes'] = '' + sorted_['other'] = '' + for key in unsorted: + if 'Note' in key: + # all notes are just sentences, so there is no need in special + # delimiter + sorted_['notes'] += unsorted[key] + ' ' + elif key.lower() not in sorted_: + sorted_['other'] += unsorted[key] + ' | ' + + return sorted_ + + +def get_id_from_in_game_name(hero_name, skill_name): + ''' Finds skill id. + + This function is needed to prevent collision: when a few heroes have + skill with the same name. + + Args: + hero_name (str): hero part of in-game ability name + skill_name (str): skill part of in-game ability name + + Returns: + int or None: int if id is found, None otherwise + ''' + + query = session.query(HeroModel.HeroID) + hero_id = query.filter(HeroModel.in_game_name == hero_name).first()[0] + + query = session.query(AbilityModel.ID) + ability_id_ = query.filter(AbilityModel.HeroID == hero_id, + AbilityModel.name == skill_name).first() + + if ability_id_ is None: + return None + else: + return ability_id_[0] diff --git a/pool/shard002/Python/0026261_create.py b/pool/shard002/Python/0026261_create.py new file mode 100644 index 0000000000000000000000000000000000000000..4e99543631fb2f9d2be4b76207f3b5bc32a5ac48 --- /dev/null +++ b/pool/shard002/Python/0026261_create.py @@ -0,0 +1,20 @@ +""" +Create a simple, single-elimination demo tournament with 8 teams. + +""" +from django.contrib.auth.models import User + +from .utils import generate_tournament + + +teams = ['Team {}'.format(i) for i in range(1, 9)] + +team_defaults = { + 'creator': User.objects.get(pk=1), +} + + +generate_tournament( + teams=teams, + team_defaults=team_defaults +) diff --git a/pool/shard002/Python/0026266_choral.py b/pool/shard002/Python/0026266_choral.py new file mode 100644 index 0000000000000000000000000000000000000000..b7397e4646573d748b738ab873fa5794a5a5d293 --- /dev/null +++ b/pool/shard002/Python/0026266_choral.py @@ -0,0 +1,41 @@ +"""A simple choral texture.""" + +import oort +import random +oort.print_off() +oort.control_rate(15000) + +playing = True +def play(): + oort.wait(random.choice(range(10))*0.1) + while playing: + dur = 2 + random.randint(-10, 10)*.05 + w.dur = dur*random.randint(2,4) + w.pitch = oort.mtof(random.choice(scale)) + w.play() + oort.wait(dur) + +def control(): + global playing + global scale + for _ in xrange(6): + offset = random.randint(-2,2) + scale = [x+offset for x in scale] + oort.wait(20) + playing = False + +w = oort.WAVETABLE() +w.amp = 5000 +w.wavetable = oort.maketable('wave', 1000, 1, 0.1) + +adsr = oort.ADSR(2, 0.5, 0.5, 2) +shimmer = oort.Shimmer(amt=0.03, count=10) +w.apply_behaviors(shimmer, adsr) + +scale = [ p+octave*12 + for p in 0,2,4,6,7,9,10 + for octave in 4,5,6 ] +oort.sprout(control) + +for _ in range(2): + oort.sprout(play) \ No newline at end of file diff --git a/pool/shard002/Python/0026267_test_objectevent.py b/pool/shard002/Python/0026267_test_objectevent.py new file mode 100644 index 0000000000000000000000000000000000000000..d5eca94b6bffbec7fb9cf7de8fee057a6fad1239 --- /dev/null +++ b/pool/shard002/Python/0026267_test_objectevent.py @@ -0,0 +1,86 @@ +############################################################################## +# +# Copyright (c) 2001, 2002 Zope Corporation and Contributors. +# All Rights Reserved. +# +# This software is subject to the provisions of the Zope Public License, +# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. +# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED +# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS +# FOR A PARTICULAR PURPOSE. +# +############################################################################## +"""Object Event Tests + +$Id: test_objectevent.py 67630 2006-04-27 00:54:03Z jim $ +""" +import unittest +import zope.component.event +from zope.testing import doctest + +from zope.app.container.contained import Contained, ObjectRemovedEvent +from zope.app.container.interfaces import IContained, IObjectRemovedEvent +from zope.app.container.sample import SampleContainer +from zope.app.testing.placelesssetup import setUp, tearDown +from zope.app.testing import ztapi + +class TestObjectEventNotifications(unittest.TestCase): + + def setUp(self): + self.callbackTriggered = False + setUp() + + def tearDown(self): + tearDown() + + def testNotify(self): + events = [] + + def record(*args): + events.append(args) + + ztapi.subscribe([IContained, IObjectRemovedEvent], None, record) + + item = Contained() + event = ObjectRemovedEvent(item) + zope.component.event.objectEventNotify(event) + self.assertEqual([(item, event)], events) + + def testNotifyNobody(self): + # Check that notify won't raise an exception in absence of + # of subscribers. + events = [] + item = Contained() + evt = ObjectRemovedEvent(item) + zope.component.event.objectEventNotify(evt) + self.assertEqual([], events) + + def testVeto(self): + zope.component.provideHandler(zope.component.event.objectEventNotify) + container = SampleContainer() + item = Contained() + + # This will fire an event. + container['Fred'] = item + + class Veto(Exception): + pass + + def callback(item, event): + self.callbackTriggered = True + self.assertEqual(item, event.object) + raise Veto + + ztapi.subscribe([IContained, IObjectRemovedEvent], None, callback) + + # del container['Fred'] will fire an ObjectRemovedEvent event. + self.assertRaises(Veto, container.__delitem__, 'Fred') + +def test_suite(): + return unittest.TestSuite(( + unittest.makeSuite(TestObjectEventNotifications), + )) + +if __name__=='__main__': + unittest.main(defaultTest='test_suite') diff --git a/pool/shard002/Python/0026272_cmd_run.py b/pool/shard002/Python/0026272_cmd_run.py new file mode 100644 index 0000000000000000000000000000000000000000..3093faaa7b4b37989e401de8a5088600ee15e213 --- /dev/null +++ b/pool/shard002/Python/0026272_cmd_run.py @@ -0,0 +1,159 @@ +import sys +import codecs + +from .exceptions import InvalidCommand +from .task import Task +from .control import TaskControl +from .runner import Runner, MRunner +from .reporter import REPORTERS +from .cmd_base import DoitCmdBase + + +# verbosity +opt_verbosity = {'name':'verbosity', + 'short':'v', + 'long':'verbosity', + 'type':int, + 'default': None, + 'help': +"""0 capture (do not print) stdout/stderr from task. +1 capture stdout only. +2 do not capture anything (print everything immediately). +[default: 1]""" + } + + +# select output file +opt_outfile = {'name': 'outfile', + 'short':'o', + 'long': 'output-file', + 'type': str, + 'default': sys.stdout, + 'help':"write output into file [default: stdout]" + } + + +# always execute task +opt_always = {'name': 'always', + 'short': 'a', + 'long': 'always-execute', + 'type': bool, + 'default': False, + 'help': "always execute tasks even if up-to-date [default: " + "%(default)s]" + } + +# continue executing tasks even after a failure +opt_continue = {'name': 'continue', + 'short': 'c', + 'long': 'continue', + 'inverse': 'no-continue', + 'type': bool, + 'default': False, + 'help': "continue executing tasks even after a failure " + "[default: %(default)s]" + } + + +opt_num_process = {'name': 'num_process', + 'short': 'n', + 'long': 'process', + 'type': int, + 'default': 0, + 'help': "number of subprocesses" + "[default: %(default)s]" + } + + +# reporter +opt_reporter = {'name':'reporter', + 'short':'r', + 'long':'reporter', + 'type':str, #TODO type choice (limit the accepted strings) + 'default': 'default', + 'help': +"""Choose output reporter. Available: +'default': report output on console +'executed-only': no output for skipped (up-to-date) and group tasks +'json': output result in json format +""" + } + + + + + +class Run(DoitCmdBase): + doc_purpose = "run tasks" + doc_usage = "[TASK/TARGET...]" + doc_description = None + + cmd_options = (opt_always, opt_continue, opt_verbosity, + opt_reporter, opt_outfile, opt_num_process) + + def _execute(self, outfile, + verbosity=None, always=False, continue_=False, + reporter='default', num_process=0): + """ + @param reporter: (str) one of provided reporters or ... + (class) user defined reporter class (can only be specified + from DOIT_CONFIG - never from command line) + (reporter instance) - only used in unittests + """ + # get tasks to be executed + # self.control is saved on instance to be used by 'auto' command + self.control = TaskControl(self.task_list) + self.control.process(self.sel_tasks) + + # reporter + if isinstance(reporter, basestring): + if reporter not in REPORTERS: + msg = ("No reporter named '%s'." + " Type 'doit help run' to see a list " + "of available reporters.") + raise InvalidCommand(msg % reporter) + reporter_cls = REPORTERS[reporter] + else: + # user defined class + reporter_cls = reporter + + # verbosity + if verbosity is None: + use_verbosity = Task.DEFAULT_VERBOSITY + else: + use_verbosity = verbosity + show_out = use_verbosity < 2 # show on error report + + # outstream + if isinstance(outfile, basestring): + outstream = codecs.open(outfile, 'w', encoding='utf-8') + else: # outfile is a file-like object (like StringIO or sys.stdout) + outstream = outfile + + # run + try: + # FIXME stderr will be shown twice in case of task error/failure + if isinstance(reporter_cls, type): + reporter_obj = reporter_cls(outstream, {'show_out':show_out, + 'show_err': True}) + else: # also accepts reporter instances + reporter_obj = reporter_cls + + + if not MRunner.available(): + num_process = 0 + sys.stderr.write("WARNING: multiprocessing module not available, " + + "running on single process.") + + if num_process == 0: + runner = Runner(self.dep_file, reporter_obj, continue_, + always, verbosity) + else: + runner = MRunner(self.dep_file, reporter_obj, continue_, + always, verbosity, num_process) + + return runner.run_all(self.control.task_dispatcher()) + finally: + if isinstance(outfile, str): + outstream.close() + diff --git a/pool/shard002/Python/0026273_test_t-test.py b/pool/shard002/Python/0026273_test_t-test.py new file mode 100644 index 0000000000000000000000000000000000000000..9a88b4f77fe65d420ab6c10be49a70360bcfae86 --- /dev/null +++ b/pool/shard002/Python/0026273_test_t-test.py @@ -0,0 +1,30 @@ +"""test_t-test.py +Tests for the functions in the t-test.py + +Run with: + nosetests test_t-test.py +""" +from __future__ import print_function +import os, sys +import numpy as np +from numpy.testing import assert_almost_equal, assert_array_equal + +#Append path to functions +sys.path.append(os.path.join(os.path.dirname(__file__), "../functions/")) +from t_stat import * + +def test_t_stat(): + psychopathy = [11.416, 4.514, 12.204, 14.835, + 8.416, 6.563, 17.343, 13.02, + 15.19 , 11.902, 22.721, 22.324] + clammy = [0.389, 0.2 , 0.241, 0.463, + 4.585, 1.097, 1.642, 4.972, + 7.957, 5.585, 5.527, 6.964] + age = [22.5, 25.3, 24.6, 21.4, + 20.7, 23.3, 23.8, 21.7, + 21.3, 25.2, 24.6, 21.8] + X = np.column_stack((np.ones(12), clammy)) + Y = np.asarray(psychopathy) + B, t, df, p = t_stat(Y, X) + assert_array_equal((np.around(t[1][:6],6),np.around(p[1][:6],6)), + ( [1.914389], [0.042295])) diff --git a/pool/shard002/Python/0026274_store_controller.py b/pool/shard002/Python/0026274_store_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..ce7e61c2d72d9867385fb87ed19308b113fc2d6d --- /dev/null +++ b/pool/shard002/Python/0026274_store_controller.py @@ -0,0 +1,35 @@ +import pyramid_handlers + +from blue_yellow_app.controllers.base_controller import BaseController +from blue_yellow_app.services.albums_service import AlbumsService +from blue_yellow_app.services.store_service import StoreService + + +class StoreController(BaseController): + @pyramid_handlers.action() + def complete(self): + # {'stripeToken': 'tok_19aUhV4bdW93NdzOnsPOc8K4', + # 'stripeTokenType': 'card', + # 'stripeEmail': 'mikeckennedy@gmail.com', + # 'action': 'complete', + # 'id': 28} + + album_id = int(self.data_dict.get('id', -1)) + album = AlbumsService.get_album_by_id(album_id) + + token = self.data_dict.get('stripeToken') + StoreService.purchase_album(self.logged_in_user, album, album.price, token) + + # TODO: send email receipt to self.data_dict['stripeEmail'] + + self.redirect('/store/success/{}'.format(album.id)) + + @pyramid_handlers.action(renderer='templates/store/success.pt') + def success(self): + album_id = int(self.data_dict.get('id', -1)) + album = AlbumsService.get_album_by_id(album_id) + return {'album': album} + + @pyramid_handlers.action(renderer='templates/store/failed.pt') + def failed(self): + return {} diff --git a/pool/shard002/Python/0026284_test_isoinfo.py b/pool/shard002/Python/0026284_test_isoinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..e73a84ce6535ab38683038dd3c8035442f9a05b9 --- /dev/null +++ b/pool/shard002/Python/0026284_test_isoinfo.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# Copyright (C) 2013-2015 Bastian Kleineidam +# +# 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 ArchiveTest +from .. import needs_program + +class TestIsoinfo(ArchiveTest): + + program = 'isoinfo' + + @needs_program(program) + def test_isoinfo(self): + self.archive_list('t.iso') + + @needs_program(program) + def test_isoinfo_file(self): + self.archive_list('t.iso.foo') diff --git a/pool/shard002/Python/0026288_status_command.py b/pool/shard002/Python/0026288_status_command.py new file mode 100644 index 0000000000000000000000000000000000000000..6693eb31b91f881326b6c7d8a989f44e03bbcb67 --- /dev/null +++ b/pool/shard002/Python/0026288_status_command.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- + +from cleo import InputOption +from orator.migrations import Migrator, DatabaseMigrationRepository +from .base_command import BaseCommand + + +class StatusCommand(BaseCommand): + + def configure(self): + super(StatusCommand, self).configure() + + self.set_name('migrations:status') + self.set_description('Show a list of migrations up/down') + self.add_option('database', 'd', InputOption.VALUE_OPTIONAL, + 'The database connection to use') + self.add_option('path', 'p', InputOption.VALUE_OPTIONAL, + 'The path of migrations files to be executed.') + + def execute(self, i, o): + """ + Executes the command. + + :type i: cleo.inputs.input.Input + :type o: cleo.outputs.output.Output + """ + super(StatusCommand, self).execute(i, o) + + database = i.get_option('database') + repository = DatabaseMigrationRepository(self._resolver, 'migrations') + + migrator = Migrator(repository, self._resolver) + + if not migrator.repository_exists(): + return o.writeln('No migrations found') + + self._prepare_database(migrator, database, i, o) + + path = i.get_option('path') + + if path is None: + path = self._get_migration_path() + + ran = migrator.get_repository().get_ran() + + migrations = [] + for migration in migrator._get_migration_files(path): + if migration in ran: + migrations.append(['%s' % migration, 'Yes']) + else: + migrations.append(['%s' % migration, 'No']) + + if migrations: + table = self.get_helper('table') + table.set_headers(['Migration', 'Ran?']) + table.set_rows(migrations) + table.render(o) + else: + return o.writeln('No migrations found') + + for note in migrator.get_notes(): + o.writeln(note) + + def _prepare_database(self, migrator, database, i, o): + migrator.set_connection(database) diff --git a/pool/shard002/Python/0026293_middleware.py b/pool/shard002/Python/0026293_middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..9bf0a7758a03ad9483c83d18165c6ff69581974f --- /dev/null +++ b/pool/shard002/Python/0026293_middleware.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- + +from __future__ import unicode_literals + +from copy import deepcopy + +from django.conf import settings +from django.contrib import admin +from django.core.exceptions import ImproperlyConfigured +from django.utils.six import string_types + +try: + from django.urls import resolve, Resolver404 +except ModuleNotFoundError: + # Deprecated since Django 1.10, removed in Django 2.0 + from django.urls.urlresolvers import resolve, Resolver404 + +try: + from django.utils.deprecation import MiddlewareMixin +except ImportError: + # Not required for Django <= 1.9, see: + # https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware + MiddlewareMixin = object + + +class ModelAdminReorder(MiddlewareMixin): + + def init_config(self, request, app_list): + self.request = request + self.app_list = app_list + + self.config = getattr(settings, 'ADMIN_REORDER', None) + if not self.config: + # ADMIN_REORDER settings is not defined. + raise ImproperlyConfigured('ADMIN_REORDER config is not defined.') + + if not isinstance(self.config, (tuple, list)): + raise ImproperlyConfigured( + 'ADMIN_REORDER config parameter must be tuple or list. ' + 'Got {config}'.format(config=self.config)) + + admin_index = admin.site.index(request) + try: + # try to get all installed models + app_list = admin_index.context_data['app_list'] + except KeyError: + # use app_list from context if this fails + pass + + # Flatten all models from apps + self.models_list = [] + for app in app_list: + for model in app['models']: + model['model_name'] = self.get_model_name( + app['app_label'], model['object_name']) + self.models_list.append(model) + + def get_app_list(self): + ordered_app_list = [] + for app_config in self.config: + app = self.make_app(app_config) + if app: + ordered_app_list.append(app) + return ordered_app_list + + def make_app(self, app_config): + if not isinstance(app_config, (dict, string_types)): + raise TypeError('ADMIN_REORDER list item must be ' + 'dict or string. Got %s' % repr(app_config)) + + if isinstance(app_config, string_types): + # Keep original label and models + return self.find_app(app_config) + else: + return self.process_app(app_config) + + def find_app(self, app_label): + for app in self.app_list: + if app['app_label'] == app_label: + return app + + def get_model_name(self, app_name, model_name): + if '.' not in model_name: + model_name = '%s.%s' % (app_name, model_name) + return model_name + + def process_app(self, app_config): + if 'app' not in app_config: + raise NameError('ADMIN_REORDER list item must define ' + 'a "app" name. Got %s' % repr(app_config)) + + app = self.find_app(app_config['app']) + if app: + app = deepcopy(app) + # Rename app + if 'label' in app_config: + app['name'] = app_config['label'] + + # Process app models + if 'models' in app_config: + models_config = app_config.get('models') + models = self.process_models(models_config) + if models: + app['models'] = models + else: + return None + return app + + def process_models(self, models_config): + if not isinstance(models_config, (dict, list, tuple)): + raise TypeError('"models" config for ADMIN_REORDER list ' + 'item must be dict or list/tuple. ' + 'Got %s' % repr(models_config)) + + ordered_models_list = [] + for model_config in models_config: + model = None + if isinstance(model_config, dict): + model = self.process_model(model_config) + else: + model = self.find_model(model_config) + + if model: + ordered_models_list.append(model) + + return ordered_models_list + + def find_model(self, model_name): + for model in self.models_list: + if model['model_name'] == model_name: + return model + + def process_model(self, model_config): + # Process model defined as { model: 'model', 'label': 'label' } + for key in ('model', 'label', ): + if key not in model_config: + return + model = self.find_model(model_config['model']) + if model: + model['name'] = model_config['label'] + return model + + def process_template_response(self, request, response): + try: + url = resolve(request.path_info) + except Resolver404: + return response + if not url.app_name == 'admin' and \ + url.url_name not in ['index', 'app_list']: + # current view is not a django admin index + # or app_list view, bail out! + return response + + try: + app_list = response.context_data['app_list'] + except KeyError: + # there is no app_list! nothing to reorder + return response + + self.init_config(request, app_list) + ordered_app_list = self.get_app_list() + response.context_data['app_list'] = ordered_app_list + return response diff --git a/pool/shard002/Python/0026294_pipeline_hof.py b/pool/shard002/Python/0026294_pipeline_hof.py new file mode 100644 index 0000000000000000000000000000000000000000..6f1054fa76a227e8c923a2db9a344d349d77e288 --- /dev/null +++ b/pool/shard002/Python/0026294_pipeline_hof.py @@ -0,0 +1,39 @@ +from pipeline_base import PipelineBlock + +class Filter(PipelineBlock): + """ + Filter out data through this block by checking the truth of the given function. + """ + def __init__(self, function): + self.function = function + + def run(self, input_data): + return (element for element in input_data if self.function(element)) + + +class Fold(PipelineBlock): + """ + Successively reduce inputs with the given binary function. + """ + def __init__(self, function): + self.function = function + + def run(self, input_data): + input_iter = iter(input_data) + x = next(input_iter) + for element in input_iter: + x = self.function(x, element) + return x + + +class Map(PipelineBlock): + """ + Map each item passing through this block using the given function. + """ + def __init__(self, function): + self.function = function + + def run(self, input_data): + return (self.function(element) for element in input_data) + + diff --git a/pool/shard002/Python/0026296_simpletreemodel.py b/pool/shard002/Python/0026296_simpletreemodel.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1c9cf22adfa5a60858d3076df1dfc81e8dd4af --- /dev/null +++ b/pool/shard002/Python/0026296_simpletreemodel.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python + + +############################################################################# +## +## Copyright (C) 2013 Riverbank Computing Limited. +## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +## All rights reserved. +## +## This file is part of the examples of PyQt. +## +## $QT_BEGIN_LICENSE:BSD$ +## You may use this file under the terms of the BSD license as follows: +## +## "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 Nokia Corporation and its Subsidiary(-ies) 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." +## $QT_END_LICENSE$ +## +############################################################################# + + +from PyQt5.QtCore import QAbstractItemModel, QFile, QIODevice, QModelIndex, Qt +from PyQt5.QtWidgets import QApplication, QTreeView + +import simpletreemodel_rc + + +class TreeItem(object): + def __init__(self, data, parent=None): + self.parentItem = parent + self.itemData = data + self.childItems = [] + + def appendChild(self, item): + self.childItems.append(item) + + def child(self, row): + return self.childItems[row] + + def childCount(self): + return len(self.childItems) + + def columnCount(self): + return len(self.itemData) + + def data(self, column): + try: + return self.itemData[column] + except IndexError: + return None + + def parent(self): + return self.parentItem + + def row(self): + if self.parentItem: + return self.parentItem.childItems.index(self) + + return 0 + + +class TreeModel(QAbstractItemModel): + def __init__(self, data, parent=None): + super(TreeModel, self).__init__(parent) + + self.rootItem = TreeItem(("Title", "Summary")) + self.setupModelData(data.split('\n'), self.rootItem) + + def columnCount(self, parent): + if parent.isValid(): + return parent.internalPointer().columnCount() + else: + return self.rootItem.columnCount() + + def data(self, index, role): + if not index.isValid(): + return None + + if role != Qt.DisplayRole: + return None + + item = index.internalPointer() + + return item.data(index.column()) + + def flags(self, index): + if not index.isValid(): + return Qt.NoItemFlags + + return Qt.ItemIsEnabled | Qt.ItemIsSelectable + + def headerData(self, section, orientation, role): + if orientation == Qt.Horizontal and role == Qt.DisplayRole: + return self.rootItem.data(section) + + return None + + def index(self, row, column, parent): + if not self.hasIndex(row, column, parent): + return QModelIndex() + + if not parent.isValid(): + parentItem = self.rootItem + else: + parentItem = parent.internalPointer() + + childItem = parentItem.child(row) + if childItem: + return self.createIndex(row, column, childItem) + else: + return QModelIndex() + + def parent(self, index): + if not index.isValid(): + return QModelIndex() + + childItem = index.internalPointer() + parentItem = childItem.parent() + + if parentItem == self.rootItem: + return QModelIndex() + + return self.createIndex(parentItem.row(), 0, parentItem) + + def rowCount(self, parent): + if parent.column() > 0: + return 0 + + if not parent.isValid(): + parentItem = self.rootItem + else: + parentItem = parent.internalPointer() + + return parentItem.childCount() + + def setupModelData(self, lines, parent): + parents = [parent] + indentations = [0] + + number = 0 + + while number < len(lines): + position = 0 + while position < len(lines[number]): + if lines[number][position] != ' ': + break + position += 1 + + lineData = lines[number][position:].trimmed() + + if lineData: + # Read the column data from the rest of the line. + columnData = [s for s in lineData.split('\t') if s] + + if position > indentations[-1]: + # The last child of the current parent is now the new + # parent unless the current parent has no children. + + if parents[-1].childCount() > 0: + parents.append(parents[-1].child(parents[-1].childCount() - 1)) + indentations.append(position) + + else: + while position < indentations[-1] and len(parents) > 0: + parents.pop() + indentations.pop() + + # Append a new item to the current parent's list of children. + parents[-1].appendChild(TreeItem(columnData, parents[-1])) + + number += 1 + + +if __name__ == '__main__': + + import sys + + app = QApplication(sys.argv) + + f = QFile(':/default.txt') + f.open(QIODevice.ReadOnly) + model = TreeModel(f.readAll()) + f.close() + + view = QTreeView() + view.setModel(model) + view.setWindowTitle("Simple Tree Model") + view.show() + sys.exit(app.exec_()) diff --git a/pool/shard002/Python/0026300_hsts_header.py b/pool/shard002/Python/0026300_hsts_header.py new file mode 100644 index 0000000000000000000000000000000000000000..bbc5c7d7ae2a55fe46d3b1803902dbfc84e1cd0e --- /dev/null +++ b/pool/shard002/Python/0026300_hsts_header.py @@ -0,0 +1,52 @@ +import requests +import time +from ..utils.log import log, INFO, ERROR, PASS +from ..tests import TestWithDependency + +__all__ = ["hsts_header"] + + +##### +# Test : Check a Strict Transport Security Header is Present +##### +@TestWithDependency("HSTS_HEADER") +def hsts_header(ISAAC_WEB, WAIT_DUR, **kwargs): + """Test if responses from Isaac contain a Strict Transport Security Header. + + - 'ISAAC_WEB' is the string URL of the Isaac website to be tested. + """ + time.sleep(WAIT_DUR) + try: + log(INFO, "Making direct HTTP request to '%s'" % ISAAC_WEB) + response = requests.get(ISAAC_WEB) + assert "Strict-Transport-Security" in response.headers, "No HSTS header present in response from '%s'!" % ISAAC_WEB + hsts_header = response.headers["Strict-Transport-Security"] + log(INFO, "HSTS header present in response: '%s'." % hsts_header) + hsts_directives = [p.strip() for p in hsts_header.split(";")] + n_hsts_directives = len(hsts_directives) + assert n_hsts_directives == 3, "Expected 3 directives in header, found %s!" % n_hsts_directives + + assert any([d.startswith("max-age=") for d in hsts_directives]), "HSTS requires a max-age directive to be effective!" + assert "includeSubDomains" in hsts_directives, "Expected 'includeSubdomains' directive: not found!" + assert "preload" in hsts_directives, "Expected 'includeSubdomains' directive: not found!" + log(INFO, "HSTS header contains all required directives.") + + max_age_directive = [d for d in hsts_directives if d.startswith("max-age=")][0] + max_age = int(max_age_directive.replace("max-age=", "")) + assert max_age > 60*60*24*365, "HSTS max-age should be greater than 1 year!" + log(INFO, "HSTS header contains suitable max-age directive.") + + log(PASS, "Valid and sensible HSTS header found.") + return True + except AssertionError as e: + log(ERROR, e.message) + return False + except IndexError: + log(ERROR, "Can't access max-age directive; can't continue!") + return False + except ValueError: + log(ERROR, "Malformed max-age directive!") + return False + except IOError: + log(ERROR, "Cannot connect to '%s'; can't continue!" % ISAAC_WEB) + return False diff --git a/pool/shard002/Python/0026303_pwb_tests.py b/pool/shard002/Python/0026303_pwb_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..94535f323277458db0fe4afdbf0193a7e98188e0 --- /dev/null +++ b/pool/shard002/Python/0026303_pwb_tests.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +""" +Test pwb.py. + +If pwb.py does not load python files as expected, more tests from coverage +should be added locally. +https://bitbucket.org/ned/coveragepy/src/default/tests/test_execfile.py +""" +# +# (C) Pywikibot team, 2007-2014 +# +# Distributed under the terms of the MIT license. +# +from __future__ import absolute_import, unicode_literals + +__version__ = '$Id$' + +import sys + +from tests import join_tests_path, create_path_func +from tests.utils import execute, execute_pwb +from tests.aspects import unittest, PwbTestCase + +join_pwb_tests_path = create_path_func(join_tests_path, 'pwb') + + +class TestPwb(PwbTestCase): + + """ + Test pwb.py functionality. + + This is registered as a Site test because it will not run + without a user-config.py + """ + + # site must be explicitly set for pwb tests. This test does not require + # network access, because tests/pwb/print_locals.py does not use + # handle_args, etc. so version.py doesnt talk on the network. + site = False + net = False + + def _do_check(self, name): + package_name = 'tests.pwb.' + name + script_path = join_pwb_tests_path(name + '.py') + + direct = execute([sys.executable, '-m', package_name]) + vpwb = execute_pwb([script_path]) + self.maxDiff = None + self.assertEqual(direct['stdout'], vpwb['stdout']) + + return (direct, vpwb) + + def test_env(self): + """ + Test external environment of pywikibot. + + Make sure the environment is not contaminated, and is the same as + the environment we get when directly running a script. + """ + self._do_check('print_env') + + def test_locals(self): + """ + Test internal environment of pywikibot. + + Make sure the environment is not contaminated, and is the same as + the environment we get when directly running a script. + """ + self._do_check('print_locals') + + def test_unicode(self): + """Test printing unicode in pywikibot.""" + (direct, vpwb) = self._do_check('print_unicode') + + self.assertEqual('Häuser', direct['stdout'].strip()) + self.assertEqual('Häuser', direct['stderr'].strip()) + self.assertEqual('Häuser', vpwb['stdout'].strip()) + self.assertEqual('Häuser', vpwb['stderr'].strip()) + + +if __name__ == "__main__": + unittest.main(verbosity=10) diff --git a/pool/shard002/Python/0026305_test_ec2utils.py b/pool/shard002/Python/0026305_test_ec2utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9dceb7de1225a09a11026f6d00745ee9c249dff5 --- /dev/null +++ b/pool/shard002/Python/0026305_test_ec2utils.py @@ -0,0 +1,61 @@ +# Copyright 2014 - Red Hat, 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. + +from nova.api.ec2 import ec2utils +from nova import context +from nova import objects +from nova import test + + +class EC2UtilsTestCase(test.TestCase): + def setUp(self): + self.ctxt = context.get_admin_context() + ec2utils.reset_cache() + super(EC2UtilsTestCase, self).setUp() + + def test_get_int_id_from_snapshot_uuid(self): + smap = objects.EC2SnapshotMapping(self.ctxt, uuid='fake-uuid') + smap.create() + smap_id = ec2utils.get_int_id_from_snapshot_uuid(self.ctxt, + 'fake-uuid') + self.assertEqual(smap.id, smap_id) + + def test_get_int_id_from_snapshot_uuid_creates_mapping(self): + smap_id = ec2utils.get_int_id_from_snapshot_uuid(self.ctxt, + 'fake-uuid') + smap = objects.EC2SnapshotMapping.get_by_id(self.ctxt, smap_id) + self.assertEqual('fake-uuid', smap.uuid) + + def test_get_snapshot_uuid_from_int_id(self): + smap = objects.EC2SnapshotMapping(self.ctxt, uuid='fake-uuid') + smap.create() + smap_uuid = ec2utils.get_snapshot_uuid_from_int_id(self.ctxt, smap.id) + self.assertEqual(smap.uuid, smap_uuid) + + def test_id_to_glance_id(self): + s3imap = objects.S3ImageMapping(self.ctxt, uuid='fake-uuid') + s3imap.create() + uuid = ec2utils.id_to_glance_id(self.ctxt, s3imap.id) + self.assertEqual(uuid, s3imap.uuid) + + def test_glance_id_to_id(self): + s3imap = objects.S3ImageMapping(self.ctxt, uuid='fake-uuid') + s3imap.create() + s3imap_id = ec2utils.glance_id_to_id(self.ctxt, s3imap.uuid) + self.assertEqual(s3imap_id, s3imap.id) + + def test_glance_id_to_id_creates_mapping(self): + s3imap_id = ec2utils.glance_id_to_id(self.ctxt, 'fake-uuid') + s3imap = objects.S3ImageMapping.get_by_id(self.ctxt, s3imap_id) + self.assertEqual('fake-uuid', s3imap.uuid) diff --git a/pool/shard002/Python/0026311_result.py b/pool/shard002/Python/0026311_result.py new file mode 100644 index 0000000000000000000000000000000000000000..0920facb3f37e2c217dea704fb4a766e542a4a54 --- /dev/null +++ b/pool/shard002/Python/0026311_result.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +class Result(object): + STATUS_ERROR = "error" + STATUS_SUCCESS = "success" + _default_code = 500 + + def __init__(self, status, code=_default_code, data={}, msg=""): + self._status = status + self._code = code + self._data = data + self._msg = msg + + def status(self): + return self._status + + def code(self): + return self._code + + def data(self): + return self._data + + def msg(self): + return self._msg + + def setData(self, obj): + self._data = obj + + def json(self): + return { "status": self._status, "code": self._code } + +class Error(Result): + def __init__(self, code, msg): + super(Error, self).__init__(status=Result.STATUS_ERROR, code=code, msg=msg) + + def json(self): + return { "status": self._status, "code": self._code, "msg": self._msg } + +class Success(Result): + def __init__(self, data): + super(Success, self).__init__(status=Result.STATUS_SUCCESS, code=200, data=data) + + def json(self): + return { "status": self._status, "code": self._code, "data": self._data } diff --git a/pool/shard002/Python/0026313_renderer_test.py b/pool/shard002/Python/0026313_renderer_test.py new file mode 100644 index 0000000000000000000000000000000000000000..bb134f62566df184045f6811bde6bf263fb93044 --- /dev/null +++ b/pool/shard002/Python/0026313_renderer_test.py @@ -0,0 +1,46 @@ +"""Tests for the renderer.""" + +import unittest +import mock +from grow.pods import pods +from grow import storage +from grow.common import bulk_errors +from grow.rendering import render_controller +from grow.rendering import renderer +from grow.testing import testing + + +class RendererTestCase(unittest.TestCase): + """Test the renderer.""" + + def setUp(self): + self.dir_path = testing.create_test_pod_dir() + self.pod = pods.Pod(self.dir_path, storage=storage.FileStorage) + self.render = renderer.Renderer() + + def test_renderer(self): + """Renders the docs without errors.""" + self.pod.router.add_all(use_cache=False) + routes = self.pod.router.routes + self.render.rendered_docs(self.pod, routes) + + def test_renderer_sans_threading(self): + """Renders the docs without threading.""" + self.pod.router.add_all(use_cache=False) + routes = self.pod.router.routes + self.render.rendered_docs(self.pod, routes, use_threading=False) + + @mock.patch.object(render_controller.RenderDocumentController, 'render') + def test_render(self, mock_render): + """Renders the docs with errors.""" + mock_render.side_effect = ValueError() + + self.pod.router.add_all(use_cache=False) + routes = self.pod.router.routes + + with self.assertRaises(bulk_errors.BulkErrors): + self.render.rendered_docs(self.pod, routes) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard002/Python/0026316_taskwarrior.py b/pool/shard002/Python/0026316_taskwarrior.py new file mode 100644 index 0000000000000000000000000000000000000000..afef17d136bec0cdee25a96bea0251a813b09e40 --- /dev/null +++ b/pool/shard002/Python/0026316_taskwarrior.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +""" +Display currently active (started) taskwarrior tasks. + +Configuration parameters: + - cache_timeout : how often we refresh this module in seconds (5s default) + +Requires + - task + +@author James Smith http://jazmit.github.io/ +@license BSD +""" + +# import your useful libs here +from time import time +from subprocess import check_output +import json +import shlex + + +class Py3status: + """ + """ + # available configuration parameters + cache_timeout = 5 + + def taskWarrior(self, i3s_output_list, i3s_config): + command = 'task start.before:tomorrow status:pending export' + taskwarrior_output = check_output(shlex.split(command)) + tasks_json = json.loads(taskwarrior_output.decode('utf-8')) + + def describeTask(taskObj): + return str(taskObj['id']) + ' ' + taskObj['description'] + + result = ', '.join(map(describeTask, tasks_json)) + response = { + 'cached_until': time() + self.cache_timeout, + 'full_text': result + } + return response + + +if __name__ == "__main__": + """ + Test this module by calling it directly. + """ + from time import sleep + x = Py3status() + config = { + 'color_bad': '#FF0000', + 'color_degraded': '#FFFF00', + 'color_good': '#00FF00' + } + while True: + print(x.taskWarrior([], config)) + sleep(1) diff --git a/pool/shard002/Python/0026318_social_auth.py b/pool/shard002/Python/0026318_social_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..90aae6438034ddffdf47ee69af13e6c6f143f56c --- /dev/null +++ b/pool/shard002/Python/0026318_social_auth.py @@ -0,0 +1,87 @@ +from social.exceptions import AuthAlreadyAssociated, AuthException, \ + AuthForbidden + + +def social_details(backend, response, *args, **kwargs): + return {'details': backend.get_user_details(response)} + + +def social_uid(backend, details, response, *args, **kwargs): + return {'uid': backend.get_user_id(details, response)} + + +def auth_allowed(backend, details, response, *args, **kwargs): + if not backend.auth_allowed(response, details): + raise AuthForbidden(backend) + + +def social_user(backend, uid, user=None, *args, **kwargs): + provider = backend.name + social = backend.strategy.storage.user.get_social_auth(provider, uid) + if social: + if user and social.user != user: + msg = 'This {0} account is already in use.'.format(provider) + raise AuthAlreadyAssociated(backend, msg) + elif not user: + user = social.user + return {'social': social, + 'user': user, + 'is_new': user is None, + 'new_association': False} + + +def associate_user(backend, uid, user=None, social=None, *args, **kwargs): + if user and not social: + try: + social = backend.strategy.storage.user.create_social_auth( + user, uid, backend.name + ) + except Exception as err: + if not backend.strategy.storage.is_integrity_error(err): + raise + # Protect for possible race condition, those bastard with FTL + # clicking capabilities, check issue #131: + # https://github.com/omab/django-social-auth/issues/131 + return social_user(backend, uid, user, *args, **kwargs) + else: + return {'social': social, + 'user': social.user, + 'new_association': True} + + +def associate_by_email(backend, details, user=None, *args, **kwargs): + """ + Associate current auth with a user with the same email address in the DB. + + This pipeline entry is not 100% secure unless you know that the providers + enabled enforce email verification on their side, otherwise a user can + attempt to take over another user account by using the same (not validated) + email address on some provider. This pipeline entry is disabled by + default. + """ + if user: + return None + + email = details.get('email') + if email: + # Try to associate accounts registered with the same email address, + # only if it's a single object. AuthException is raised if multiple + # objects are returned. + users = list(backend.strategy.storage.user.get_users_by_email(email)) + if len(users) == 0: + return None + elif len(users) > 1: + raise AuthException( + backend, + 'The given email address is associated with another account' + ) + else: + return {'user': users[0]} + + +def load_extra_data(backend, details, response, uid, user, *args, **kwargs): + social = kwargs.get('social') or \ + backend.strategy.storage.user.get_social_auth(backend.name, uid) + if social: + extra_data = backend.extra_data(user, uid, response, details) + social.set_extra_data(extra_data) diff --git a/pool/shard002/Python/0026322_yaml.py b/pool/shard002/Python/0026322_yaml.py new file mode 100644 index 0000000000000000000000000000000000000000..81691cbc2ae75c88a289b17201f4d5ea067979a5 --- /dev/null +++ b/pool/shard002/Python/0026322_yaml.py @@ -0,0 +1,80 @@ +""" +YAML serializer. + +Requires PyYaml (http://pyyaml.org/), but that's checked for in __init__. +""" + +import collections +import decimal +from io import StringIO + +import yaml + +from django.core.serializers.base import DeserializationError +from django.core.serializers.python import ( + Deserializer as PythonDeserializer, Serializer as PythonSerializer, +) +from django.db import models + +# Use the C (faster) implementation if possible +try: + from yaml import CSafeLoader as SafeLoader + from yaml import CSafeDumper as SafeDumper +except ImportError: + from yaml import SafeLoader, SafeDumper + + +class DjangoSafeDumper(SafeDumper): + def represent_decimal(self, data): + return self.represent_scalar('tag:yaml.org,2002:str', str(data)) + + def represent_ordered_dict(self, data): + return self.represent_mapping('tag:yaml.org,2002:map', data.items()) + + +DjangoSafeDumper.add_representer( + decimal.Decimal, DjangoSafeDumper.represent_decimal) +DjangoSafeDumper.add_representer( + collections.OrderedDict, DjangoSafeDumper.represent_ordered_dict) + + +class Serializer(PythonSerializer): + """Convert a queryset to YAML.""" + + internal_use_only = False + + def handle_field(self, obj, field): + # A nasty special case: base YAML doesn't support serialization of time + # types (as opposed to dates or datetimes, which it does support). Since + # we want to use the "safe" serializer for better interoperability, we + # need to do something with those pesky times. Converting 'em to strings + # isn't perfect, but it's better than a "!!python/time" type which would + # halt deserialization under any other language. + if isinstance(field, models.TimeField) and getattr(obj, field.name) is not None: + self._current[field.name] = str(getattr(obj, field.name)) + else: + super().handle_field(obj, field) + + def end_serialization(self): + yaml.dump(self.objects, self.stream, + Dumper=DjangoSafeDumper, **self.options) + + def getvalue(self): + # Grandparent super + return super(PythonSerializer, self).getvalue() + + +def Deserializer(stream_or_string, **options): + """Deserialize a stream or string of YAML data.""" + if isinstance(stream_or_string, bytes): + stream_or_string = stream_or_string.decode() + if isinstance(stream_or_string, str): + stream = StringIO(stream_or_string) + else: + stream = stream_or_string + try: + yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options) + except (GeneratorExit, DeserializationError): + raise + except Exception as exc: + raise DeserializationError() from exc diff --git a/pool/shard002/Python/0026326_batch_reports.py b/pool/shard002/Python/0026326_batch_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..6397d54adf2182be4a770ab6e6d4bb2811de979a --- /dev/null +++ b/pool/shard002/Python/0026326_batch_reports.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +# encoding: utf-8 + +import sys +import os + +path = os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))) +sys.path.append(path) +os.environ['DJANGO_SETTINGS_MODULE'] = 'fixmystreet.settings' + +import datetime +from datetime import datetime as dt +from django.core.mail import send_mail +from django.template.loader import render_to_string +from apps.mainapp.models import Report +from fixmystreet import settings + + +reminder_email_count = 0 +councillor_email_count = 0 +# +## send new reports to ward councillors +#for ward in Ward.objects.all(): +# new_reports = ward.report_set.filter(ward=ward,is_confirmed=True,is_fixed=False,sent_at__isnull=True).order_by("-created_at") +# if len(new_reports) > 0 : +# subject = render_to_string("emails/batch_reports/new_reports/subject.txt", +# {'ward': ward }) +# message = render_to_string("emails/batch_reports/new_reports/message.html", +# {'new_reports': new_reports, 'ward': ward }) +# +# msg = EmailMessage(subject, message,settings.EMAIL_FROM_USER,[ward.councillor.email, settings.ADMIN_EMAIL]) +# msg.content_subtype = "html" # Main content is now text/html +# msg.send() +# +# print "sending report for ward " + ward.name +# new_reports.update(sent_at=dt.now()) +# councillor_email_count += 1 + +# send old reports that have not been updated +one_month_ago = dt.today() - datetime.timedelta(days=31) +reminder_reports = Report.objects.filter(is_confirmed=True, status='not-fixed', reminded_at__lte=one_month_ago, + updated_at__lte=one_month_ago).order_by("ward", "-created_at") + +for report in reminder_reports: + subject = render_to_string("emails/batch_reports/reminders/subject.txt", + {'report': report}) + message = render_to_string("emails/batch_reports/reminders/message.txt", + {'report': report}) + + send_mail(subject, message, settings.EMAIL_FROM_USER, [report.first_update().email], fail_silently=False) + + report.reminded_at = dt.now() + report.save() + reminder_email_count += 1 + +# notify admin reports were run +send_mail('Ward Summary Reports Run %s' % ( dt.now() ), + '%d Report Summaries Sent to Councillors\n%d Reminders Sent' % ( + councillor_email_count, reminder_email_count ), + settings.EMAIL_FROM_USER, [settings.ADMIN_EMAIL], fail_silently=False) + diff --git a/pool/shard002/Python/0026334_launch.py b/pool/shard002/Python/0026334_launch.py new file mode 100644 index 0000000000000000000000000000000000000000..092b2f6476e08e3024b709a19f28db18103a713f --- /dev/null +++ b/pool/shard002/Python/0026334_launch.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python + +from __future__ import print_function +from __future__ import division +# import multiprocessing as mp +# from time import sleep +from Sounds import Sound_Func +# from Speech import SphinxServer +from Joystick import Joystick_Func +from pygecko import FileStorage +from hardware import HW_Func +from multiprocessing import Process +from chaos import Chaos_Func +import time + + +def main(): + fs = FileStorage() + fs.readJson("net.json") + + try: + hw = Process(target=HW_Func).start() + snd = Process(target=Sound_Func).start() + chaos = Process(target=Chaos_Func).start() + js = Process(target=Joystick_Func).start() + + while True: + time.sleep(3) + + except KeyboardInterrupt: + print('<<<<<<<< keyboard >>>>>>>>>>>') + if snd.is_alive(): + snd.join(0.1) + snd.terminate() + if hw.is_alive(): + hw.join(0.1) + hw.terminate() + if chaos.is_alive(): + chaos.join() + chaos.terminate() + if js.is_alive(): + js.join() + js.terminate() + + +if __name__ == "__main__": + main() diff --git a/pool/shard002/Python/0026335_Naca.py b/pool/shard002/Python/0026335_Naca.py new file mode 100644 index 0000000000000000000000000000000000000000..50453fbfbe532e27800b02e8f6c4ddace29ff5ea --- /dev/null +++ b/pool/shard002/Python/0026335_Naca.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- + +def Naca_00XX(c, t, x_list): + """ + Generates a simetric NACA airfoil. + Inputs: + :param c: chord + :param t: max thickness as a fraction of the chord. + :param x_list: points between 0 and c (chord lenght) + + Returns dictionary with keys 'u'pper and 'l'ower + + The Naca function can be found in: https://en.wikipedia.org/wiki/NACA_airfoil + + Created on Wed Feb 03 12:50:52 2016 + + @author: Endryws and Pedro Leal + """ + y_upper = [] + y_lower = [] + for x in x_list: + xc= x/c # Is just for increase speed and facilitate future changes. + a1 = 5*t*c + t1 = 0.2969*(math.sqrt(xc)) + t2 = -0.1260*xc + t3 = -0.3516*(xc**2) + t4 = 0.2843*(xc**3) + t5 = -0.1015*(xc**4) + y = (a1*(t1+t2+t3+t4+t5)) + y_upper.append(y) + y_lower.append(y*(-1)) # is just for pick the y axis + # negative numbers + y = {'u': y_upper, 'l':y_lower} + return y + +if __name__ == '__main__': + import matplotlib.pyplot as plt + import math + + from airfoil_module import create_x + + c = 1. #c is the chord length + t = 0.12 # is the maximum thickness as a fraction of the chord + #(t*100 = the last two nunbers of the NACA denomination) + + number_of_points = 200 + + p = 0.5 #this variabel is here to force the points fall inside the model. + + x_list = create_x(c, n = number_of_points, distribution = 'polar') # This function receives + # inicial point,finalpoint, + #number of therms between + # inicial and final point + y = Naca_00XX(c,t,x_list) + + + fig = plt.figure() + + fig.add_subplot(111) + plt.scatter(x_list,y['u']) + plt.scatter(x_list,y['l']) + + + plt.grid() + plt.xlabel('x values') + plt.ylabel('y values') \ No newline at end of file diff --git a/pool/shard002/Python/0026340_forecast.py b/pool/shard002/Python/0026340_forecast.py new file mode 100644 index 0000000000000000000000000000000000000000..35926d499f10cbf0c2b9daf1f28c99699caa901f --- /dev/null +++ b/pool/shard002/Python/0026340_forecast.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python + +import sys, urllib, urllib2, re, logging, json, uuid, ast, datetime, os, requests, time, collections +from redten.shellprinting import lg, good, boom, mark, anmt, info +from redten.redten_client import RedTenClient, ppj + +""" +More documentation and samples: + +- Forecast: https://github.com/jay-johnson/sci-pype/blob/master/red10/Red10-SPY-Multi-Model-Price-Forecast.ipynb +- Predictions with the IRIS dataset: https://github.com/jay-johnson/sci-pype/blob/master/red10/Red10-IRIS-Predictions.ipynb + +""" + +# Login to red10 +rt = RedTenClient() + +csv_file = "" +rloc = "" +sloc = "" + +ds_name = "SPY" +if len(sys.argv) > 1: + ds_name = str(sys.argv[1]).upper() + +# What column do you want to predict values? +target_column_name = "FClose" + +# possible values in the Target Column +target_column_values = [ "GoodBuys", "BadBuys", "Not Finished" ] + +# What columns can the algorithms use for training and learning? +feature_column_names = [ "FHigh", "FLow", "FOpen", "FClose", "FVolume" ] + +ignore_features = [ # Prune non-int/float columns as needed: + "Ticker", + "Date", + "FDate", + "FPrice", + "DcsnDate", + "Decision" + ] + +train_xgb = { + "learning_rate" : 0.20, + "num_estimators" : 50, + "sub_sample" : 0.20, + "col_sample_by_tree" : 0.90, + "col_sample_by_level" : 1.0, + "objective" : "reg:linear", + "max_depth" : 3, + "max_delta_step" : 0, + "min_child_weight" : 1, + "reg_alpha" : 0, + "reg_lambda" : 1, + "base_score" : 0.6, + "gamma" : 0, + "seed" : 42, + "silent" : True + } + +predict_row = { + "FHigh" : 5.4, + "FLow" : 3.4, + "FOpen" : 1.7, + "FClose" : 0.2, + "FVolume" : 0 + } + +units_ahead_set = [ 5, 10, 15, 20, 25, 30 ] +units_ahead_type = "Days" + +algo_name = "xgb-regressor" +title = str(ds_name) + " Forecast v5 - " + str(rt.uni_key()) +desc = "Forecast simulation" +label_column_name = target_column_name +test_ratio = 0.1 +sample_filter_rules = {} + +# list of emails to send the analysis to on successful completion +send_to_email = [] + +# Allow a list of comma separated emails to be passed in +# example: email1@email.com,email2@email.com +# note no spaces between them +if str(os.getenv("ENV_REDTEN_FORECAST_EMAILS", "")).strip().lstrip() != "": + send_to_email = str(os.getenv("ENV_REDTEN_FORECAST_EMAILS", "")).strip().lstrip().split(",") + +# allow the target dataset to load from the env for automation with docker +if csv_file == "" and sloc == "" and rloc == "": + csv_file = str(os.getenv("ENV_REDTEN_CSV_FILE", "")).strip().lstrip() + +post_data = { + "predict_this_data" : predict_row, + "title" : title, + "desc" : desc, + "ds_name" : ds_name, + "feature_column_names" : feature_column_names, + "ignore_features" : ignore_features, + "csv_file" : csv_file, + "rloc" : rloc, + "sloc" : sloc, + "algo_name" : algo_name, + "test_ratio" : test_ratio, + "target_column_values" : target_column_values, + "target_column_name" : target_column_name, + "label_column_name" : label_column_name, + "user_id" : rt.get_uid(), + "train" : train_xgb, + "max_features" : 10, + "tracking_type" : "", + "units_ahead_set" : units_ahead_set, + "units_ahead_type" : units_ahead_type, + "prediction_type" : "Forecast", + "ml_type" : "Playbook-UnitsAhead", + "forecast_type" : "ETFPriceForecasting", + "forecast_version" : 5, + "valid_forecast_threshold" : 0.3, + "sample_filters" : sample_filter_rules, + "predict_units_back" : 90, + "bypass_trading_day" : 1, + "send_to_email" : send_to_email, + "version" : 1 + } + + +""" + +Wait on the job to finish + +""" + +anmt("Launching Job") + +job_data = {} +job_report = {} +job_res = {} +job_response = rt.run_job(post_data=post_data) + +if job_response["status"] != "valid": + boom("Forecast job failed with error=" + str(job_response["status"])) + sys.exit(1) +else: + if "id" not in job_response["data"]: + boom("Failed to create new forecast job") + sys.exit(1) + else: + job_id = job_response["data"]["id"] + job_status = job_response["data"]["status"] + lg("Started Forecast job=" + str(job_id) + " with current status=" + str(job_status)) +# end of if job was valid or not + +lg("Started Forecast=" + str(ds_name) + " job=" + str(job_id), 6) + + +""" + +Wait on the job to finish + +""" + + +if job_id == None: + boom("Failed to start a new job") +else: + lg("Waiting on results", 6) + job_res = rt.wait_on_job(job_id) + + if job_res["status"] != "SUCCESS": + boom("Job=" + str(job_id) + " failed with status=" + str(job_res["status"]) + " err=" + str(job_res["error"])) + else: + job_data = job_res["record"] + anmt("Job Report:") + lg(ppj(job_data), 5) +# end of waiting + + +""" + +Get Job Analysis + +""" + + +job_report = {} +if job_id == None: + boom("Failed to start a new job") +else: + # Get the analysis, but do not auto-show the plots + job_report = rt.get_job_analysis(job_id, show_plots=False) + if len(job_report) == 0: + boom("Job=" + str(job_id) + " failed") + sys.exit(1) + else: + lg("") + # if the job failed +# end of get job analysis + + +""" + +Build Forecast Results + +""" + +lg("Building Forecast=" + str(ds_name) + " Results for job=" + str(job_id), 6) + +# Build the forecast accuracy dictionary from the analysis +# and show the forecast dataframes +acc_results = rt.build_forecast_results(job_report) +for col in acc_results: + col_node = acc_results[col] + + predictions_df = col_node["predictions_df"] + date_predictions_df = col_node["date_predictions_df"] + train_predictions_df = col_node["train_predictions_df"] + + lg("--------------------------------------------------") + # for all columns in the accuracy dictionary: + lg("Column=" + str(col) + " accuracy=" + str(col_node["accuracy"]) + " mse=" + str(col_node["mse"]) + " num_predictions=" + str(len(col_node["date_predictions_df"].index))) + # end of header line + + # show the timeseries forecast + lg(date_predictions_df.head(5), 6) + + lg("") +# end of showing prediction results + + + +""" + +Get Analysis Images + +""" + +lg("Getting Forecast=" + str(ds_name) + " Analysis Images for job=" + str(job_id), 6) + +# unless matplotlib is installed this will fail showing plots: +job_res = rt.get_job_analysis(job_id, show_plots=False) + +sys.exit(0) diff --git a/pool/shard002/Python/0026343_0001_initial.py b/pool/shard002/Python/0026343_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..2edf56d94c243260e4c8f3e4ced3006da061509f --- /dev/null +++ b/pool/shard002/Python/0026343_0001_initial.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +from django.conf import settings +import oioioi.base.fields +import oioioi.participants.fields + + +class Migration(migrations.Migration): + + dependencies = [ + ('contests', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Participant', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('status', oioioi.base.fields.EnumField(default=b'ACTIVE', max_length=64, choices=[(b'ACTIVE', 'Active'), (b'BANNED', 'Banned')])), + ('anonymous', models.BooleanField(default=False)), + ('contest', models.ForeignKey(to='contests.Contest')), + ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), + ], + options={ + }, + bases=(models.Model,), + ), + migrations.CreateModel( + name='TestRegistration', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('name', models.CharField(max_length=255)), + ('participant', oioioi.participants.fields.OneToOneBothHandsCascadingParticipantField(related_name='participants_testregistration', to='participants.Participant')), + ], + options={ + 'abstract': False, + }, + bases=(models.Model,), + ), + migrations.AlterUniqueTogether( + name='participant', + unique_together=set([('contest', 'user')]), + ), + ] diff --git a/pool/shard002/Python/0026345_image_services.py b/pool/shard002/Python/0026345_image_services.py new file mode 100644 index 0000000000000000000000000000000000000000..59b4ec015e3146c9fb0398f08db09e3c7810de92 --- /dev/null +++ b/pool/shard002/Python/0026345_image_services.py @@ -0,0 +1,85 @@ +# coding: utf-8 +# +# Copyright 2016 The Oppia 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. + +"""Provides app identity services.""" + +from __future__ import annotations + +import io + +from PIL import Image +from typing import Tuple + + +def _get_pil_image_dimensions(pil_image: Image) -> Tuple[int, int]: + """Gets the dimensions of the Pillow Image. + + Args: + pil_image: Image. A file in the Pillow Image format. + + Returns: + tuple(int, int). Returns height and width of the image. + """ + width, height = pil_image.size + return height, width + + +def get_image_dimensions(file_content: bytes) -> Tuple[int, int]: + """Gets the dimensions of the image with the given file_content. + + Args: + file_content: str. The content of the file. + + Returns: + tuple(int). Returns height and width of the image. + """ + image = Image.open(io.BytesIO(file_content)) + return _get_pil_image_dimensions(image) + + +def compress_image(image_content: bytes, scaling_factor: float) -> bytes: + """Compresses the image by resizing the image with the scaling factor. + + Args: + image_content: str. Content of the file to be compressed. + scaling_factor: float. The number by which the dimensions of the image + will be scaled. This is expected to be in the interval (0, 1]. + + Returns: + str. Returns the content of the compressed image. + + Raises: + ValueError. Scaling factor is not in the interval (0, 1]. + """ + if scaling_factor > 1 or scaling_factor <= 0: + raise ValueError( + 'Scaling factor should be in the interval (0, 1], received %f.' + % scaling_factor) + image = Image.open(io.BytesIO(image_content)) + + image_format = image.format + height, width = _get_pil_image_dimensions(image) + new_width = int(width * scaling_factor) + new_height = int(height * scaling_factor) + new_image_dimensions = (new_width, new_height) + + # NOTE: image.thumbnail() function does not work when the scale factor + # is greater than 1. + image.thumbnail(new_image_dimensions, Image.ANTIALIAS) + with io.BytesIO() as output: + image.save(output, format=image_format) + new_image_content = output.getvalue() + return new_image_content diff --git a/pool/shard002/Python/0026347_domainvalidate.py b/pool/shard002/Python/0026347_domainvalidate.py new file mode 100644 index 0000000000000000000000000000000000000000..2b1fe4a547a4ce1917373859515fd85ac240fc6c --- /dev/null +++ b/pool/shard002/Python/0026347_domainvalidate.py @@ -0,0 +1,24 @@ +"""EasyEngine domain validation module.""" +from urllib.parse import urlparse + + +def ValidateDomain(url): + """ + This function returns domain name removing http:// and https:// + returns domain name only with or without www as user provided. + """ + + # Check if http:// or https:// present remove it if present + domain_name = url.split('/') + if 'http:' in domain_name or 'https:' in domain_name: + domain_name = domain_name[2] + else: + domain_name = domain_name[0] + www_domain_name = domain_name.split('.') + final_domain = '' + if www_domain_name[0] == 'www': + final_domain = '.'.join(www_domain_name[1:]) + else: + final_domain = domain_name + + return (final_domain, domain_name) diff --git a/pool/shard002/Python/0026348_hashing.py b/pool/shard002/Python/0026348_hashing.py new file mode 100644 index 0000000000000000000000000000000000000000..ab844151a42e4a807145ef61511d4a7d8414f13d --- /dev/null +++ b/pool/shard002/Python/0026348_hashing.py @@ -0,0 +1,17 @@ +import hashlib +import random + + +NUMBER_OF_ITERATIONS = 100001 + + +def get_salt(user: bytes): + random.seed(user) + h = hashlib.sha256() + h.update(user) + return h.digest() + bytes(str(random.uniform(-1024.0, 1023.0)), encoding='utf8') + + +def hash_password(password: bytes, user: bytes): + salt = get_salt(user) + return hashlib.pbkdf2_hmac('sha256', password, salt, NUMBER_OF_ITERATIONS) diff --git a/pool/shard002/Python/0026355_plot_solutions.py b/pool/shard002/Python/0026355_plot_solutions.py new file mode 100644 index 0000000000000000000000000000000000000000..3f3608d0658aeca3c0a1d1e0ef86543620acf3ae --- /dev/null +++ b/pool/shard002/Python/0026355_plot_solutions.py @@ -0,0 +1,27 @@ +from matplotlib import pyplot as plt +import numpy as np + + +def plot_line_expansion(edisgo_obj, timesteps): + + pypsa_plot = edisgo_obj.to_pypsa(mode="mv", timesteps=timesteps) + bus_index = pypsa_plot.buses.index + pypsa_plot.buses.x.loc[ + bus_index + ] = edisgo_obj.topology.mv_grid.buses_df.x.loc[bus_index] + pypsa_plot.buses.y.loc[ + bus_index + ] = edisgo_obj.topology.mv_grid.buses_df.y.loc[bus_index] + line_colors = edisgo_obj.opf_results.lines.squeeze() + fig = plt.figure(figsize=(12, 8)) + ax = plt.gca() + v = np.linspace(min(line_colors), max(line_colors), 101) + psa_plot = pypsa_plot.plot( + line_colors=line_colors, line_cmap=plt.cm.cool, ax=ax, geomap=False + ) + cb = plt.colorbar(psa_plot[1]) + cb.set_clim(vmin=v[0], vmax=v[-1]) + cb.set_label("Number of installed lines") + plt.show() + + return fig, ax diff --git a/pool/shard002/Python/0026359_exceptions.py b/pool/shard002/Python/0026359_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..fb699f6ddddb08556b707367a3a4e10a01772daf --- /dev/null +++ b/pool/shard002/Python/0026359_exceptions.py @@ -0,0 +1,98 @@ +import traceback + +from django.conf import settings +from django.core.exceptions import PermissionDenied +from django.core.signals import got_request_exception +from django.http import Http404 +from django.utils.translation import gettext_lazy as _ + +from rest_framework import exceptions +from rest_framework import status +from rest_framework.response import Response +from rest_framework.views import set_rollback + + +class UnavailableForLegalReasons(exceptions.APIException): + status_code = status.HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS + default_detail = _('Unavailable for legal reasons.') + default_code = 'unavailable_for_legal_reasons' + + +def custom_exception_handler(exc, context=None): + """ + Custom exception handler for DRF, which ensures every exception we throw + is caught, returned as a nice DRF Response, while still going to sentry + etc. + + This is mostly copied from DRF exception handler, with the following + changes/additions: + - A condition preventing set_rollback() from being called in some cases + where we know there might be something to record in the database + - Handling of non-API exceptions, returning an 500 error that looks like an + API response, while still logging things to Sentry. + """ + # If propagate is true, bail early. + if settings.DEBUG_PROPAGATE_EXCEPTIONS: + raise + + if isinstance(exc, Http404): + exc = exceptions.NotFound() + elif isinstance(exc, PermissionDenied): + exc = exceptions.PermissionDenied() + + if isinstance(exc, exceptions.APIException): + headers = {} + if getattr(exc, 'auth_header', None): + headers['WWW-Authenticate'] = exc.auth_header + if getattr(exc, 'wait', None): + headers['Retry-After'] = '%d' % exc.wait + + if isinstance(exc.detail, (list, dict)): + data = exc.detail + code_or_codes = exc.get_codes() + else: + data = {'detail': exc.detail} + code_or_codes = exc.get_codes() + + # If it's not a throttled/permission denied coming from a restriction, + # we can roll the current transaction back. Otherwise don't, we may + # need to record something in the database. + # Note: `code_or_codes` can be a string, or a list of strings, or even + # a dict of strings here, depending on what happened. Fortunately the + # only thing we care about is the most basic case, a string, we don't + # need to test for the rest. + if not isinstance(exc, exceptions.Throttled) and not ( + isinstance(exc, exceptions.PermissionDenied) + and code_or_codes == 'permission_denied_restriction' + ): + set_rollback() + if isinstance(exc, UnavailableForLegalReasons): + url = 'https://www.mozilla.org/about/policy/transparency/' + headers['Link'] = f'<{url}>; rel="blocked-by"' + return Response(data, status=exc.status_code, headers=headers) + else: + # Not a DRF exception, we want to return an APIfied 500 error while + # still logging it to Sentry. + data = base_500_data() + + # Send the got_request_exception signal so other apps like sentry + # are aware of the exception. The sender does not match what a real + # exception would do (we don't have access to the handler here) but it + # should not be an issue, what matters is the request. + request = context.get('request') + sender = context.get('view').__class__ + got_request_exception.send(sender, request=request) + + # Send the 500 response back. + response = Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + return response + + +def base_500_data(): + # Start with a generic default error message. + data = {'detail': 'Internal Server Error'} + + if settings.DEBUG: + data['traceback'] = traceback.format_exc() + return data diff --git a/pool/shard002/Python/0026360_GenerateDataset.py b/pool/shard002/Python/0026360_GenerateDataset.py new file mode 100644 index 0000000000000000000000000000000000000000..d3f6b1a586cd6cee54dc0c1e610c86de4f37c72d --- /dev/null +++ b/pool/shard002/Python/0026360_GenerateDataset.py @@ -0,0 +1,90 @@ +""" +Simulate how Droplets will perform with Young's Model on Grid Graphs with different density + +Author: Yang Li +Date: July 14, 2017 + +# randomly generate N droplets with diameter = 4.5cm within a square + of length 60cm + + +""" + +from PatternFormation import * + +# 'factor' value kind of means how much strength to push each activator againt each other +def GenerateDataset(pattern_def, path_to, dens): + + (patternType, activatorHeight, activatorWidth, inhibitorHeight, inhibitorWidth, factor) = pattern_def + + lims = [27, 27] + step_size = 1.0/np.sqrt(dens) + xCoordinates = [] + yCoordinates = [] + + ''' randomly generate a set of coordination, and make sure there are no duplicated ones + ''' + for x in np.arange(0, lims[0]+1, step_size): + for y in np.arange(0, lims[1]+1, step_size): + xCoordinates.append(x) + yCoordinates.append(y) + print ("--> Coordination ready to go!") + + num = len(xCoordinates) + ag = PatternFormation(num, activatorHeight, activatorWidth, inhibitorHeight, inhibitorWidth, patternType, factor) + ag.initDroplets(xCoordinates, yCoordinates) + ag.initCircles() + print ("--> Graph ready to go!") + + imageSet = None + typeSet = None + for fi in np.arange(5, 10, 0.1): + for _ in range(100): + ag.resetDropletColors() + ag.factor = (float)('%.2f' % (-0.1*fi)) + counter = 0 + while ag.oneLoop() > 0: + counter += 1 + + # ag.drawPattern_Grid_BW('dens{}'.format(dens), lims, path_to) + print ("--> Done with drawing with factor", ag.factor) + # ag.saveData('dens{}'.format(dens), lims, path_to) + image, ptype = ag.getData() + if imageSet == None: + imageSet = image + typeSet = ptype + else: + imageSet = np.concatenate((imageSet, image), axis=0) + typeSet = np.concatenate((typeSet, ptype), axis=0) + + print typeSet.shape + print imageSet.shape + + data = { + 'image': imageSet, + 'type': typeSet } + + filename = "{}/Type-{}-[{},{},{},{}].pkl".format(path_to, patternType, activatorHeight,activatorWidth,inhibitorHeight,inhibitorWidth) + + pickle_file = open(filename, 'wb') + pickle.dump(data, pickle_file) + pickle_file.close() + + +if __name__ == "__main__": + # path_to = "D:/Github/Data/turing_pattern/Aug8_gridGraph_square" + path_to = "/Users/Yang/Documents/Data/PatternFormation/Feb6_dataset" + + # pattern_def_0 = (0, 2, 5, 6, 5, None) + pattern_def_1 = (0, 4, 10, 12, 10, None) + # pattern_def_1 = (1, 5, 2, 5, 6, -0.50) + pattern_def_2 = (2, 6, 6, 10, 10, None) + + pattern_def_set = [pattern_def_1, pattern_def_2] + for pd in pattern_def_set: + for i in range(1, 2): + dens = i + print ("\n Start! -- [Pattern]:", pd, "[dens]:", dens) + t0 = time.time() + GenerateDataset(pd, path_to, dens) + print ("\n Done! -- [Pattern]:", pd, "[dens]:", dens, "[Time used]:", time.time()-t0) diff --git a/pool/shard002/Python/0026371_settings.py b/pool/shard002/Python/0026371_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..54b69816486a67d18b2ba12212f980d07f47771f --- /dev/null +++ b/pool/shard002/Python/0026371_settings.py @@ -0,0 +1,21 @@ +import yaml + +from dataclasses import dataclass + +@dataclass +class AppConfig: + environment: str = "development" + dbtype: str = "" + dbname: str = "" + +def get_settings() -> AppConfig: + """Get application settings from configuration file""" + + with open('config/settings.yaml', 'r') as yml: + config = yaml.load(yml, Loader=yaml.FullLoader)['app'] + + return AppConfig( + environment=config['environment'], + dbtype=config['dbtype'], + dbname=config['dbname'], + ) diff --git a/pool/shard002/Python/0026377_utils.py b/pool/shard002/Python/0026377_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6e89541b608d5766046197d104144f51f7813a5c --- /dev/null +++ b/pool/shard002/Python/0026377_utils.py @@ -0,0 +1,105 @@ +import re +import socket + +import tldextract + +from domains.models import IP, TLD, Domain, Subdomain +from spyder.models import DiscoveryRelationship + + +def extract_subdomain(url): + """ + Receives a url and returns an object created by tldextract. + If there is no proper tldextract subdomain object, returns None. + If there is an IP, saves it. + :param url: + :return: + """ + extract_result = tldextract.extract(url.lower()) + # make sure we have a valid domain and TLD + if extract_result.domain and extract_result.suffix: + return extract_result + else: + # try to extract ip from url + if extract_result.domain: + ip_list = re.findall(r'[0-9]+(?:\.[0-9]+){3}', extract_result.domain) + if ip_list: + for ip in ip_list: + new_ip = IP.objects.get_or_create(ip=ip) + # return nothing + return None + + +def import_subdomain(url, discovered_by=None): + """ + Receives a url and saves the TLD/domain/subdomain. + If the subdomain isn't empty, also tries to save with an empty subdomain. + :param url: + :param discovered_by: the subdomain that pointed to the url + :return: + """ + + extract_result = extract_subdomain(url.lower()) + if extract_result: + new_tld = TLD.objects.get_or_create(tld=extract_result.suffix) + new_domain = Domain.objects.get_or_create(tld=new_tld[0], + domain=extract_result.domain) + new_subdomain = Subdomain.objects.get_or_create(domain=new_domain[0], + subdomain=extract_result.subdomain) + + # also create with empty subdomain + new_empty_subdomain = Subdomain.objects.get_or_create(domain=new_domain[0], + subdomain="") + + if discovered_by: + new_discovery_relationship = DiscoveryRelationship.objects.get_or_create( + origin_subdomain=discovered_by, + destination_subdomain=new_subdomain[0]) + new_discovery_relationship = DiscoveryRelationship.objects.get_or_create( + origin_subdomain=discovered_by, + destination_subdomain=new_empty_subdomain[0]) + + return new_subdomain[0] + else: + return None + + +def get_ip(domain): + """ + Returns the first IP address string that responds as the given domain name. + """ + try: + return socket.gethostbyname(domain) + except Exception: + return False + + +def get_ip_ex(domain): + """ + Returns an array containing one or more IP address strings that respond as the + given domain name. + """ + try: + return socket.gethostbyname_ex(domain)[2] + except Exception: + return False + + +def get_host(ip): + """ + Returns the 'True Host' name for a given IP address. + """ + try: + return socket.gethostbyaddr(ip)[0] + except Exception: + return False + + +def get_alias(domain): + """ + Returns an array containing a list of aliases for the given domain. + """ + try: + return socket.gethostbyname_ex(domain)[1] + except Exception: + return False diff --git a/pool/shard002/Python/0026380_complete_tutorial.py b/pool/shard002/Python/0026380_complete_tutorial.py new file mode 100644 index 0000000000000000000000000000000000000000..2543224ecdad3725ff4289741289a43253d4a430 --- /dev/null +++ b/pool/shard002/Python/0026380_complete_tutorial.py @@ -0,0 +1,181 @@ +import random + +from pokemongo_bot import logger +from pokemongo_bot.base_task import BaseTask +from pokemongo_bot.worker_result import WorkerResult +from pokemongo_bot.human_behaviour import sleep + + + +class CompleteTutorial(BaseTask): + + SUPPORTED_TASK_API_VERSION = 1 + + def initialize(self): + self.api = self.bot.api + self.nickname = self.config.get('nickname','') + self.team = self.config.get('team',0) + self.may_run = True + + def should_run(self): + return self.may_run + + def work(self): + + if not self.should_run(): + return WorkerResult.SUCCESS + + # Only execute the worker once to avoid error loop + self.may_run = False + + if self._check_tutorial_state(): + return WorkerResult.SUCCESS + else: + return WorkerResult.ERROR + + def _check_tutorial_state(self): + self._player=self.bot.player_data + + tutorial_state = self._player.get('tutorial_state', []) + # LEGAL_SCREEN = 0 + if not 0 in tutorial_state: + sleep(2) + if self._set_tutorial_state(0): + self.logger.info('Completed legal screen') + tutorial_state = self._player.get('tutorial_state', []) + else: + return False + + # AVATAR_SELECTION = 1 + if not 1 in tutorial_state: + sleep(7) + if self._set_avatar(): + if self._set_tutorial_state(1): + self.logger.info('Completed avatar selection') + tutorial_state = self._player.get('tutorial_state', []) + else: + return False + else: + self.logger.error('Error during avatar selection') + return False + + # POKEMON_CAPTURE = 3 + if not 3 in tutorial_state: + sleep(10) + if self._encounter_tutorial(): + self.logger.info('Completed first capture') + else: + self.logger.error('Error during first capture') + return False + + # NAME_SELECTION = 4 + if not 4 in tutorial_state: + if not self.nickname: + self.logger.info("No nickname defined in config") + return False + + self.logger.info(u'Trying to set {} as nickname'.format(self.nickname)) + sleep(5) + if self._set_nickname(self.nickname): + self._set_tutorial_state(4) + tutorial_state = self._player.get('tutorial_state', []) + else: + self.logger.error('Error trying to set nickname') + return False + + # FIRST_TIME_EXPERIENCE_COMPLETE = 7 + if not 7 in tutorial_state: + if self._set_tutorial_state(7): + self.logger.info('Completed first time experience') + else: + return False + + return True + + def _encounter_tutorial(self): + # You just need to call the API with the pokemon you choose + # Probably can't get MewTwo as first pokemon though + first_pokemon_id = random.choice([1, 4, 7]) + response_dict = self.api.encounter_tutorial_complete( + pokemon_id=first_pokemon_id) + try: + if response_dict['responses']['ENCOUNTER_TUTORIAL_COMPLETE']['result'] == 1: + return True + else: + self.logger.error("Error during encouter tutorial") + return False + except KeyError: + self.logger.error("KeyError during encouter tutorial") + return False + + def _random_avatar(self): + avatar= {} + # 0 = Male, 1 = Female + avatar['gender']=random.randint(0,1) + # What is the max value of each parameter ? + # Default is 0, anyway human player will stop + # at the first choices in general, so fully + # random on the whole avatar space is not the way to go either + avatar['skin']=random.randint(0,3) + avatar['hair']=random.randint(0,3) + avatar['shirt']=random.randint(0,3) + avatar['pants']=random.randint(0,3) + avatar['hat']=random.randint(0,3) + avatar['shoes']=random.randint(0,3) + avatar['eyes']=random.randint(0,3) + avatar['backpack']=random.randint(0,3) + return avatar + + def _set_avatar(self): + avatar = self._random_avatar() + response_dict = self.api.set_avatar(player_avatar=avatar) + status = response_dict['responses']['SET_AVATAR']['status'] + try: + if status == 1: + return True + else: + error_codes = { + 0: 'UNSET', + 1: 'SUCCESS', + 2: 'AVATAR_ALREADY_SET', + 3: 'FAILURE', + } + self.logger.error("Error during avatar selection : {}".format(error_codes[status])) + return False + except KeyError: + self.logger.error("KeyError during avatar selection") + return False + + def _set_nickname(self, nickname): + response_dict = self.api.claim_codename(codename=nickname) + try: + result = response_dict['responses']['CLAIM_CODENAME']['status'] + if result == 1: + self.logger.info(u'Name changed to {}'.format(nickname)) + return True + else: + # Would be nice to get the text directly from the proto Enum + error_codes = { + 0: 'UNSET', + 1: 'SUCCESS', + 2: 'CODENAME_NOT_AVAILABLE', + 3: 'CODENAME_NOT_VALID', + 4: 'CURRENT_OWNER', + 5: 'CODENAME_CHANGE_NOT_ALLOWED' + } + self.logger.error( + u'Error while changing nickname : {}'.format(error_codes[result])) + return False + except KeyError: + return False + + def _set_tutorial_state(self, completed): + response_dict = self.api.mark_tutorial_complete(tutorials_completed=[ + completed], send_marketing_emails=False, send_push_notifications=False) + try: + self._player = response_dict['responses'][ + 'MARK_TUTORIAL_COMPLETE']['player_data'] + return response_dict['responses']['MARK_TUTORIAL_COMPLETE']['success'] + except KeyError: + self.logger.error("KeyError while setting tutorial state") + return False diff --git a/pool/shard002/Python/0026388_reqpart.py b/pool/shard002/Python/0026388_reqpart.py new file mode 100644 index 0000000000000000000000000000000000000000..cd4c54e2003f636f3769ce30e40842bcd3a582c4 --- /dev/null +++ b/pool/shard002/Python/0026388_reqpart.py @@ -0,0 +1,69 @@ +# +# Chris Lumens +# +# Copyright 2015 Red Hat, Inc. +# +# This copyrighted material is made available to anyone wishing to use, modify, +# copy, or redistribute it subject to the terms and conditions of the GNU +# General Public License v.2. This program is distributed in the hope that it +# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the +# implied warranties 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. Any Red Hat +# trademarks that are incorporated in the source code or documentation are not +# subject to the GNU General Public License and may only be used or replicated +# with the express permission of Red Hat, Inc. +# +from pykickstart.base import KickstartCommand +from pykickstart.errors import KickstartParseError, formatErrorMsg +from pykickstart.options import KSOptionParser + +import gettext +_ = lambda x: gettext.ldgettext("pykickstart", x) + +class F23_ReqPart(KickstartCommand): + removedKeywords = KickstartCommand.removedKeywords + removedAttrs = KickstartCommand.removedAttrs + + def __init__(self, writePriority=100, *args, **kwargs): + KickstartCommand.__init__(self, writePriority, *args, **kwargs) + self.reqpart = kwargs.get("reqpart", False) + self.addBoot = kwargs.get("addBoot", False) + + self.op = self._getParser() + + def _getArgsAsStr(self): + retval = "" + + if self.addBoot: + retval += " --add-boot" + + return retval + + def __str__(self): + retval = KickstartCommand.__str__(self) + if self.reqpart: + retval += "reqpart%s\n" % self._getArgsAsStr() + return retval + + def _getParser(self): + op = KSOptionParser() + op.add_option("--add-boot", action="store_true", dest="addBoot", default=False) + return op + + def parse(self, args): + # Using reqpart and autopart at the same time is not allowed. + if self.handler.autopart.seen: + errorMsg = _("The %s and reqpart commands can't be used at the same time") % \ + "autopart" + raise KickstartParseError(formatErrorMsg(self.lineno, msg=errorMsg)) + + (opts, _extra) = self.op.parse_args(args=args, lineno=self.lineno) + self._setToSelf(self.op, opts) + self.reqpart = True + return self + +RHEL7_ReqPart = F23_ReqPart diff --git a/pool/shard002/Python/0026393_rhev-keyring.py b/pool/shard002/Python/0026393_rhev-keyring.py new file mode 100644 index 0000000000000000000000000000000000000000..7e63a024d3526d6f75b6b8aa8fb9e885b0afd05f --- /dev/null +++ b/pool/shard002/Python/0026393_rhev-keyring.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Author: Pablo Iranzo Gomez (Pablo.Iranzo@gmail.com) +# +# Description: Script for setting the keyring password for RHEV scripts +# +# Requires: python keyring +# +# 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. + +import optparse + +from rhev_functions import * + +description = """ +RHEV-keyring is a script for mantaining the keyring used by rhev script for storing password + +""" + +# Option parsing +p = optparse.OptionParser("rhev-clone.py [arguments]", description=description) +p.add_option("-u", "--user", dest="username", help="Username to connect to RHEVM API", metavar="admin@internal", + default=False) +p.add_option("-w", "--password", dest="password", help="Password to use with username", metavar="admin", + default=False) +p.add_option("-W", action="store_true", dest="askpassword", help="Ask for password", metavar="admin", default=False) +p.add_option('-q', "--query", action="store_true", dest="query", help="Query the values stored", default=False) + +(options, args) = p.parse_args() + +if options.askpassword: + options.password = getpass.getpass("Enter password: ") + +# keyring.set_password('redhat', 'kerberos', '') +# remotepasseval = keyring.get_password('redhat', 'kerberos') + +if options.query: + print "Username: %s" % keyring.get_password('rhevm-utils', 'username') + print "Password: %s" % keyring.get_password('rhevm-utils', 'password') + +if options.username: + keyring.set_password('rhevm-utils', 'username', options.username) +if options.password: + keyring.set_password('rhevm-utils', 'password', options.password) diff --git a/pool/shard002/Python/0026412_to3008.py b/pool/shard002/Python/0026412_to3008.py new file mode 100644 index 0000000000000000000000000000000000000000..f6f0463b0e39eca7cf9e1cb613bab2eb632f115f --- /dev/null +++ b/pool/shard002/Python/0026412_to3008.py @@ -0,0 +1,49 @@ +from Acquisition import aq_inner +from Acquisition import aq_parent +from Products.CMFCore.utils import getToolByName +from Products.Archetypes.config import REFERENCE_CATALOG + +def upgrade(tool): + """Added bika.lims.analysisservice.edit.js + """ + + portal = aq_parent(aq_inner(tool)) + setup = portal.portal_setup + + # update affected tools + setup.runImportStepFromProfile('profile-bika.lims:default', 'jsregistry') + + # apply new method/calculation data to old Analysis Services + portal = aq_parent(aq_inner(tool)) + pc = getToolByName(portal, 'portal_catalog') + bsc = getToolByName(portal, 'bika_setup_catalog') + rc=getToolByName(portal, REFERENCE_CATALOG) + proxies = pc(portal_type="AnalysisService") + for proxy in proxies: + an = proxy.getObject() + rels = an.at_references.objectValues() + oldmethod = None + oldinstrument = None + oldcalc = None + for rel in rels: + if rel.relationship == 'AnalysisServiceCalculation': + oldcalc=rc.lookupObject(rel.targetUID) + elif rel.relationship == 'AnalysisServiceInstrument': + oldinstrument=rc.lookupObject(rel.targetUID) + elif rel.relationship == 'AnalysisServiceMethod': + oldmethod=rc.lookupObject(rel.targetUID) + if oldmethod and oldcalc and oldinstrument: + break + + # Reset the method, instrument and calculations + if oldmethod: + an.Schema().getField('Methods').set(an, [oldmethod.UID(),]) + an.Schema().getField('_Method').set(an, oldmethod.UID()) + if oldinstrument: + an.Schema().getField('Instruments').set(an, [oldinstrument.UID(),]) + an.Schema().getField('Instrument').set(an, oldinstrument.UID()) + if oldcalc: + an.setUseDefaultCalculation(False); + an.Schema().getField('DeferredCalculation').set(an, oldcalc.UID()) + + return True diff --git a/pool/shard002/Python/0026415_init__.py b/pool/shard002/Python/0026415_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fdcd7447c89c65c4dbd06025030fdd491c024f7d --- /dev/null +++ b/pool/shard002/Python/0026415_init__.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- +""" +.. module: switching + +Aquesta llibreria proveeix de les classes i mètodes necessaris pel switching + +""" +import os + +__version__ = '2.12.2' + +_ROOT = os.path.abspath(os.path.dirname(__file__)) + + +def get_data(path): + filename = isinstance(path, (list, tuple)) and path[0] or path + return os.path.join(_ROOT, 'data', filename) diff --git a/pool/shard002/Python/0026416_user_subscriptions_dal.py b/pool/shard002/Python/0026416_user_subscriptions_dal.py new file mode 100644 index 0000000000000000000000000000000000000000..53793269cbe2003e33995e71675e72978eb0d50f --- /dev/null +++ b/pool/shard002/Python/0026416_user_subscriptions_dal.py @@ -0,0 +1,34 @@ +#! /usr/bin/env python3 + +# __author__ = "Praneesh Kataru" +# __credits__ = [] +# __version__ = "0.1.1" +# __maintainer__ = "Praneesh Kataru" +# __email__ = "pranuvitmsse05@gmail.com" +# __status__ = "Prototype" + +import json +from os import path + + +class UserSubscriptionsDAL: + db_exception = None + user_subscriptions = None + + def __init__(self): + self.user_subscription_db_file = path.join(path.dirname(path.abspath(__file__)), 'database/UserSubscriptions.json') + try: + with open(self.user_subscription_db_file, 'r') as json_data: + self.user_subscriptions = json.load(json_data) + except Exception as general_exception: + self.db_exception = general_exception + + def get_subscription_url_by_user_id(self, user_id): + """ Returns the subscription URL for stock quotes """ + if user_id in self.user_subscriptions: + ret_subscribe_url = self.user_subscriptions[user_id] + else: + ret_subscribe_url = self.user_subscriptions['restofworld'] + return self.db_exception, ret_subscribe_url + + diff --git a/pool/shard002/Python/0026417_mrf_size.py b/pool/shard002/Python/0026417_mrf_size.py new file mode 100644 index 0000000000000000000000000000000000000000..4786d5539433e2087aac858d39f19bf2cb135ffe --- /dev/null +++ b/pool/shard002/Python/0026417_mrf_size.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +# +# 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. +# +#------------------------------------------------------------------------------- +# Name: MRF_size +# Purpose: Visualize an MRF size index content +# +# Author: luci6974 +# +# Created: 30/07/2015 +# Copyright: (c) luci6974 2015-2017 +#------------------------------------------------------------------------------- + +'''Builds a GDAL vrt that visualizes the size of tiles in an MRF index''' +# +# Only trivial MRFs for now, flat files, default index name. Should be extended +# to support all MRFs +# +# It creates a gdal VRT file with a pixel per tile, where the pixel value +# is the size of the respective tile +# This is very useful to understand the state of an MRF +# Since most tiles are compressed, the size of the tile tends to be proportional +# to the entropy (information) of the data within the tile. +# + +import xml.etree.ElementTree as XML +import sys +import os.path as path + +def usage(): + print('Takes one argument, a MRF file name, ' + \ + 'builds a .vrt that contains the tile size info') + +def XMLprettify(elem, level=0): + 'XML prettifier' + i = "\n" + level*" " + if len(elem): + if not elem.text or not elem.text.strip(): + elem.text = i + " " + if not elem.tail or not elem.tail.strip(): + elem.tail = i + for elem in elem: + XMLprettify(elem, level+1) + if not elem.tail or not elem.tail.strip(): + elem.tail = i + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = i + +def attr(node, key, default): + return default if node is None or node.get(key) is None else node.get(key) + +class PointXYZC(object): + def __init__(self, node, defaults = (-1, -1, 1, 1)): + key = 'x','y','z','c' + self.x, self.y, self.z, self.c = ( + int(attr(node, key[i], defaults[i])) for i in range(4)) + + def __str__(self): + f = "PointXYZC ({p.x}, {p.y}, {p.z}, {p.c})" + return f.format(p = self) + +class BBOX(object): + def __init__(self, node, defaults): + key = 'minx', 'miny', 'maxx', 'maxy' + self.minx, self.miny, self.maxx, self.maxy = ( + float(attr(node, key[i], defaults[i])) for i in range(4)) + + def __str__(self): + f = "BBOX ({p.minx}, {p.miny}, {p.maxx}, {p.maxy})" + return f.format(p = self) + +class MRF(object): + 'MRF metadata reader' + def __init__(self, name): + try: + root = XML.parse(name).getroot() + except: + raise "Can't parse " + name + + if root.tag != 'MRF_META': + raise name + ' is not an MRF metadata file' + + self.name = name + #Get the basic raster info + self.size = PointXYZC(root.find('Raster/Size')) + self.pagesize = PointXYZC(root.find('Raster/PageSize'), + (512, 512, 1, self.size.c)) + self.projection = root.find('GeoTags/Projection').text + self.bbox = BBOX(root.find('GeoTags/BoundingBox'), + (0, 0, self.size.x, self.size.y)) + + def geotransform(self): + 'gdal style affine geotransform as a list' + return [ + self.bbox.minx, (self.bbox.maxx - self.bbox.minx)/self.size.x, 0, + self.bbox.maxy, 0, (self.bbox.miny - self.bbox.maxy)/self.size.y] + +def VRT_Size(mrf): + 'Builds and returns a gdal VRT XML tree' + xsz = int (1 + (mrf.size.x-1) / mrf.pagesize.x) + ysz = int (1 + (mrf.size.y-1) / mrf.pagesize.y) + root = XML.Element('VRTDataset', { + 'rasterXSize':str(xsz), + 'rasterYSize':str(ysz) + }) + XML.SubElement(root,'SRS').text = mrf.projection + gt = mrf.geotransform() + # Adjust for pagesize + gt[1] *= mrf.pagesize.x + gt[5] *= mrf.pagesize.y + XML.SubElement(root,'GeoTransform').text = ",".join((str(x) for x in gt)) + bands = int(mrf.size.c / mrf.pagesize.c) + for band in range(bands): + xband = XML.SubElement(root, 'VRTRasterBand', { + 'band':str(band+1), + 'dataType':'UInt32', + 'subClass':'VRTRawRasterBand' + }) + idxname = path.splitext(path.basename(mrf.name))[0] + '.idx' + XML.SubElement(xband,'SourceFilename', { 'relativetoVRT':"1" }).text =\ + idxname + XML.SubElement(xband,'ImageOffset').text = str(12 + 16 * band) + XML.SubElement(xband,'PixelOffset').text = str(16 * bands) + XML.SubElement(xband,'LineOffset').text = str(16 * xsz * bands) + XML.SubElement(xband,'NoDataValue').text = '0' + XML.SubElement(xband,'ByteOrder').text = 'MSB' + + return XML.ElementTree(root) + +def main(): + if (len(sys.argv) != 2): + usage() + return + name = sys.argv[1] + outname = path.splitext(name)[0] + '_size.vrt' + vrt = VRT_Size(MRF(name)) + XMLprettify(vrt.getroot()) + vrt.write(outname) + +if __name__ == '__main__': + main() diff --git a/pool/shard002/Python/0026420_nrk.py b/pool/shard002/Python/0026420_nrk.py new file mode 100644 index 0000000000000000000000000000000000000000..ecff3a676c25a712fc3fdd9b87586d6b6ed5f9f2 --- /dev/null +++ b/pool/shard002/Python/0026420_nrk.py @@ -0,0 +1,96 @@ +import logging +import re +from urllib.parse import urljoin + +from streamlink.plugin import Plugin, pluginmatcher +from streamlink.plugin.api import validate +from streamlink.stream.hls import HLSStream +from streamlink.stream.http import HTTPStream + +log = logging.getLogger(__name__) + + +@pluginmatcher(re.compile( + r"https?://(?:tv|radio)\.nrk\.no/(program|direkte|serie|podkast)(?:/.+)?/([^/]+)" +)) +class NRK(Plugin): + _psapi_url = 'https://psapi.nrk.no' + # Program type to manifest type mapping + _program_type_map = { + 'direkte': 'channel', + 'serie': 'program', + 'program': 'program', + 'podkast': 'podcast', + } + + _program_id_re = re.compile(r' 0: + assert padding_idx < self.num_embeddings, 'Padding_idx must be within num_embeddings' + elif padding_idx < 0: + assert padding_idx >= -self.num_embeddings, 'Padding_idx must be within num_embeddings' + padding_idx = self.num_embeddings + padding_idx + self.padding_idx = padding_idx + self.max_norm = max_norm + self.norm_type = norm_type + self.scale_grad_by_freq = scale_grad_by_freq + if _weight is None: + self.weight = nn.Parameter(torch.Tensor(num_embeddings, embedding_dim)) + self.reset_parameters() + else: + assert list(_weight.shape) == [num_embeddings, embedding_dim], \ + 'Shape of weight does not match num_embeddings and embedding_dim' + self.weight = nn.Parameter(_weight) + self.sparse = sparse + + # quantization parameters + self.p = p + self.bits = bits + self.method = method + self.update_step = update_step + self.counter = 0 + + def reset_parameters(self): + nn.init.normal_(self.weight) + if self.padding_idx is not None: + with torch.no_grad(): + self.weight[self.padding_idx].fill_(0) + + def forward(self, input): + # train with QuantNoise and evaluate the fully quantized network + p = self.p if self.training else 1 + + # update parameters every 1000 iterations + if self.counter % self.update_step == 0: + self.scale = None + self.zero_point = None + self.counter += 1 + + # quantize weight + weight_quantized, self.scale, self.zero_point = emulate_int( + self.weight.detach(), + bits=self.bits, + method=self.method, + scale=self.scale, + zero_point=self.zero_point, + ) + + # mask to apply noise + mask = torch.zeros_like(self.weight) + mask.bernoulli_(1 - p) + noise = (weight_quantized - self.weight).masked_fill(mask.bool(), 0) + + # using straight-through estimator (STE) + clamp_low = - self.scale * self.zero_point + clamp_high = self.scale * (2 ** self.bits - 1 - self.zero_point) + weight = torch.clamp(self.weight, clamp_low.item(), clamp_high.item()) + noise.detach() + + # return output + output = F.embedding( + input, weight, self.padding_idx, self.max_norm, + self.norm_type, self.scale_grad_by_freq, self.sparse) + return output + + def extra_repr(self): + s = '{num_embeddings}, {embedding_dim}' + if self.padding_idx is not None: + s += ', padding_idx={padding_idx}' + if self.max_norm is not None: + s += ', max_norm={max_norm}' + if self.norm_type != 2: + s += ', norm_type={norm_type}' + if self.scale_grad_by_freq is not False: + s += ', scale_grad_by_freq={scale_grad_by_freq}' + if self.sparse is not False: + s += ', sparse=True' + s += 'quant_noise={p}, bits={bits}, method={method}' + return s.format(**self.__dict__) diff --git a/pool/shard002/Python/0026424_conf.py b/pool/shard002/Python/0026424_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..fd696c6a1142d7e8d3ac749c6310ff69c730c139 --- /dev/null +++ b/pool/shard002/Python/0026424_conf.py @@ -0,0 +1,323 @@ +# -*- coding: utf-8 -*- +# +# This file is part of Invenio. +# Copyright (C) 2015 CERN. +# +# Invenio 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. +# +# Invenio 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 Invenio; if not, write to the +# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, +# MA 02111-1307, USA. +# +# In applying this license, CERN does not +# waive the privileges and immunities granted to it by virtue of its status +# as an Intergovernmental Organization or submit itself to any jurisdiction. + +from __future__ import print_function + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath('..')) +sys.path.insert(0, os.path.abspath('_ext')) + +import ultramock +ultramock.activate() + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.intersphinx', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'Invenio-Base' +copyright = u'2015, CERN' +author = u'CERN' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. + +# Get the version string. Cannot be done with import! +g = {} +with open(os.path.join('..', 'invenio_base', 'version.py'), 'rt') as fp: + exec(fp.read(), g) + version = g['__version__'] + +# The full version, including alpha/beta/rc tags. +release = version + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +#keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- +on_rtd = os.environ.get('READTHEDOCS', None) == 'True' + +# only set the theme when we are not on RTD +if not on_rtd: + try: + import sphinx_rtd_theme + html_theme = "sphinx_rtd_theme" + html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + except ImportError: + print("`sphinx_rtd_theme` not found, pip install it", file=sys.stderr) + html_theme = 'alabaster' + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +#html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +#html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +#html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'invenio-base_namedoc' + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', + +# Latex figure (float) alignment +#'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'invenio-base.tex', u'invenio-base Documentation', + u'CERN', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'invenio-base', u'invenio-base Documentation', + [author], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'invenio-base', u'Invenio-Base Documentation', + author, 'invenio-base', 'Base package for building the Invenio application.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'https://docs.python.org/': None} diff --git a/pool/shard002/Python/0026429_test_hold.py b/pool/shard002/Python/0026429_test_hold.py new file mode 100644 index 0000000000000000000000000000000000000000..5158945053b75714d6a75bd09a096f654606f146 --- /dev/null +++ b/pool/shard002/Python/0026429_test_hold.py @@ -0,0 +1,92 @@ +# Copyright (C) 2011-2012 by the Free Software Foundation, Inc. +# +# This file is part of GNU Mailman. +# +# GNU Mailman 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. +# +# GNU Mailman 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 +# GNU Mailman. If not, see . + +"""Additional tests for the hold chain.""" + +from __future__ import absolute_import, unicode_literals + +__metaclass__ = type +__all__ = [ + ] + + +import unittest + +from zope.component import getUtility + +from mailman.app.lifecycle import create_list +from mailman.chains.hold import autorespond_to_sender +from mailman.interfaces.autorespond import IAutoResponseSet, Response +from mailman.interfaces.usermanager import IUserManager +from mailman.testing.helpers import configuration, get_queue_messages +from mailman.testing.layers import ConfigLayer + + + +class TestAutorespond(unittest.TestCase): + """Test autorespond_to_sender()""" + + layer = ConfigLayer + + def setUp(self): + self._mlist = create_list('test@example.com') + # Python 2.7 has assertMultiLineEqual. Let this work without bounds. + self.maxDiff = None + self.eq = getattr(self, 'assertMultiLineEqual', self.assertEqual) + + @configuration('mta', max_autoresponses_per_day=1) + def test_max_autoresponses_per_day(self): + # The last one we sent was the last one we should send today. Instead + # of sending an automatic response, send them the "no more today" + # message. Start by simulating a response having been sent to an + # address already. + anne = getUtility(IUserManager).create_address('anne@example.com') + response_set = IAutoResponseSet(self._mlist) + response_set.response_sent(anne, Response.hold) + # Trigger the sending of a "last response for today" using the default + # language (i.e. the mailing list's preferred language). + autorespond_to_sender(self._mlist, 'anne@example.com') + # So first, there should be one more hold response sent to the user. + self.assertEqual(response_set.todays_count(anne, Response.hold), 2) + # And the virgin queue should have the message in it. + messages = get_queue_messages('virgin') + self.assertEqual(len(messages), 1) + # Remove the variable headers. + message = messages[0].msg + self.assertTrue('message-id' in message) + del message['message-id'] + self.assertTrue('date' in message) + del message['date'] + self.eq(messages[0].msg.as_string(), """\ +MIME-Version: 1.0 +Content-Type: text/plain; charset="us-ascii" +Content-Transfer-Encoding: 7bit +Subject: Last autoresponse notification for today +From: test-owner@example.com +To: anne@example.com +Precedence: bulk + +We have received a message from your address +requesting an automated response from the test@example.com mailing +list. + +The number we have seen today: 1. In order to avoid problems such as +mail loops between email robots, we will not be sending you any +further responses today. Please try again tomorrow. + +If you believe this message is in error, or if you have any questions, +please contact the list owner at test-owner@example.com.""") diff --git a/pool/shard002/Python/0026438_TextItem.py b/pool/shard002/Python/0026438_TextItem.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd0320c4423e9ab29ce7553d01882f14ac280f3 --- /dev/null +++ b/pool/shard002/Python/0026438_TextItem.py @@ -0,0 +1,218 @@ +import numpy as np +from ..Qt import QtCore, QtGui +from ..Point import Point +from .. import functions as fn +from .GraphicsObject import GraphicsObject + + +class TextItem(GraphicsObject): + """ + GraphicsItem displaying unscaled text (the text will always appear normal even inside a scaled ViewBox). + """ + def __init__(self, text='', color=(200,200,200), html=None, anchor=(0,0), + border=None, fill=None, angle=0, rotateAxis=None): + """ + ============== ================================================================================= + **Arguments:** + *text* The text to display + *color* The color of the text (any format accepted by pg.mkColor) + *html* If specified, this overrides both *text* and *color* + *anchor* A QPointF or (x,y) sequence indicating what region of the text box will + be anchored to the item's position. A value of (0,0) sets the upper-left corner + of the text box to be at the position specified by setPos(), while a value of (1,1) + sets the lower-right corner. + *border* A pen to use when drawing the border + *fill* A brush to use when filling within the border + *angle* Angle in degrees to rotate text. Default is 0; text will be displayed upright. + *rotateAxis* If None, then a text angle of 0 always points along the +x axis of the scene. + If a QPointF or (x,y) sequence is given, then it represents a vector direction + in the parent's coordinate system that the 0-degree line will be aligned to. This + Allows text to follow both the position and orientation of its parent while still + discarding any scale and shear factors. + ============== ================================================================================= + + + The effects of the `rotateAxis` and `angle` arguments are added independently. So for example: + + * rotateAxis=None, angle=0 -> normal horizontal text + * rotateAxis=None, angle=90 -> normal vertical text + * rotateAxis=(1, 0), angle=0 -> text aligned with x axis of its parent + * rotateAxis=(0, 1), angle=0 -> text aligned with y axis of its parent + * rotateAxis=(1, 0), angle=90 -> text orthogonal to x axis of its parent + """ + + self.anchor = Point(anchor) + self.rotateAxis = None if rotateAxis is None else Point(rotateAxis) + #self.angle = 0 + GraphicsObject.__init__(self) + self.textItem = QtGui.QGraphicsTextItem() + self.textItem.setParentItem(self) + self._lastTransform = None + self._lastScene = None + self._bounds = QtCore.QRectF() + if html is None: + self.setColor(color) + self.setText(text) + else: + self.setHtml(html) + self.fill = fn.mkBrush(fill) + self.border = fn.mkPen(border) + self.setAngle(angle) + + def setText(self, text, color=None): + """ + Set the text of this item. + + This method sets the plain text of the item; see also setHtml(). + """ + if color is not None: + self.setColor(color) + self.setPlainText(text) + + def setPlainText(self, text): + """ + Set the plain text to be rendered by this item. + + See QtGui.QGraphicsTextItem.setPlainText(). + """ + if text != self.toPlainText(): + self.textItem.setPlainText(text) + self.updateTextPos() + + def toPlainText(self): + return self.textItem.toPlainText() + + def setHtml(self, html): + """ + Set the HTML code to be rendered by this item. + + See QtGui.QGraphicsTextItem.setHtml(). + """ + if self.toHtml() != html: + self.textItem.setHtml(html) + self.updateTextPos() + + def toHtml(self): + return self.textItem.toHtml() + + def setTextWidth(self, *args): + """ + Set the width of the text. + + If the text requires more space than the width limit, then it will be + wrapped into multiple lines. + + See QtGui.QGraphicsTextItem.setTextWidth(). + """ + self.textItem.setTextWidth(*args) + self.updateTextPos() + + def setFont(self, *args): + """ + Set the font for this text. + + See QtGui.QGraphicsTextItem.setFont(). + """ + self.textItem.setFont(*args) + self.updateTextPos() + + def setAngle(self, angle): + self.angle = angle + self.updateTransform() + + def setAnchor(self, anchor): + self.anchor = Point(anchor) + self.updateTextPos() + + def setColor(self, color): + """ + Set the color for this text. + + See QtGui.QGraphicsItem.setDefaultTextColor(). + """ + self.color = fn.mkColor(color) + self.textItem.setDefaultTextColor(self.color) + + def updateTextPos(self): + # update text position to obey anchor + r = self.textItem.boundingRect() + tl = self.textItem.mapToParent(r.topLeft()) + br = self.textItem.mapToParent(r.bottomRight()) + offset = (br - tl) * self.anchor + self.textItem.setPos(-offset) + + ### Needed to maintain font size when rendering to image with increased resolution + #self.textItem.resetTransform() + ##self.textItem.rotate(self.angle) + #if self._exportOpts is not False and 'resolutionScale' in self._exportOpts: + #s = self._exportOpts['resolutionScale'] + #self.textItem.scale(s, s) + + def boundingRect(self): + return self.textItem.mapToParent(self.textItem.boundingRect()).boundingRect() + + def viewTransformChanged(self): + # called whenever view transform has changed. + # Do this here to avoid double-updates when view changes. + self.updateTransform() + + def paint(self, p, *args): + # this is not ideal because it requires the transform to be updated at every draw. + # ideally, we would have a sceneTransformChanged event to react to.. + s = self.scene() + ls = self._lastScene + if s is not ls: + if ls is not None: + ls.sigPrepareForPaint.disconnect(self.updateTransform) + self._lastScene = s + if s is not None: + s.sigPrepareForPaint.connect(self.updateTransform) + self.updateTransform() + p.setTransform(self.sceneTransform()) + + if self.border.style() != QtCore.Qt.NoPen or self.fill.style() != QtCore.Qt.NoBrush: + p.setPen(self.border) + p.setBrush(self.fill) + p.setRenderHint(p.Antialiasing, True) + p.drawPolygon(self.textItem.mapToParent(self.textItem.boundingRect())) + + def setVisible(self, v): + GraphicsObject.setVisible(self, v) + if v: + self.updateTransform() + + def updateTransform(self): + if not self.isVisible(): + return + + # update transform such that this item has the correct orientation + # and scaling relative to the scene, but inherits its position from its + # parent. + # This is similar to setting ItemIgnoresTransformations = True, but + # does not break mouse interaction and collision detection. + p = self.parentItem() + if p is None: + pt = QtGui.QTransform() + else: + pt = p.sceneTransform() + + if pt == self._lastTransform: + return + + t = pt.inverted()[0] + # reset translation + t.setMatrix(t.m11(), t.m12(), t.m13(), t.m21(), t.m22(), t.m23(), 0, 0, t.m33()) + + # apply rotation + angle = -self.angle + if self.rotateAxis is not None: + d = pt.map(self.rotateAxis) - pt.map(Point(0, 0)) + a = np.arctan2(d.y(), d.x()) * 180 / np.pi + angle += a + t.rotate(angle) + + self.setTransform(t) + + self._lastTransform = pt + + self.updateTextPos() diff --git a/pool/shard002/Python/0026441_periodic_table_widget.py b/pool/shard002/Python/0026441_periodic_table_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..986a0745028d8eeb2db423e1b8100c2e89a7689d --- /dev/null +++ b/pool/shard002/Python/0026441_periodic_table_widget.py @@ -0,0 +1,203 @@ +# +# Project: MXCuBE +# https://github.com/mxcube +# +# This file is part of MXCuBE software. +# +# MXCuBE 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. +# +# MXCuBE 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 MXCuBE. If not, see . + +PYMCA_IMPORTED = False +try: + from PyMca5.PyMca import QPeriodicTable + PYMCA_IMPORTED = 5 +except BaseException: + try: + from PyMca import QPeriodicTable + PYMCA_IMPORTED = 4 + except BaseException: + pass + +from gui.utils import QtImport + + +__credits__ = ["MXCuBE collaboration"] +__license__ = "LGPLv3+" + + +class PeriodicTableWidget(QtImport.QWidget): + + elementEdgeSelectedSignal = QtImport.pyqtSignal(str, str) + + def __init__(self, parent=None, name=None, fl=0): + + QtImport.QWidget.__init__(self, parent, QtImport.Qt.WindowFlags(fl)) + if name is not None: + self.setObjectName(name) + self.selected_element = None + self.selected_edge = "L3" + + # Signals ------------------------------------------------------------ + + # Slots --------------------------------------------------------------- + + # Graphic elements ---------------------------------------------------- + if PYMCA_IMPORTED: + self.periodic_table = CustomPeriodicTable(self) + else: + self.periodic_elements_combo = QtImport.QComboBox(self) + self.periodic_elements_combo.setFixedWidth(100) + + self.edge_widget = QtImport.QWidget(self) + edge_label = QtImport.QLabel("Edge:", self.edge_widget) + self.edge_combo = QtImport.QComboBox(self.edge_widget) + + # Layout -------------------------------------------------------------- + _edge_hlayout = QtImport.QHBoxLayout(self.edge_widget) + if not PYMCA_IMPORTED: + _edge_hlayout.addWidget(self.periodic_elements_combo) + _edge_hlayout.addWidget(edge_label) + _edge_hlayout.addWidget(self.edge_combo) + _edge_hlayout.addStretch(0) + _edge_hlayout.setSpacing(2) + _edge_hlayout.setContentsMargins(0, 0, 0, 0) + + _main_vlayout = QtImport.QVBoxLayout(self) + if PYMCA_IMPORTED: + _main_vlayout.addWidget(self.periodic_table, QtImport.Qt.AlignHCenter) + _main_vlayout.addWidget(self.edge_widget) + _main_vlayout.addStretch(0) + _main_vlayout.setSpacing(2) + _main_vlayout.setContentsMargins(2, 2, 2, 2) + + # SizePolicies -------------------------------------------------------- + + # Qt signal/slot connections ------------------------------------------ + if PYMCA_IMPORTED: + self.periodic_table.edgeSelectedSignal.connect(self.edge_selected) + else: + self.periodic_elements_combo.activated.connect(self.element_combo_activated) + self.edge_combo.addItem("K") + self.edge_combo.activated.connect(self.edge_combo_activated) + self.edge_combo.setEnabled(False) + + # Other --------------------------------------------------------------- + + def element_combo_activated(self, element): + self.selected_element = str(self.periodic_elements_combo.currentText()) + self.selected_edge = str(self.edge_combo.currentText()) + self.elementEdgeSelectedSignal.emit(self.selected_element, self.selected_edge) + + def edge_selected(self, element, edge): + self.selected_element = str(element) + self.selected_edge = str(edge) + self.edge_widget.setEnabled(self.selected_edge != "K") + + self.edge_combo.clear() + if edge == "K": + edge_list = "K" + else: + edge_list = ("L1", "L2", "L3") + for item in edge_list: + self.edge_combo.addItem(item) + self.edge_combo.setCurrentIndex(edge_list.index(item)) + self.edge_combo.setEnabled(self.edge_combo.count() > 1) + self.elementEdgeSelectedSignal.emit(self.selected_element, self.selected_edge) + + def set_current_element_edge(self, element, edge): + if PYMCA_IMPORTED: + self.periodic_table.table_element_clicked(element, edge) + + def get_selected_element_edge(self): + return self.selected_element, self.selected_edge + + def edge_combo_activated(self, item_index): + self.selected_edge = str(self.edge_combo.currentText()) + self.elementEdgeSelectedSignal.emit(self.selected_element, self.selected_edge) + + def set_elements(self, elements): + if PYMCA_IMPORTED: + self.periodic_table.setElements(elements) + else: + for element in elements: + self.periodic_elements_combo.addItem(element["symbol"]) + + +if PYMCA_IMPORTED: + + class CustomPeriodicTable(QPeriodicTable.QPeriodicTable): + + edgeSelectedSignal = QtImport.pyqtSignal(str, str) + + def __init__(self, *args): + QPeriodicTable.QPeriodicTable.__init__(self, *args) + + self.elements_dict = {} + if PYMCA_IMPORTED == 5: + self.sigElementClicked.connect(self.table_element_clicked) + else: + QtImport.QObject.connect( + self, QtImport.SIGNAL("elementClicked"), self.table_element_clicked + ) + for b in self.eltButton: + self.eltButton[b].colors[0] = QtImport.QColor(QtImport.Qt.green) + self.eltButton[b].colors[1] = QtImport.QColor(QtImport.Qt.darkGreen) + self.eltButton[b].setEnabled(False) + for el in QPeriodicTable.Elements: + symbol = el[0] + self.elements_dict[symbol] = el + + def elementEnter(self, symbol, z=None, name=None): + b = self.eltButton[symbol] + if b.isEnabled(): + b.setCurrent(True) + + def elementLeave(self, symbol): + b = self.eltButton[symbol] + if b.isEnabled(): + b.setCurrent(False) + + def table_element_clicked(self, symbol, energy=None): + if isinstance(symbol, tuple) and len(symbol) > 0: + symbol = symbol[0] + + if energy is None: + energy = self.energies_dict[symbol] + self.setSelection((symbol,)) + if energy is None: + energy = self.energies_dict[symbol] + else: + index = self.elements_dict[symbol][1] + name = self.elements_dict[symbol][4] + txt = "%s - %s (%s,%s)" % (symbol, energy, index, name) + self.eltLabel.setText(txt) + self.edgeSelectedSignal.emit(symbol, energy) + # self.widgetSynchronizeSignal([symbol, energy]) + + def setElements(self, elements): + self.energies_dict = {} + for b in self.eltButton: + self.eltButton[b].setEnabled(False) + first_element = None + for element in elements: + symbol = element["symbol"] + if first_element is None: + first_element = symbol + energy = element["energy"] + self.energies_dict[symbol] = energy + b = self.eltButton[symbol] + b.setEnabled(True) + + def widgetSynchronize(self, state): + symbol = state[0] + self.tableElementChanged(symbol) diff --git a/pool/shard002/Python/0026444_env.py b/pool/shard002/Python/0026444_env.py new file mode 100644 index 0000000000000000000000000000000000000000..5f793ff8b57b23ab0118c322adce7e866f034225 --- /dev/null +++ b/pool/shard002/Python/0026444_env.py @@ -0,0 +1,61 @@ +# 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 logging import config as log_config + +from alembic import context +from oslo_db.sqlalchemy import enginefacade + +try: + # NOTE(whaom): This is to register the DB2 alembic code which + # is an optional runtime dependency. + from ibm_db_alembic.ibm_db import IbmDbImpl # noqa +except ImportError: + pass + +from ironic.db.sqlalchemy import models + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +log_config.fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +target_metadata = models.Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + engine = enginefacade.get_legacy_facade().get_engine() + with engine.connect() as connection: + context.configure(connection=connection, + target_metadata=target_metadata) + with context.begin_transaction(): + context.run_migrations() + + +run_migrations_online() diff --git a/pool/shard002/Python/0026449_test_scatter_colormap.py b/pool/shard002/Python/0026449_test_scatter_colormap.py new file mode 100644 index 0000000000000000000000000000000000000000..cc883f74bec4ddf2cdbfef1da4099284e4da30dc --- /dev/null +++ b/pool/shard002/Python/0026449_test_scatter_colormap.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +# +import helpers + + +def plot(): + from matplotlib import pyplot as plt + import numpy as np + fig = plt.figure() + np.random.seed(123) + plt.scatter( + np.random.randn(10), + np.random.randn(10), + np.random.rand(10)*90 + 10, + np.random.randn(10) + ) + return fig + + +def test(): + phash = helpers.Phash(plot()) + assert phash.phash == 'cf616c42e4ec738c', phash.get_details() + return diff --git a/pool/shard002/Python/0026456_test_utils.py b/pool/shard002/Python/0026456_test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f4f1cb727e9036096cb4f4cb4afcda33b332ae7b --- /dev/null +++ b/pool/shard002/Python/0026456_test_utils.py @@ -0,0 +1,56 @@ +# coding: utf-8 + +""" + django find&replace + ~~~~~~~~~~~~~~~ + + :copyleft: 2015 by find&replace team, see AUTHORS for more details. + :created: 2015 by JensDiemer.de + :license: GNU GPL v3 or above, see LICENSE for more details. +""" + +from __future__ import absolute_import, print_function + +from pprint import pprint + +from django.db import models +from django.test import SimpleTestCase + +from find_and_replace.model_fields import filter_model_fields, field_list2choices, \ + field2dot_name + + +class UtilsTest(SimpleTestCase): + def test(self): + filtered_fields = filter_model_fields( + app_labels = ("auth", "cms"), + model_fields = ( + models.TextField, + models.CharField, + ) + ) + # pprint(filtered_fields) + # [, + # , + # , + # ... + # , + # ] + + field_choices = field_list2choices(filtered_fields) + pprint(field_choices) + # [(0, 'auth.Group.name'), + # (1, 'auth.Permission.codename'), + # (2, 'auth.Permission.name'), + # ... + # (30, 'cms.Title.title'), + # (31, 'cms.UserSettings.language')] + + self.assertEqual(field2dot_name(filtered_fields[2]), 'auth.Permission.name') + self.assertEqual(field_choices[2][1], 'auth.Permission.name') + + self.assertEqual(field2dot_name(filtered_fields[30]), 'cms.Title.title') + self.assertEqual(field_choices[30][1], 'cms.Title.title') + + self.assertEqual(len(filtered_fields), 32) + self.assertEqual(len(field_choices), 32) \ No newline at end of file diff --git a/pool/shard002/Python/0026462_test_dep_getcpv.py b/pool/shard002/Python/0026462_test_dep_getcpv.py new file mode 100644 index 0000000000000000000000000000000000000000..79c1514a1ce8655b7fc40156dcde65fa50390a21 --- /dev/null +++ b/pool/shard002/Python/0026462_test_dep_getcpv.py @@ -0,0 +1,37 @@ +# test_dep_getcpv.py -- Portage Unit Testing Functionality +# Copyright 2006 Gentoo Foundation +# Distributed under the terms of the GNU General Public License v2 + +from portage.tests import TestCase +from portage.dep import dep_getcpv + +class DepGetCPV(TestCase): + """ A simple testcase for isvalidatom + """ + + def testDepGetCPV(self): + + prefix_ops = [ + "<", ">", "=", "~", "<=", + ">=", "!=", "!<", "!>", "!~" + ] + + bad_prefix_ops = [">~", "<~", "~>", "~<"] + postfix_ops = [("=", "*"),] + + cpvs = ["sys-apps/portage-2.1", "sys-apps/portage-2.1", + "sys-apps/portage-2.1"] + slots = [None, ":foo", ":2"] + for cpv in cpvs: + for slot in slots: + for prefix in prefix_ops: + mycpv = prefix + cpv + if slot: + mycpv += slot + self.assertEqual(dep_getcpv(mycpv), cpv) + + for prefix, postfix in postfix_ops: + mycpv = prefix + cpv + postfix + if slot: + mycpv += slot + self.assertEqual(dep_getcpv(mycpv), cpv) diff --git a/pool/shard002/Python/0026464_present_road.py b/pool/shard002/Python/0026464_present_road.py new file mode 100644 index 0000000000000000000000000000000000000000..ae8c8a08afa0a389e994f72115e927e5ce108daa --- /dev/null +++ b/pool/shard002/Python/0026464_present_road.py @@ -0,0 +1,63 @@ +#!/usr/bin/python2.7 + +import re + +cities = {} +smallest_cost = 999999999 +biggest_cost = 0 + +class city: + def __init__(self, name): + self.name = name + self.roads = {} + + def __repr__(self): + return str(self.roads) + '\n' + + def add_road(self, destination, cost): + self.roads[destination] = cost + if destination not in cities: + new_destination = city(destination) + cities[destination] = new_destination + new_destination.add_road(self.name, cost) + elif self.name not in cities[destination].get_destinations(): + cities[destination].add_road(self.name, cost) + + def get_destinations(self): + return list(self.roads.keys()) + + def get_road_cost(self, destination): + return self.roads[destination] + +def extremum_road_cost(cities_to_visit, current_city='', cost=0): + global smallest_cost + global biggest_cost + + if len(cities_to_visit) == 0: + if cost < smallest_cost: + smallest_cost = cost + elif cost > biggest_cost: + biggest_cost = cost + else: + if current_city == '': + for first_city in cities_to_visit: + extremum_road_cost([x for x in cities_to_visit if x != first_city], first_city) + else: + for city in cities_to_visit: + extremum_road_cost([x for x in cities_to_visit if x != city], city, cost + cities[current_city].get_road_cost(city)) + +with open('input.txt') as input_file: + regex = '^(\w+) \w+ (\w+) = (\d+)' + for line in input_file: + split_line = re.search(regex, line) + if split_line.group(1) not in cities: + new_city = city(split_line.group(1)) + + new_city.add_road(split_line.group(2), int(split_line.group(3))) + cities[split_line.group(1)] = new_city + else: + cities[split_line.group(1)].add_road(split_line.group(2), int(split_line.group(3))) + +extremum_road_cost(cities.keys()) +print 'shortest_path: ' + str(smallest_cost) +print 'longest_path: ' + str(biggest_cost) \ No newline at end of file diff --git a/pool/shard002/Python/0026467_mac.py b/pool/shard002/Python/0026467_mac.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5347dd4161b08b873a76ba799c9eb079de3c08 --- /dev/null +++ b/pool/shard002/Python/0026467_mac.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +import re + + +class Mac(object): + REGEXP = r'^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$' + + def __init__(self, mac): + if type(mac) != str: + raise ValueError('Argument mac must be string') + if re.search(self.REGEXP, mac) is None: + raise ValueError('Argument mac must be valid mac') + + self.mac = mac.lower() + + def __str__(self, *args, **kwargs): + return self.mac + + def __repr__(self): + return '"{}"'.format(str(self)) + + def __eq__(self, other): + return self.mac == other.mac + + def __hash__(self): + return hash(self.mac) + + @classmethod + def correct(cls, mac): + return cls(':'.join([mac[i:i+2].lower() for i in range(0, len(mac), 2)])) + + @staticmethod + def raw(mac): + return mac.replace(":", "").upper() diff --git a/pool/shard002/Python/0026469_acsncRunSupComp.py b/pool/shard002/Python/0026469_acsncRunSupComp.py new file mode 100644 index 0000000000000000000000000000000000000000..8fca2d89026e4bc5b5dcecce4b3b9954897f0f87 --- /dev/null +++ b/pool/shard002/Python/0026469_acsncRunSupComp.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +#******************************************************************************* +# ALMA - Atacama Large Millimiter Array +# (c) Associated Universities Inc., 2002 +# (c) European Southern Observatory, 2002 +# Copyright by ESO (in the framework of the ALMA collaboration) +# and Cosylab 2002, All rights reserved +# +# 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., 59 Temple Place, Suite 330, Boston, +# MA 02111-1307 USA +# +# @(#) $Id: acsncTestConSup.py,v 1.6 2006/03/08 17:50:44 dfugate Exp $ + +""" +""" + +from Acspy.Clients.SimpleClient import PySimpleClient +from sys import argv +from time import sleep + +channel_name = str(argv[2]) +autoconnect = str(argv[3]) == 'autoreconnect' +num_sec = int(argv[4]) +num_events = int(argv[5]) +sleep_val = int(argv[6]) + +# in long numSec,in long numEvents,in long sleepVal + +# Make an instance of the PySimpleClient +simpleClient = PySimpleClient() + +supplier = simpleClient.getComponent(argv[1]) +supplier.execTest(channel_name, autoconnect, num_sec, num_events, sleep_val) +sleep(2) +simpleClient.releaseComponent(argv[1]) diff --git a/pool/shard002/Python/0026472_MyState.py b/pool/shard002/Python/0026472_MyState.py new file mode 100644 index 0000000000000000000000000000000000000000..dd6e2634c7cfdfe9e6a6118ef87edfd38803170b --- /dev/null +++ b/pool/shard002/Python/0026472_MyState.py @@ -0,0 +1,80 @@ +__author__ = 'Nicole' + +import json +import random +import time + +GREEN = 'green' +CONSERVATIVE = 'conservative' +LIBERAL = 'liberal' +LIBERTARIAN = 'libertarian' +MAX_CACHED_POINTS = 400 + +STATES = [GREEN, CONSERVATIVE, LIBERAL, LIBERTARIAN] + + +class MyStates: + def __init__(self): + self.currentStates = [CurrentStateOfParty(GREEN), CurrentStateOfParty(CONSERVATIVE), CurrentStateOfParty(LIBERAL), CurrentStateOfParty(LIBERTARIAN)] + self.newPoints = list() + self.existingPoints = list() + self.totalPoints = 0 + + def passStateToFrontEnd(self): + pointsToPass = list() + for point in self.newPoints: + self.existingPoints.append(point) + # serialize points: + pointsToPass.append(json.dumps(point.newPoint.exportToFrontEnd())) + # empty the old new points: + self.newPoints = list() + return {'newPoints': pointsToPass, 'timestamp': time.time()} + + def addNewPoint(self, point): + self.newPoints.append(point) + state = self.getState(point.party) + self.totalPoints += 1 + state.percentTotal = state.totalPoints / self.totalPoints + if self.totalPoints >= MAX_CACHED_POINTS: + self.existingPoints.pop(1) + self.totalPoints -= 1 + + +class CurrentStateOfParty: + def __init__(self, party): + self.party = party + self.percentTotal = 0 + self.certainty = 0 + self.positivity = 0 + self.totalPoints = 0 + + def addNewPoint(self, point): + self.certainty = (self.certainty * self.totalPoints + point.newPoint.tendency) / (self.totalPoints + 1) + self.positivity = (self.positivity * self.totalPoints + point.positivity) / (self.totalPoints + 1) + self.totalPoints += 1 + + def exportToFrontEnd(self): + return {'party': self.party, 'percentTotal': self.percentTotal, 'certainty': self.certainty, 'positivity': self.positivity} + + def exportRandomness(self): + return {'party': "conservative", 'percentTotal': random.randint(-60,60), 'certainty': random.randint(-60,60), 'positivity': random.randint(-60,60)} + + +class StateOfPoint: + def __init__(self): + self.newPoint = NewPoint() + self.positivity = 0 + + +class NewPoint: + def __init__(self): + self.tendency = 0 + self.lat = 0 + self.long = 0 + self.party = None + + def exportToFrontEnd(self): + return {"lat": self.lat, "long": self.long, "tendency": self.tendency, "party": self.party} + + def exportRandomness(self): + return {"lat": random.randint(-60,60), "long": random.randint(-60,60), "tendency": random.randint(-60,60), "party": random.randint(-60,60)} \ No newline at end of file diff --git a/pool/shard002/Python/0026476_json_harddisk_csv.py b/pool/shard002/Python/0026476_json_harddisk_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..98d4c1cce6e10d7179aeba24b85d3f2d6826283c --- /dev/null +++ b/pool/shard002/Python/0026476_json_harddisk_csv.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +# Copyright 2000-2019 Reciclanet Asociación Educativa-Reciclanet Hezkuntza Elkartea www.reciclanet.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 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 json +import csv +import os + +path_to_json = "./jsons/" + +try: + json_files = os.listdir(path_to_json) +except FileNotFoundError: + print("No existe el directorio " + path_to_json + " con los archivos JSON") + exit() + +with open("discos_duros.csv", "a+") as computer: + csv_write_file = csv.writer(computer) + computer.seek(0) + csv_reader = csv.reader(computer) + + for json_file in json_files: + + with open(path_to_json + json_file, "r") as read_file: + data_file = json.load(read_file) + + for index in data_file["components"]: + if index["@type"] == "HardDrive": + + for row in csv_reader: + if row[2] == index["serialNumber"]: + print("El archivo/disco ya está procesado: porque coinciden los S/N") + break + else: + print("Añadiendo línea... S/N: " + index["serialNumber"] + ", Label: " + data_file["label"]) + + try: + hdd_manufacturer = index["manufacturer"] + except KeyError: + hdd_manufacturer = "-" + + csv_write_file.writerow([ + hdd_manufacturer, + index["model"], + index["serialNumber"], + "Sobrescritura", + str(index["size"] / 1000) + " GB", + "", + data_file["label"], + ]) + break + else: + continue diff --git a/pool/shard002/Python/0026484_Historia1.py b/pool/shard002/Python/0026484_Historia1.py new file mode 100644 index 0000000000000000000000000000000000000000..4b8ca15ee9f3e16b10c31056c738729d32bcbf03 --- /dev/null +++ b/pool/shard002/Python/0026484_Historia1.py @@ -0,0 +1,48 @@ +from Personagem import Personagem +from Batalha import Batalha +from Decisao import Decisao + + +jogador = Personagem(input("Qual será o nome do seu personagem?\nR: "),100,100,100,100,100,100) +monstro = Personagem("Demonio",10,10,10,10,10,10) +batalha = Batalha() +decisao = Decisao() +print("""-------------------------------------------------- +%s era um jovem campones, vivia na tranquila vila de Edremor, quando +tudo mudou! Ele encontrou uma espada, enterrada em uma pedra e uma estranha +luz emanava dela, chamando-o para empunha-la, gritava em sua vontade, ecoava +em sua mente as palavras USE-ME, foi então que ele decidiu tira-la da pedra. + +Assim começou sua jornada! +-------------------------------------------------- +Na estrada para Ebalithur encontrou um %s, oque deseja fazer? +--------------------------------------------------"""%(jogador.Nome,monstro.Nome)) +if decisao.AtacarOuFugir() == 'ATACAR': + ganhador = batalha.Normal(jogador,monstro) + if ganhador.Nome == jogador.Nome: + print("Com um golpe certeiro na garganta de seu oponente, %s mata o %s"%(jogador.Nome,monstro.Nome)) + decisao.EscolherAtributoParaAumentar(3,ganhador) + else: + print("O jogador foi derrotado") +else: + print("---------------------------------------------------") + print("O jogador fugiu em direção a floresta!") + +print("""-------------------------------------------------- +%s adentra a floresta, e lá se depara com dois caminhos um a sua direita, +com vários galhos cheios de espinhos e um ar gelido como a brisa de inverno, +o da esquerda era ensolarado e cheio de flores, porem uma estranha sensação +lhe vinha no estomago ao olhar tambem para este caminho. +-------------------------------------------------- +Qual caminho deseja seguir, direita ou esquerda? +--------------------------------------------------"""%(jogador.Nome)) +direcaoEscolhida = decisao.Direcao(True,True,False,False,False,False) +if direcaoEscolhida == "DIREITA": + print("Você escolheu a DIREITA") +elif direcaoEscolhida == "ESQUERDA": + print("Você escolheu a ESQUERDA") +else: + print("Erro na escolha da direção!") +print("---------------------------------------------------") +print("Fim de Jogo.") +input("Pressione ENTER para finalizar") diff --git a/pool/shard002/Python/0026487_endpoint.py b/pool/shard002/Python/0026487_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7f5ad28178ef9912a6e5adf2ca2106ce484583 --- /dev/null +++ b/pool/shard002/Python/0026487_endpoint.py @@ -0,0 +1,45 @@ +# Copyright 2014-2015 Red Hat, 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. + +from oslo_config import cfg +from oslo_log import log + +from ceilometer.agent import plugin_base as plugin +from ceilometer.i18n import _LW + +LOG = log.getLogger(__name__) + +cfg.CONF.import_group('service_credentials', 'ceilometer.service') + + +class EndpointDiscovery(plugin.DiscoveryBase): + """Discovery that supplies service endpoints. + + This discovery should be used when the relevant APIs are not well suited + to dividing the pollster's work into smaller pieces than a whole service + at once. Example of this is the floating_ip pollster which calls + nova.floating_ips.list() and therefore gets all floating IPs at once. + """ + + @staticmethod + def discover(manager, param=None): + endpoints = manager.keystone.service_catalog.get_urls( + service_type=param, + endpoint_type=cfg.CONF.service_credentials.os_endpoint_type, + region_name=cfg.CONF.service_credentials.os_region_name) + if not endpoints: + LOG.warning(_LW('No endpoints found for service %s'), + "" if param is None else param) + return [] + return endpoints diff --git a/pool/shard002/Python/0026488_ExeBuilder.py b/pool/shard002/Python/0026488_ExeBuilder.py new file mode 100644 index 0000000000000000000000000000000000000000..b92300bfd193c077f941dd23219f548f8b668504 --- /dev/null +++ b/pool/shard002/Python/0026488_ExeBuilder.py @@ -0,0 +1,150 @@ +__author__ = 'matth' +import ctypes.util +import os +import shutil +import subprocess +import sys +import tempfile + +if sys.version_info[0] == 2: + from .custom_py2exe_py2 import custom_py2exe +else: + from .custom_py2exe_py3 import custom_py2exe + + +def in_directory(f, directory): + #make both absolute + directory = os.path.join(os.path.abspath(directory), '') + f = os.path.abspath(f) + + if sys.platform.startswith('win'): + directory = directory.lower() + f = f.lower() + + #return true, if the common prefix of both is equal to directory + #e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b + return os.path.commonprefix([f, directory]) == directory + + +class ExeBuilder(object): + + def __init__(self, dest_dir, script=None, module_name=None, module_exe_name=None, service_module=None, needs_admin=False, icon=None, console=True): + self.dest_dir = dest_dir + self.script = script + self.service_module = service_module + self.module_name = module_name + if service_module or module_name: + self.module_exe_base_name = os.path.splitext(module_exe_name)[0] if module_exe_name else (service_module or module_name).split('.')[-1] + else: + self.module_exe_base_name = None + self.needs_admin = needs_admin + self.icon = icon + self.console = console + self._tdir = None + + def include_cwd_in_pythonpath(self): + return True + + def include_pythoncom_and_pywintypes_in_pythonpath(self): + return True + + def create_tmp_dir(self): + tdir = tempfile.mkdtemp(prefix="pyexebuild") + return tdir + + def clean_up_tmp_dir(self, tdir): + pass + + def get_extra_relative_path_elements(self): + e = [] + # pywintypes and pythoncom have weird contortions to find DLLs: (look at the source in pywintypes.py) + # They also do something different if 'frozen' - which is the case when running from the exe + # We need to add the pywin32_system32 folder to the pythonpath: + if self.include_pythoncom_and_pywintypes_in_pythonpath(): + e.append("Lib\\site-packages\\pywin32_system32") + return e + + def build(self): + self._tdir = self.create_tmp_dir() + try: + custom_py2exe(self).build_exe() + python_dll_name = "Python%d%d.dll" % sys.version_info[:2] + self._copy_dll(python_dll_name) + if sys.version_info[0] == 3: + self._copy_dll("Python3.dll") + python_dll = ctypes.util.find_library(python_dll_name) + if not python_dll or not os.path.exists(python_dll): + raise Exception("Cannot find " + python_dll_name) + shutil.copy2(python_dll, self.dest_dir) + finally: + self.clean_up_tmp_dir(self._tdir) + self._tdir = None + + def _copy_dll(self, dll_name): + dll = ctypes.util.find_library(dll_name) + if not dll or not os.path.exists(dll): + raise Exception("Cannot find " + dll_name) + shutil.copy2(dll, self.dest_dir) + + def get_relative_built_in_python_path(self): + p = subprocess.check_output([self.get_python_executable(), "-S", "-s", "-E", "-c", "import sys; print(sys.path)"]) + pythonpath = eval(p) + + pythonpath = filter( + lambda p: os.path.isabs(p), + pythonpath) + + pythonpath = filter( + lambda p: os.path.exists(p), + pythonpath) + + pythonpath = filter( + lambda p: p.lower().rstrip('\\') == sys.prefix.lower().rstrip('\\') or in_directory(p, sys.prefix), + pythonpath) + + pythonpath = [os.path.relpath(p, sys.prefix) for p in pythonpath] + + return pythonpath + + def get_python_executable(self): + return sys.executable + + def get_code_snippet_to_set_sys_prefixes(self): + return r""" +sys.prefix = %r +sys.exec_prefix = %r +""" % (sys.prefix, sys.exec_prefix) + + def get_relative_lib_path(self): + """Returns path to python library files (usually /Lib/) relative to the executable""" + lib_path = os.path.join(sys.prefix, "Lib") + exe_path = self.dest_dir + relative_lib_path = os.path.relpath(lib_path, exe_path) + return relative_lib_path + + def get_code_snippet_to_set_sys_path(self): + return r""" +sys.path = %s[(sys.prefix if p == '.' else sys.prefix + "\\" + p) for p in %r] +import site +site.main() # Needed for Python 3.3 and up. Called automatically in 3.2 and below +""" % ( + ("[''] + " if self.include_cwd_in_pythonpath() else ""), + self.get_relative_built_in_python_path() + self.get_extra_relative_path_elements()) + + +if __name__ == '__main__': + default_dest_dir = os.path.join(os.path.dirname(sys.prefix), "bin") + import argparse + parser = argparse.ArgumentParser() + parser.add_argument('--script',help='Define a script to be made into an executable') + parser.add_argument('--module-name',help='Specify a module that should be run using runpy (i.e. like python -m)') + parser.add_argument('--module-exe-name',help='Specify name of the exe to produce for a module based exe (service-module or module-name)') + parser.add_argument('--service-module', help='A module to make into a Windows service') + parser.add_argument('--dest-dir', help='Destination directory', default=default_dest_dir) + parser.add_argument('--icon', help='Icon to use for the executable', default=None) + parser.add_argument('--admin', action="store_true", default=False, help="If specified, the created exe will request Administrator privileges") + options = parser.parse_args(sys.argv[1:]) + if not options.script and not options.service_module and not options.module_name: + parser.error("Must provide either a script, a module name or a service module name") + ExeBuilder(options.dest_dir, options.script, options.module_name, options.module_exe_name, options.service_module, options.admin, options.icon).build() + diff --git a/pool/shard002/Python/0026489_init__.py b/pool/shard002/Python/0026489_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b02b7b5bd91ee8828efea6c0fd1c9ee7dad56f61 --- /dev/null +++ b/pool/shard002/Python/0026489_init__.py @@ -0,0 +1,115 @@ +# Copyright 2018 Open Source Robotics Foundation, 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. + +from rosidl_adapter.parser import parse_message_string +from rosidl_adapter.resource import expand_template + + +def convert_msg_to_idl(package_dir, package_name, input_file, output_dir): + assert package_dir.is_absolute() + assert not input_file.is_absolute() + assert input_file.suffix == '.msg' + + abs_input_file = package_dir / input_file + print(f'Reading input file: {abs_input_file}') + abs_input_file = package_dir / input_file + content = abs_input_file.read_text(encoding='utf-8') + msg = parse_message_string(package_name, input_file.stem, content) + + output_file = output_dir / input_file.with_suffix('.idl').name + abs_output_file = output_file.absolute() + print(f'Writing output file: {abs_output_file}') + data = { + 'pkg_name': package_name, + 'relative_input_file': input_file.as_posix(), + 'msg': msg, + } + + expand_template('msg.idl.em', data, output_file, encoding='iso-8859-1') + return output_file + + +MSG_TYPE_TO_IDL = { + 'bool': 'boolean', + 'byte': 'octet', + 'char': 'uint8', + 'int8': 'int8', + 'uint8': 'uint8', + 'int16': 'int16', + 'uint16': 'uint16', + 'int32': 'int32', + 'uint32': 'uint32', + 'int64': 'int64', + 'uint64': 'uint64', + 'float32': 'float', + 'float64': 'double', + 'string': 'string', + 'wstring': 'wstring', +} + + +def to_idl_literal(idl_type, value): + if idl_type[-1] == ']' or idl_type.startswith('sequence<'): + content = repr(tuple(value)).replace('\\', r'\\').replace('"', r'\"') + return f'"{content}"' + + if 'boolean' == idl_type: + return 'TRUE' if value else 'FALSE' + if idl_type.startswith('string'): + return string_to_idl_string_literal(value) + if idl_type.startswith('wstring'): + return string_to_idl_wstring_literal(value) + return value + + +def string_to_idl_string_literal(string): + """Convert string to character literal as described in IDL 4.2 section 7.2.6.3 .""" + estr = string.encode().decode('unicode_escape') + estr = estr.replace('"', r'\"') + return '"{0}"'.format(estr) + + +def string_to_idl_wstring_literal(string): + return string_to_idl_string_literal(string) + + +def get_include_file(base_type): + if base_type.is_primitive_type(): + return None + return f'{base_type.pkg_name}/msg/{base_type.type}.idl' + + +def get_idl_type(type_): + if isinstance(type_, str): + identifier = MSG_TYPE_TO_IDL[type_] + elif type_.is_primitive_type(): + identifier = MSG_TYPE_TO_IDL[type_.type] + if ( + identifier in ('string', 'wstring') and + type_.string_upper_bound is not None + ): + identifier += f'<{type_.string_upper_bound}>' + else: + identifier = f'{type_.pkg_name}::msg::{type_.type}' + + if isinstance(type_, str) or not type_.is_array: + return identifier + + if type_.is_fixed_size_array(): + return f'{identifier}[{type_.array_size}]' + + if not type_.is_upper_bound: + return f'sequence<{identifier}>' + + return f'sequence<{identifier}, {type_.array_size}>' diff --git a/pool/shard002/Python/0026494_PhaseChangerLineAnalyzer.py b/pool/shard002/Python/0026494_PhaseChangerLineAnalyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..6edb085019deb3b7361036686d4cb95b892f589f --- /dev/null +++ b/pool/shard002/Python/0026494_PhaseChangerLineAnalyzer.py @@ -0,0 +1,37 @@ +# ICE Revision: $Id$ +"""Analyzes lines with regular expressions and changes the phase if it fits""" + +import re + +from .GeneralLineAnalyzer import GeneralLineAnalyzer + +class PhaseChangerLineAnalyzer(GeneralLineAnalyzer): + """Parses lines for an arbitrary regular expression + and sets the phase if it fits + """ + + + def __init__(self, + exp, + idNr=None): + """ + :param name: name of the expression (needed for output + :param exp: that holds the phase name + :param idNr: number of the pattern group that is used as the phase name + """ + GeneralLineAnalyzer.__init__(self, + doTimelines=False, + doFiles=False) + + self.idNr=idNr + self.exp=re.compile(exp) + self.registerRegexp(self.exp) + + def doAnalysis(self,line): + """Look for the pattern. If it matches set the phase name""" + + m=self.exp.match(line.strip()) + if m!=None: + self.setPhase(m.group(self.idNr)) + +# Should work with Python3 and Python2 diff --git a/pool/shard002/Python/0026495_setup.py b/pool/shard002/Python/0026495_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..b74774698f67e47e0a08d992b725b0e5a87b32f5 --- /dev/null +++ b/pool/shard002/Python/0026495_setup.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +# Copyright (c) 2012, 2013 Paul Tagliamonte +# +# 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. + +import os +import re +import sys + +from setuptools import find_packages, setup + +PKG = "hua" +VERSIONFILE = os.path.join(PKG, "version.py") +verstr = "unknown" +try: + verstrline = open(VERSIONFILE, "rt").read() +except EnvironmentError: + pass # Okay, there is no version file. +else: + VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" + mo = re.search(VSRE, verstrline, re.M) + if mo: + __version__ = mo.group(1) + else: + msg = "if %s.py exists, it is required to be well-formed" % VERSIONFILE + raise RuntimeError(msg) + +long_description = """Hua is a Lisp to lua compiler. It gives lua +simple and powerful meta programming ability.""" + +install_requires = ['hy>=0.11.0', 'lupa>=1.1'] +if sys.version_info[:2] < (2, 7): + install_requires.append('argparse>=1.2.1') + install_requires.append('importlib>=1.0.2') +if os.name == 'nt': + install_requires.append('pyreadline==2.0') + +setup( + name=PKG, + #version=__version__, + version="0.0.1", + install_requires=install_requires, + entry_points={ + 'console_scripts': [ + 'hua = hua.cmdline:hua_main', + 'huac = hua.cmdline:huac_main', + ] + }, + packages=find_packages(exclude=['tests*']), + package_data={ + 'hua.core': ['*.hy', '*.hua'], + }, + author="Zhao Shenyang", + author_email="dev@zsy.im", + long_description=long_description, + description='Lisp to lua compiler.', + license="Expat", + url="", + platforms=['any'], + classifiers=[ + "Development Status :: 2 - Pre-Alpha", + "Intended Audience :: Developers", + "License :: DFSG approved", + "License :: OSI Approved :: MIT License", # Really "Expat". Ugh. + "Operating System :: OS Independent", + "Programming Language :: Lisp", + "Programming Language :: lua", + "Programming Language :: Python", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.6", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.3", + "Programming Language :: Python :: 3.4", + "Topic :: Software Development :: Code Generators", + "Topic :: Software Development :: Compilers", + "Topic :: Software Development :: Libraries", + ] +) diff --git a/pool/shard002/Python/0026496_init__.py b/pool/shard002/Python/0026496_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa50b92d7b9bf6f0d92a55f269ca9683c26e89c6 --- /dev/null +++ b/pool/shard002/Python/0026496_init__.py @@ -0,0 +1,38 @@ +# Copyright 2014-2015 Luc Saffre +# This file is part of Lino Welfare. +# +# Lino Welfare 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. +# +# Lino Welfare 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 Lino Welfare. If not, see +# . +""" +This module is not actively used. +""" + +from lino.api import ad + +from django.utils.translation import ugettext_lazy as _ + + +class Plugin(ad.Plugin): + + verbose_name = _("Client projects") + + def setup_config_menu(self, site, user_type, m): + m = m.add_menu(self.app_label, self.verbose_name) + m.add_action('projects.ProjectTypes') + + def setup_explorer_menu(self, site, user_type, m): + m = m.add_menu(self.app_label, self.verbose_name) + m.add_action('projects.Projects') + + diff --git a/pool/shard002/Python/0026498_convert_dict_to_c.py b/pool/shard002/Python/0026498_convert_dict_to_c.py new file mode 100644 index 0000000000000000000000000000000000000000..b4f89e8855f52ed518456fcdd1c1e83b83d7ec9b --- /dev/null +++ b/pool/shard002/Python/0026498_convert_dict_to_c.py @@ -0,0 +1,47 @@ +## script to convert a lookup table of unicode characters from a javascript thing I found on +## github into a lookup table that can be stored in the flash on the oggbox +## +## https://github.com/yvg/js-replace-diacritics/blob/master/replace-diacritics.js +## + +fr = open("diacritical_marks_js.txt", "rb") + +d = fr.read() + +fr.close() + +fw = open("unicode_table.c", "wb") + +d = d.splitlines() +cs = {} +for line in d: + k,v = line.strip().split(":") + if k.strip("\'") == "": + k = "\x00" + v = v.strip("/[]ig,\\u") + v = v.split("\\u") + v = map(lambda x: int(x,16), v) + + for c in v: + if(c > 127): + cs[c] = k + +keys = cs.keys() +keys.sort() + +fw.write("#include \"unicode_table.h\"\n") +fw.write("\n") +fw.write("const int unicode_table_len = %d;\n" % len(keys)) +fw.write("\n") +fw.write("const struct unicode_item unicode_table[] = {\n") +for k in keys: + if len(cs[k]) == 1: + fw.write(" {%d, \"\\x%02x\"},\n" % (k, ord(cs[k]))) + else: + fw.write(" {%d, \"\\x%02x\\x%02x\"},\n" % (k, ord(cs[k][0]), ord(cs[k][1]))) + +print "Total characters:", len(cs) +print "Highest value:", max(cs.keys()) + +fw.write("};\n") +fw.close() \ No newline at end of file diff --git a/pool/shard002/Python/0026501_conf.py b/pool/shard002/Python/0026501_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..0ba4b2b192ca82ff155bc8ddf66acdd9156bd9de --- /dev/null +++ b/pool/shard002/Python/0026501_conf.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# qpimage documentation build configuration file, created by +# sphinx-quickstart on Tue Sep 26 17:55:31 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import os +import os.path as op +import sys + +import qpimage + +# include parent directory +pdir = op.dirname(op.dirname(op.abspath(__file__))) +sys.path.insert(0, pdir) +# include extensions +sys.path.append(op.abspath('extensions')) + +# RTD version +if "READTHEDOCS_VERSION" in os.environ: + rtd_version = os.environ["READTHEDOCS_VERSION"] +else: + rtd_version = "latest" +# Used for linking to libraries in the qpimage universe +rtd_link = "stable" if rtd_version != "latest" else "latest" + +# http://www.sphinx-doc.org/en/stable/ext/autodoc.html#confval-autodoc_member_order +# Order class attributes and functions in separate blocks +autodoc_member_order = 'bysource' +autoclass_content = 'both' + +# Display link to GitHub repo instead of doc on rtfd +rst_prolog = """ +:github_url: https://github.com/RI-imaging/qpimage +""" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = ['sphinx.ext.autodoc', + 'sphinx.ext.autosummary', + 'sphinx.ext.graphviz', + 'sphinx.ext.intersphinx', + 'sphinx.ext.mathjax', + 'sphinx.ext.viewcode', + 'sphinx.ext.napoleon', + 'sphinxcontrib.bibtex', + 'fancy_include', + 'github_changelog', + 'qpimage_defs', + ] + +# specify bibtex files (required for sphinxcontrib.bibtex>=2.0) +bibtex_bibfiles = ['qpimage.bib'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'qpimage' +copyright = '2017, Paul Müller' +author = 'Paul Müller' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +# +# The full version, including alpha/beta/rc tags. +# This gets 'version' +version = qpimage.__version__ +release = version + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +# html_static_path = ['_static'] + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'qpimagedoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'qpimage.tex', 'qpimage Documentation', + 'Paul Müller', 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'qpimage', 'qpimage Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'qpimage', 'qpimage Documentation', + author, 'qpimage', 'Quantitative phase image management', + 'Scientific'), +] + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ('https://docs.python.org/', None), + "numpy": ('http://docs.scipy.org/doc/numpy', None), + "scipy": ('https://docs.scipy.org/doc/scipy/reference/', None), + "skimage": ('http://scikit-image.org/docs/stable/', None), + "h5py": ('http://docs.h5py.org/en/stable/', None), + "lmfit": ('http://lmfit.github.io/lmfit-py/', None), + "nrefocus": ('http://nrefocus.readthedocs.io/en/'+rtd_link, None), + "drymass": ('http://drymass.readthedocs.io/en/'+rtd_link, None), + "qpsphere": ('http://qpsphere.readthedocs.io/en/'+rtd_link, None), + "qpformat": ('http://qpformat.readthedocs.io/en/'+rtd_link, None), + "cellsino": ('http://cellsino.readthedocs.io/en/'+rtd_link, None), +} diff --git a/pool/shard002/Python/0026508_cache_db.py b/pool/shard002/Python/0026508_cache_db.py new file mode 100644 index 0000000000000000000000000000000000000000..fc3eba810e53e5ad2290850ddea9945bf36f67d6 --- /dev/null +++ b/pool/shard002/Python/0026508_cache_db.py @@ -0,0 +1,50 @@ +import cache +import db + +class Cache_Db: + mycache = None + def __init__(self, db_conn_details, cache_conn_details): + self.mydb = db.get_connection(db_conn_details) + self.mycache = cache.get_connection(cache_conn_details) + + + def insert(self, student): + print 'inserting <' + str(student) + '> into cache_db' + if self.mydb.insert(student.student_id, student) and \ + self.mycache.insert(student.student_id, student): + return True + else: return False + + def remove(self,student_id): + if self.mydb.remove(student_id) and self.mycache.remove(student_id): + return True + else: + return False + + def get_by_id(self,student_id): + student = self.mycache.get_by_id(student_id) + if student == None: + student = self.mydb.get_by_id(student_id) + self.mycache.insert(student_id, student) + return student + + """ Currently supports only cache!""" + def get_latest(self, num): + students = self.mycache.get_latest(num) + ## following code is needed only if we assume cache is not omnipotent + #if len(students) < num: + # students = db.get_latest(num) + # cache.upsert(students) + return students + + """ Currently supports only db!""" + def get_by_attribute(self, attribute, value): + students = self.mydb.get_by_attribute(attribute, value) + return students + + def _clear(self): + self.mydb._clear() + self.mycache._clear() + +def get_connection(db_conn_details, cache_conn_details): + return Cache_Db(db_conn_details, cache_conn_details) diff --git a/pool/shard002/Python/0026509_html_soup.py b/pool/shard002/Python/0026509_html_soup.py new file mode 100644 index 0000000000000000000000000000000000000000..7803655d48d777e3a75a874f98c0b96179ac8780 --- /dev/null +++ b/pool/shard002/Python/0026509_html_soup.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Please note that the function 'make_request' is provided for your reference only. +# You will not be able to to actually use it from within the Udacity web UI +# All your changes should be in the 'extract_data' function + +from bs4 import BeautifulSoup +import requests +import json + +html_page = "page_source.html" + + +def extract_data(page): + data = {"eventvalidation": "", + "viewstate": ""} + with open(page, "r") as html: + soup = BeautifulSoup(html) + _eventValid = soup.find(id="__EVENTVALIDATION") + data["eventvalidation"]=_eventValid["value"] + _viewState = soup.find(id="__VIEWSTATE") + data["viewstate"]=_viewState["value"] + + return data + + +def make_request(data): + eventvalidation = data["eventvalidation"] + viewstate = data["viewstate"] + + r = requests.post("http://www.transtats.bts.gov/Data_Elements.aspx?Data=2", + data={'AirportList': "BOS", + 'CarrierList': "VX", + 'Submit': 'Submit', + "__EVENTTARGET": "", + "__EVENTARGUMENT": "", + "__EVENTVALIDATION": eventvalidation, + "__VIEWSTATE": viewstate + }) + + return r.text + + +def test(): + data = extract_data(html_page) + assert data["eventvalidation"] != "" + assert data["eventvalidation"].startswith("/wEWjAkCoIj1ng0") + assert data["viewstate"].startswith("/wEPDwUKLTI") + + +test() \ No newline at end of file diff --git a/pool/shard002/Python/0026512_compilemessages.py b/pool/shard002/Python/0026512_compilemessages.py new file mode 100644 index 0000000000000000000000000000000000000000..483535ddf4512f211ca380b4b78ab02737ad90b3 --- /dev/null +++ b/pool/shard002/Python/0026512_compilemessages.py @@ -0,0 +1,122 @@ +from __future__ import print_function + +import os +import re +import ujson + +from typing import Any, Dict, List, Text + +from django.core.management.commands import compilemessages +from django.conf import settings + +import polib + +from zerver.lib.i18n import with_language + +class Command(compilemessages.Command): + + def handle(self, *args, **options): + # type: (*Any, **Any) -> None + if settings.PRODUCTION: + # HACK: When using upgrade-zulip-from-git, we're in a + # production environment where STATIC_ROOT will include + # past versions; this ensures we only process the current + # version + settings.STATIC_ROOT = os.path.join(settings.DEPLOY_ROOT, "static") + settings.LOCALE_PATHS = (os.path.join(settings.DEPLOY_ROOT, 'static/locale'),) + super(Command, self).handle(*args, **options) + self.extract_language_options() + self.create_language_name_map() + + def create_language_name_map(self): + # type: () -> None + join = os.path.join + static_root = settings.STATIC_ROOT + path = join(static_root, 'locale', 'language_options.json') + output_path = join(static_root, 'locale', 'language_name_map.json') + + with open(path, 'r') as reader: + languages = ujson.load(reader) + lang_list = [] + for lang_info in languages['languages']: + name = lang_info['name'] + lang_info['name'] = with_language(name, lang_info['code']) + lang_list.append(lang_info) + + lang_list.sort(key=lambda lang: lang['name']) + + with open(output_path, 'w') as output_file: + ujson.dump({'name_map': lang_list}, output_file, indent=4) + + def get_po_filename(self, locale_path, locale): + # type: (Text, Text) -> Text + po_template = '{}/{}/LC_MESSAGES/django.po' + return po_template.format(locale_path, locale) + + def get_json_filename(self, locale_path, locale): + # type: (Text, Text) -> Text + return "{}/{}/translations.json".format(locale_path, locale) + + def extract_language_options(self): + # type: () -> None + locale_path = u"{}/locale".format(settings.STATIC_ROOT) + output_path = u"{}/language_options.json".format(locale_path) + + data = {'languages': []} # type: Dict[str, List[Dict[str, Any]]] + lang_name_re = re.compile('"Language-Team: (.*?) \(') + + locales = os.listdir(locale_path) + locales.append(u'en') + locales = list(set(locales)) + + for locale in locales: + info = {} # type: Dict[str, Any] + if locale == u'en': + data['languages'].append({ + 'code': u'en', + 'name': u'English', + }) + continue + filename = self.get_po_filename(locale_path, locale) + if not os.path.exists(filename): + continue + + with open(filename, 'r') as reader: + result = lang_name_re.search(reader.read()) + if result: + try: + name = result.group(1) + except Exception: + print("Problem in parsing {}".format(filename)) + raise + else: + raise Exception("Unknown language %s" % (locale,)) + + percentage = self.get_translation_percentage(locale_path, locale) + + info['name'] = name + info['code'] = locale + info['percent_translated'] = percentage + + if info: + data['languages'].append(info) + + with open(output_path, 'w') as writer: + ujson.dump(data, writer, indent=2) + + def get_translation_percentage(self, locale_path, locale): + # type: (Text, Text) -> int + + # backend stats + po = polib.pofile(self.get_po_filename(locale_path, locale)) + not_translated = len(po.untranslated_entries()) + total = len(po.translated_entries()) + not_translated + + # frontend stats + with open(self.get_json_filename(locale_path, locale)) as reader: + for key, value in ujson.load(reader).items(): + total += 1 + if key == value: + not_translated += 1 + + return (total - not_translated) * 100 // total diff --git a/pool/shard002/Python/0026526_gameobj_factor.py b/pool/shard002/Python/0026526_gameobj_factor.py new file mode 100644 index 0000000000000000000000000000000000000000..6da2e060a5c7da926130dabd53323935665f86d2 --- /dev/null +++ b/pool/shard002/Python/0026526_gameobj_factor.py @@ -0,0 +1,174 @@ +# Flexlay - A Generic 2D Game Editor +# 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 csv +import logging +from collections import OrderedDict + +from flexlay import ObjectBrush, Config +from .gameobj import * +from .worldmap_object import * +from .sprite import SuperTuxSprite + + +def format_sprite_name(name): + """ + sprite_name -> Sprite Name + """ + name = name.replace("_", " ") + name = name.title() + return name + + +class SuperTuxGameObjFactory: + """ + identifier: section in the .stl file, used for load and save, most of the time, also for Drag&drop + sprite: used in the object selection and/or in the ObjMapSpriteObject + functor: creates the object + + ObjectBrush(sprite, metadata) + + See editor/supertux-editor/LevelObjects/Objects.cs + """ + supertux_gui = None + + def __init__(self): + GameObj.factory = self + self.objects = OrderedDict() + # List of (identifier, image, tag) + self.badguys = [] + self.init_factories() + + def create_gameobj_at(self, identifier, pos): + data = self.objects.get(identifier) + if data is None: + logging.warning("couldn't create: %r at %s" % (identifier, pos)) + else: + _, constructor = data + obj = constructor() + obj.objmap_object.pos = pos + return obj + + def create_gameobj(self, identifier, sexpr): + data = self.objects.get(identifier) + if data is None: + logging.warning("couldn't create: %r" % identifier) + else: + _, constructor = data + obj = constructor() + obj.read(sexpr) + obj.update() + return obj + + def create_object_brushes(self): + """Creates Object Brushes for each sprite""" + # print("Creating object brushes...") + brushes = [] + for identifier, (sprite, constructor) in self.objects.items(): + if sprite is not None: + brush = ObjectBrush(SuperTuxSprite.from_file(os.path.join(Config.current.datadir, sprite)).get_sprite(), + identifier) + brushes.append(brush) + return brushes + + def add_object(self, gameobj_class): + self.objects[gameobj_class.identifier] = (gameobj_class.sprite, gameobj_class) + + def add_badguy(self, identifier, sprite, tag=None): + self.objects[identifier] = (sprite, lambda: BadGuy(identifier, sprite)) + if tag: + self.badguys.append((identifier, sprite, tag)) + else: + self.badguys.append((identifier, sprite)) + + def add_simple_object(self, identifier, sprite): + self.objects[identifier] = (sprite, lambda: SimpleObject(identifier, sprite)) + + def add_simple_tile(self, identifier, sprite): + self.objects[identifier] = (sprite, lambda: SimpleTileObject(identifier, sprite)) + + def add_particle_system(self, identifier, sprite, kind): + self.objects[identifier] = (sprite, lambda: ParticleSystem(kind, sprite)) + + def init_factories(self): + self.add_simple_object("point", "images/engine/editor/point.png") + self.add_simple_object("rock", "images/tiles/blocks/block11.png") + self.add_simple_object("heavycoin", "images/objects/coin/heavy_coin.png") + + self.add_simple_tile("unstable_tile", "images/objects/unstable_tile/crumbling-1.png") + + self.add_object(AmbientSound) + self.add_object(Background) + self.add_object(Camera) + self.add_object(Decal) + self.add_object(Dispenser) + self.add_object(SequenceTrigger) + self.add_object(ScriptTrigger) + + self.add_object(BonusBlock) + self.add_object(Candle) + self.add_object(DartTrap) + self.add_object(Door) + self.add_object(GhostFlame) + self.add_object(Gradient) + self.add_object(InfoBlock) + self.add_object(InvisibleWall) + self.add_object(LevelTime) + self.add_object(Platform) + self.add_object(Powerup) + self.add_object(Pushbutton) + self.add_object(ResetPoint) + self.add_object(ScriptedObject) + self.add_object(SecretArea) + self.add_object(SpawnPoint) + self.add_object(Switch) + self.add_object(Torch) + self.add_object(Tux) + self.add_object(Trampoline) + self.add_object(WeakBlock) + self.add_object(WilloWisp) + self.add_object(Wind) + + self.add_object(WorldmapLevel) + self.add_object(WorldmapSpawnpoint) + self.add_object(SpecialTile) + + self.add_badguy("pneumatic-platform", "images/engine/editor/pneumaticplatform.png") + self.add_badguy("bicycle-platform", "images/engine/editor/bicycleplatform.png") + self.add_badguy("flying-platform", "images/objects/flying_platform/flying_platform.sprite") + self.add_badguy("hurting_platform", "images/objects/sawblade/sawblade.sprite") + + self.add_particle_system("particles-clouds", "images/engine/editor/clouds.png", "clouds") + self.add_particle_system("particles-rain", "images/engine/editor/rain.png", "rain") + self.add_particle_system("particles-snow", "images/engine/editor/snow.png", "snow") + + self.load_CSV() + + def load_CSV(self): + with open('data/supertux/objects.csv', 'r') as csvfile: + reader = csv.reader(csvfile) + for row in reader: + identifier = row[0] + path = row[1] + name = format_sprite_name(identifier) if len(row) < 3 else row[2] + self.add_badguy(identifier, path) + + +supertux_gameobj_factory = SuperTuxGameObjFactory() + + +# EOF # diff --git a/pool/shard002/Python/0026527_test_request_daily_builds.py b/pool/shard002/Python/0026527_test_request_daily_builds.py new file mode 100644 index 0000000000000000000000000000000000000000..d3c94e326ea7b94fecd33df4b4b3f2a04fc24cc0 --- /dev/null +++ b/pool/shard002/Python/0026527_test_request_daily_builds.py @@ -0,0 +1,50 @@ +# Copyright 2010-2012 Canonical Ltd. This software is licensed under the +# GNU Affero General Public License version 3 (see the file LICENSE). + +"""Test the request_daily_builds script""" + +import transaction + +from lp.services.scripts.tests import run_script +from lp.soyuz.enums import ArchivePurpose +from lp.testing import TestCaseWithFactory +from lp.testing.layers import ZopelessAppServerLayer + + +class TestRequestDailyBuilds(TestCaseWithFactory): + + layer = ZopelessAppServerLayer + + def test_request_daily_builds(self): + """Ensure the request_daily_builds script requests daily builds.""" + prod_branch = self.factory.makeProductBranch() + prod_recipe = self.factory.makeSourcePackageRecipe( + build_daily=True, is_stale=True, branches=[prod_branch]) + pack_branch = self.factory.makePackageBranch() + pack_recipe = self.factory.makeSourcePackageRecipe( + build_daily=True, is_stale=True, branches=[pack_branch]) + self.assertEqual(0, prod_recipe.pending_builds.count()) + self.assertEqual(0, pack_recipe.pending_builds.count()) + transaction.commit() + retcode, stdout, stderr = run_script( + 'cronscripts/request_daily_builds.py', []) + self.assertIn('Requested 2 daily builds.', stderr) + self.assertEqual(1, prod_recipe.pending_builds.count()) + self.assertEqual(1, pack_recipe.pending_builds.count()) + self.assertFalse(prod_recipe.is_stale) + self.assertFalse(pack_recipe.is_stale) + + def test_request_daily_builds_oops(self): + """Ensure errors are handled cleanly.""" + archive = self.factory.makeArchive(purpose=ArchivePurpose.COPY) + recipe = self.factory.makeSourcePackageRecipe( + daily_build_archive=archive, build_daily=True) + transaction.commit() + retcode, stdout, stderr = run_script( + 'cronscripts/request_daily_builds.py', []) + self.assertEqual(0, recipe.pending_builds.count()) + self.assertIn('Requested 0 daily builds.', stderr) + self.oops_capture.sync() + self.assertEqual('NonPPABuildRequest', self.oopses[0]['type']) + self.assertEqual( + 1, len(self.oopses), "Too many OOPSes: %r" % (self.oopses,)) diff --git a/pool/shard002/Python/0026528_netcdf2tif.py b/pool/shard002/Python/0026528_netcdf2tif.py new file mode 100644 index 0000000000000000000000000000000000000000..1cf227bc170134b640ecd40fa50c75a13de49c55 --- /dev/null +++ b/pool/shard002/Python/0026528_netcdf2tif.py @@ -0,0 +1,127 @@ +"""Script to read NetCDF raster files, process and store as tif + +This requires scientific python +""" + +import os +import sys +import numpy +from Scientific.IO.NetCDF import NetCDFFile +from safe.storage.raster import Raster +from safe.storage.utilities import raster_geometry2geotransform + + +def convert_netcdf2tif(filename, n): + """Convert netcdf to tif aggregating firsts n bands + """ + + if not isinstance(filename, basestring): + msg = 'Argument filename should be a string. I got %s' % filename + raise RuntimeError(msg) + + basename, ext = os.path.splitext(filename) + msg = ('Expected NetCDF file with extension .nc - ' + 'Instead I got %s' % filename) + if ext != '.nc': + raise RuntimeError(msg) + + try: + n = int(n) + except: + msg = 'Argument N should be an integer. I got %s' % n + raise RuntimeError(msg) + + print filename, n + + # Read NetCDF file + fid = NetCDFFile(filename) + dimensions = fid.dimensions.keys() + variables = fid.variables.keys() + + title = getattr(fid, 'title') + institution = getattr(fid, 'institution') + source = getattr(fid, 'source') + history = getattr(fid, 'history') + references = getattr(fid, 'references') + conventions = getattr(fid, 'Conventions') + coordinate_system = getattr(fid, 'coordinate_system') + + print 'Read from %s' % filename + print 'Title: %s' % title + print 'Institution: %s' % institution + print 'Source: %s' % source + print 'History: %s' % history + print 'References: %s' % references + print 'Conventions: %s' % conventions + print 'Coordinate system: %s' % coordinate_system + + print 'Dimensions: %s' % dimensions + print 'Variables: %s' % variables + + # Get data + x = fid.variables['x'][:] + y = fid.variables['y'][:] + t = fid.variables['time'][:] + inundation_depth = fid.variables['Inundation_Depth'][:] + + T = inundation_depth.shape[0] # Number of time steps + M = inundation_depth.shape[1] # Steps in the y direction + N = inundation_depth.shape[2] # Steps in the x direction + + # Compute the max of the first n timesteps + A = numpy.zeros((M, N), dtype='float') + for i in range(n): + B = inundation_depth[i, :, :] + A = numpy.maximum(A, B) + + geotransform = raster_geometry2geotransform(x, y) + print 'Geotransform', geotransform + + # Write result to tif file + R = Raster(data=A, + projection="""PROJCS["DGN95 / Indonesia TM-3 zone 48.2", + GEOGCS["DGN95", + DATUM["Datum_Geodesi_Nasional_1995", + SPHEROID["WGS 84",6378137,298.257223563, + AUTHORITY["EPSG","7030"]], + TOWGS84[0,0,0,0,0,0,0], + AUTHORITY["EPSG","6755"]], + PRIMEM["Greenwich",0, + AUTHORITY["EPSG","8901"]], + UNIT["degree",0.01745329251994328, + AUTHORITY["EPSG","9122"]], + AUTHORITY["EPSG","4755"]], + UNIT["metre",1, + AUTHORITY["EPSG","9001"]], + PROJECTION["Transverse_Mercator"], + PARAMETER["latitude_of_origin",0], + PARAMETER["central_meridian",106.5], + PARAMETER["scale_factor",0.9999], + PARAMETER["false_easting",200000], + PARAMETER["false_northing",1500000], + AUTHORITY["EPSG","23834"], + AXIS["X",EAST], + AXIS["Y",NORTH]]""", + geotransform=geotransform, + keywords={'category': 'hazard', + 'subcategory': 'flood', + 'unit': 'm', + 'title': ('Hypothetical %d hour flood forecast ' + 'in Jakarta' % n)}) + R.write_to_file('%s_%d_hours.tif' % (basename, n)) + print 'Success: %d hour forecast written to %s' % (n, R.filename) + + +def usage(): + s = 'python netcdf2tif.py .nc ' + return s + +if __name__ == '__main__': + + if len(sys.argv) != 3: + print usage() + else: + filename = sys.argv[1] + N = sys.argv[2] + + convert_netcdf2tif(filename, N) diff --git a/pool/shard002/Python/0026529_setup.py b/pool/shard002/Python/0026529_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8b900659af3af7dbb286eafeeaa1e31d383c3ee2 --- /dev/null +++ b/pool/shard002/Python/0026529_setup.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +#This file is part of Tryton. The COPYRIGHT file at the top level of +#this repository contains the full copyright notices and license terms. + +from setuptools import setup, find_packages +import re + +info = eval(file('__tryton__.py').read()) + +requires = ['BeautifulSoup < 3.1'] +for dep in info.get('depends', []): + if not re.match(r'(ir|res|workflow|webdav)(\W|$)', dep): + requires.append('trytond_' + dep) + +major_version, minor_version, _ = info.get('version', '0.0.1').split('.', 2) +requires.append('trytond >= %s.%s' % (major_version, minor_version)) +requires.append('trytond < %s.%s' % (major_version, int(minor_version) + 1)) + +setup(name='trytond_google_translate', + version=info.get('version', '0.0.1'), + description=info.get('description', ''), + author=info.get('author', ''), + author_email=info.get('email', ''), + url=info.get('website', ''), + download_url="http://downloads.tryton.org/" + \ + info.get('version', '0.0.1').rsplit('.', 1)[0] + '/', + package_dir={'trytond.modules.google_translate': '.'}, + packages=[ + 'trytond.modules.google_translate', + ], + package_data={ + 'trytond.modules.google_translate': info.get('xml', []) \ + + info.get('translation', []), + }, + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Environment :: Plugins', + 'Intended Audience :: Developers', + 'Intended Audience :: Financial and Insurance Industry', + 'Intended Audience :: Legal Industry', + 'Intended Audience :: Manufacturing', + 'License :: OSI Approved :: GNU General Public License (GPL)', + 'Natural Language :: English', + 'Natural Language :: French', + 'Natural Language :: German', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Topic :: Office/Business', + ], + license='GPL-3', + install_requires=requires, + zip_safe=False, + entry_points=""" + [trytond.modules] + google_translate = trytond.modules.google_translate + """, +) diff --git a/pool/shard002/Python/0026531_setup.py b/pool/shard002/Python/0026531_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..e517d346f4bd11bdbae825df1b82ef49ebc113f7 --- /dev/null +++ b/pool/shard002/Python/0026531_setup.py @@ -0,0 +1,73 @@ +from setuptools import find_packages, setup, Extension +import subprocess +import sys +import os + +def install_and_import(package): + import importlib + try: + importlib.import_module(package) + except ImportError: + import pip + pip.main(['install', package]) + finally: + globals()[package] = importlib.import_module(package) + +# make sure numpy is installed, as we need numpy to compile the C extensions. +# If numpy is not installed, automatically install it using pip. +install_and_import('numpy') + +def generate_cython(): + cwd = os.path.abspath(os.path.dirname(__file__)) + print("Cythonizing sources") + p = subprocess.call([sys.executable, os.path.join(cwd, + 'build_tools', + 'cythonize.py'), + 'py_stringmatching'], + cwd=cwd) + if p != 0: + raise RuntimeError("Running cythonize failed!") + + +if __name__ == "__main__": + + no_frills = (len(sys.argv) >= 2 and ('--help' in sys.argv[1:] or + sys.argv[1] in ('--help-commands', + 'egg_info', '--version', + 'clean'))) + + cwd = os.path.abspath(os.path.dirname(__file__)) + if not os.path.exists(os.path.join(cwd, 'PKG-INFO')) and not no_frills: + # Generate Cython sources, unless building from source release + generate_cython() + + # specify extensions that need to be compiled + extensions = [Extension("py_stringmatching.similarity_measure.cython_levenshtein", + ["py_stringmatching/similarity_measure/cython_levenshtein.c"], + include_dirs=[numpy.get_include()])] + + # find packages to be included. exclude benchmarks. + packages = find_packages(exclude=["benchmarks"]) + + setup( + name='py_stringmatching', + version='0.1.1', + description='Python library for string matching.', + long_description=""" + String matching is an important problem in many settings such as data integration, natural language processing,etc. + This package aims to implement most commonly used string matching measures. + """, + url='http://github.com/anhaidgroup/py_stringmatching', + author='Paul Suganthan G. C.', + author_email='paulgc@cs.wisc.edu', + license=['BSD'], + packages=packages, + install_requires=[ + 'numpy >= 1.7.0', + 'six' + ], + ext_modules=extensions, + include_package_data=True, + zip_safe=False + ) + diff --git a/pool/shard002/Python/0026534_testperf.py b/pool/shard002/Python/0026534_testperf.py new file mode 100644 index 0000000000000000000000000000000000000000..7891eebba21ac5f84dfbcf1db82277b919ffb3ce --- /dev/null +++ b/pool/shard002/Python/0026534_testperf.py @@ -0,0 +1,64 @@ +import unittest +import numpy as np +from .. import DataSet, perf, helpers + +class TestPerf(unittest.TestCase): + def setUp(self): + np.random.seed(1) + self.d = DataSet( + X=helpers.to_one_of_n([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0]), + Y=helpers.to_one_of_n([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2])) + + def test_class_loss(self): + d = self.d + targets = np.array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]).astype(bool) + d2 = DataSet(X=d.X + (0.1 * np.random.rand(*d.X.shape)), default=d) + np.testing.assert_equal(perf.class_loss(d), targets) + np.testing.assert_equal(perf.class_loss(d2), targets) + + def test_accurracy(self): + self.assertEqual(perf.accuracy(self.d), (12 - 3) / 12.) + + def test_conf_mat(self): + c = perf.conf_mat(self.d) + ct = np.array([[3, 1, 0], [0, 3, 1], [1, 0, 3]]) + np.testing.assert_equal(c, ct) + + def test_format_confusion_matrix(self): + c = perf.format_confmat(perf.conf_mat(self.d), self.d) + target = [['Label\\Pred.', 'class0', 'class1', 'class2'], + ['class0', 3, 1, 0], + ['class1', 0, 3, 1], + ['class2', 1, 0, 3]] + self.assertEqual(c, target) + + def test_AUC(self): + d1 = DataSet(helpers.to_one_of_n([0, 0, 1, 1, 1, 1]).T, + helpers.to_one_of_n([0, 0, 1, 1, 1, 1]).T) + d0 = DataSet(helpers.to_one_of_n([1, 1, 0, 0, 0, 0]).T, + helpers.to_one_of_n([0, 0, 1, 1, 1, 1]).T) + dr = DataSet(helpers.to_one_of_n([1, 0, 1, 0, 1, 0]).T, + helpers.to_one_of_n([1, 1, 1, 1, 0, 0]).T) + + self.assertEqual(perf.auc(d0), 0) + self.assertEqual(perf.auc(d1), 1) + self.assertEqual(perf.auc(dr), .5) + + def test_mutinf(self): + d1 = DataSet(helpers.to_one_of_n([0, 0, 0, 1, 1, 1]).T, + helpers.to_one_of_n([0, 0, 0, 1, 1, 1]).T) + d0 = DataSet(helpers.to_one_of_n([1, 1, 1, 0, 0, 0]).T, + helpers.to_one_of_n([0, 0, 0, 1, 1, 1]).T) + dr = DataSet(helpers.to_one_of_n([1, 0, 1, 0, 1, 0]).T, + helpers.to_one_of_n([1, 1, 1, 1, 0, 0]).T) + + self.assertAlmostEqual(perf.mutinf(d1), 1) + self.assertAlmostEqual(perf.mutinf(d0), 1) + self.assertAlmostEqual(perf.mutinf(dr), 0) + + def test_mean_std(self): + ds = [DataSet(xs=np.random.rand(30, 2), ys=helpers.to_one_of_n( + np.arange(30) % 2).T) for i in range(20)] + m, s = perf.mean_std(perf.auc, ds) + self.assertAlmostEqual(m, 0.5, 1) + self.assertAlmostEqual(s, 0.1, 1) diff --git a/pool/shard002/Python/0026535_vmware_guest_tools_upgrade.py b/pool/shard002/Python/0026535_vmware_guest_tools_upgrade.py new file mode 100644 index 0000000000000000000000000000000000000000..34c627ebd5c88026031829a0ae93ca1a1c31ae1e --- /dev/null +++ b/pool/shard002/Python/0026535_vmware_guest_tools_upgrade.py @@ -0,0 +1,180 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# Copyright: (c) 2018, Mike Klebolt +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = ''' +--- +module: vmware_guest_tools_upgrade +short_description: Module to upgrade VMTools +version_added: 2.8 +description: + - This module upgrades the VMware Tools on Windows and Linux guests. +requirements: + - "python >= 2.6" + - PyVmomi +notes: + - In order to upgrade VMTools, please power on virtual machine before hand - either 'manually' or using module M(vmware_guest_powerstate). +options: + name: + description: + - Name of the virtual machine to work with. + - This is required if C(UUID) is not supplied. + name_match: + description: + - If multiple virtual machines matching the name, use the first or last found. + default: 'first' + choices: ['first', 'last'] + uuid: + description: + - UUID of the instance to manage if known, this is VMware's unique identifier. + - This is required if C(name) is not supplied. + folder: + description: + - Destination folder, absolute or relative path to find an existing guest. + - This is required, if C(name) is supplied. + - The folder should include the datacenter. ESX's datacenter is ha-datacenter + - 'Examples:' + - ' folder: /ha-datacenter/vm' + - ' folder: ha-datacenter/vm' + - ' folder: /datacenter1/vm' + - ' folder: datacenter1/vm' + - ' folder: /datacenter1/vm/folder1' + - ' folder: datacenter1/vm/folder1' + - ' folder: /folder1/datacenter1/vm' + - ' folder: folder1/datacenter1/vm' + - ' folder: /folder1/datacenter1/vm/folder2' + - ' folder: vm/folder2' + datacenter: + description: + - Destination datacenter where the virtual machine exists. + required: True +extends_documentation_fragment: vmware.documentation +author: + - Mike Klebolt (@MikeKlebolt) +''' + +EXAMPLES = ''' +- name: Upgrade VMware Tools + vmware_guest_tools_upgrade: + hostname: "{{ vcenter_hostname }}" + username: "{{ vcenter_username }}" + password: "{{ vcenter_password }}" + datacenter: "{{ datacenter_name }}" + uuid: 421e4592-c069-924d-ce20-7e7533fab926 + delegate_to: localhost +''' + +RETURN = ''' # ''' + + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec, wait_for_task +from ansible.module_utils._text import to_native + + +class PyVmomiHelper(PyVmomi): + def __init__(self, module): + super(PyVmomiHelper, self).__init__(module) + + def upgrade_tools(self, vm): + result = {'failed': False, 'changed': False, 'msg': ''} + # Exit if VMware tools is already up to date + if vm.guest.toolsStatus == "toolsOk": + result.update( + changed=False, + msg="VMware tools is already up to date", + ) + return result + + # Fail if VM is not powered on + elif vm.summary.runtime.powerState != "poweredOn": + result.update( + failed=True, + msg="VM must be powered on to upgrade tools", + ) + return result + + # Fail if VMware tools is either not running or not installed + elif vm.guest.toolsStatus in ["toolsNotRunning", "toolsNotInstalled"]: + result.update( + failed=True, + msg="VMware tools is either not running or not installed", + ) + return result + + # If vmware tools is out of date, check major OS family + # Upgrade tools on Linux and Windows guests + elif vm.guest.toolsStatus == "toolsOld": + try: + if vm.guest.guestFamily in ["linuxGuest", "windowsGuest"]: + task = vm.UpgradeTools() + changed, err_msg = wait_for_task(task) + result.update(changed=changed, msg=to_native(err_msg)) + else: + result.update(msg='Guest Operating System is other than Linux and Windows.') + return result + except Exception as exc: + result.update( + failed=True, + msg='Error while upgrading VMware tools %s' % to_native(exc), + ) + return result + else: + result.update( + failed=True, + msg="VMware tools could not be upgraded", + ) + return result + + +def main(): + argument_spec = vmware_argument_spec() + argument_spec.update( + name=dict(type='str'), + name_match=dict(type='str', choices=['first', 'last'], default='first'), + uuid=dict(type='str'), + folder=dict(type='str'), + datacenter=dict(type='str', required=True), + ) + module = AnsibleModule(argument_spec=argument_spec, + required_one_of=[['name', 'uuid']]) + + if module.params['folder']: + # FindByInventoryPath() does not require an absolute path + # so we should leave the input folder path unmodified + module.params['folder'] = module.params['folder'].rstrip('/') + + pyv = PyVmomiHelper(module) + # Check if the VM exists before continuing + vm = pyv.get_vm() + + # VM already exists + if vm: + try: + result = pyv.upgrade_tools(vm) + if result['changed']: + module.exit_json(changed=result['changed']) + elif result['failed']: + module.fail_json(msg=result['msg']) + else: + module.exit_json(msg=result['msg'], changed=result['changed']) + except Exception as exc: + module.fail_json(msg='Unknown error: %s' % to_native(exc)) + else: + module.fail_json(msg='Unable to find VM %s' % (module.params.get('uuid') or module.params.get('name'))) + + +if __name__ == '__main__': + main() diff --git a/pool/shard002/Python/0026538_gftools-gen-html.py b/pool/shard002/Python/0026538_gftools-gen-html.py new file mode 100644 index 0000000000000000000000000000000000000000..7b803f1a971594501077fc05c5bb6dae51a2a826 --- /dev/null +++ b/pool/shard002/Python/0026538_gftools-gen-html.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +""" +gftools gen-html aka diffbrowsers2. + +Generate html documents to proof a font family, or generate documents to +diff two families. + +Examples: +# Generate proofing documents for a single font +gftools gen-html proof font1.ttf + +# Generate proofing documents for a family of fonts +gftools gen-html proof font1.ttf font2.ttf font3.ttf + +# Output test pages to a dir +gftools gen-html proof font1.ttf -o ~/Desktop/myFamily + +# Generate proofing documents and output images using Browserstack +# (a subscription is required) +gftools gen-html proof font1.ttf --imgs + +# Generate diff documents +gftools gen-html diff -fb ./fonts_before/font1.ttf -fa ./fonts_after/font1.ttf +""" +from pkg_resources import resource_filename +from gftools.html import HtmlProof, HtmlDiff +import argparse + + +def main(): + html_templates_dir = resource_filename("gftools", "templates") + + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers( + dest="command", required=True, metavar='"proof" or "diff"' + ) + + # Optional args which can be used in all subparsers + universal_options_parser = argparse.ArgumentParser(add_help=False) + universal_options_parser.add_argument( + "--pages", + nargs="+", + help="Choose which templates to populate. By default, all templates " + "are populated.", + ) + universal_options_parser.add_argument( + "--pt-size", "-pt", help="Change pt size of document text", default=14 + ) + universal_options_parser.add_argument( + "--imgs", + action="store_true", + help="Output images using Browserstack.", + ) + universal_options_parser.add_argument( + "--out", "-o", help="Output dir", default="diffbrowsers" + ) + universal_options_parser.add_argument( + "--template-dir", + "-td", + help="HTML template directory. By default, gftools/templates is used.", + default=resource_filename("gftools", "templates"), + ) + + proof_parser = subparsers.add_parser( + "proof", + parents=[universal_options_parser], + help="Generate html proofing documents for a family", + ) + proof_parser.add_argument("fonts", nargs="+") + + diff_parser = subparsers.add_parser( + "diff", + parents=[universal_options_parser], + help="Generate html diff documents which compares two families. " + "Variable fonts can be compared against static fonts because we " + "match the fvar instances against the static fonts. To Match fonts " + "we use the font's name table records. For static fonts, the fullname " + "is used e.g 'Maven Pro Medium'. For variable fonts, the family name " + "+ fvar instance subfamilyname is used e.g 'Maven Pro' + 'Medium'.", + ) + diff_parser.add_argument("--fonts-before", "-fb", nargs="+", required=True) + diff_parser.add_argument("--fonts-after", "-fa", nargs="+", required=True) + + args = parser.parse_args() + + if args.command == "proof": + html = HtmlProof(args.fonts, args.out, template_dir=args.template_dir) + + elif args.command == "diff": + html = HtmlDiff( + args.fonts_before, + args.fonts_after, + args.out, + template_dir=args.template_dir, + ) + + html.build_pages(args.pages, pt_size=args.pt_size) + + if args.imgs: + html.save_imgs() + + +if __name__ == "__main__": + main() diff --git a/pool/shard002/Python/0026539_log_reporter.py b/pool/shard002/Python/0026539_log_reporter.py new file mode 100644 index 0000000000000000000000000000000000000000..58b27f69102410f0a0b34fc2e4acdb112082591f --- /dev/null +++ b/pool/shard002/Python/0026539_log_reporter.py @@ -0,0 +1,88 @@ +from collections import deque +from functools import wraps +from threading import Condition, Event, Lock + + +def chunked(buffer, chunk_size=4096): + """ + Given a deque, chunk it up into ~chunk_size, but be aware of newline + termination as an intended goal. + """ + result = '' + while buffer: + result += buffer.popleft() + while '\n' in result: + newline_pos = result.rfind('\n', 0, chunk_size) + if newline_pos == -1: + newline_pos = chunk_size + else: + newline_pos += 1 + yield result[:newline_pos] + result = result[newline_pos:] + + if result: + yield result + + +def _locked(func): + @wraps(func) + def wrapped(self, *args, **kwargs): + with self.lock: + return func(self, *args, **kwargs) + return wrapped + + +class ThreadSafeDeque(deque): + def __init__(self, *args, **kwargs): + self.lock = Lock() + super().__init__(*args, **kwargs) + + append = _locked(deque.append) + appendleft = _locked(deque.appendleft) + clear = _locked(deque.clear) + extend = _locked(deque.extend) + extendleft = _locked(deque.extendleft) + pop = _locked(deque.pop) + popleft = _locked(deque.popleft) + remove = _locked(deque.remove) + reverse = _locked(deque.reverse) + rotate = _locked(deque.rotate) + + +class LogReporter(object): + source = 'console' + + def __init__(self, api, jobstep_id, source=None): + self.api = api + self.jobstep_id = jobstep_id + if source is not None: + self.source = source + + self.buffer = ThreadSafeDeque() + self.done = Event() + self.cv = Condition() + + def process(self): + with self.cv: + self.done.clear() + while not self.done.is_set() or self.buffer: + for chunk in chunked(self.buffer): + self.api.append_log(self.jobstep_id, { + 'text': chunk, + 'source': self.source, + }) + if not self.done.is_set(): + self.cv.wait(5) + + def write(self, chunk): + with self.cv: + self.buffer.append(chunk) + self.cv.notifyAll() + + def close(self): + with self.cv: + self.done.set() + self.cv.notifyAll() + + def flush(self): + pass diff --git a/pool/shard002/Python/0026541_darkamp.py b/pool/shard002/Python/0026541_darkamp.py new file mode 100644 index 0000000000000000000000000000000000000000..51c845503a833ccfef8c85d17373854e34dd755d --- /dev/null +++ b/pool/shard002/Python/0026541_darkamp.py @@ -0,0 +1,135 @@ +from twisted.internet.defer import gatherResults, maybeDeferred +from twisted.protocols.amp import AMP, Command, Integer, String, Unicode + +class BranchLeafError(Exception): + """ + You thought I was a branch. + + FYI I am a leaf. + """ + +class UnknownHashError(Exception): + """ + The requested hash could not be found. + + This probably isn't fatal. + """ + +class Bai(Command): + + arguments = [] + response = [] + + requiresAnswer = False + +class CheckAPI(Command): + + arguments = [] + response = [("version", Integer())] + +class HazTree(Command): + + arguments = [ + ("hash", String()), + ("size", Integer()), + ] + response = [ + ("first_hash", String()), + ("first_size", Integer()), + ("second_hash", String()), + ("second_size", Integer()), + ] + errors = { + BranchLeafError: "BRANCH_LEAF", + UnknownHashError: "UNKNOWN_HASH", + } + +class KThnxBai(Command): + + arguments = [] + response = [] + + requiresAnswer = False + +class SendPeze(Command): + + arguments = [ + ("hash", String()), + ("size", Integer()), + ("piece", Integer()), + ] + response = [ + ("data", String()), + ] + +class Version(Command): + + arguments = [] + response = [("version", Unicode())] + +class DarkAMP(AMP): + + remote_version = "Unknown" + remote_api = "Unknown" + + def bai(self): + self.transport.loseConnection() + Bai.responder(bai) + + def checkapi(self): + return {"version": 2} + CheckAPI.responder(checkapi) + + def haztree(self, hash, size): + branch = self.factory.db.find_branch(hash, size) + if not branch: + raise UnknownHashError() + if branch.is_leaf: + raise BranchLeafError() + return { + "first_hash": branch.children[0].hash, + "first_size": branch.children[0].size, + "second_hash": branch.children[1].hash, + "second_size": branch.children[1].size, + } + HazTree.responder(haztree) + + def kthnxbai(self): + self.callRemote(Bai) + self.transport.loseConnection() + KThnxBai.responder(kthnxbai) + + def sendpeze(self, hash, size, piece): + d = maybeDeferred(self.factory.sendpeze, hash, size, piece) + @d.addCallback + def cb(data): + if data is None: + raise UnknownHashError("Couldn't find hash") + return {"data": data} + return d + SendPeze.responder(sendpeze) + + def version(self): + return {"version": "Darklight pre-alpha"} + Version.responder(version) + + def get_remote_info(self): + """ + Get information about this connection. + + Returns a Deferred which will fire with a tuple of API and version. + """ + + d1 = self.callRemote(CheckAPI) + @d1.addCallback + def cb1(d): + self.remote_api = d["version"] + return self.remote_api + + d2 = self.callRemote(Version) + @d2.addCallback + def cb2(d): + self.remote_version = d["version"] + return self.remote_version + + return gatherResults([d1, d2]) diff --git a/pool/shard002/Python/0026542_acceptance_tests.py b/pool/shard002/Python/0026542_acceptance_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..ebed4e9b4915a5a6642ca253d87d6fbedf57d984 --- /dev/null +++ b/pool/shard002/Python/0026542_acceptance_tests.py @@ -0,0 +1,40 @@ +import os.path +import unittest +import subprocess +import logging + +logging.basicConfig(level=logging.INFO) + +php_interpreter = "php" +python_interpreter = "python" +if os.path.isfile("t/config.py"): + import config + php_interpreter = config.php + python_interpreter = config.python + + +def comparison_factory(php_file_name): + def unit_test_actual(self): + subprocess.call([python_interpreter, "php2py.py", php_file_name]) + php_result = subprocess.check_output([php_interpreter, php_file_name]) + python_result = subprocess.check_output([python_interpreter, "php2py_run.py", php_file_name]) + self.assertSequenceEqual(php_result.split(b"\n"), python_result.split(b"\n")) + return unit_test_actual + + +class ComparisonTests(unittest.TestCase): + pass + + +# TODO: autogeneration of list +tests = [ + "hello00", + "hello01", + "hello02", + "defines00", + "defines01", +] +for t in tests: + test_name = "test_{}".format(t) + php_file_name = "t/php/{}.php".format(t) + setattr(ComparisonTests, test_name, comparison_factory(php_file_name)) diff --git a/pool/shard002/Python/0026543_test_server.py b/pool/shard002/Python/0026543_test_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e03855d943fc42bb20b648a9a8e7650e82d5b1 --- /dev/null +++ b/pool/shard002/Python/0026543_test_server.py @@ -0,0 +1,209 @@ +"""Tests for the HTTP server.""" +# -*- coding: utf-8 -*- +# vim: set fileencoding=utf-8 : + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +import os +import socket +import tempfile +import threading + +import pytest +import requests +import requests_unixsocket + +from .._compat import bton, ntob +from .._compat import IS_MACOS +from ..server import IS_UID_GID_RESOLVABLE, Gateway, HTTPServer +from ..testing import ( + ANY_INTERFACE_IPV4, + ANY_INTERFACE_IPV6, + EPHEMERAL_PORT, + get_server_client, +) + + +unix_only_sock_test = pytest.mark.skipif( + not hasattr(socket, 'AF_UNIX'), + reason='UNIX domain sockets are only available under UNIX-based OS', +) + + +non_macos_sock_test = pytest.mark.skipif( + IS_MACOS, + reason='Peercreds lookup does not work under macOS/BSD currently.', +) + + +@pytest.fixture +def unix_sock_file(): + """Check that bound UNIX socket address is stored in server.""" + tmp_sock_fh, tmp_sock_fname = tempfile.mkstemp() + + yield tmp_sock_fname + + os.close(tmp_sock_fh) + os.unlink(tmp_sock_fname) + + +def test_prepare_makes_server_ready(): + """Check that prepare() makes the server ready, and stop() clears it.""" + httpserver = HTTPServer( + bind_addr=(ANY_INTERFACE_IPV4, EPHEMERAL_PORT), + gateway=Gateway, + ) + + assert not httpserver.ready + assert not httpserver.requests._threads + + httpserver.prepare() + + assert httpserver.ready + assert httpserver.requests._threads + for thr in httpserver.requests._threads: + assert thr.ready + + httpserver.stop() + + assert not httpserver.requests._threads + assert not httpserver.ready + + +def test_stop_interrupts_serve(): + """Check that stop() interrupts running of serve().""" + httpserver = HTTPServer( + bind_addr=(ANY_INTERFACE_IPV4, EPHEMERAL_PORT), + gateway=Gateway, + ) + + httpserver.prepare() + serve_thread = threading.Thread(target=httpserver.serve) + serve_thread.start() + + serve_thread.join(0.5) + assert serve_thread.is_alive() + + httpserver.stop() + + serve_thread.join(0.5) + assert not serve_thread.is_alive() + + +@pytest.mark.parametrize( + 'ip_addr', + ( + ANY_INTERFACE_IPV4, + ANY_INTERFACE_IPV6, + ), +) +def test_bind_addr_inet(http_server, ip_addr): + """Check that bound IP address is stored in server.""" + httpserver = http_server.send((ip_addr, EPHEMERAL_PORT)) + + assert httpserver.bind_addr[0] == ip_addr + assert httpserver.bind_addr[1] != EPHEMERAL_PORT + + +@unix_only_sock_test +def test_bind_addr_unix(http_server, unix_sock_file): + """Check that bound UNIX socket address is stored in server.""" + httpserver = http_server.send(unix_sock_file) + + assert httpserver.bind_addr == unix_sock_file + + +@pytest.mark.skip(reason="Abstract sockets don't work currently") +@unix_only_sock_test +def test_bind_addr_unix_abstract(http_server): + """Check that bound UNIX socket address is stored in server.""" + unix_abstract_sock = b'\x00cheroot/test/socket/here.sock' + httpserver = http_server.send(unix_abstract_sock) + + assert httpserver.bind_addr == unix_abstract_sock + + +PEERCRED_IDS_URI = '/peer_creds/ids' +PEERCRED_TEXTS_URI = '/peer_creds/texts' + + +class _TestGateway(Gateway): + def respond(self): + req = self.req + conn = req.conn + req_uri = bton(req.uri) + if req_uri == PEERCRED_IDS_URI: + peer_creds = conn.peer_pid, conn.peer_uid, conn.peer_gid + self.send_payload('|'.join(map(str, peer_creds))) + return + elif req_uri == PEERCRED_TEXTS_URI: + self.send_payload('!'.join((conn.peer_user, conn.peer_group))) + return + return super(_TestGateway, self).respond() + + def send_payload(self, payload): + req = self.req + req.status = b'200 OK' + req.ensure_headers_sent() + req.write(ntob(payload)) + + +@pytest.fixture +def peercreds_enabled_server_and_client(http_server, unix_sock_file): + """Construct a test server with `peercreds_enabled`.""" + httpserver = http_server.send(unix_sock_file) + httpserver.gateway = _TestGateway + httpserver.peercreds_enabled = True + return httpserver, get_server_client(httpserver) + + +@unix_only_sock_test +@non_macos_sock_test +def test_peercreds_unix_sock(peercreds_enabled_server_and_client): + """Check that peercred lookup works when enabled.""" + httpserver, testclient = peercreds_enabled_server_and_client + + unix_base_uri = 'http+unix://{}'.format( + httpserver.bind_addr.replace('/', '%2F'), + ) + + expected_peercreds = os.getpid(), os.getuid(), os.getgid() + expected_peercreds = '|'.join(map(str, expected_peercreds)) + + with requests_unixsocket.monkeypatch(): + peercreds_resp = requests.get(unix_base_uri + PEERCRED_IDS_URI) + peercreds_resp.raise_for_status() + assert peercreds_resp.text == expected_peercreds + + peercreds_text_resp = requests.get(unix_base_uri + PEERCRED_TEXTS_URI) + assert peercreds_text_resp.status_code == 500 + + +@pytest.mark.skipif( + not IS_UID_GID_RESOLVABLE, + reason='Modules `grp` and `pwd` are not available ' + 'under the current platform', +) +@unix_only_sock_test +@non_macos_sock_test +def test_peercreds_unix_sock_with_lookup(peercreds_enabled_server_and_client): + """Check that peercred resolution works when enabled.""" + httpserver, testclient = peercreds_enabled_server_and_client + httpserver.peercreds_resolve_enabled = True + + unix_base_uri = 'http+unix://{}'.format( + httpserver.bind_addr.replace('/', '%2F'), + ) + + import grp + import pwd + expected_textcreds = ( + pwd.getpwuid(os.getuid()).pw_name, + grp.getgrgid(os.getgid()).gr_name, + ) + expected_textcreds = '!'.join(map(str, expected_textcreds)) + with requests_unixsocket.monkeypatch(): + peercreds_text_resp = requests.get(unix_base_uri + PEERCRED_TEXTS_URI) + peercreds_text_resp.raise_for_status() + assert peercreds_text_resp.text == expected_textcreds diff --git a/pool/shard002/Python/0026546_getBitcoinAddressDetails.py b/pool/shard002/Python/0026546_getBitcoinAddressDetails.py new file mode 100644 index 0000000000000000000000000000000000000000..0b188f025f0ac0f7c8329dec2215f91612f7b85e --- /dev/null +++ b/pool/shard002/Python/0026546_getBitcoinAddressDetails.py @@ -0,0 +1,69 @@ +################################################################################ +# +# Copyright 2015-2020 Félix Brezo and Yaiza Rubio +# +# This program is part of OSRFramework. 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 . +# +################################################################################ + + +import argparse +import json +import sys +import urllib2 + + +def getBitcoinAddressDetails(address=None): + ''' + Method that checks the presence of a Bitcoin Address in blockchain.info: +{ + "total_sent": 41301084, + "total_received": 52195147, + "final_balance": 10894063, + "address": "1APKyS2TEdFMjXjJfMCgavFtoWuv2QNXTw", + "hash160": "66f21efc754af07e87913db46bf24df2eb0d5075", +... +} + + :param address: Bitcoin address to verify. + + :return: Python structure for the json received. If nothing was found, it will return an empty dictionary. + ''' + try: + apiURL = "https://blockchain.info/rawaddr/" + str(address) + + # Accessing the HIBP API + data = urllib2.urlopen(apiURL).read() + + # Reading the text data onto python structures + jsonData = json.loads(data) + return jsonData + except: + # No information was found, then we return a null entity + return {} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description='A library that wraps the search about a Bitcoin address in blockchain.info.', prog='getBitcoinAddressDetails.py', epilog="", add_help=False) + # Adding the main options + # Defining the mutually exclusive group for the main options + parser.add_argument('-q', '--query', metavar='', action='store', help='query to be performed to blockchain.info.', required=True) + + groupAbout = parser.add_argument_group('About arguments', 'Showing additional information about this program.') + groupAbout.add_argument('-h', '--help', action='help', help='shows this help and exists.') + groupAbout.add_argument('--version', action='version', version='%(prog)s 0.1.0', help='shows the version of the program and exists.') + + args = parser.parse_args() + + print(json.dumps(getBitcoinAddressDetails(address=args.query), indent=2)) diff --git a/pool/shard002/Python/0026547_func_fib_opt.py b/pool/shard002/Python/0026547_func_fib_opt.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2effee43c29a6232cf6b61444e158d0f4b0de0 --- /dev/null +++ b/pool/shard002/Python/0026547_func_fib_opt.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python +# coding: utf-8 +#copyRight by heibanke +import time + +def time_cost(f): + def _f(*arg, **kwarg): + start = time.clock() + a=f(*arg,**kwarg) + end = time.clock() + print f.__name__,"run cost time is ",end-start + return a + return _f + + +def fib(n): + if n<=2: + return 1 + else: + return fib(n-1)+fib(n-2) + +#@time_cost +def fib_opt(n): + a,b,i=0,1,0 + + while i 2: + params = sys.argv[2:] + if os.path.exists(filename): + e.run_file(filename, params) + + diff --git a/pool/shard002/Python/0026566_add_ms1_matrix.py b/pool/shard002/Python/0026566_add_ms1_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..f08245e77eda0e3ce3912d92265c52cfe0699279 --- /dev/null +++ b/pool/shard002/Python/0026566_add_ms1_matrix.py @@ -0,0 +1,94 @@ +import os +import pickle +import numpy as np +import sys +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ms2ldaviz.settings") + +import django +django.setup() + + +# This is to process files that have document names stored as mz_rt +# it extracts the acutal mz and rt from the name and adds them to the metadata +# This version works for multi-file experiments + + +import jsonpickle +import csv + +from basicviz.models import MultiFileExperiment,Experiment,Document,PeakSet,IntensityInstance + +if __name__ == '__main__': + multifile_experiment_name = sys.argv[1] + combined_file_name = sys.argv[2] + + mfe = MultiFileExperiment.objects.get(name = multifile_experiment_name) + links = mfe.multilink_set.all() + print("Found {} links".format(len(links))) + experiments = [l.experiment for l in links] + + raw_data = [] + mz_list = [] + rt_list = [] + id_list = [] + intensities = [] + counts = [] + count_hist = {} + with open(combined_file_name,'r') as f: + reader = csv.reader(f,delimiter='\t') + heads = reader.next() + for line in reader: + raw_data.append(line) + id = int(line[0]) + mz = float(line[1]) + rt = float(line[2]) + new_intensity = [float(a) if not a=="" else 'nan' for a in line[3:]] + new_count = sum([1 for a in new_intensity if type(a) == float]) + counts.append(new_count) + if new_count in count_hist: + count_hist[new_count] += 1 + else: + count_hist[new_count] = 1 + intensities.append(new_intensity) + mz_list.append(mz) + rt_list.append(rt) + id_list.append(id) + + print("Loaded {} peaksets".format(len(raw_data))) + print("Diagnostics: intensities present:") + ch = zip(count_hist.keys(),count_hist.values()) + ch = sorted(ch,key = lambda x: x[0]) + + for c,h in ch: + print(c,h) + + + # Hack the names about to make them match - this should be provided to the script + # to avoid errors...fix! + + # MOdified for beer v urine where the names in the ms1 file are the start of the experiment names + experiment_match = {} + short_heads = [] + for head in heads[3:]: # Iterate over the ms1 names + # s = head.split('_') + # new_name = s[0] + '_' + s[1] + '_' + s[2] + short_heads.append(head) # Use the full name from the file + match = [e for e in experiments if head in e.name] + experiment_match[head] = match[0] + + + + print("Making the peakset objects") + for i,mz_value in enumerate(mz_list): + rt_value = rt_list[i] + new_peakset = PeakSet.objects.get_or_create(multifileexperiment = mfe,mz = mz_value,rt = rt_value, + original_file = combined_file_name,original_id = id_list[i])[0] + for j,intense in enumerate(intensities[i]): + if not intense == 'nan': + exper = experiment_match[short_heads[j]] + ii = IntensityInstance.objects.get_or_create(peakset = new_peakset,experiment = exper)[0] + ii.intensity = intense + ii.save() + if i%100 == 0: + print("Done: {}".format(i)) + diff --git a/pool/shard002/Python/0026571_algorithm.py b/pool/shard002/Python/0026571_algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..bd7b1d2b65641706b548001998c5cc108c5b4362 --- /dev/null +++ b/pool/shard002/Python/0026571_algorithm.py @@ -0,0 +1,236 @@ +from __future__ import (absolute_import, division, print_function) +from mantiddoc.directives.base import AlgorithmBaseDirective #pylint: disable=unused-import +import os +import re +from six import iteritems + +REDIRECT_TEMPLATE = "redirect.html" + +DEPRECATE_USE_ALG_RE = re.compile(r"Use\s(([A-Z][a-zA-Z0-9]+)\s(version ([0-9])+)?)\s*instead.") + +# Maximum height in pixels a screenshot image +# Any higher than this an an obvious gap starts to appear between the "Properties" header +# and the rest +SCREENSHOT_MAX_HEIGHT = 250 + +#-------------------------------------------------------------------------- +class AlgorithmDirective(AlgorithmBaseDirective): + + """ + Inserts details of an algorithm by querying Mantid + + Adds: + - A referenceable link for use with Sphinx ":ref:`` tags". If this is + the highest version of the algorithm being processed then a both + a versioned link is created and a non-versioned link + - A title + - A screenshot of the algorithm + - Table of contents + + If the algorithms is deprecated then a warning is inserted. + + It requires a SCREENSHOTS_DIR environment variable to be set to the + directory where a screenshot should be generated. If it is not set then + a RuntimeError occurs + """ + + required_arguments, optional_arguments = 0, 0 + + def execute(self): + """ + Called by Sphinx when the ..algorithm:: directive is encountered + """ + self._insert_pagetitle() + picture = self._create_screenshot() + self._insert_screenshot_link(picture) + self._insert_toc() + self._insert_deprecation_warning() + + return [] + + def _insert_pagetitle(self): + """ + Outputs a reference to the top of the algorithm's rst + of the form ".. _algm-AlgorithmName-vVersion:", so that + the page can be referenced using + :ref:`algm-AlgorithmName-version`. If this is the highest + version then it outputs a reference ".. _algm-AlgorithmName: instead + + It then outputs a title for the page + """ + from mantid.api import AlgorithmFactory + + alg_name = self.algorithm_name() + version = self.algorithm_version() + + # page reference must come directly before the title if it wants + # to be referenced without defining the link text. Here we put the + # specific version one first so that it always must be referenced + # using the full link text ":ref`LinkText `:" + self.add_rst(".. _algm-%s-v%d:\n\n" % (alg_name, version)) + if AlgorithmFactory.highestVersion(alg_name) == version: + self.add_rst(".. _algm-%s:\n\n" % alg_name) + + # title + title = "%s v%d" % (alg_name, version) + self.add_rst(self.make_header(title, True)) + self.add_rst(u"\n.. index:: %s-v%d\n\n" % (alg_name, version)) + + def _insert_toc(self): + """ + Outputs a title for the page + """ + self.add_rst(".. contents:: Table of Contents\n :local:\n") + + def _create_screenshot(self): + """ + Creates a screenshot for the named algorithm in the "images/screenshots" + subdirectory. + + The file will be named "algorithmname-vX_dlg.png", e.g. Rebin-v1_dlg.png + + Returns: + screenshot: A mantiddoc.tools.Screenshot object + """ + try: + screenshots_dir = self._screenshot_directory() + except RuntimeError: + return None + + # Generate image + from mantiddoc.tools.screenshot import algorithm_screenshot + if not os.path.exists(screenshots_dir): + os.makedirs(screenshots_dir) + + try: + picture = algorithm_screenshot(self.algorithm_name(), screenshots_dir, version=self.algorithm_version()) + except RuntimeError as exc: + env = self.state.document.settings.env + env.warn(env.docname, "Unable to generate screenshot for '%s' - %s" % (self.algorithm_name(), str(exc))) + picture = None + + return picture + + def _insert_screenshot_link(self, picture): + """ + Outputs an image link with a custom :class: style. The filename is + extracted from the path given and then a relative link to the + directory specified by the SCREENSHOTS_DIR environment variable from + the root source directory is formed. + + Args: + picture (Screenshot): A Screenshot object + """ + env = self.state.document.settings.env + format_str = ".. figure:: %s\n"\ + " :class: screenshot\n"\ + " :width: %dpx\n"\ + " :align: right\n\n"\ + " %s\n\n" + + # Sphinx assumes that an absolute path is actually relative to the directory containing the + # conf.py file and a relative path is relative to the directory where the current rst file + # is located. + if picture: + screenshots_dir, filename = os.path.split(picture.imgpath) + # Find the width of the image + width, height = picture.width, picture.height + + if height > SCREENSHOT_MAX_HEIGHT: + aspect_ratio = float(width)/height + width = int(SCREENSHOT_MAX_HEIGHT*aspect_ratio) + #endif + + # relative path to image + rel_path = os.path.relpath(screenshots_dir, env.srcdir) + # This is a href link so is expected to be in unix style + rel_path = rel_path.replace("\\","/") + # stick a "/" as the first character so Sphinx computes relative location from source directory + path = "/" + rel_path + "/" + filename + else: + # use stock not found image + path = "/images/ImageNotFound.png" + width = 200 + + caption = "**" + self.algorithm_name() + "** dialog." + self.add_rst(format_str % (path, width, caption)) + + def _screenshot_directory(self): + """ + Returns a full path where the screenshots should be generated. They are + put in a screenshots subdirectory of the main images directory in the source + tree. Sphinx then handles copying them to the final location + + Arguments: + env (BuildEnvironment): Allows access to find the source directory + + Returns: + str: A string containing a path to where the screenshots should be created. This will + be a filesystem path + """ + try: + return os.environ["SCREENSHOTS_DIR"] + except: + raise RuntimeError("The '.. algorithm::' directive requires a SCREENSHOTS_DIR environment variable to be set.") + + def _insert_deprecation_warning(self): + """ + If the algorithm version is deprecated then construct a warning message + """ + from mantid.api import DeprecatedAlgorithmChecker + + checker = DeprecatedAlgorithmChecker(self.algorithm_name(), self.algorithm_version()) + msg = checker.isDeprecated() + if len(msg) == 0: + return + + # Check for message to use another algorithm an insert a link + match = DEPRECATE_USE_ALG_RE.search(msg) + if match is not None and len(match.groups()) == 4: + link_text = match.group(1) + alg_name = match.group(2) + version = match.group(4) + link = "algm-%s%s" + if version is not None: + link = link % (alg_name, "-v" + str(version)) + else: + link = link % (alg_name, "") + replacement = "Use :ref:`%s <%s>` instead." % (link_text, link) + msg = DEPRECATE_USE_ALG_RE.sub(replacement, msg) + # endif + + self.add_rst(".. warning:: %s" % msg) + + +#------------------------------------------------------------------------------------------------------------ + +def html_collect_pages(dummy_app): + """ + Write out unversioned algorithm pages that redirect to the highest version of the algorithm + """ + from mantid.api import AlgorithmFactory + + template = REDIRECT_TEMPLATE + all_algs = AlgorithmFactory.getRegisteredAlgorithms(True) + + for name, versions in iteritems(all_algs): + redirect_pagename = "algorithms/%s" % name + versions.sort() + highest_version = versions[-1] + target = "%s-v%d.html" % (name, highest_version) + context = {"name" : name, "target" : target} + yield (redirect_pagename, context, template) + +#------------------------------------------------------------------------------------------------------------ + +def setup(app): + """ + Setup the directives when the extension is activated + + Args: + app: The main Sphinx application object + """ + app.add_directive('algorithm', AlgorithmDirective) + + # connect event html collection to handler + app.connect("html-collect-pages", html_collect_pages) diff --git a/pool/shard002/Python/0026574_utils.py b/pool/shard002/Python/0026574_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1d93296b36d1e53a2cacdad03e61238a3a26cd11 --- /dev/null +++ b/pool/shard002/Python/0026574_utils.py @@ -0,0 +1,28 @@ +import subprocess + +PACKAGE_DICT = { + 'pytraj': 'https://github.com/amber-md/pytraj', + 'cpptraj': 'https://github.com/amber-md/cpptraj', + 'parmed': 'https://github.com/parmed/parmed' +} + +def get_version_from_github(package_name): + """ + >>> get_version_from_github('pytraj') + v1.0.9 + """ + url = PACKAGE_DICT[package_name] + output = subprocess.check_output('git ls-remote --tags {}'.format(url).split()) + tag_lines = output.decode().strip().split('\n') + versions_str = [tag_line.split('\t')[-1].split('/')[-1] for tag_line in tag_lines] + for index, version in enumerate(versions_str): + if version.startswith('v'): + if package_name in ['parmed']: + versions_str[index] = version.strip('v') + return sorted(versions_str)[-1] + +if __name__ == '__main__': + import sys + name = sys.argv[1].lower().strip() + name = name.strip('/') + print(get_version_from_github(name)) diff --git a/pool/shard002/Python/0026578_security-key-spaces.py b/pool/shard002/Python/0026578_security-key-spaces.py new file mode 100644 index 0000000000000000000000000000000000000000..967603ce5a09279d1dc8ac35c7c4b32234726860 --- /dev/null +++ b/pool/shard002/Python/0026578_security-key-spaces.py @@ -0,0 +1,15 @@ +# Enter your code here. Read input from STDIN. Print output to STDOUT +import sys +arr=raw_input() +e=int(raw_input()) +array=[] +for i in range(0,len(arr)): + if(chr(ord(arr[i])+e)>'9'): + array.append(chr(ord(arr[i])+e-10)) + elif(chr(ord(arr[i])+e)>'z'): + array.append(chr(ord(arr[i])+e-26)) + else: + array.append(chr(ord(arr[i])+e)) + +for i in range(0,len(arr)): + sys.stdout.write(array[i]) diff --git a/pool/shard002/Python/0026579_mslib.py b/pool/shard002/Python/0026579_mslib.py new file mode 100644 index 0000000000000000000000000000000000000000..22683a74c22c96022ec01d97080d3aefb26bc069 --- /dev/null +++ b/pool/shard002/Python/0026579_mslib.py @@ -0,0 +1,64 @@ +"""SCons.Tool.mslib + +Tool-specific initialization for lib (MicroSoft library archiver). + +There normally shouldn't be any need to import this module directly. +It will usually be imported through the generic SCons.Tool.Tool() +selection method. + +""" + +# +# Copyright (c) 2001 - 2016 The SCons Foundation +# +# 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. +# + +__revision__ = "src/engine/SCons/Tool/mslib.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" + +import SCons.Defaults +import SCons.Tool +import SCons.Tool.msvs +import SCons.Tool.msvc +import SCons.Util + +from MSCommon import msvc_exists, msvc_setup_env_once + +def generate(env): + """Add Builders and construction variables for lib to an Environment.""" + SCons.Tool.createStaticLibBuilder(env) + + # Set-up ms tools paths + msvc_setup_env_once(env) + + env['AR'] = 'lib' + env['ARFLAGS'] = SCons.Util.CLVar('/nologo') + env['ARCOM'] = "${TEMPFILE('$AR $ARFLAGS /OUT:$TARGET $SOURCES','$ARCOMSTR')}" + env['LIBPREFIX'] = '' + env['LIBSUFFIX'] = '.lib' + +def exists(env): + return msvc_exists() + +# Local Variables: +# tab-width:4 +# indent-tabs-mode:nil +# End: +# vim: set expandtab tabstop=4 shiftwidth=4: diff --git a/pool/shard002/Python/0026580_plugin.py b/pool/shard002/Python/0026580_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc84a35b60c37d09aaca37f18c4716b8fa73d88 --- /dev/null +++ b/pool/shard002/Python/0026580_plugin.py @@ -0,0 +1,92 @@ +# Authored by Markus E. +# https://github.com/mrksngl + +import datetime +import logging +import os +import wordclock_tools.wordclock_colors as wcc +import random + + +class plugin: + """ + A class to display the current time (default mode). + This default mode needs to be adapted to the hardware + layout of the wordclock (the choosen stencil) and is + the most essential time display mode of the wordclock. + """ + + def __init__(self, config): + """ + Initializations for the startup of the current wordclock plugin + """ + # Get plugin name (according to the folder, it is contained in) + self.name = os.path.dirname(__file__).split('/')[-1] + self.pretty_name = "Matrix with time" + self.description = "There is no spoon?" + + self.purist = config.getboolean('plugin_time_default', 'purist') + + self.bg_color = wcc.BLACK # default background color + self.word_color = wcc.WHITE # default word color + self.minute_color = wcc.WHITE # default minute color + + self.threshold = 0.9 + + # Colors from black to green (and a bit gray-ish) + self.colors = [] + for i in range(0, 8): + self.colors.append(wcc.Color(0, int(255.0 / 10 * i), 0)) + self.colors.append(wcc.Color(50, 204, 30)) + self.colors.append(wcc.Color(50, 230, 30)) + self.colors.append(wcc.Color(80, 255, 60)) + + def run(self, wcd, wci): + """ + Displays time until aborted by user interaction on pin button_return + """ + # initialize rain start: set to end coordinate + rain = [20 for _ in range(0, 11)] + while True: + # Check if text needs to be displayed + if wcd.wst.ScrollText.checkIfScrollIsRequired(now): + wcd.showText(wcd.wst.scrolltext) + + if not(wcc.scrollactive): + # Set background color + wcd.setColorToAll(self.bg_color, includeMinutes=True) + # Set current time + now = datetime.datetime.now() + # Returns indices, which represent the current time, when beeing illuminated + taw_indices = wcd.taw.get_time(now, self.purist) + + wcd.setColorBy1DCoordinates(taw_indices, self.word_color) + wcd.setMinutes(now, self.minute_color) + + for x, y in enumerate(rain): + if y == 20: + # reset y coordinate randomly + if random.random() > self.threshold: + rain[x] = 0 + else: + # simple alpha blending using our predefined colors + y0 = max(y - 10, 0) + y1 = min(9, y) + ci = y0 - (y - 10) + for yi, yn in enumerate(range(y0, y1 + 1)): + color = self.colors[ci + yi] + wcd.setColorBy2DCoordinates(x, yn, color) + # advance y coordinate + rain[x] = y + 1 + + wcd.show() + + event = wci.waitForEvent(0.1) + if event == wci.EVENT_BUTTON_RETURN \ + or event == wci.EVENT_EXIT_PLUGIN \ + or event == wci.EVENT_NEXT_PLUGIN_REQUESTED: + return + elif event == wci.EVENT_BUTTON_LEFT: + self.threshold = min(0.95, self.threshold + 0.05) + elif event == wci.EVENT_BUTTON_RIGHT: + self.threshold = max(0.7, self.threshold - 0.05) diff --git a/pool/shard002/Python/0026581_gemcombineparam.py b/pool/shard002/Python/0026581_gemcombineparam.py new file mode 100644 index 0000000000000000000000000000000000000000..f728fd93f52489b273963a6636c8571e536aac25 --- /dev/null +++ b/pool/shard002/Python/0026581_gemcombineparam.py @@ -0,0 +1,140 @@ +from astrodata.eti.pyrafetiparam import PyrafETIParam, IrafStdout +from pyraf import iraf +from astrodata.adutils import logutils + +log = logutils.get_logger(__name__) + +class GemcombineParam(PyrafETIParam): + """This class coordinates the ETI parameters as it pertains to the IRAF + task gemcombine directly. + """ + rc = None + adinput = None + key = None + value = None + def __init__(self, rc=None, key=None, value=None): + """ + :param rc: Used to store reduction information + :type rc: ReductionContext + + :param key: A parameter name that is added as a dict key in prepare + :type key: any + + :param value: A parameter value that is added as a dict value + in prepare + :type value: any + """ + log.debug("GemcombineParam __init__") + PyrafETIParam.__init__(self, rc) + self.adinput = self.rc.get_inputs_as_astrodata() + self.key = key + self.value = value + + def nonecheck(self, param=None): + if param is None or param == "None": + param = "none" + return param + + def prepare(self): + log.debug("Gemcombine prepare()") + self.paramdict.update({self.key:self.value}) + + +class FlVardq(GemcombineParam): + rc = None + fl_vardq = None + def __init__(self, rc=None): + log.debug("FlVardq __init__") + GemcombineParam.__init__(self, rc) + self.fl_vardq = iraf.no + for ad in self.adinput: + if ad["VAR"]: + self.fl_vardq = iraf.yes + break + + def prepare(self): + log.debug("FlVardq prepare()") + self.paramdict.update({"fl_vardq":self.fl_vardq}) + +class FlDqprop(GemcombineParam): + rc = None + fl_dqprop = None + def __init__(self, rc=None): + log.debug("FlDqprop __init__") + GemcombineParam.__init__(self, rc) + self.fl_dqprop = iraf.no + for ad in self.adinput: + if ad["DQ"]: + self.fl_dqprop = iraf.yes + break + + def prepare(self): + log.debug("FlDqprop prepare()") + self.paramdict.update({"fl_dqprop":self.fl_dqprop}) + +class Masktype(GemcombineParam): + rc = None + masktype = None + def __init__(self, rc=None): + log.debug("Masktype __init__") + GemcombineParam.__init__(self, rc) + if rc["mask"]: + self.masktype = "goodvalue" + else: + self.masktype = "none" + + def prepare(self): + log.debug("Masktype prepare()") + self.paramdict.update({"masktype":self.masktype}) + +class Combine(GemcombineParam): + rc = None + operation = None + def __init__(self, rc=None): + log.debug("Combine __init__") + GemcombineParam.__init__(self, rc) + self.operation = self.nonecheck(rc["operation"]) + + def prepare(self): + log.debug("Combine prepare()") + self.paramdict.update({"combine":self.operation}) + +class Nlow(GemcombineParam): + rc = None + nlow = None + def __init__(self, rc=None): + log.debug("Nlow __init__") + GemcombineParam.__init__(self, rc) + self.nlow = self.nonecheck(rc["nlow"]) + + def prepare(self): + log.debug("Nlow prepare()") + self.paramdict.update({"nlow":self.nlow}) + +class Nhigh(GemcombineParam): + rc = None + nhigh = None + def __init__(self, rc=None): + log.debug("Nhigh __init__") + GemcombineParam.__init__(self, rc) + self.nhigh = self.nonecheck(rc["nhigh"]) + + def prepare(self): + log.debug("Nhigh prepare()") + self.paramdict.update({"nhigh":self.nhigh}) + +class Reject(GemcombineParam): + rc = None + reject_method = None + def __init__(self, rc=None): + log.debug("Reject __init__") + GemcombineParam.__init__(self, rc) + self.reject_method = self.nonecheck(rc["reject_method"]) + + def prepare(self): + log.debug("Reject prepare()") + self.paramdict.update({"reject":self.reject_method}) + + +hardcoded_params = {'title':'DEFAULT','Stdout':IrafStdout(),'Stderr':IrafStdout()} + diff --git a/pool/shard002/Python/0026586_test_discover.py b/pool/shard002/Python/0026586_test_discover.py new file mode 100644 index 0000000000000000000000000000000000000000..b66dc3418d47b493e0cf79a7637de85dbd736896 --- /dev/null +++ b/pool/shard002/Python/0026586_test_discover.py @@ -0,0 +1,54 @@ +# Copyright 2013 IBM Corp. +# +# 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 os +import sys + +from tempest.test_discover import plugins + +if sys.version_info >= (2, 7): + import unittest +else: + import unittest2 as unittest + + +def load_tests(loader, tests, pattern): + ext_plugins = plugins.TempestTestPluginManager() + + suite = unittest.TestSuite() + base_path = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0] + base_path = os.path.split(base_path)[0] + # Load local tempest tests + for test_dir in ['tempest/lis']: + full_test_dir = os.path.join(base_path, test_dir) + if not pattern: + suite.addTests(loader.discover(full_test_dir, + top_level_dir=base_path)) + else: + suite.addTests(loader.discover(full_test_dir, pattern=pattern, + top_level_dir=base_path)) + + plugin_load_tests = ext_plugins.get_plugin_load_tests_tuple() + if not plugin_load_tests: + return suite + + # Load any installed plugin tests + for plugin in plugin_load_tests: + test_dir, top_path = plugin_load_tests[plugin] + if not pattern: + suite.addTests(loader.discover(test_dir, top_level_dir=top_path)) + else: + suite.addTests(loader.discover(test_dir, pattern=pattern, + top_level_dir=top_path)) + return suite diff --git a/pool/shard002/Python/0026588_test_inspector.py b/pool/shard002/Python/0026588_test_inspector.py new file mode 100644 index 0000000000000000000000000000000000000000..cb76a18a60c2c6100f15ba8ee9b4b6df7c08af1b --- /dev/null +++ b/pool/shard002/Python/0026588_test_inspector.py @@ -0,0 +1,154 @@ +# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: + +# Copyright 2020-2021 Florian Bruhin (The Compiler) +# +# This file is part of qutebrowser. +# +# qutebrowser 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. +# +# qutebrowser 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 qutebrowser. If not, see . + +import pytest + +from PyQt5.QtWidgets import QWidget + +from qutebrowser.browser import inspector +from qutebrowser.misc import miscwidgets + + +class FakeInspector(inspector.AbstractWebInspector): + + def __init__(self, + inspector_widget: QWidget, + splitter: miscwidgets.InspectorSplitter, + win_id: int, + parent: QWidget = None) -> None: + super().__init__(splitter, win_id, parent) + self._set_widget(inspector_widget) + self._inspected_page = None + self.needs_recreate = False + + def inspect(self, page): + self._inspected_page = page + + def _needs_recreate(self): + return self.needs_recreate + + +@pytest.fixture +def webview_widget(blue_widget): + return blue_widget + + +@pytest.fixture +def inspector_widget(red_widget): + return red_widget + + +@pytest.fixture +def splitter(qtbot, webview_widget): + splitter = miscwidgets.InspectorSplitter( + win_id=0, main_webview=webview_widget) + qtbot.add_widget(splitter) + return splitter + + +@pytest.fixture +def fake_inspector(qtbot, splitter, inspector_widget, + state_config, mode_manager): + insp = FakeInspector(inspector_widget=inspector_widget, + splitter=splitter, + win_id=0) + qtbot.add_widget(insp) + return insp + + +@pytest.mark.parametrize('position, splitter_count, window_visible', [ + (inspector.Position.window, 1, True), + (inspector.Position.left, 2, False), + (inspector.Position.top, 2, False), +]) +def test_set_position(position, splitter_count, window_visible, + fake_inspector, splitter): + fake_inspector.set_position(position) + assert splitter.count() == splitter_count + assert (fake_inspector.isWindow() and + fake_inspector.isVisible()) == window_visible + + +def test_toggle_window(fake_inspector): + fake_inspector.set_position(inspector.Position.window) + for visible in [True, False, True]: + assert (fake_inspector.isWindow() and + fake_inspector.isVisible()) == visible + fake_inspector.toggle() + + +def test_toggle_docked(fake_inspector, splitter, inspector_widget): + fake_inspector.set_position(inspector.Position.right) + splitter.show() + for visible in [True, False, True]: + assert inspector_widget.isVisible() == visible + fake_inspector.toggle() + + +def test_implicit_toggling(fake_inspector, splitter, inspector_widget): + fake_inspector.set_position(inspector.Position.right) + splitter.show() + assert inspector_widget.isVisible() + fake_inspector.set_position(None) + assert not inspector_widget.isVisible() + + +def test_position_saving(fake_inspector, state_config): + assert 'position' not in state_config['inspector'] + fake_inspector.set_position(inspector.Position.left) + assert state_config['inspector']['position'] == 'left' + + +@pytest.mark.parametrize('config_value, expected', [ + (None, inspector.Position.right), + ('top', inspector.Position.top), +]) +def test_position_loading(config_value, expected, + fake_inspector, state_config): + if config_value is None: + assert 'position' not in state_config['inspector'] + else: + state_config['inspector']['position'] = config_value + + fake_inspector.set_position(None) + assert fake_inspector._position == expected + + +@pytest.mark.parametrize('hidden_again', [True, False]) +@pytest.mark.parametrize('needs_recreate', [True, False]) +def test_detach_after_toggling(hidden_again, needs_recreate, + fake_inspector, inspector_widget, splitter, + qtbot): + """Make sure we can still detach into a window after showing inline.""" + fake_inspector.set_position(inspector.Position.right) + splitter.show() + assert inspector_widget.isVisible() + + if hidden_again: + fake_inspector.toggle() + assert not inspector_widget.isVisible() + + if needs_recreate: + fake_inspector.needs_recreate = True + with qtbot.waitSignal(fake_inspector.recreate): + fake_inspector.set_position(inspector.Position.window) + else: + with qtbot.assertNotEmitted(fake_inspector.recreate): + fake_inspector.set_position(inspector.Position.window) + assert fake_inspector.isVisible() and fake_inspector.isWindow() diff --git a/pool/shard002/Python/0026599_sift.py b/pool/shard002/Python/0026599_sift.py new file mode 100644 index 0000000000000000000000000000000000000000..f3e97b525c5dd461ef36bb7a8816f926272a1cc4 --- /dev/null +++ b/pool/shard002/Python/0026599_sift.py @@ -0,0 +1,130 @@ +#encoding:utf-8 + +from PIL import Image +import os +import cv2 +from numpy import * +from pylab import * + +def read_features_from_file(imgname): + im = cv2.imread(imgname) + im = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) + sift = cv2.SIFT() + + kp, desc = sift.detectAndCompute(im,None) + return kp, desc + +def plot_features(im,kp,circle=False): + """ show image with features. input: im (image as array), + locs (row, col, scale, orientation of each feature) """ + if circle: + img=cv2.drawKeypoints(im,kp,flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) + else: + img=cv2.drawKeypoints(im,kp) + + imshow(img) + axis('off') + + +def match(desc1,desc2): + """ 对第一副图像的每个描述子,找到在第二幅图像中的匹配 OpenCV 版""" + + dist_ratio = 0.6 + desc1_size = desc1.shape + + # BFMatcher with default params + bf = cv2.BFMatcher() + matches = bf.knnMatch(desc1,desc2, k=2) + + # Apply ratio test + good = [] + for m,n in matches: + if m.distance < dist_ratio*n.distance: + good.append(m) + + # 仿照原书的输出 + matchscores = zeros((desc1_size[0],1)) + for m in good: + matchscores[m.queryIdx] = m.trainIdx + + return matchscores + + +def appendimages(im1,im2): + """ return a new image that appends the two images side-by-side.""" + + #select the image with the fewest rows and fill in enough empty rows + rows1 = im1.shape[0] + rows2 = im2.shape[0] + + if rows1 < rows2: + im1 = concatenate((im1,zeros((rows2-rows1,im1.shape[1]))), axis=0) + elif rows1 > rows2: + im2 = concatenate((im2,zeros((rows1-rows2,im2.shape[1]))), axis=0) + #if none of these cases they are equal, no filling needed. + + return concatenate((im1,im2), axis=1) + + +def plot_matches(im1,im2,kp1,kp2,matchscores,show_below=True): + """ OpwnCV 版: + show a figure with lines joining the accepted matches + input: im1,im2 (images as arrays), locs1,locs2 (location of features), + matchscores (as output from 'match'), show_below (if images should be shown below). """ + + im3 = appendimages(im1,im2) + if show_below: + im3 = vstack((im3,im3)) + + # show image + imshow(im3) + + # draw lines for matches + cols1 = im1.shape[1] + for i in range(len(matchscores)): + if matchscores[i] > 0: + pt1 = kp1[i].pt + pt2 = kp2[int(matchscores[i,0])].pt + plot([pt1[0],pt2[0]+cols1], [pt1[1], pt2[1]], 'c') + axis('off') + + +def match_twosided(desc1,desc2): + """ two-sided symmetric version of match(). """ + + matches_12 = match(desc1,desc2) + matches_21 = match(desc2,desc1) + + ndx_12 = matches_12.nonzero()[0] + + #remove matches that are not symmetric + for n in ndx_12: + if matches_21[int(matches_12[n])] != n: + matches_12[n] = 0 + + return matches_12 + + +if __name__ == "__main__": + + process_image('box.pgm','tmp.sift') + l,d = read_features_from_file('tmp.sift') + + im = array(Image.open('box.pgm')) + figure() + plot_features(im,l,True) + gray() + + process_image('scene.pgm','tmp2.sift') + l2,d2 = read_features_from_file('tmp2.sift') + im2 = array(Image.open('scene.pgm')) + + m = match_twosided(d,d2) + figure() + plot_matches(im,im2,l,l2,m) + + gray() + show() + + + diff --git a/pool/shard002/Python/0026600_test_btwix.py b/pool/shard002/Python/0026600_test_btwix.py new file mode 100644 index 0000000000000000000000000000000000000000..feb2e864720c4edaa659b57d944c2c16a2220278 --- /dev/null +++ b/pool/shard002/Python/0026600_test_btwix.py @@ -0,0 +1,87 @@ +# -*- encoding: utf-8 -*- +from ghosts.stringy.btwix import btwix, btwixes +from ghosts.stringy.tests.major_general import major_general + +enz = '; ' +"""Default end string for the tests""" + +compleex = major_general.format(enz=enz) +"""A complex string to test.""" + + +def test_btwix_simple(): + + simple = '

Hello

' + + assert 'Hello' == btwix(simple, '

', '

', False) + assert simple == btwix(simple, '

', '

', True) + + +def expected(starz, stwix, preappend): + """This returns the expected complete phrase of the test. Specify when your + `btwix` call has preappend==True. + """ + if preappend: + return '{}{}{}'.format(starz, stwix, enz) + else: + return stwix + + +def test_expected(): + + preappend = True + starz = 'know' + stwix = ' the kings of England' + + assert expected(starz, stwix, preappend) == '{}{}{}'.format(starz, stwix, enz) + """The expected string will match the btwix string if correct: and + preappend starz and enz. + """ + + preappend = False + assert expected(starz, stwix, preappend) == stwix + """The expected string will match the btwix string if correct: and + preappend==False. + """ + + +def test_btwix_major_simple(): + + preappend = True + starz = 'know' + stwix = ' the kings of England' + + assert btwix(compleex, starz, enz, preappend) == expected(starz, stwix, preappend) + + +def test_btwix_major_array(): + + preappend = False + starz = 'quote' + stwixes = [ + ' the fights historical', + ' in elegiacs all the crimes of Heliogabalus'] + + results = btwixes(compleex, starz, enz, preappend, 0) + + assert results == stwixes + + + +def test_btwix_no_starz(): + + preappend = True + starz = '' + stwix = ' the kings of England' + + assert btwix(compleex, starz, enz, preappend) == '' + + + +def test_btwix_no_enz(): + + preappend = True + starz = 'know' + stwix = ' the kings of England' + + assert btwix(compleex, starz, '', preappend) == '' diff --git a/pool/shard002/Python/0026603_test_gaussian_kde.py b/pool/shard002/Python/0026603_test_gaussian_kde.py new file mode 100644 index 0000000000000000000000000000000000000000..e76e6b58c41d15155edbde84b558aaf9abf409f1 --- /dev/null +++ b/pool/shard002/Python/0026603_test_gaussian_kde.py @@ -0,0 +1,63 @@ +"""Tests for Gaussian kernel density estimation.""" +import numpy +import chaospy + + +def test_gaussian_kde_1d_integration(): + """Make sure that 1D distribution integration is correct.""" + dist = chaospy.GaussianKDE([0, 1, 2]) + t = numpy.mgrid[-2.6:4.6:2e5j] + scale = numpy.ptp(t) + assert numpy.isclose(numpy.mean(dist.pdf(t)*scale), 1.) + assert numpy.isclose(numpy.mean(t*dist.pdf(t)*scale), 1.) + + +def test_gaussian_kde_2d_integration(): + """Make sure that 2D distribution integration is correct.""" + dist = chaospy.GaussianKDE([[0, 2], [2, 0]]) + samples = dist.sample(1e4) + assert numpy.allclose(numpy.mean(samples, axis=-1), 1, rtol=1e-1) + + +def test_gaussian_kde_rotation(): + """Make sure rotation does not affect mapping.""" + dist = chaospy.GaussianKDE([[0, 0, 2], [0, 2, 0], [2, 0, 0]], rotation=[0, 1, 2]) + grid = numpy.mgrid[0.01:0.99:2j, 0.01:0.99:2j, 0.01:0.99:2j].reshape(3, 8) + inverse = dist.inv(grid) + assert numpy.allclose(dist.fwd(inverse), grid) + assert numpy.allclose(dist.pdf(inverse), + [2.550e-05, 2.553e-05, 2.553e-05, 2.552e-05, + 2.525e-05, 2.522e-05, 2.522e-05, 2.519e-05]) + assert numpy.allclose( + inverse, + [[-1.38424, -1.38424, -1.38424, -1.38424, 3.19971, 3.19971, 3.19971, 3.19971], + [-1.31003, -1.31003, 3.31003, 3.31003, -1.48391, -1.48391, 1.48429, 1.48429], + [ 0.51571, 3.48391, -1.48391, 1.48413, -1.48391, 1.48429, -1.48391, 1.48429]], + rtol=1e-5, + ) + dist = chaospy.GaussianKDE([[0, 0, 2], [0, 2, 0], [2, 0, 0]], rotation=[2, 1, 0]) + inverse = dist.inv(grid) + assert numpy.allclose(dist.fwd(inverse), grid) + assert numpy.allclose(dist.pdf(inverse), + [2.550e-05, 2.525e-05, 2.553e-05, 2.522e-05, + 2.553e-05, 2.522e-05, 2.552e-05, 2.519e-05]) + assert numpy.allclose( + inverse, + [[ 0.51571, -1.48391, -1.48391, -1.48391, 3.48391, 1.48429, 1.48413, 1.48429], + [-1.31003, -1.48391, 3.31003, 1.48429, -1.31003, -1.48391, 3.31003, 1.48429], + [-1.38424, 3.19971, -1.38424, 3.19971, -1.38424, 3.19971, -1.38424, 3.19971]], + rtol=1e-5, + ) + dist = chaospy.GaussianKDE([[0, 0, 2], [0, 2, 0], [2, 0, 0]], rotation=[0, 2, 1]) + inverse = dist.inv(grid) + assert numpy.allclose(dist.fwd(inverse), grid) + assert numpy.allclose(dist.pdf(inverse), + [2.550e-05, 2.553e-05, 2.553e-05, 2.552e-05, + 2.525e-05, 2.522e-05, 2.522e-05, 2.519e-05]) + assert numpy.allclose( + inverse, + [[-1.38424, -1.38424, -1.38424, -1.38424, 3.19971, 3.19971, 3.19971, 3.19971], + [ 0.51571, -1.48391, 3.48391, 1.48413, -1.48391, -1.48391, 1.48429, 1.48429], + [-1.31003, 3.31003, -1.31003, 3.31003, -1.48391, 1.48429, -1.48391, 1.48429]], + rtol=1e-5, + ) diff --git a/pool/shard002/Python/0026614_test_bad_start.py b/pool/shard002/Python/0026614_test_bad_start.py new file mode 100644 index 0000000000000000000000000000000000000000..eb46a55b3912acc147c4a485421f9c7e4de29501 --- /dev/null +++ b/pool/shard002/Python/0026614_test_bad_start.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python +# Copyright (C) 2009-2014: +# Gabes Jean, naparuba@gmail.com +# Gerhard Lausser, Gerhard.Lausser@consol.de +# +# This file is part of Shinken. +# +# Shinken 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. +# +# Shinken 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 Shinken. If not, see . + +# +# This file is used to test reading and processing of config files +# + +import os +import tempfile +import shutil + +from shinken_test import * + +import shinken.log as shinken_log + +from shinken.daemon import InvalidPidFile, InvalidWorkDir +from shinken.http_daemon import PortNotFree + +from shinken.daemons.pollerdaemon import Poller +from shinken.daemons.brokerdaemon import Broker +from shinken.daemons.schedulerdaemon import Shinken +from shinken.daemons.reactionnerdaemon import Reactionner +from shinken.daemons.arbiterdaemon import Arbiter +try: + import pwd, grp + from pwd import getpwnam + from grp import getgrnam + + + def get_cur_user(): + return pwd.getpwuid(os.getuid()).pw_name + + def get_cur_group(): + return grp.getgrgid(os.getgid()).gr_name + +except ImportError, exp: # Like in nt system or Android + # temporary workaround: + def get_cur_user(): + return os.getlogin() + + def get_cur_group(): + return os.getlogin() + +curdir = os.getcwd() + +daemons_config = { + Broker: "etc/core/daemons/brokerd.ini", + Poller: "etc/core/daemons/pollerd.ini", + Reactionner: "etc/core/daemons/reactionnerd.ini", + Shinken: "etc/core/daemons/schedulerd.ini", + Arbiter: ["etc/core/shinken.cfg"] +} + +import random + +HIGH_PORT = random.randint(30000,65000) +run = 0 # We will open some ports but not close them (yes it's not good) and +# so we will open a range from a high port + +class template_Daemon_Bad_Start(): + + def setUp(self): + time_hacker.set_real_time() + + def get_login_and_group(self, p): + try: + p.user = get_cur_user() + p.group = get_cur_group() + except OSError: # on some rare case, we can have a problem here + # so bypass it and keep default value + return + + def create_daemon(self): + cls = self.daemon_cls + return cls(daemons_config[cls], False, True, False, None, '') + + + def get_daemon(self): + global run + os.chdir(curdir) + shinken_log.local_log = None # otherwise get some "trashs" logs.. + d = self.create_daemon() + + d.load_config_file() + d.http_backend = 'wsgiref' + d.port = HIGH_PORT + run # random high port, I hope no one is using it :) + run += 1 + self.get_login_and_group(d) + return d + + + def test_bad_piddir(self): + print "Testing bad pidfile ..." + d = self.get_daemon() + d.workdir = tempfile.mkdtemp() + d.pidfile = os.path.join('/DONOTEXISTS', "daemon.pid") + prev_dir = os.getcwd() + self.assertRaises(InvalidPidFile, d.do_daemon_init_and_start, fake=True) + shutil.rmtree(d.workdir) + os.chdir(prev_dir) + + def test_bad_workdir(self): + print("Testing bad workdir ... mypid=%d" % (os.getpid())) + d = self.get_daemon() + d.workdir = '/DONOTEXISTS' + prev_dir = os.getcwd() + self.assertRaises(InvalidWorkDir, d.do_daemon_init_and_start, fake=True) + d.do_stop() + os.chdir(prev_dir) + + def test_port_not_free(self): + print("Testing port not free ... mypid=%d" % (os.getpid())) + d1 = self.get_daemon() + d1.workdir = tempfile.mkdtemp() + prev_dir = os.getcwd() # We have to remember where we are to get back after + d1.do_daemon_init_and_start(fake=True) + new_dir = os.getcwd() # We have to remember this one also + os.chdir(prev_dir) + os.unlink(os.path.join(new_dir, d1.pidfile)) ## so that second poller will not see first started poller + d2 = self.get_daemon() + d2.workdir = d1.workdir + # TODO: find a way in Pyro4 to get the port + if hasattr(d1.http_daemon, 'port'): + d2.port = d1.http_daemon.port + self.assertRaises(PortNotFree, d2.do_daemon_init_and_start, fake=True) + d2.do_stop() + d1.do_stop() + try: + os.unlink(d1.pidfile) + except Exception: + pass + if hasattr(d1, 'local_log'): + os.unlink(os.path.join(d1.workdir, d1.local_log)) + shutil.rmtree(d1.workdir) + os.chdir(prev_dir) # Back to previous dir for next test! + + +class Test_Broker_Bad_Start(template_Daemon_Bad_Start, ShinkenTest): + daemon_cls = Broker + + +class Test_Scheduler_Bad_Start(template_Daemon_Bad_Start, ShinkenTest): + daemon_cls = Shinken + + +class Test_Poller_Bad_Start(template_Daemon_Bad_Start, ShinkenTest): + daemon_cls = Poller + + +class Test_Reactionner_Bad_Start(template_Daemon_Bad_Start, ShinkenTest): + daemon_cls = Reactionner + + +class Test_Arbiter_Bad_Start(template_Daemon_Bad_Start, ShinkenTest): + daemon_cls = Arbiter + + def create_daemon(self): + """ arbiter is always a bit special .. """ + cls = self.daemon_cls + #Arbiter(config_files, is_daemon, do_replace, verify_only, debug, debug_file, profile) + return cls(daemons_config[cls], False, True, False, False, None, '') + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard002/Python/0026616_logfile.py b/pool/shard002/Python/0026616_logfile.py new file mode 100644 index 0000000000000000000000000000000000000000..86475c811edeca48b9d64e4977df60cb4e853db5 --- /dev/null +++ b/pool/shard002/Python/0026616_logfile.py @@ -0,0 +1,98 @@ +# This file is part of Buildbot. Buildbot 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. +# +# 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. +# +# Copyright Buildbot Team Members + +from __future__ import absolute_import +from __future__ import print_function +from future.utils import itervalues +from future.utils import text_type + +from twisted.internet import defer +from twisted.python import log + +from buildbot import util +from buildbot.util import lineboundaries + + +class FakeLogFile(object): + + def __init__(self, name, step): + self.name = name + self.header = '' + self.stdout = '' + self.stderr = '' + self.lbfs = {} + self.finished = False + self.step = step + self.subPoint = util.subscription.SubscriptionPoint("%r log" % (name,)) + + def getName(self): + return self.name + + def subscribe(self, callback): + log.msg("NOTE: fake logfile subscription never produces anything") + return self.subPoint.subscribe(callback) + + def _getLbf(self, stream, meth): + try: + return self.lbfs[stream] + except KeyError: + def wholeLines(lines): + if not isinstance(lines, text_type): + lines = lines.decode('utf-8') + if self.name in self.step.logobservers: + for obs in self.step.logobservers[self.name]: + getattr(obs, meth)(lines) + lbf = self.lbfs[stream] = \ + lineboundaries.LineBoundaryFinder(wholeLines) + return lbf + + def addHeader(self, text): + self.header += text + self._getLbf('h', 'headerReceived').append(text) + return defer.succeed(None) + + def addStdout(self, text): + self.stdout += text + self._getLbf('o', 'outReceived').append(text) + return defer.succeed(None) + + def addStderr(self, text): + self.stderr += text + self._getLbf('e', 'errReceived').append(text) + return defer.succeed(None) + + def isFinished(self): + return self.finished + + def waitUntilFinished(self): + log.msg("NOTE: fake waitUntilFinished doesn't actually wait") + return defer.Deferred() + + def flushFakeLogfile(self): + for lbf in itervalues(self.lbfs): + lbf.flush() + + def finish(self): + self.flushFakeLogfile() + self.finished = True + return defer.succeed(None) + + def fakeData(self, header='', stdout='', stderr=''): + if header: + self.header += header + if stdout: + self.stdout += stdout + if stderr: + self.stderr += stderr diff --git a/pool/shard002/Python/0026617_splitter.py b/pool/shard002/Python/0026617_splitter.py new file mode 100644 index 0000000000000000000000000000000000000000..ec5512e8793819480bb3a4e52c807966b5882dcc --- /dev/null +++ b/pool/shard002/Python/0026617_splitter.py @@ -0,0 +1,96 @@ +import astropy.table +import numpy as np +import pandas as pd + +def load(path, + x_cols=('psfMag_u', 'psfMag_g', 'psfMag_r', 'psfMag_i', 'psfMag_z'), + y_col='redshift', + class_col='class', + class_val='Galaxy'): + + # Cast x_cols to list so Pandas doesn't complain… + x_cols_l = list(x_cols) + + if '.h5' in path or '.hdf' in path: + # We have an HDF5 file + data = pd.read_hdf(path) + return data, x_cols_l, y_col + + elif '.fits' in path: + x_cols_l = ['umag', 'gmag', 'rmag', 'imag', 'zmag'] + y_col = 'z' + dat = astropy.table.Table.read(path, format='fits') + data = dat.to_pandas() + data = data[x_cols_l + [y_col]] + return data, x_cols_l, y_col + + else: + # We have a CSV file + + data_iter = pd.read_csv( + path, + iterator=True, + chunksize=100000, + usecols=x_cols_l + [y_col, class_col]) + + # Filter out anything that is not a galaxy without loading the + # whole file into memory. + data = pd.concat(chunk[chunk[class_col] == class_val] + for chunk in data_iter) + + return data[x_cols_l + [y_col]], x_cols_l, y_col + + +def split(data, train_n, test_n): + data, x_cols, y_col = data + + X_data = data[x_cols].as_matrix() + y_data = data[y_col].as_matrix() + assert X_data.shape[0] == y_data.shape[0] == data.shape[0] + assert X_data.shape[1] == data.shape[1] - 1 + assert len(y_data.shape) == 1 + + # Shuffle data + indices = list(range(data.shape[0])) + np.random.seed(seed=12) + np.random.shuffle(indices) + X_data = X_data[indices] + y_data = y_data[indices] + + train_X = X_data[:train_n] + test_X = X_data[train_n:train_n+test_n] + train_y = y_data[:train_n] + test_y = y_data[train_n:train_n+test_n] + + assert train_X.shape == (train_n, len(x_cols)) + assert train_y.shape == (train_n,) + assert test_X.shape == (test_n, len(x_cols)) + assert test_y.shape == (test_n,) + + return (train_X, train_y), (test_X, test_y) + + +def save_as_hdf5(path, data): + data.to_hdf(path, '👀') + + +if __name__ == '__main__': + # TODO: Use argparse if this gets any longer... + + import sys + if len(sys.argv) == 3 and sys.argv[2] == '--test': + # Tiny test + data = load(sys.argv[1]) + data = split(data, 2, 1) + print(data) + elif len(sys.argv) == 4 and sys.argv[2] == '--to-hdf5': + data, _, _ = load(sys.argv[1]) + save_as_hdf5(sys.argv[3], data) + elif len(sys.argv) == 3 and sys.argv[2] == '--time': + from time import time + start_time = time() + data = load(sys.argv[1]) + total_time = time() - start_time + print('Took {}s'.format(total_time)) + else: + print('No options specified.') diff --git a/pool/shard002/Python/0026624_conf.py b/pool/shard002/Python/0026624_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..5e85615cf8a130425b97b505ec1507a9482d2ff3 --- /dev/null +++ b/pool/shard002/Python/0026624_conf.py @@ -0,0 +1,45 @@ +""" +Get and process settings for django-OneTimePassword +""" +from django.conf import settings +from importlib import import_module + + +# Default settings + +OTP_TIME_SYNCHRONIZED_GENERATOR = 'django_OneTimePassword.generators.sha512TS' + +OTP_TIME_SYNCHRONIZED_OPTIONS = { + 'length': 6, + 'interval': 30, + 'dictionary': "abcdefghijklmnopqrstuvwxyz0123456789" +} + + +# Try get settings + +OTP_TIME_SYNCHRONIZED_GENERATOR = getattr( + settings, + 'OTP_TIME_SYNCHRONIZED_GENERATOR', + OTP_TIME_SYNCHRONIZED_GENERATOR +) + +OTP_TIME_SYNCHRONIZED_OPTIONS = getattr( + settings, + 'OTP_TIME_SYNCHRONIZED_OPTIONS', + OTP_TIME_SYNCHRONIZED_OPTIONS +) + + +# Get password generatos + +OTP_TIME_SYNCHRONIZED_GENERATOR = getattr( + import_module('.'.join(OTP_TIME_SYNCHRONIZED_GENERATOR.split('.')[:-1])), + OTP_TIME_SYNCHRONIZED_GENERATOR.split('.')[-1] +) + +# Instance generators + +OTP_TIME_SYNCHRONIZED = OTP_TIME_SYNCHRONIZED_GENERATOR( + **OTP_TIME_SYNCHRONIZED_OPTIONS +) diff --git a/pool/shard002/Python/0026625_utils.py b/pool/shard002/Python/0026625_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ab5ccfbf0583539207d7c8de985429a418295bc8 --- /dev/null +++ b/pool/shard002/Python/0026625_utils.py @@ -0,0 +1,224 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright (c) 2011 OpenStack, LLC. +# +# 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. + +"""Compute-related Utilities and helpers.""" + +import netaddr + +import nova.context +from nova import db +from nova import exception +from nova import flags +from nova import log +from nova import network +from nova.network import model as network_model +from nova import notifications +from nova.notifier import api as notifier_api +from nova import utils + + +FLAGS = flags.FLAGS +LOG = log.getLogger(__name__) + + +def notify_usage_exists(context, instance_ref, current_period=False, + ignore_missing_network_data=True, + system_metadata=None, extra_usage_info=None): + """Generates 'exists' notification for an instance for usage auditing + purposes. + + :param current_period: if True, this will generate a usage for the + current usage period; if False, this will generate a usage for the + previous audit period. + + :param ignore_missing_network_data: if True, log any exceptions generated + while getting network info; if False, raise the exception. + :param system_metadata: system_metadata DB entries for the instance, + if not None. *NOTE*: Currently unused here in trunk, but needed for + potential custom modifications. + :param extra_usage_info: Dictionary containing extra values to add or + override in the notification if not None. + """ + + audit_start, audit_end = notifications.audit_period_bounds(current_period) + + bw = notifications.bandwidth_usage(instance_ref, audit_start, + ignore_missing_network_data) + + if system_metadata is None: + try: + system_metadata = db.instance_system_metadata_get( + context, instance_ref.uuid) + except exception.NotFound: + system_metadata = {} + + # add image metadata to the notification: + image_meta = notifications.image_meta(system_metadata) + + extra_info = dict(audit_period_beginning=str(audit_start), + audit_period_ending=str(audit_end), + bandwidth=bw, image_meta=image_meta) + + if extra_usage_info: + extra_info.update(extra_usage_info) + + notify_about_instance_usage(context, instance_ref, 'exists', + system_metadata=system_metadata, extra_usage_info=extra_info) + + +def legacy_network_info(network_model): + """ + Return the legacy network_info representation of the network_model + """ + def get_ip(ip): + if not ip: + return None + return ip['address'] + + def fixed_ip_dict(ip, subnet): + if ip['version'] == 4: + netmask = str(subnet.as_netaddr().netmask) + else: + netmask = subnet.as_netaddr()._prefixlen + + return {'ip': ip['address'], + 'enabled': '1', + 'netmask': netmask, + 'gateway': get_ip(subnet['gateway'])} + + def get_meta(model, key, default=None): + if 'meta' in model and key in model['meta']: + return model['meta'][key] + return default + + def convert_routes(routes): + routes_list = [] + for route in routes: + r = {'route': str(netaddr.IPNetwork(route['cidr']).network), + 'netmask': str(netaddr.IPNetwork(route['cidr']).netmask), + 'gateway': get_ip(route['gateway'])} + routes_list.append(r) + return routes_list + + network_info = [] + for vif in network_model: + if not vif['network'] or not vif['network']['subnets']: + continue + network = vif['network'] + + # NOTE(jkoelker) The legacy format only supports one subnet per + # network, so we only use the 1st one of each type + # NOTE(tr3buchet): o.O + v4_subnets = [] + v6_subnets = [] + for subnet in vif['network']['subnets']: + if subnet['version'] == 4: + v4_subnets.append(subnet) + else: + v6_subnets.append(subnet) + + subnet_v4 = None + subnet_v6 = None + + if v4_subnets: + subnet_v4 = v4_subnets[0] + + if v6_subnets: + subnet_v6 = v6_subnets[0] + + if not subnet_v4: + raise exception.NovaException( + message=_('v4 subnets are required for legacy nw_info')) + + routes = convert_routes(subnet_v4['routes']) + + should_create_bridge = get_meta(network, 'should_create_bridge', + False) + should_create_vlan = get_meta(network, 'should_create_vlan', False) + gateway = get_ip(subnet_v4['gateway']) + dhcp_server = get_meta(subnet_v4, 'dhcp_server') + network_dict = dict(bridge=network['bridge'], + id=network['id'], + cidr=subnet_v4['cidr'], + cidr_v6=subnet_v6['cidr'] if subnet_v6 else None, + vlan=get_meta(network, 'vlan'), + injected=get_meta(network, 'injected', False), + multi_host=get_meta(network, 'multi_host', + False), + bridge_interface=get_meta(network, + 'bridge_interface')) + # NOTE(tr3buchet): the 'ips' bit here is tricky, we support a single + # subnet but we want all the IPs to be there + # so we use the v4_subnets[0] and its IPs are first + # so that eth0 will be from subnet_v4, the rest of the + # IPs will be aliased eth0:1 etc and the gateways from + # their subnets will not be used + info_dict = dict(label=network['label'], + broadcast=str(subnet_v4.as_netaddr().broadcast), + mac=vif['address'], + vif_uuid=vif['id'], + rxtx_cap=get_meta(network, 'rxtx_cap', 0), + dns=[get_ip(ip) for ip in subnet_v4['dns']], + ips=[fixed_ip_dict(ip, subnet) + for subnet in v4_subnets + for ip in subnet['ips']], + should_create_bridge=should_create_bridge, + should_create_vlan=should_create_vlan, + dhcp_server=dhcp_server) + if routes: + info_dict['routes'] = routes + + if gateway: + info_dict['gateway'] = gateway + + if v6_subnets: + if subnet_v6['gateway']: + info_dict['gateway_v6'] = get_ip(subnet_v6['gateway']) + info_dict['ip6s'] = [fixed_ip_dict(ip, subnet_v6) + for ip in subnet_v6['ips']] + + network_info.append((network_dict, info_dict)) + return network_info + + +def notify_about_instance_usage(context, instance, event_suffix, + network_info=None, system_metadata=None, + extra_usage_info=None, host=None): + """ + Send a notification about an instance. + + :param event_suffix: Event type like "delete.start" or "exists" + :param network_info: Networking information, if provided. + :param system_metadata: system_metadata DB entries for the instance, + if provided. + :param extra_usage_info: Dictionary containing extra values to add or + override in the notification. + :param host: Compute host for the instance, if specified. Default is + FLAGS.host + """ + + if not host: + host = FLAGS.host + + if not extra_usage_info: + extra_usage_info = {} + + usage_info = notifications.usage_from_instance(context, instance, + network_info, system_metadata, **extra_usage_info) + + notifier_api.notify(context, 'compute.%s' % host, + 'compute.instance.%s' % event_suffix, + notifier_api.INFO, usage_info) diff --git a/pool/shard002/Python/0026627_ppa.py b/pool/shard002/Python/0026627_ppa.py new file mode 100644 index 0000000000000000000000000000000000000000..c5283f82f2c648348e1f76b8242df9e2467f6a89 --- /dev/null +++ b/pool/shard002/Python/0026627_ppa.py @@ -0,0 +1,124 @@ +# Setup +import time +import webbrowser +import md5 +import sys +import hashlib +import random +from urllib2 import urlopen +from yahoo_finance import Share + + +# Makes the webbrowser command +def open_link(link): + webbrowser.open(link) + speak("Opening web browser") + pause(2) + +# Makes the pause command +def pause(seconds): + time.sleep(seconds) + +# Makes the speak command +def speak(text): + print(text) + +# Makes the warning command +def warning(warning_text): + print(warning_text) + +# Makes the sha1 encrypter command +def encrypt_sha1(textsha1): + hash_objectsha1 = hashlib.sha1(textsha1) + hex_digsha1 = hash_objectsha1.hexdigest() + speak("Proccesing...") + speak(hex_digsha1) + +# Makes the sha224 encrypter command +def encrypt_sha224(textsha224): + hash_objectsha224 = hashlib.sha224(textsha224) + hex_digsha224 = hash_objectsha224.hexdigest() + speak("Proccesing...") + speak(hex_digsha224) + +# Makes the sha256 encrypter command +def encrypt_sha256(textsha256): + hash_objectsha256 = hashlib.sha256(textsha256) + hex_digsha256 = hash_objectsha256.hexdigest() + speak("Proccesing...") + speak(hex_digsha256) + +# Initializes the time and date +time.ctime() +current_time = time.strftime('%H:%M') +current_date = time.strftime('%d %B %Y') + +speak("Hello! i am PAI, your owm personal assistant") + +# Main program +var = 1 +while var == 1: + input = raw_input(">>>") + if input in {"help", "help me", }: + file = open('bin/commands.txt', 'r') + file_contents = file.read() + print (file_contents) + file.close() + elif input in {"exit", "kill", "escape"}: + speak("Killing PPA...") + sys.exit() + elif input in {"time", "the current time", "current time"}: + speak("The current time is " + current_time) + elif input in {"search", "google"}: + speak("What do you want to Google?") + google = raw_input(">>>") + google.replace(" ", "+") + open_link('https://www.google.nl/#q=' + google.replace(" ", "+")) + elif input in {"hello ppa", "hello", "hello!", "Hello PPA"}: + print("Hello human!") + elif input in {"date", "the current date", "current date"}: + print("The current date is " + current_date) + elif input in {"what is your favorite song?", "favorite song"}: + speak("I really like human music!") + pause(1) + speak("Let me show it to you!") + open_link('https://www.youtube.com/watch?v=q4k1IK_o59M') + elif input in {"im hungry", "i want to eat", "restaurant"}: + speak("What do you want to eat?") + eat = raw_input(">>>") + open_link('https://www.google.nl/maps/search/' + eat.replace(" ", "+")) + elif input in {"what is my ip?", "my ip", "ip", "what's my ip?", "whats my ip?", "whats my ip", "what is my ip"}: + ip = urlopen('http://ip.42.pl/raw').read() + speak(ip) + elif input in {"md5"}: + speak("What do you want to hash to MD5?") + md5_string = raw_input('>>>') + speak("proccesing...") + speak( md5.md5(md5_string).hexdigest() ) + elif input in {"sha1"}: + speak("What do you want to encrypt?") + sha1_input = raw_input('>>>') + encrypt_sha1(sha1_input) + elif input in {"sha1"}: + speak("What do you want to encrypt?") + sha1_input = raw_input('>>>') + encrypt_sha1(sha1_input) + elif input in {"sha224"}: + speak("What do you want to encrypt?") + sha224_input = raw_input('>>>') + encrypt_sha224(sha224_input) + elif input in {"sha256"}: + speak("What do you want to encrypt?") + sha256_input = raw_input('>>>') + encrypt_sha256(sha256_input) + elif input in {"what is per?"}: + speak("A huge dumbass...") + pause(2) + speak("Take my word for it") + elif input in {"random", "random number"}: + mini = raw_input + print random.randrange(1,100) + elif input in {"stocks", "stock", "stock prices"}: + + else: + warning("That is not a valid command") diff --git a/pool/shard002/Python/0026628_util.py b/pool/shard002/Python/0026628_util.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b88a61e6423f8adba8037ef592fd58278b36b3 --- /dev/null +++ b/pool/shard002/Python/0026628_util.py @@ -0,0 +1,68 @@ +from django.utils.html import conditional_escape +from django.utils.encoding import smart_unicode, StrAndUnicode, force_unicode +from django.utils.safestring import mark_safe + +def flatatt(attrs): + """ + Convert a dictionary of attributes to a single string. + The returned string will contain a leading space followed by key="value", + XML-style pairs. It is assumed that the keys do not need to be XML-escaped. + If the passed dictionary is empty, then return an empty string. + """ + return u''.join([u' %s="%s"' % (k, conditional_escape(v)) for k, v in attrs.items()]) + +class ErrorDict(dict, StrAndUnicode): + """ + A collection of errors that knows how to display itself in various formats. + + The dictionary keys are the field names, and the values are the errors. + """ + def __unicode__(self): + return self.as_ul() + + def as_ul(self): + if not self: return u'' + return mark_safe(u'
    %s
' + % ''.join([u'
  • %s%s
  • ' % (k, force_unicode(v)) + for k, v in self.items()])) + + def as_text(self): + return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u' * %s' % force_unicode(i) for i in v])) for k, v in self.items()]) + +class ErrorList(list, StrAndUnicode): + """ + A collection of errors that knows how to display itself in various formats. + """ + def __unicode__(self): + return self.as_ul() + + def as_ul(self): + if not self: return u'' + return mark_safe(u'
      %s
    ' + % ''.join([u'
  • %s
  • ' % conditional_escape(force_unicode(e)) for e in self])) + + def as_text(self): + if not self: return u'' + return u'\n'.join([u'* %s' % force_unicode(e) for e in self]) + + def __repr__(self): + return repr([force_unicode(e) for e in self]) + +class ValidationError(Exception): + def __init__(self, message): + """ + ValidationError can be passed any object that can be printed (usually + a string) or a list of objects. + """ + if isinstance(message, list): + self.messages = ErrorList([smart_unicode(msg) for msg in message]) + else: + message = smart_unicode(message) + self.messages = ErrorList([message]) + + def __str__(self): + # This is needed because, without a __str__(), printing an exception + # instance would result in this: + # AttributeError: ValidationError instance has no attribute 'args' + # See http://www.python.org/doc/current/tut/node10.html#handling + return repr(self.messages) diff --git a/pool/shard002/Python/0026630_domain_a.py b/pool/shard002/Python/0026630_domain_a.py new file mode 100644 index 0000000000000000000000000000000000000000..a40261a71a97556e6cffcd27acbece14d0d9615d --- /dev/null +++ b/pool/shard002/Python/0026630_domain_a.py @@ -0,0 +1,158 @@ +from flask import Blueprint, g, render_template, request, url_for, redirect +from wtforms import Form, StringField, BooleanField, validators +from dnsforever.web.tools import random_string +from dnsforever.web.tools.session import login, get_user, get_domain +from dnsforever.models import Domain, RecordA + +app = Blueprint('domain_a', __name__, url_prefix='/domain//a') + + +@app.route('/') +@login(True, '/') +def record_list(domain): + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + records = g.session.query(RecordA).filter(RecordA.domain == domain)\ + .order_by(RecordA.name).all() + + if not records: + return redirect(url_for('domain_a.record_new', domain=domain.name)) + + return render_template('domain_a/list.html', + domain=domain, + records=records) + + +class RecordAForm(Form): + name = StringField('name', + [validators.Regexp('(^$)|' + '(^([a-z0-9\-]+\.)*([a-z0-9\-]+)$)')]) + # TODO: Check max length of name. + ip = StringField('ip', [validators.IPAddress()]) + memo = StringField('memo', [validators.Length(max=1000)]) + + +@app.route('/new', methods=['GET']) +@login(True, '/') +def record_new(domain): + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + form = RecordAForm(ip=request.remote_addr) + + return render_template('domain_a/new.html', + domain=domain, + form=form) + + +@app.route('/', methods=['GET']) +@login(True, '/') +def record_edit(domain, record_id): + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + record = g.session.query(RecordA).filter(RecordA.id == record_id)\ + .filter(RecordA.domain == domain)\ + .first() + if not record: + return redirect(url_for('domain_a.record_list', domain=domain.name)) + + form = RecordAForm(name=record.name, ip=record.ip, memo=record.memo) + + return render_template('domain_a/edit.html', + domain=domain, + form=form) + + +@app.route('/new', methods=['POST']) +@login(True, '/') +def record_new_process(domain): + form = RecordAForm(request.form) + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + if not form.validate(): + return render_template('domain_a/new.html', + domain=domain, + form=form) + + try: + a_record = RecordA(domain=domain, + name=form.name.data or None, + ip=form.ip.data, + memo=form.memo.data) + with g.session.begin(): + a_record.update() + g.session.add(a_record) + except ValueError as e: + form.name.errors.append(e) + return render_template('domain_a/new.html', + domain=domain, + form=form) + + return redirect(url_for('domain_a.record_list', domain=domain.name)) + + +@app.route('/', methods=['POST']) +@login(True, '/') +def record_edit_process(domain, record_id): + form = RecordAForm(request.form) + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + record = g.session.query(RecordA).filter(RecordA.id == record_id)\ + .filter(RecordA.domain == domain)\ + .first() + if not record: + return redirect(url_for('domain_a.record_list', domain=domain.name)) + + form.name.data = record.name + + if not form.validate(): + return render_template('domain_a/edit.html', + domain=domain, + form=form) + + record.ip = form.ip.data + record.memo = form.memo.data + + with g.session.begin(): + record.update() + g.session.add(record) + + return redirect(url_for('domain_a.record_list', domain=domain.name)) + + +@app.route('//del', methods=['GET', 'POST']) +@login(True, '/') +def record_delete(domain, record_id): + domain = get_domain(domain) + + if not domain: + return redirect(url_for('domain.index')) + + record = g.session.query(RecordA).filter(RecordA.id == record_id)\ + .filter(RecordA.domain == domain)\ + .first() + if not record: + return redirect(url_for('domain_a.record_list', domain=domain.name)) + + if request.method == 'POST': + with g.session.begin(): + record.domain.update() + g.session.add(record.domain) + g.session.delete(record) + return redirect(url_for('domain_a.record_list', domain=domain.name)) + + return render_template('domain_a/del.html', domain=domain, record=record) diff --git a/pool/shard002/Python/0026632_find.py b/pool/shard002/Python/0026632_find.py new file mode 100644 index 0000000000000000000000000000000000000000..26628ed4596f47ab0f08e2dafb77fb62f8f437cd --- /dev/null +++ b/pool/shard002/Python/0026632_find.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python +# Copyright 2012 Google Inc. All Rights Reserved. +"""Find files on the client.""" +import stat + +from grr.lib import aff4 +from grr.lib import flow +from grr.lib.rdfvalues import structs as rdf_structs +from grr.proto import flows_pb2 + + +class FindFilesArgs(rdf_structs.RDFProtoStruct): + protobuf = flows_pb2.FindFilesArgs + + def Validate(self): + """Ensure that the request is sane.""" + self.findspec.Validate() + + +class FindFiles(flow.GRRFlow): + r"""Find files on the client. + + The logic is: + - Find files under "Path" + - Filter for files with os.path.basename matching "Path Regular Expression" + - Filter for files with sizes between min and max limits + - Filter for files that contain "Data Regular Expression" in the first 1MB + of file data + - Return AFF4Collection of the results + + Path and data regexes, and file size limits are optional. Don"t encode path + information in the regex. See correct usage below. + + Example: + + Path="/usr/local" + Path Regular Expression="admin" + + Match: "/usr/local/bin/admin" (file) + Match: "/usr/local/admin" (directory) + No Match: "/usr/admin/local/blah" + + The result from this flow is an AFF4Collection which will be created on the + output path, containing all aff4 objects on the client which match the + criteria. These files will not be downloaded by this flow, only the metadata + of the file is fetched. + + Note: This flow is inefficient for collecting a large number of files. + + Returns to parent flow: + rdf_client.StatEntry objects for each found file. + """ + + category = "/Filesystem/" + args_type = FindFilesArgs + friendly_name = "Find Files" + + @flow.StateHandler(next_state="IterateFind") + def Start(self, unused_response): + """Issue the find request to the client.""" + self.state.Register("received_count", 0) + self.state.Register("collection", None) + + # Build up the request protobuf. + self.args.findspec.iterator.number = self.args.iteration_count + + # Convert the filename glob to a regular expression. + if self.args.findspec.path_glob: + self.args.findspec.path_regex = self.args.findspec.path_glob.AsRegEx() + + # Call the client with it + self.CallClient("Find", self.state.args.findspec, next_state="IterateFind") + + @flow.StateHandler(next_state="IterateFind") + def IterateFind(self, responses): + """Iterate in this state until no more results are available.""" + if not responses.success: + raise IOError(responses.status) + + for response in responses: + # Create the file in the VFS + vfs_urn = aff4.AFF4Object.VFSGRRClient.PathspecToURN( + response.hit.pathspec, self.client_id) + + response.hit.aff4path = vfs_urn + + # TODO(user): This ends up being fairly expensive. + if stat.S_ISDIR(response.hit.st_mode): + fd = aff4.FACTORY.Create(vfs_urn, "VFSDirectory", token=self.token) + else: + fd = aff4.FACTORY.Create(vfs_urn, "VFSFile", token=self.token) + + stat_response = fd.Schema.STAT(response.hit) + fd.Set(stat_response) + + fd.Set(fd.Schema.PATHSPEC(response.hit.pathspec)) + fd.Close(sync=False) + + # Send the stat to the parent flow. + self.SendReply(stat_response) + + self.state.received_count += len(responses) + + # Exit if we hit the max result count we wanted or we're finished. Note that + # we may exceed the max_results if the iteration yielded too many results, + # we simply will not return to the client for another iteration. + if (self.state.received_count < self.state.args.max_results and + responses.iterator.state != responses.iterator.State.FINISHED): + + self.state.args.findspec.iterator = responses.iterator + + # If we are close to max_results reduce the iterator. + self.state.args.findspec.iterator.number = min( + self.state.args.findspec.iterator.number, + self.state.args.max_results - self.state.received_count) + + self.CallClient("Find", self.state.args.findspec, + next_state="IterateFind") + self.Log("%d files processed.", self.state.received_count) diff --git a/pool/shard002/Python/0026633_test_hierarchy.py b/pool/shard002/Python/0026633_test_hierarchy.py new file mode 100644 index 0000000000000000000000000000000000000000..923a449129e6ad0e3eea93cbfa11bac560c85cc6 --- /dev/null +++ b/pool/shard002/Python/0026633_test_hierarchy.py @@ -0,0 +1,42 @@ +# This code is so you can run the samples without installing the package +import sys +import os +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) +# + + +import cocos +from cocos.director import director +from cocos.actions import Rotate, MoveBy, ScaleBy +from cocos.sprite import Sprite + +import pyglet + +class TestLayer(cocos.layer.Layer): + def __init__(self): + super( TestLayer, self ).__init__() + + x,y = director.get_window_size() + + self.sprite = Sprite( 'grossini.png', (x/2, y/2) ) + self.add( self.sprite ) + + self.sprite2 = Sprite( 'grossinis_sister1.png', (0, 101) ) + self.sprite.add( self.sprite2 ) + + self.sprite3 = Sprite( 'grossinis_sister2.png', (0, 102) ) + self.sprite2.add( self.sprite3 ) + + self.sprite.do( Rotate(360,10) ) + self.sprite2.do( ScaleBy(2,5)+ScaleBy(0.5,5) ) + self.sprite2.do( Rotate(360,10) ) + self.sprite3.do( Rotate(360,10) ) + self.sprite3.do( ScaleBy(2,5)+ScaleBy(0.5,5) ) + + + +if __name__ == "__main__": + director.init() + test_layer = TestLayer () + main_scene = cocos.scene.Scene (test_layer) + director.run (main_scene) diff --git a/pool/shard002/Python/0026637_timeformat.py b/pool/shard002/Python/0026637_timeformat.py new file mode 100644 index 0000000000000000000000000000000000000000..9486c78f6120807257c6c4b8a5848865c22f42ba --- /dev/null +++ b/pool/shard002/Python/0026637_timeformat.py @@ -0,0 +1,127 @@ +import datetime + +from botcore.util import formatting + + +def timesince(d, now=None, count=2, accuracy=6, simple=False): + """ + Takes two datetime objects and returns the time between d and now + as a nicely formatted string, e.g. "10 minutes". If d occurs after now, + then "0 minutes" is returned. + This function has a number of optional arguments that can be combined: + + SIMPLE: displays the time in a simple format + >> timesince(SECONDS) + 1 hour, 2 minutes and 34 seconds + >> timesince(SECONDS, simple=True) + 1h 2m 34s + + COUNT: how many periods should be shown (default 3) + >> timesince(SECONDS) + 147 years, 9 months and 8 weeks + >> timesince(SECONDS, count=6) + 147 years, 9 months, 7 weeks, 18 hours, 12 minutes and 34 seconds + """ + + # Convert int or float (unix epoch) to datetime.datetime for comparison + if isinstance(d, int) or isinstance(d, float): + d = datetime.datetime.fromtimestamp(d) + + if isinstance(now, int) or isinstance(now, float): + now = datetime.datetime.fromtimestamp(now) + + # Convert datetime.date to datetime.datetime for comparison. + if not isinstance(d, datetime.datetime): + d = datetime.datetime(d.year, d.month, d.day) + if now and not isinstance(now, datetime.datetime): + now = datetime.datetime(now.year, now.month, now.day) + + if not now: + now = datetime.datetime.now() + + # ignore microsecond part of 'd' since we removed it from 'now' + delta = now - (d - datetime.timedelta(0, 0, d.microsecond)) + since = delta.days * 24 * 60 * 60 + delta.seconds + + if since <= 0: + # d is in the future compared to now, stop processing. + return '0 ' + 'minutes' + + # pass the number in seconds on to format_time to make the output string + return format_time(since, count, accuracy, simple) + + +def timeuntil(d, now=None, count=2, accuracy=6, simple=False): + """ + Like timesince, but returns a string measuring the time until + the given time. + """ + if not now: + now = datetime.datetime.now() + return timesince(now, d, count, accuracy, simple) + + +def format_time(seconds, count=3, accuracy=6, simple=False): + """ + Takes a length of time in seconds and returns a string describing that length of time. + This function has a number of optional arguments that can be combined: + + SIMPLE: displays the time in a simple format + >> format_time(SECONDS) + 1 hour, 2 minutes and 34 seconds + >> format_time(SECONDS, simple=True) + 1h 2m 34s + + COUNT: how many periods should be shown (default 3) + >> format_time(SECONDS) + 147 years, 9 months and 8 weeks + >> format_time(SECONDS, count=6) + 147 years, 9 months, 7 weeks, 18 hours, 12 minutes and 34 seconds + """ + + if simple: + periods = [ + ('c', 60 * 60 * 24 * 365 * 100), + ('de', 60 * 60 * 24 * 365 * 10), + ('y', 60 * 60 * 24 * 365), + ('m', 60 * 60 * 24 * 30), + ('d', 60 * 60 * 24), + ('h', 60 * 60), + ('m', 60), + ('s', 1) + ] + else: + periods = [ + (('century', 'centuries'), 60 * 60 * 24 * 365 * 100), + (('decade', 'decades'), 60 * 60 * 24 * 365 * 10), + (('year', 'years'), 60 * 60 * 24 * 365), + (('month', 'months'), 60 * 60 * 24 * 30), + (('day', 'days'), 60 * 60 * 24), + (('hour', 'hours'), 60 * 60), + (('minute', 'minutes'), 60), + (('second', 'seconds'), 1) + ] + + periods = periods[-accuracy:] + + strings = [] + i = 0 + for period_name, period_seconds in periods: + if i < count: + if seconds > period_seconds: + period_value, seconds = divmod(seconds, period_seconds) + i += 1 + if simple: + strings.append("{}{}".format(period_value, period_name)) + else: + if period_value == 1: + strings.append("{} {}".format(period_value, period_name[0])) + else: + strings.append("{} {}".format(period_value, period_name[1])) + else: + break + + if simple: + return " ".join(strings) + else: + return formatting.get_text_list(strings, "and") diff --git a/pool/shard002/Python/0026639_individual.py b/pool/shard002/Python/0026639_individual.py new file mode 100644 index 0000000000000000000000000000000000000000..06e4cd8c4287855b7a544575e18aaf834b66fa19 --- /dev/null +++ b/pool/shard002/Python/0026639_individual.py @@ -0,0 +1,190 @@ +""" +Copyright (c) 2017, University of Southern Denmark +All rights reserved. +This code is licensed under BSD 2-clause license. +See LICENSE file in the project root for license terms. +""" +import logging +import random +import pandas as pd +import numpy as np +import copy +from modestpy.estim.error import calc_err + + +class Individual(object): + + def __init__(self, est_objects, population, genes=None, + use_init_guess=False, ftype='NRMSE'): + """ + Individual can be initialized using `genes` OR initial guess + in `est_objects` (genes are inferred from parameters and vice versa). + Otherwise, random genes are assumed. + + :param est_objects: List of EstPar objects with estimated parameters + :type est_objects: list(EstPar) + :param Population population: Population instance + :param genes: Genes (can be also inferred from `parameters`) + :type genes: dict(str: float) + :param bool use_init_guess: If True, use initial guess from + `est_objects` + :param str ftype: Cost function type, 'RMSE' or 'NRMSE' + """ + + self.logger = logging.getLogger(type(self).__name__) + + # Reference to the population object + self.population = population + + # Assign variables shared across the population + self.ideal = population.ideal + self.model = population.model + + # Cost function type + self.ftype = ftype + + # Deep copy EstPar instances to avoid sharing between individuals + self.est_par_objects = copy.deepcopy(est_objects) + + # Generate genes + if not genes and not use_init_guess: + # Generate random genes + est_names = Individual._get_names(self.est_par_objects) + self.genes = Individual._random_genes(est_names) + elif genes and not use_init_guess: + # Use provided genes + self.genes = copy.deepcopy(genes) + elif use_init_guess and not genes: + # Infer genes from parameters + self.genes = dict() + for p in self.est_par_objects: + self.genes[p.name] = (p.value - p.lo) / (p.hi - p.lo) + assert self.genes[p.name] >= 0. and self.genes[p.name] <= 1., \ + 'Initial guess outside the bounds' + else: + msg = 'Either genes or parameters have to be None' + self.logger.error(msg) + raise ValueError(msg) + + # Update parameters + self._update_parameters() + + # Individual result + self.result = None + self.error = None + + # Main methods ------------------------------ + def calculate(self): + # Just in case, individual result and error + # are cleared before simulation + self.reset() + # Important to set estimated parameters just before simulation, + # because all individuals share the same model instance + self.model.set_param(self.est_par_df) + # Simulation + self.result = self.model.simulate() + # Make sure the returned result is not empty + assert self.result.empty is False, \ + 'Empty result returned from simulation... (?)' + # Calculate error + self.logger.debug("Calculating error ({}) in individual {}" + .format(self.ftype, self.genes)) + self.error = calc_err(self.result, self.ideal, ftype=self.ftype) + + def reset(self): + self.result = None + self.error = None + self.est_par_objects = copy.deepcopy(self.est_par_objects) + + def set_gene(self, name, value): + self.genes[name] = value + self._update_parameters() + + def get_gene(self, name): + return self.genes[name] + + def get_sorted_gene_names(self): + return sorted(self.genes.keys()) + + def get_estimates(self, as_dict=False): + """ + :param as_dict: boolean (True to get dictionary instead DataFrame) + :return: DataFrame with estimated parameters + """ + df = pd.DataFrame() + for par in self.est_par_objects: + df[par.name] = np.array([par.value]) + if as_dict: + return df.to_dict() + else: + return df + + def get_estimates_and_error(self): + estimates = self.get_estimates() + estimates['_error_'] = self.error['tot'] + return estimates + + def get_clone(self): + clone = Individual(self.est_par_objects, self.population, + self.genes, ftype=self.ftype) + return clone + + # Private methods --------------------------- + def _update_parameters(self): + # Calculate parameter values + self.est_par_objects = self._calc_parameters(self.genes) + # Convert estimated parameters to dataframe + self.est_par_df = Individual._est_pars_2_df(self.est_par_objects) + + @staticmethod + def _est_pars_2_df(est_pars): + df = pd.DataFrame() + for p in est_pars: + df[p.name] = np.array([p.value]) + return df + + def _calc_parameters(self, genes): + """ + Calculates parameters based on genes and limits. + :return: None + """ + for par in self.est_par_objects: + gene = genes[par.name] + par.value = par.lo + gene * (par.hi - par.lo) + return self.est_par_objects + + @staticmethod + def _random_genes(par_names): + """ + Generates random genes. + :return: dict(str: float) + """ + genes = dict() + for par in par_names: + g = 0 + while g == 0: # Because random.random() can return 0 + g = random.random() + genes[par] = g + return genes + + @staticmethod + def _get_names(est_params): + names = list() + for par in est_params: + names.append(par.name) + return names + + # Overriden methods -------------------------- + def __str__(self): + s = 'Individual (' + for par in self.est_par_objects: + s += par.name + '={0:.3f}'.format(par.value) + s += ', ' + # Delete trailing comma + s = s[:-2] + s += '), err=' + if self.error: + s += '{:.4f} '.format(self.error['tot']) + else: + s += 'None' + return s diff --git a/pool/shard002/Python/0026640_func.py b/pool/shard002/Python/0026640_func.py new file mode 100644 index 0000000000000000000000000000000000000000..daab1fe1b5bacf0cef3aab5f16c8650ba415e85e --- /dev/null +++ b/pool/shard002/Python/0026640_func.py @@ -0,0 +1,249 @@ +# +# GoogleAppsAccountManager: frontend/_func +# Copyright (C) 2012-2013 KAMEI Yutaka +# +# License: GNU General Public License version 2 or later +# Date: 2012-12-28, since 2012-12-28 +# + +import sys +from GoogleAppsAccountManager.frontend import _messages + +# Parse config file +# +# Config file name must be "gapps-tool.conf" +# Format like below +# +# admin_name: "jack" +# domain: "example.com" +# result_file: "/var/log/gapp-tool.result" +# +def parseConfig(specified_config=None): + import os.path + + # Parameters + admin_name = "admin_name" + domain = "domain" + result_file = "result_file" + + config_file = None + if specified_config is not None: + # Read specified config file + config_file = open(os.path.expanduser(specified_config), "r") + else: + # Read default config files + default_conf_name = "gapps-tool.conf" + file_names = [ "/etc/{}" .format(default_conf_name) + , "/etc/gapps-tool/{}" .format(default_conf_name) + , "~/.config/{}" .format(default_conf_name) + , "~/.config/gapps-tool/{}" .format(default_conf_name) + , "/opt/test/etc/{}" .format(default_conf_name) + , "/opt/test/etc/gapps-tool/{}" .format(default_conf_name) + , "{}" .format(default_conf_name) + ] + for file_name in file_names: + try: + config_file = open(os.path.expanduser(file_name), "r") + except: + pass + else: + break + + if config_file is None: + return None + + param_dict = "{" + config_file.read().replace("\n", ",") + "}" + try: + param_dict = eval(param_dict) + except Exception, e: + return str(e) + + if not param_dict.has_key("admin_name") or not param_dict.has_key("domain"): + return None + else: + return param_dict + +# Login and get auth token +def getAuthTokenByLogin(admin_name, domain): + import getpass + from GoogleAppsAccountManager import login + + admin_pass = getpass.getpass("Administrator's Password:", stream=sys.stderr) + admin_email = "{}@{}".format(admin_name, domain) + return login.clientLogin(admin_email, admin_pass) + +# Get user's password by interactive shell +def getHashedPassword_interactive(hash_function_name): + import getpass + import hashlib + MAX_RETRY = 3 + + if hash_function_name == "SHA-1": + hashMethod = hashlib.sha1 + elif hash_function_name == "MD5": + hashMethod = hashlib.md5 + else: + sys.stderr.write("{} is not supported.\n".format(hash_function_name)) + raise Exception() + + for cnt in range(MAX_RETRY): + user_pass = getpass.getpass("New User's Password:", stream=sys.stderr) + check_pass = getpass.getpass("Retype new User's Password:", stream=sys.stderr) + if user_pass == check_pass: + return hashMethod(user_pass).hexdigest() + sys.stderr.write("Sorry, passwords do not match.\n") + + sys.stderr.write("Try again.\n") + raise Exception() + +# Get user's password +def getHashedPassword(plain_pass, hash_function_name): + import hashlib + if plain_pass is None: + return None + if hash_function_name == "SHA-1": + return hashlib.sha1(plain_pass).hexdigest() + elif hash_function_name == "MD5": + return hashlib.md5(plain_pass).hexdigest() + +# Get "true" string, "false" string or None +# e.g. When you want to handle --lock and --unlock options, +# this may be of help. +# +# A and notA arguments must be True or False boolean object. +def getTrueOrFalse(A, notA): + if (A == True) and (notA == True): + sys.stderr.write(_messages.CONFLICTED_OPTIONS) + return False + elif A == True: + return "true" + elif notA == True: + return "false" + else: + return None + +# Check record has correct field +# record must be dictionary +def checkRecordHasKey(record, *fields): + for key in fields: + if not record.has_key(key): + sys.stderr.write("error: csv record is not correct.\n") + return False + return True + +# Check csv file has correct header +def checkValidHeader(header, *must_keys): + for key in must_keys: + if not key in header: + sys.stderr.write( + "error: Invalid csv header. CSV header must be like below.\n" + "\n{}\n\n".format(",".join(must_keys)) + ) + return False + return True + +# Check record has value +def checkRecordHasValue(record, *fields): + for key in fields: + if record[key] == "": + sys.stderr.write("error: {} must have value.\n".format(key)) + return False + return True + +# Replace space to None object +def replaceSpace2None(val, orig="", src=None): + if val == orig: + return src + else: + return val + +# Core operation +def operate(f, target, operation_name, result_file, *args, **kwargs): + import time + from GoogleAppsAccountManager import errors + + try: + f(*args, **kwargs) + except errors.ResponseError_xml, e: + detail = ( "error code \"{}\": invalid input \"{}\": reason \"{}\"" + .format(e.error_code, e.invalid_input, e.reason) + ) + sys.stdout.write( _messages.FAILED_RESULT + .format( target = target + , operation = operation_name + , detail = detail + , date = time.strftime("%b %d %H:%M:%S") + ) + ) + if result_file is not None: + with open(result_file, "a") as f: + f.write( _messages.FAILED_RESULT + .format( target = target + , operation = operation_name + , detail = detail + , date = time.strftime("%b %d %H:%M:%S") + ) + ) + return False + except errors.ResponseError_string, e: + detail = e.reason + sys.stdout.write( _messages.FAILED_RESULT + .format( target = target + , operation = operation_name + , detail = detail + , date = time.strftime("%b %d %H:%M:%S") + ) + ) + if result_file is not None: + with open(result_file, "a") as f: + f.write( _messages.FAILED_RESULT + .format( target = target + , operation = operation_name + , detail = detail + , date = time.strftime("%b %d %H:%M:%S") + ) + ) + return False + except errors.NoParametersError, e: + detail = "No parameters specified" + sys.stdout.write( _messages.FAILED_RESULT + .format( target = target + , operation = operation_name + , detail = detail + , date = time.strftime("%b %d %H:%M:%S") + ) + ) + if result_file is not None: + with open(result_file, "a") as f: + f.write( _messages.FAILED_RESULT + .format( target = target + , operation = operation_name + , detail = detail + , date = time.strftime("%b %d %H:%M:%S") + ) + ) + return False + except Exception, e: + import traceback + traceback.print_exc() + return False + else: + if "list" in operation_name: + return True + + sys.stdout.write( _messages.SUCCESS_RESULT + .format( target = target + , operation = operation_name + , date = time.strftime("%b %d %H:%M:%S") + ) + ) + if result_file is not None: + with open(result_file, "a") as f: + f.write( _messages.SUCCESS_RESULT + .format( target = target + , operation = operation_name + , date = time.strftime("%b %d %H:%M:%S") + ) + ) + return True + diff --git a/pool/shard002/Python/0026643_init__.py b/pool/shard002/Python/0026643_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7aec17bf484a77141904a68d6af2dada538f6bf9 --- /dev/null +++ b/pool/shard002/Python/0026643_init__.py @@ -0,0 +1,137 @@ +# Copyright (c) 2019 Cloudify Platform Ltd. 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 json +import os +import sys +from tempfile import NamedTemporaryFile + + +DEPRECATED_KEYS = [ + 'site_yaml_path', + 'inventory_config', + 'variable_manager_config', + 'passwords', + 'modules', + 'private_key_file'] +LIST_TYPES = ['skip-tags', 'tags'] +DIRECT_PARAMS = ['start_at_task', 'scp_extra_args', 'sftp_extra_args', + 'ssh_common_args', 'ssh_extra_args', 'timeout'] + + +def get_fileno(): + try: + return sys.stdout.fileno + except AttributeError: + return + + +class CloudifyAnsibleSDKError(Exception): + """Generic Error for handling issues preparing + the Ansible Playbook. + """ + + pass + + +class AnsiblePlaybookFromFile(object): + """ Object for communication to Ansible Library.""" + + def __init__(self, + playbook_path=None, + sources='localhost,', + options_config=None, + run_data=None, + verbosity=2, + logger=None, + site_yaml_path=None, + environment_variables=None, + additional_args=None, + **kwargs): + + self.playbook = site_yaml_path or playbook_path + self.sources = sources + self.options_config = options_config or {} + self.run_data = run_data or {} + self.environment_variables = environment_variables or {} + self.additional_args = additional_args or '' + self._verbosity = verbosity + self.logger = logger + + for deprecated_key in DEPRECATED_KEYS: + if deprecated_key in kwargs: + self.logger.error( + 'This key been deprecated: {0} {1}'.format( + deprecated_key, kwargs[deprecated_key])) + + # add known additional params to additional_args + for field in DIRECT_PARAMS: + if kwargs.get(field): + self.additional_args += "--{field} {value} ".format( + field=field.replace("_", "-"), + value=json.dumps(kwargs[field])) + + @property + def env(self): + _env = os.environ.copy() + for key, value in self.environment_variables.items(): + _env[key] = value + return _env + + @property + def verbosity(self): + verbosity = '-v' + for i in range(1, self._verbosity): + verbosity += 'v' + return verbosity + + @property + def options(self): + options_list = [] + if 'extra_vars' not in self.options_config: + self.options_config['extra_vars'] = {} + self.options_config['extra_vars'].update(self.run_data) + for key, value in self.options_config.items(): + if key == 'extra_vars': + f = NamedTemporaryFile(delete=False) + with open(f.name, 'w') as outfile: + json.dump(value, outfile) + value = '@{filepath}'.format(filepath=f.name) + elif key == 'verbosity': + self.logger.error('No such option verbosity') + del key + continue + key = key.replace("_", "-") + if isinstance(value, dict): + value = json.dumps(value) + elif isinstance(value, list) and key not in LIST_TYPES: + value = [i for i in value] + elif isinstance(value, list): + value = u",".join(value) + options_list.append( + '--{key}={value}'.format(key=key, value=repr(value))) + return ' '.join(options_list) + + @property + def process_args(self): + return [ + self.verbosity, + '-i {0}'.format(self.sources), + self.options, + self.additional_args, + self.playbook + ] + + def execute(self, process_execution_func, **kwargs): + return process_execution_func(**kwargs) diff --git a/pool/shard002/Python/0026652_test_readme.py b/pool/shard002/Python/0026652_test_readme.py new file mode 100644 index 0000000000000000000000000000000000000000..cee1508ffb54dffd61bc42d559f33b7e51634233 --- /dev/null +++ b/pool/shard002/Python/0026652_test_readme.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python +# -*- coding: utf-8; py-indent-offset:4 -*- +############################################################################### +# +# Copyright (C) 2015 Daniel Rodriguez +# +# 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 __future__ import (absolute_import, division, print_function, + unicode_literals) + + +from metaframe import MetaFrame + +# First creating the class with MetaFrame as metaclass + +class A(MetaFrame.as_metaclass(object)): + + @classmethod + def _new_do(cls, *args, **kwargs): + + nkwargs = dict() + for key, val in kwargs.items(): + + # Remove any argument with a value of None + if val is None: + continue + + try: + val = float(val) + except: + continue + + nkwargs[key] = val + + # The only nuisance being the cumbersome call to _new_do + # super doesn't work + obj, args, kwargs = cls.__class__._new_do(cls, *args, **nkwargs) + return obj, args, kwargs + + def __init__(self, **kwargs): + for key, val in kwargs.items(): + print('key, val, type', key, val, type(val)) + + +a = A(p1=72, p2=None, p3='hello', p4=None, p5='72.5') + + +# Now with a subclassed MetaB from MetaFrame +# Here super can be applied to find the higher in the hierarchy _new_do + +class MetaB(MetaFrame): + + def _new_do(cls, *args, **kwargs): + + nkwargs = dict() + for key, val in kwargs.items(): + + # Remove any argument with a value of None + if val is None: + continue + + try: + val = float(val) + except: + continue + + nkwargs[key] = val + + # super can be called directly + obj, args, kwargs = super(MetaB, cls)._new_do(*args, **nkwargs) + return obj, args, kwargs + + +class B(MetaB.as_metaclass()): + def __init__(self, **kwargs): + for key, val in kwargs.items(): + print('key, val, type', key, val, type(val)) + + +b = B(p1=27, p2=None, p3='olleh', p4=None, p5='5.27') diff --git a/pool/shard002/Python/0026657_debugger_test.py b/pool/shard002/Python/0026657_debugger_test.py new file mode 100644 index 0000000000000000000000000000000000000000..817690bc81e9aa9bd73b599fee0443b327cfc361 --- /dev/null +++ b/pool/shard002/Python/0026657_debugger_test.py @@ -0,0 +1,44 @@ + +import unittest + +from PySide2.QtCore import SIGNAL, QTimer +from PySide2.QtScript import QScriptEngine +from PySide2.QtScriptTools import QScriptEngineDebugger + +from helper import UsesQApplication + +class DebuggerTest(UsesQApplication): + + def setUp(self): + UsesQApplication.setUp(self) + self.engine = QScriptEngine() + self.debugger = QScriptEngineDebugger() + self.has_suspended = 0 + self.has_resumed = 0 + self.count = 3 + + def suspended(self): + self.has_suspended += 1 + # Will emit evaluationResumed until there are more instructions to be run + QTimer.singleShot(100, self.debugger.action(QScriptEngineDebugger.StepIntoAction).trigger) + + def resumed(self): + # Will be called when debugger.state() change from Suspended to Running + # except for the first time. + self.has_resumed += 1 + + def testBasic(self): + '''Interrupt and resume evaluation with QScriptEngineDebugger''' + + self.debugger.attachTo(self.engine) + self.debugger.setAutoShowStandardWindow(False) + self.debugger.connect(SIGNAL('evaluationSuspended()'), self.suspended) + self.debugger.connect(SIGNAL('evaluationResumed()'), self.resumed) + + self.debugger.action(QScriptEngineDebugger.InterruptAction).trigger() + self.engine.evaluate("3+4\n2+1\n5+1") + self.assert_(self.has_resumed >= 1) + self.assert_(self.has_suspended >= 1) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard002/Python/0026676_6f3aadb613f_.py b/pool/shard002/Python/0026676_6f3aadb613f_.py new file mode 100644 index 0000000000000000000000000000000000000000..90c92f41386ddf735d91f3e3f06d281a413567d1 --- /dev/null +++ b/pool/shard002/Python/0026676_6f3aadb613f_.py @@ -0,0 +1,40 @@ +"""Add table impact + +Revision ID: 6f3aadb613f +Revises: 1894217a6b3f +Create Date: 2014-07-02 16:58:02.545151 + +""" + +# revision identifiers, used by Alembic. +revision = '6f3aadb613f' +down_revision = '4adbb49a02f0' + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +impact_status = sa.Enum('published', 'archived', name='impact_status') + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('impact', + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=True), + sa.Column('id', postgresql.UUID(), nullable=False), + sa.Column('disruption_id', postgresql.UUID(), nullable=True), + sa.ForeignKeyConstraint(['disruption_id'], [u'disruption.id'] ), + sa.PrimaryKeyConstraint('id') + ) + impact_status.create(op.get_bind(), True) + op.add_column('impact', sa.Column('status', impact_status, nullable=False, server_default='published', index=True)) + op.create_index('ix_impact_status', 'impact', ['status'], unique=False) + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_index('ix_impact_status', 'impact') + op.drop_table('impact') + impact_status.drop(op.get_bind()) + ### end Alembic commands ### diff --git a/pool/shard002/Python/0026677_Coco-Bits_vs_TL.py b/pool/shard002/Python/0026677_Coco-Bits_vs_TL.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c430e2c08a15e13768331f779b053076b9ae4b --- /dev/null +++ b/pool/shard002/Python/0026677_Coco-Bits_vs_TL.py @@ -0,0 +1,28 @@ +def valid(n): + if(n >= 0 and n <= 255): + return True; + return False; + +def validIp(v): + for i in v: + if(not valid(int(i))): + return False + return True; + +v = [] +t = input() +try: + while(t): + st = raw_input() + v = st.split(".") + t = t - 1 + if(len(v) != 4 and len(v) != 6): + print "NO\n" + else: + if(validIp(v)): + print "SI\n" + else: + print "NO\n" +except val: + print "NO\n" + diff --git a/pool/shard002/Python/0026686_mem_device_doc.py b/pool/shard002/Python/0026686_mem_device_doc.py new file mode 100644 index 0000000000000000000000000000000000000000..bd5c86c0f92f60d28fad6bd3f7dd8aa3fbca9d54 --- /dev/null +++ b/pool/shard002/Python/0026686_mem_device_doc.py @@ -0,0 +1,133 @@ +from utils import enter_depend_test, STEPS, RESULT, SETUP +enter_depend_test() + +from depend_test_framework.test_object import Mist, MistDeadEndException, MistClearException +from depend_test_framework.dependency import Provider, Consumer + + +def set_memory_device(params, env): + """ + Add memory device in guest xml + """ + params.doc_logger.info(STEPS + """ + + + %d + %s + + + """ % (params.memdevice.size, params.memdevice.node)) + info = env.get_data('$guest_name.config').data + info['memory'] += params.memdevice.size + +def verify_memory_device(params, env): + """ + check memroy device + """ + pass + +def set_maxmemory(params, env): + """ + Add maxmemory in guest xml for memory device + """ + params.doc_logger.info(STEPS + """ + %d + """ % (params.maxmemory.slots, params.maxmemory.size)) + info = env.get_data('$guest_name.config').data + info['maxmemory'] = dict(params.maxmemory) + +def attach_mem_device(params, env): + """ + Hotplug memory device + """ + params.doc_logger.info(STEPS + """ + # cat memdev.xml + + + %d + %d + + + """ % (params.memdevice.size, params.memdevice.node)) + params.doc_logger.info("# virsh attach-device %s memdev.xml --live" % params.guest_name) + params.doc_logger.info(RESULT + "Device attached successfully") + + info = env.get_data('$guest_name.active').data + info['memory'] += params.memdevice.size + + +def detach_mem_device(params, env): + """ + Hot unplug memory device + """ + params.doc_logger.info(STEPS + """ + # cat memdev.xml + + + %d + %d + + + """ % (params.memdevice.size, params.memdevice.node)) + params.doc_logger.info("# virsh detach-device %s memdev.xml --live" % params.guest_name) + params.doc_logger.info(RESULT + "Device detached successfully") + + info = env.get_data('$guest_name.active').data + info['memory'] -= params.memdevice.size + +def check_mem_device_audit(params, env): + """ + Check the audit system + """ + params.doc_logger.info(STEPS + "Make sure the auditd is running") + + start1 = [Provider('$guest_name.active', Provider.SET), + Provider('$guest_name.active.memdevice', Provider.CLEAR)] + end1 = [Provider('$guest_name.active.memdevice', Provider.SET)] + + start2 = [Provider('$guest_name.active', Provider.CLEAR), + Provider('$guest_name.active.memdevice', Provider.CLEAR)] + end2 = [Provider('$guest_name.active.memdevice', Provider.SET)] + + start3 = [Provider('$guest_name.active.memdevice', Provider.SET)] + end3 = [Provider('$guest_name.active.memdevice', Provider.CLEAR), + Provider('$guest_name.active', Provider.SET)] + + def check_mem_audit_log(name, func, params, env): + """ + Check the memory device audit log + """ + if name is not 'start': + old_mem = env.get_data('$guest_name.active').data.get('memory') + else: + old_mem = 0 + func(params, env) + + active_info = env.get_data('$guest_name.active').data + new_mem = active_info.get('memory') + params.doc_logger.info("") + params.doc_logger.info(STEPS + "# ausearch -m VIRT_RESOURCE -ts recent") + params.doc_logger.info(RESULT + """ +... +type=VIRT_RESOURCE ... msg='virt=kvm resrc=mem reason=%s vm="%s" uuid=%s old-mem=%d new-mem=%d exe="/usr/sbin/libvirtd" hostname=? addr=? terminal=? res=success' +... + """ % ('start' if name is 'start' else 'update', + active_info.get('name'), + active_info.get('uuid'), old_mem, new_mem)) + + return Mist({"attach": (start1, end1), + "start": (start2, end2), + "detach": (start3, end3)}, + check_mem_audit_log) + + +def check_maxmemory(params, env): + """ + Check maxmemory qemu cmdline + """ + active_info = env.get_data('$guest_name.active').data + mem = active_info.get('memory') + max_mem = active_info.get('maxmemory') + params.doc_logger.info(STEPS + "# ps aux|grep qemu") + params.doc_logger.info(RESULT + "-m size=%dk,slots=%d,maxmem=%dk", + mem, max_mem['slots'], max_mem['size']) diff --git a/pool/shard002/Python/0026689_test_oppiacron.py b/pool/shard002/Python/0026689_test_oppiacron.py new file mode 100644 index 0000000000000000000000000000000000000000..8c5adc56694378facb7c44a4b7523bd8e1b93cf4 --- /dev/null +++ b/pool/shard002/Python/0026689_test_oppiacron.py @@ -0,0 +1,29 @@ +import pytest + +from io import StringIO +from django.core.management import call_command +from oppia.test import OppiaTestCase + + +class OppiaCronTest(OppiaTestCase): + + fixtures = ['tests/test_user.json', + 'tests/test_oppia.json', + 'tests/test_quiz.json', + 'tests/test_permissions.json', + 'default_badges.json', + 'tests/test_course_permissions.json'] + + @pytest.mark.xfail(reason="works on local, but not on Github workflow \ + see issue: https://oppia.atlassian.net/browse/OPPIA-19") + def test_oppiacron_output(self): + out = StringIO() + call_command('oppiacron', stdout=out) + self.assertEqual(u'Cleaning up:', out.getvalue()[0:12]) + + @pytest.mark.xfail(reason="works on local, but not on Github workflow \ + see issue: https://oppia.atlassian.net/browse/OPPIA-19") + def test_oppiacron_hours_output(self): + out = StringIO() + call_command('oppiacron', '--hours=48', stdout=out) + self.assertEqual(u'Cleaning up:', out.getvalue()[0:12]) diff --git a/pool/shard002/Python/0026691_config_flow.py b/pool/shard002/Python/0026691_config_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3c39f148a4656b3340ea3556b921159b505f02 --- /dev/null +++ b/pool/shard002/Python/0026691_config_flow.py @@ -0,0 +1,43 @@ +"""Config flow to configure the CPU Speed integration.""" +from __future__ import annotations + +from typing import Any + +from cpuinfo import cpuinfo + +from homeassistant.config_entries import ConfigFlow +from homeassistant.const import CONF_NAME +from homeassistant.data_entry_flow import FlowResult + +from .const import DOMAIN + + +class CPUSpeedFlowHandler(ConfigFlow, domain=DOMAIN): + """Config flow for CPU Speed.""" + + VERSION = 1 + + _imported_name: str | None = None + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: + """Handle a flow initialized by the user.""" + await self.async_set_unique_id(DOMAIN) + self._abort_if_unique_id_configured() + + if user_input is None: + return self.async_show_form(step_id="user") + + if not await self.hass.async_add_executor_job(cpuinfo.get_cpu_info): + return self.async_abort(reason="not_compatible") + + return self.async_create_entry( + title=self._imported_name or "CPU Speed", + data={}, + ) + + async def async_step_import(self, config: dict[str, Any]) -> FlowResult: + """Handle a flow initialized by importing a config.""" + self._imported_name = config.get(CONF_NAME) + return await self.async_step_user(user_input={}) diff --git a/pool/shard002/Python/0026694_get_binary_mnist.py b/pool/shard002/Python/0026694_get_binary_mnist.py new file mode 100644 index 0000000000000000000000000000000000000000..91fbe1d6468904fb61100c1b01724a5795b14d6b --- /dev/null +++ b/pool/shard002/Python/0026694_get_binary_mnist.py @@ -0,0 +1,41 @@ +"""Get the binarized MNIST dataset and convert to hdf5. +From https://github.com/yburda/iwae/blob/master/datasets.py +""" +import urllib.request +import os +import numpy as np +import h5py + +DATASETS_DIR = '/tmp/' +subdatasets = ['train', 'valid', 'test'] + +for subdataset in subdatasets: + filename = 'binarized_mnist_{}.amat'.format(subdataset) + url = 'http://www.cs.toronto.edu/~larocheh/public/datasets/binarized_mnist/binarized_mnist_{}.amat'.format( + subdataset) + local_filename = os.path.join(DATASETS_DIR, filename) + urllib.request.urlretrieve(url, local_filename) + + +def binarized_mnist_fixed_binarization(): + def lines_to_np_array(lines): + return np.array([[int(i) for i in line.split()] for line in lines]) + with open(os.path.join(DATASETS_DIR, 'binarized_mnist_train.amat')) as f: + lines = f.readlines() + train_data = lines_to_np_array(lines).astype('float32') + with open(os.path.join(DATASETS_DIR, 'binarized_mnist_valid.amat')) as f: + lines = f.readlines() + validation_data = lines_to_np_array(lines).astype('float32') + with open(os.path.join(DATASETS_DIR, 'binarized_mnist_test.amat')) as f: + lines = f.readlines() + test_data = lines_to_np_array(lines).astype('float32') + return train_data, validation_data, test_data + + +train, validation, test = binarized_mnist_fixed_binarization() +data_dict = {'train': train, 'valid': validation, 'test': test} +f = h5py.File(os.path.join(DATASETS_DIR, 'binarized_mnist.hdf5'), 'w') +f.create_dataset('train', data=data_dict['train']) +f.create_dataset('valid', data=data_dict['valid']) +f.create_dataset('test', data=data_dict['test']) +f.close() diff --git a/pool/shard002/Python/0026696_k_catenyms.py b/pool/shard002/Python/0026696_k_catenyms.py new file mode 100644 index 0000000000000000000000000000000000000000..9242a417d19b220bbe20e493126d4929d7b20e0b --- /dev/null +++ b/pool/shard002/Python/0026696_k_catenyms.py @@ -0,0 +1,106 @@ +''' +Determine chain of words using complete set of input + +Status: Accepted +''' +from sys import setrecursionlimit +from string import ascii_lowercase + +setrecursionlimit(2048) +CATENYMS, MATRIX = None, None +LEN_WORDS = 0 + +############################################################################### + +def start_end(in_degrees, out_degrees): + """Determine the start and end nodes of a euler walk""" + + valid = True + start, end = None, None + for letter in ascii_lowercase: + if in_degrees[letter] - out_degrees[letter] == 1: + valid &= (end is None) + end = letter + elif out_degrees[letter] - in_degrees[letter] == 1: + valid &= (start is None) + start = letter + elif out_degrees[letter] != in_degrees[letter]: + valid = False + + if valid: + if start: + return start, end + + for letter in ascii_lowercase: + if in_degrees[letter]: + return letter, letter + + return None, None + +############################################################################### + +def dfs(location): + """Determine longest possible path searching in lexicographic order""" + + global LEN_WORDS, MATRIX, CATENYMS + + if len(CATENYMS) == LEN_WORDS: + return True + + for word in sorted(set(MATRIX[location])): + MATRIX[location].remove(word) + CATENYMS.append(word) + if dfs(word[-1]): + return True + CATENYMS.pop() + MATRIX[location].append(word) + + return False + +############################################################################### + +def euler_walk(words): + """Return lexicographically least traversal of all words""" + + global LEN_WORDS, MATRIX, CATENYMS + + CATENYMS = [] + MATRIX, in_degree, out_degree = {}, {}, {} + for first_letter in ascii_lowercase: + out_degree[first_letter] = 0 + in_degree[first_letter] = 0 + MATRIX[first_letter] = [] + + for word in words: + in_degree[word[-1]] += 1 + out_degree[word[0]] += 1 + MATRIX[word[0]].append(word) + + start, end = start_end(in_degree, out_degree) + if start and end: + LEN_WORDS = len(words) + if not dfs(start): + CATENYMS = [] + +############################################################################### + +def main(): + """Read input and print output for euler walk with words as edges""" + + global CATENYMS + + for _ in range(int(input().strip())): + words = [] + for _ in range(int(input().strip())): + words.append(input().strip()) + + euler_walk(words) + if CATENYMS: + print('.'.join(CATENYMS)) + else: + print('***') + +############################################################################### + +if __name__ == '__main__': + main() diff --git a/pool/shard002/Python/0026697_yazhouse8.py b/pool/shard002/Python/0026697_yazhouse8.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcd0ce2e32ea0b6167ec0c6e417edf54f2eca9d --- /dev/null +++ b/pool/shard002/Python/0026697_yazhouse8.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import re + +from novel import single, utils + +BASE_URL = 'http://www.yazhouse8.com/article/{}.html' + + +class Yazhouse8Tool(utils.Tool): + + def __init__(self): + super().__init__() + self.remove_extras.append( + re.compile(r'^记住地址', re.M) + ) + + +class Yazhouse8(single.SingleNovel): + + def __init__(self, tid): + super().__init__(utils.base_to_url(BASE_URL, tid), + '.content', + title_type=single.TitleType.selector, + title_sel='h1', + tid=tid) + self.tool = Yazhouse8Tool diff --git a/pool/shard002/Python/0026705_test_config.py b/pool/shard002/Python/0026705_test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d0b08a57aea3783a109e4d69d4c5f5d17a4049f9 --- /dev/null +++ b/pool/shard002/Python/0026705_test_config.py @@ -0,0 +1,88 @@ +import logging +import ntpath +import os +import re +import sys + +from cStringIO import StringIO + +import pkg_resources +import gearshift +from gearshift import testutil + +rfn = pkg_resources.resource_filename +testfile = rfn(__name__, "configfile.cfg") + +logout = StringIO() +logging.logout = logout + +# last forward slash (the one before static) is hard coded in our config +# file... all other path separators are calculated platform wise... + +def test_update_from_package(): + gearshift.update_config(modulename="gearshift.tests.config") + assert gearshift.config.get("foo.bar") == "BAZ!" + print gearshift.config.get("my.static") + assert gearshift.config.get("my.static").endswith( + "gearshift%stests/static" % os.path.sep) + assert gearshift.config.app["/static"]["tools.staticdir.on"] == True + +def test_update_from_both(): + gearshift.update_config(configfile = testfile, + modulename="gearshift.tests.config") + print gearshift.config.get("foo.bar") + assert gearshift.config.get("foo.bar") == "blurb" + assert gearshift.config.get("tg.something") == 10 + print gearshift.config.get("test.dir") + assert gearshift.config.get("test.dir").endswith( + "gearshift%stests" % os.path.sep) + +callnum = 0 + +def windows_filename(*args, **kw): + """Small helper function to emulate pkg_resources.resource_filename + as if it was called on a Wwindows system even if the tester is in fact + using Linux or Mac OS X. + + We need to keep track how often the function was called, since + 'gearshift.update_config' calls 'pkg_resources.resource_filename' at least + twice and we only want to return the fake Windows path the second and + following times. + + """ + global callnum + callnum += 1 + if callnum > 1: + return "c:\\foo\\bar\\" + else: + return rfn(*args, **kw) + +def test_update_on_windows(): + """gearshift.update_config works as we intend on Windows. + """ + # save the original function + orig_resource_fn = pkg_resources.resource_filename + # monkey patch pkg resources to emulate windows + pkg_resources.resource_filename = windows_filename + + gearshift.update_config(configfile=testfile, + modulename="gearshift.tests.config") + testdir = gearshift.config.get("test.dir") + # update_config calls os.normpath on package_dir, but this will have no + # effect on non-windows systems, so we call ntpath.normpath on those here + if not sys.platform.startswith('win'): + testdir = ntpath.normpath(testdir) + + # restore original function + pkg_resources.resource_filename = orig_resource_fn + assert testdir == "c:\\foo\\bar" + +def test_logging_config(): + logout.truncate(0) + log = logging.getLogger("gearshift.tests.test_config.logconfig") + log.info("Testing") + logged = logout.getvalue() + print "Logged: %s" % logged + assert re.match(r'F1 \d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d,\d\d\d INFO ' + 'Testing', logged) + assert gearshift.config.get("tg.new_style_logging", False) diff --git a/pool/shard002/Python/0026710_urls.py b/pool/shard002/Python/0026710_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c70068ee04eaba7330cbbf8d27218f367843ac --- /dev/null +++ b/pool/shard002/Python/0026710_urls.py @@ -0,0 +1,82 @@ +import re + +from sdklib.compat import urlencode, str, urlsplit as py_urlsplit + + +def urlsplit(url): + """ + Split url into scheme, host, port, path, query + + :param str url: + :return: scheme, host, port, path, query + """ + p = '((?P.*)?.*://)?(?P[^:/ ]+).?(?P[0-9]*).*' + m = re.search(p, url) + scheme = m.group('scheme') + host = m.group('host') + port = m.group('port') + + _scheme, _netloc, path, query, _fragment = tuple(py_urlsplit(url)) + + return scheme, host, port, path, query + + +def _get_scheme_or_default(scheme): + return scheme or 'http' + + +def _get_host_or_default(host): + return host or '127.0.0.1' + + +def _get_port_or_default(port, scheme): + return port or ('443' if scheme == 'https' else '80') + + +def get_hostname_parameters_from_url(url): + scheme, host, port, _, _ = urlsplit(url) + scheme = _get_scheme_or_default(scheme) + host = _get_host_or_default(host) + port = _get_port_or_default(port, scheme=scheme) + return scheme, host, port + + +def _ensure_str_starts_with(_str, beginning, default=''): + if not _str: + return default + if not _str.startswith('/'): + return beginning + _str + return _str + + +def ensure_url_path_starts_with_slash(url_path): + return _ensure_str_starts_with(url_path, '/', default='/') + + +def ensure_url_path_format_suffix_starts_with_dot(format_suffix): + return _ensure_str_starts_with(format_suffix, '.', default='') + + +def generate_url(scheme=None, host=None, port=None, path=None, query=None): + """ + Generate URI from parameters. + + :param str scheme: + :param str host: + :param int port: + :param str path: + :param dict query: + :return: + """ + url = "" + if scheme is not None: + url += "%s://" % scheme + if host is not None: + url += host + if port is not None: + url += ":%s" % str(port) + if path is not None: + url += ensure_url_path_starts_with_slash(path) + if query is not None: + url += "?%s" % (urlencode(query)) + return url diff --git a/pool/shard002/Python/0026711_qijo.py b/pool/shard002/Python/0026711_qijo.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9236d5560949ee3e038b2e4e8ac50282709d59 --- /dev/null +++ b/pool/shard002/Python/0026711_qijo.py @@ -0,0 +1,142 @@ +# 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/. + +from __future__ import absolute_import + +from ctypes import c_void_p, POINTER, sizeof, Structure, windll, WinError, WINFUNCTYPE, addressof, c_size_t, c_ulong +from ctypes.wintypes import BOOL, BYTE, DWORD, HANDLE, LARGE_INTEGER + +LPVOID = c_void_p +LPDWORD = POINTER(DWORD) +SIZE_T = c_size_t +ULONG_PTR = POINTER(c_ulong) + +# A ULONGLONG is a 64-bit unsigned integer. +# Thus there are 8 bytes in a ULONGLONG. +# XXX why not import c_ulonglong ? +ULONGLONG = BYTE * 8 + +class IO_COUNTERS(Structure): + # The IO_COUNTERS struct is 6 ULONGLONGs. + # TODO: Replace with non-dummy fields. + _fields_ = [('dummy', ULONGLONG * 6)] + +class JOBOBJECT_BASIC_ACCOUNTING_INFORMATION(Structure): + _fields_ = [('TotalUserTime', LARGE_INTEGER), + ('TotalKernelTime', LARGE_INTEGER), + ('ThisPeriodTotalUserTime', LARGE_INTEGER), + ('ThisPeriodTotalKernelTime', LARGE_INTEGER), + ('TotalPageFaultCount', DWORD), + ('TotalProcesses', DWORD), + ('ActiveProcesses', DWORD), + ('TotalTerminatedProcesses', DWORD)] + +class JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION(Structure): + _fields_ = [('BasicInfo', JOBOBJECT_BASIC_ACCOUNTING_INFORMATION), + ('IoInfo', IO_COUNTERS)] + +# see http://msdn.microsoft.com/en-us/library/ms684147%28VS.85%29.aspx +class JOBOBJECT_BASIC_LIMIT_INFORMATION(Structure): + _fields_ = [('PerProcessUserTimeLimit', LARGE_INTEGER), + ('PerJobUserTimeLimit', LARGE_INTEGER), + ('LimitFlags', DWORD), + ('MinimumWorkingSetSize', SIZE_T), + ('MaximumWorkingSetSize', SIZE_T), + ('ActiveProcessLimit', DWORD), + ('Affinity', ULONG_PTR), + ('PriorityClass', DWORD), + ('SchedulingClass', DWORD) + ] + +class JOBOBJECT_ASSOCIATE_COMPLETION_PORT(Structure): + _fields_ = [('CompletionKey', c_ulong), + ('CompletionPort', HANDLE)] + +# see http://msdn.microsoft.com/en-us/library/ms684156%28VS.85%29.aspx +class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(Structure): + _fields_ = [('BasicLimitInformation', JOBOBJECT_BASIC_LIMIT_INFORMATION), + ('IoInfo', IO_COUNTERS), + ('ProcessMemoryLimit', SIZE_T), + ('JobMemoryLimit', SIZE_T), + ('PeakProcessMemoryUsed', SIZE_T), + ('PeakJobMemoryUsed', SIZE_T)] + +# These numbers below come from: +# http://msdn.microsoft.com/en-us/library/ms686216%28v=vs.85%29.aspx +JobObjectAssociateCompletionPortInformation = 7 +JobObjectBasicAndIoAccountingInformation = 8 +JobObjectExtendedLimitInformation = 9 + +class JobObjectInfo(object): + mapping = { 'JobObjectBasicAndIoAccountingInformation': 8, + 'JobObjectExtendedLimitInformation': 9, + 'JobObjectAssociateCompletionPortInformation': 7 + } + structures = { + 7: JOBOBJECT_ASSOCIATE_COMPLETION_PORT, + 8: JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION, + 9: JOBOBJECT_EXTENDED_LIMIT_INFORMATION + } + def __init__(self, _class): + if isinstance(_class, basestring): + assert _class in self.mapping, 'Class should be one of %s; you gave %s' % (self.mapping, _class) + _class = self.mapping[_class] + assert _class in self.structures, 'Class should be one of %s; you gave %s' % (self.structures, _class) + self.code = _class + self.info = self.structures[_class]() + + +QueryInformationJobObjectProto = WINFUNCTYPE( + BOOL, # Return type + HANDLE, # hJob + DWORD, # JobObjectInfoClass + LPVOID, # lpJobObjectInfo + DWORD, # cbJobObjectInfoLength + LPDWORD # lpReturnLength + ) + +QueryInformationJobObjectFlags = ( + (1, 'hJob'), + (1, 'JobObjectInfoClass'), + (1, 'lpJobObjectInfo'), + (1, 'cbJobObjectInfoLength'), + (1, 'lpReturnLength', None) + ) + +_QueryInformationJobObject = QueryInformationJobObjectProto( + ('QueryInformationJobObject', windll.kernel32), + QueryInformationJobObjectFlags + ) + +class SubscriptableReadOnlyStruct(object): + def __init__(self, struct): + self._struct = struct + + def _delegate(self, name): + result = getattr(self._struct, name) + if isinstance(result, Structure): + return SubscriptableReadOnlyStruct(result) + return result + + def __getitem__(self, name): + match = [fname for fname, ftype in self._struct._fields_ + if fname == name] + if match: + return self._delegate(name) + raise KeyError(name) + + def __getattr__(self, name): + return self._delegate(name) + +def QueryInformationJobObject(hJob, JobObjectInfoClass): + jobinfo = JobObjectInfo(JobObjectInfoClass) + result = _QueryInformationJobObject( + hJob=hJob, + JobObjectInfoClass=jobinfo.code, + lpJobObjectInfo=addressof(jobinfo.info), + cbJobObjectInfoLength=sizeof(jobinfo.info) + ) + if not result: + raise WinError() + return SubscriptableReadOnlyStruct(jobinfo.info) diff --git a/pool/shard002/Python/0026713_test_message.py b/pool/shard002/Python/0026713_test_message.py new file mode 100644 index 0000000000000000000000000000000000000000..7081f9ffedc9d3a73369c50f671b7f1e586ec860 --- /dev/null +++ b/pool/shard002/Python/0026713_test_message.py @@ -0,0 +1,55 @@ +"""Tests the message framework.""" + +import threading +import time +import unittest + +from messaging.message_consumer import consume_messages +from messaging.message_producer import MessageProducer + + +class TestMessage(unittest.TestCase): + """Tests the message framework.""" + + EXCHANGE = 'test' + + def setUp(self): + self.message = None + + def test_1_producer_1_consumer(self): + """Test single producer single consumer.""" + def save_message(x): + self.message = x + + def consume(): + """Function to consume messages.""" + consume_messages(self.EXCHANGE, save_message) + + consumer = threading.Thread(target=consume) + consumer.name = '{}:consume_messages'.format(self.__class__.__name__) + consumer.start() + + # Give the receiver some time to set up, see comment below + time.sleep(0.05) + self.assertIs(self.message, None) + sent_message = 'banana' + producer = MessageProducer(self.EXCHANGE) + producer.publish(sent_message) + producer.publish('QUIT') + for _ in range(10): + # Because of a race condition, if the message is sent before the + # receiver has set up, the messages are never queued or something. + # Keep resending until the thread exits. + consumer.join(0.05) + if consumer.is_alive(): + producer.publish(sent_message) + producer.publish('QUIT') + + consumer.join(0.05) + self.assertFalse(consumer.is_alive()) + producer.kill() + self.assertEqual(self.message, sent_message) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard002/Python/0026719_msc_results.py b/pool/shard002/Python/0026719_msc_results.py new file mode 100644 index 0000000000000000000000000000000000000000..119a308f9596c24d1640ac49335a1273c9a87c4a --- /dev/null +++ b/pool/shard002/Python/0026719_msc_results.py @@ -0,0 +1,78 @@ +""" + +File: msc_results.py + +Purpose: Provides results from MelodicConstraintSolver.solve(). + +""" + +class MCSResults(object): + + def __init__(self, line, tempo_event_sequence, ts_event_sequence, hct, beat_results, pitch_results): + """ + Constructor. + :param line: Line + :param tempo_event_sequence: TempoEventSequence + :param ts_event_sequence: EventSequence fo TimeSignatureEvents + :param hct: HarmonicContextTrack + :param beat_results: List of PositionDeltaInfo's + :param pitch_results: List of PMap's + """ + self.__line = line + self.__tempo_event_sequence = tempo_event_sequence + self.__ts_event_sequence = ts_event_sequence + self.__hct = hct + + self.__beat_results = beat_results + self.__pitch_results = pitch_results + + @property + def line(self): + return self.__line + + @property + def tempo_event_sequence(self): + return self.__tempo_event_sequence + + @property + def ts_event_sequence(self): + return self.__ts_event_sequence + + @property + def beat_results(self): + return self.__beat_results + + @property + def pitch_results(self): + return self.__pitch_results + + def apply(self, beat_result=None, pitch_result=None, line_copy=True): + """ + Produce a line based on a PositionDeltaInfo and a PMap, and specify if applied to original line or copy. + :param beat_result: PositionDeltaInfo + :param pitch_result: PMap + :param line_copy: True means to copy original line and administer the constraint solutions chosen + :return: Line + """ + if beat_result is not None and beat_result not in self.beat_results: + raise Exception('Given beat result not a member of beat results.') + if pitch_result is not None and pitch_result not in self.pitch_results: + raise Exception('Given pitch result not a member of pitch results.') + + beat_line = beat_result.apply(line_copy) if beat_result is not None else None + pitch_line = pitch_result.apply(self.line, line_copy) if pitch_result is not None else None + + if beat_line is None: + return pitch_line + if pitch_line is None: + return beat_line + + if beat_line != pitch_line: + note_map = {a: b for a, b in zip(pitch_line.get_all_notes(), beat_line.get_all_notes())} \ + if pitch_line != self.line else None + + for pitch_note in pitch_line.get_all_notes(): + beat_note = note_map[pitch_note] + beat_note.diatonic_pitch = pitch_note.diatonic_pitch + + return beat_line diff --git a/pool/shard002/Python/0026722_file_selection.py b/pool/shard002/Python/0026722_file_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..5a408da0dd2136b98dd20bcfb98e1a1a693cc248 --- /dev/null +++ b/pool/shard002/Python/0026722_file_selection.py @@ -0,0 +1,143 @@ +import os +from PyQt4 import QtCore, QtGui +import common + +class FileList(QtGui.QListWidget): + files_dropped = QtCore.pyqtSignal() + + def __init__(self, parent=None): + super(FileList, self).__init__(parent) + self.setAcceptDrops(True) + self.setIconSize(QtCore.QSize(32, 32)) + + # drag and drop label + self.drop_label = QtGui.QLabel(QtCore.QString('Drag and drop\nfiles here'), parent=self) + self.drop_label.setAlignment(QtCore.Qt.AlignCenter) + self.drop_label.setStyleSheet('background: url({0}/drop_files.png) no-repeat center center; color: #999999;'.format(common.supercipher_gui_dir)) + self.drop_label.hide() + + self.filenames = [] + self.update() + + def update(self): + # file list should have a background image if empty + if len(self.filenames) == 0: + self.drop_label.show() + else: + self.drop_label.hide() + + def resizeEvent(self, event): + self.drop_label.setGeometry(0, 0, self.width(), self.height()) + + def dragEnterEvent(self, event): + if event.mimeData().hasUrls: + event.accept() + else: + event.ignore() + + def dragMoveEvent(self, event): + if event.mimeData().hasUrls: + event.setDropAction(QtCore.Qt.CopyAction) + event.accept() + else: + event.ignore() + + def dropEvent(self, event): + if event.mimeData().hasUrls: + event.setDropAction(QtCore.Qt.CopyAction) + event.accept() + for url in event.mimeData().urls(): + filename = str(url.toLocalFile()) + self.add_file(filename) + else: + event.ignore() + self.files_dropped.emit() + + def add_file(self, filename): + if filename not in self.filenames: + self.filenames.append(filename) + + basename = os.path.basename(filename) + fileinfo = QtCore.QFileInfo(filename) + ip = QtGui.QFileIconProvider() + icon = ip.icon(fileinfo) + + if os.path.isfile(filename): + size = self.human_readable_filesize(fileinfo.size()) + item = QtGui.QListWidgetItem('{0} ({1})'.format(basename, size)) + item.setToolTip(QtCore.QString(size)) + else: + item = QtGui.QListWidgetItem(basename) + + item.setIcon(icon) + self.addItem(item) + + def human_readable_filesize(self, b): + thresh = 1024.0 + if b < thresh: + return '{0} B'.format(b) + units = ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'] + u = 0 + b /= thresh + while b >= thresh: + b /= thresh + u += 1 + return '{0} {1}'.format(round(b, 1), units[u]) + +class FileSelection(QtGui.QVBoxLayout): + def __init__(self): + super(FileSelection, self).__init__() + + # file list + self.file_list = FileList() + self.file_list.currentItemChanged.connect(self.update) + self.file_list.files_dropped.connect(self.update) + + # buttons + self.add_files_button = QtGui.QPushButton('Add Files') + self.add_files_button.clicked.connect(self.add_files) + self.add_dir_button = QtGui.QPushButton('Add Folder') + self.add_dir_button.clicked.connect(self.add_dir) + self.delete_button = QtGui.QPushButton('Delete') + self.delete_button.clicked.connect(self.delete_file) + button_layout = QtGui.QHBoxLayout() + button_layout.addWidget(self.add_files_button) + button_layout.addWidget(self.add_dir_button) + button_layout.addWidget(self.delete_button) + + # add the widgets + self.addWidget(self.file_list) + self.addLayout(button_layout) + + self.update() + + def update(self): + # delete button should be disabled if item isn't selected + current_item = self.file_list.currentItem() + if not current_item: + self.delete_button.setEnabled(False) + else: + self.delete_button.setEnabled(True) + + # update the file list + self.file_list.update() + + def add_files(self): + filenames = QtGui.QFileDialog.getOpenFileNames(caption='Choose files', options=QtGui.QFileDialog.ReadOnly) + if filenames: + for filename in filenames: + self.file_list.add_file(str(filename)) + self.update() + + def add_dir(self): + filename = QtGui.QFileDialog.getExistingDirectory(caption='Choose folder', options=QtGui.QFileDialog.ReadOnly) + if filename: + self.file_list.add_file(str(filename)) + self.update() + + def delete_file(self): + current_row = self.file_list.currentRow() + self.file_list.filenames.pop(current_row) + self.file_list.takeItem(current_row) + self.update() + diff --git a/pool/shard002/Python/0026730_test_sysconfig.py b/pool/shard002/Python/0026730_test_sysconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe26bf65d6427b08ba3fd248a68f4cf29c9bd05 --- /dev/null +++ b/pool/shard002/Python/0026730_test_sysconfig.py @@ -0,0 +1,117 @@ +"""Tests for distutils.sysconfig.""" +import os +import shutil +import test +import unittest + +from distutils import sysconfig +from distutils.ccompiler import get_default_compiler +from distutils.tests import support +from test.support import TESTFN, run_unittest + +class SysconfigTestCase(support.EnvironGuard, + unittest.TestCase): + def setUp(self): + super(SysconfigTestCase, self).setUp() + self.makefile = None + + def tearDown(self): + if self.makefile is not None: + os.unlink(self.makefile) + self.cleanup_testfn() + super(SysconfigTestCase, self).tearDown() + + def cleanup_testfn(self): + if os.path.isfile(TESTFN): + os.remove(TESTFN) + elif os.path.isdir(TESTFN): + shutil.rmtree(TESTFN) + + def test_get_config_h_filename(self): + config_h = sysconfig.get_config_h_filename() + self.assertTrue(os.path.isfile(config_h), config_h) + + def test_get_python_lib(self): + lib_dir = sysconfig.get_python_lib() + # XXX doesn't work on Linux when Python was never installed before + #self.assertTrue(os.path.isdir(lib_dir), lib_dir) + # test for pythonxx.lib? + self.assertNotEqual(sysconfig.get_python_lib(), + sysconfig.get_python_lib(prefix=TESTFN)) + + def test_get_python_inc(self): + inc_dir = sysconfig.get_python_inc() + # This is not much of a test. We make sure Python.h exists + # in the directory returned by get_python_inc() but we don't know + # it is the correct file. + self.assertTrue(os.path.isdir(inc_dir), inc_dir) + python_h = os.path.join(inc_dir, "Python.h") + self.assertTrue(os.path.isfile(python_h), python_h) + + def test_get_config_vars(self): + cvars = sysconfig.get_config_vars() + self.assertTrue(isinstance(cvars, dict)) + self.assertTrue(cvars) + + def test_customize_compiler(self): + + # not testing if default compiler is not unix + if get_default_compiler() != 'unix': + return + + os.environ['AR'] = 'my_ar' + os.environ['ARFLAGS'] = '-arflags' + + # make sure AR gets caught + class compiler: + compiler_type = 'unix' + + def set_executables(self, **kw): + self.exes = kw + + comp = compiler() + sysconfig.customize_compiler(comp) + self.assertEqual(comp.exes['archiver'], 'my_ar -arflags') + + def test_parse_makefile_base(self): + self.makefile = TESTFN + fd = open(self.makefile, 'w') + try: + fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=LIB'" '\n') + fd.write('VAR=$OTHER\nOTHER=foo') + finally: + fd.close() + d = sysconfig.parse_makefile(self.makefile) + self.assertEqual(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", + 'OTHER': 'foo'}) + + def test_parse_makefile_literal_dollar(self): + self.makefile = TESTFN + fd = open(self.makefile, 'w') + try: + fd.write(r"CONFIG_ARGS= '--arg1=optarg1' 'ENV=\$$LIB'" '\n') + fd.write('VAR=$OTHER\nOTHER=foo') + finally: + fd.close() + d = sysconfig.parse_makefile(self.makefile) + self.assertEqual(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", + 'OTHER': 'foo'}) + + + def test_sysconfig_module(self): + import sysconfig as global_sysconfig + self.assertEqual(global_sysconfig.get_config_var('CFLAGS'), sysconfig.get_config_var('CFLAGS')) + self.assertEqual(global_sysconfig.get_config_var('LDFLAGS'), sysconfig.get_config_var('LDFLAGS')) + self.assertEqual(global_sysconfig.get_config_var('LDSHARED'),sysconfig.get_config_var('LDSHARED')) + self.assertEqual(global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC')) + + + +def test_suite(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(SysconfigTestCase)) + return suite + + +if __name__ == '__main__': + run_unittest(test_suite()) diff --git a/pool/shard002/Python/0026736_logbook.py b/pool/shard002/Python/0026736_logbook.py new file mode 100644 index 0000000000000000000000000000000000000000..6508318a9077481e36e94e6edea2f7aa7af39124 --- /dev/null +++ b/pool/shard002/Python/0026736_logbook.py @@ -0,0 +1,262 @@ +""" +Event parser and human readable log generator. + +For more details about this component, please refer to the documentation at +https://home-assistant.io/components/logbook/ +""" +import logging +from datetime import timedelta +from itertools import groupby + +import voluptuous as vol + +import homeassistant.helpers.config_validation as cv +import homeassistant.util.dt as dt_util +from homeassistant.components import recorder, sun +from homeassistant.components.frontend import register_built_in_panel +from homeassistant.components.http import HomeAssistantView +from homeassistant.const import (EVENT_HOMEASSISTANT_START, + EVENT_HOMEASSISTANT_STOP, EVENT_STATE_CHANGED, + STATE_NOT_HOME, STATE_OFF, STATE_ON) +from homeassistant.core import DOMAIN as HA_DOMAIN +from homeassistant.core import State +from homeassistant.helpers import template +from homeassistant.helpers.entity import split_entity_id + +DOMAIN = "logbook" +DEPENDENCIES = ['recorder', 'frontend'] + +_LOGGER = logging.getLogger(__name__) + +EVENT_LOGBOOK_ENTRY = 'logbook_entry' + +GROUP_BY_MINUTES = 15 + +ATTR_NAME = 'name' +ATTR_MESSAGE = 'message' +ATTR_DOMAIN = 'domain' +ATTR_ENTITY_ID = 'entity_id' + +LOG_MESSAGE_SCHEMA = vol.Schema({ + vol.Required(ATTR_NAME): cv.string, + vol.Required(ATTR_MESSAGE): cv.string, + vol.Optional(ATTR_DOMAIN): cv.slug, + vol.Optional(ATTR_ENTITY_ID): cv.entity_id, +}) + + +def log_entry(hass, name, message, domain=None, entity_id=None): + """Add an entry to the logbook.""" + data = { + ATTR_NAME: name, + ATTR_MESSAGE: message + } + + if domain is not None: + data[ATTR_DOMAIN] = domain + if entity_id is not None: + data[ATTR_ENTITY_ID] = entity_id + hass.bus.fire(EVENT_LOGBOOK_ENTRY, data) + + +def setup(hass, config): + """Listen for download events to download files.""" + def log_message(service): + """Handle sending notification message service calls.""" + message = service.data[ATTR_MESSAGE] + name = service.data[ATTR_NAME] + domain = service.data.get(ATTR_DOMAIN) + entity_id = service.data.get(ATTR_ENTITY_ID) + + message = template.render(hass, message) + log_entry(hass, name, message, domain, entity_id) + + hass.wsgi.register_view(LogbookView) + + register_built_in_panel(hass, 'logbook', 'Logbook', + 'mdi:format-list-bulleted-type') + + hass.services.register(DOMAIN, 'log', log_message, + schema=LOG_MESSAGE_SCHEMA) + return True + + +class LogbookView(HomeAssistantView): + """Handle logbook view requests.""" + + url = '/api/logbook' + name = 'api:logbook' + extra_urls = ['/api/logbook/'] + + def get(self, request, datetime=None): + """Retrieve logbook entries.""" + start_day = dt_util.as_utc(datetime or dt_util.start_of_local_day()) + end_day = start_day + timedelta(days=1) + + events = recorder.get_model('Events') + query = recorder.query('Events').filter( + (events.time_fired > start_day) & + (events.time_fired < end_day)) + events = recorder.execute(query) + + return self.json(humanify(events)) + + +class Entry(object): + """A human readable version of the log.""" + + # pylint: disable=too-many-arguments, too-few-public-methods + def __init__(self, when=None, name=None, message=None, domain=None, + entity_id=None): + """Initialize the entry.""" + self.when = when + self.name = name + self.message = message + self.domain = domain + self.entity_id = entity_id + + def as_dict(self): + """Convert entry to a dict to be used within JSON.""" + return { + 'when': self.when, + 'name': self.name, + 'message': self.message, + 'domain': self.domain, + 'entity_id': self.entity_id, + } + + +def humanify(events): + """Generator that converts a list of events into Entry objects. + + Will try to group events if possible: + - if 2+ sensor updates in GROUP_BY_MINUTES, show last + - if home assistant stop and start happen in same minute call it restarted + """ + # pylint: disable=too-many-branches + # Group events in batches of GROUP_BY_MINUTES + for _, g_events in groupby( + events, + lambda event: event.time_fired.minute // GROUP_BY_MINUTES): + + events_batch = list(g_events) + + # Keep track of last sensor states + last_sensor_event = {} + + # Group HA start/stop events + # Maps minute of event to 1: stop, 2: stop + start + start_stop_events = {} + + # Process events + for event in events_batch: + if event.event_type == EVENT_STATE_CHANGED: + entity_id = event.data.get('entity_id') + + if entity_id is None: + continue + + if entity_id.startswith('sensor.'): + last_sensor_event[entity_id] = event + + elif event.event_type == EVENT_HOMEASSISTANT_STOP: + if event.time_fired.minute in start_stop_events: + continue + + start_stop_events[event.time_fired.minute] = 1 + + elif event.event_type == EVENT_HOMEASSISTANT_START: + if event.time_fired.minute not in start_stop_events: + continue + + start_stop_events[event.time_fired.minute] = 2 + + # Yield entries + for event in events_batch: + if event.event_type == EVENT_STATE_CHANGED: + + # Do not report on new entities + if 'old_state' not in event.data: + continue + + to_state = State.from_dict(event.data.get('new_state')) + + # If last_changed != last_updated only attributes have changed + # we do not report on that yet. Also filter auto groups. + if not to_state or \ + to_state.last_changed != to_state.last_updated or \ + to_state.domain == 'group' and \ + to_state.attributes.get('auto', False): + continue + + domain = to_state.domain + + # Skip all but the last sensor state + if domain == 'sensor' and \ + event != last_sensor_event[to_state.entity_id]: + continue + + yield Entry( + event.time_fired, + name=to_state.name, + message=_entry_message_from_state(domain, to_state), + domain=domain, + entity_id=to_state.entity_id) + + elif event.event_type == EVENT_HOMEASSISTANT_START: + if start_stop_events.get(event.time_fired.minute) == 2: + continue + + yield Entry( + event.time_fired, "Home Assistant", "started", + domain=HA_DOMAIN) + + elif event.event_type == EVENT_HOMEASSISTANT_STOP: + if start_stop_events.get(event.time_fired.minute) == 2: + action = "restarted" + else: + action = "stopped" + + yield Entry( + event.time_fired, "Home Assistant", action, + domain=HA_DOMAIN) + + elif event.event_type.lower() == EVENT_LOGBOOK_ENTRY: + domain = event.data.get(ATTR_DOMAIN) + entity_id = event.data.get(ATTR_ENTITY_ID) + if domain is None and entity_id is not None: + try: + domain = split_entity_id(str(entity_id))[0] + except IndexError: + pass + + yield Entry( + event.time_fired, event.data.get(ATTR_NAME), + event.data.get(ATTR_MESSAGE), domain, + entity_id) + + +def _entry_message_from_state(domain, state): + """Convert a state to a message for the logbook.""" + # We pass domain in so we don't have to split entity_id again + # pylint: disable=too-many-return-statements + if domain == 'device_tracker': + if state.state == STATE_NOT_HOME: + return 'is away' + else: + return 'is at {}'.format(state.state) + + elif domain == 'sun': + if state.state == sun.STATE_ABOVE_HORIZON: + return 'has risen' + else: + return 'has set' + + elif state.state == STATE_ON: + # Future: combine groups and its entity entries ? + return "turned on" + + elif state.state == STATE_OFF: + return "turned off" + + return "changed to {}".format(state.state) diff --git a/pool/shard002/Python/0026739_models.py b/pool/shard002/Python/0026739_models.py new file mode 100644 index 0000000000000000000000000000000000000000..b44f7b8759f5a9a23c1905d3845332f3d0e1c2d7 --- /dev/null +++ b/pool/shard002/Python/0026739_models.py @@ -0,0 +1,66 @@ +# encoding: utf-8 +from django.db import models + + +from django.contrib.auth.models import User + +from courses.models import Course +from groups.models import Group + +import random +import string + +from django.db import IntegrityError + + +class Invite(models.Model): + generated_by = models.ForeignKey(User, db_index=False, null=False, blank=False, related_name='invite_generated_by') + group = models.ForeignKey(Group, db_index=False, null=True, blank=True) + invited_users = models.ManyToManyField(User, blank=True) + + key = models.CharField(max_length=10, db_index=True, null=False, blank=False, unique=True) + + added_time = models.DateTimeField(auto_now_add=True) # remove default=timezone.now + update_time = models.DateTimeField(auto_now=True) # remove default=timezone.now + + def __unicode__(self): + return u"{0}".format(self.key) + + @staticmethod + def user_can_generate_invite(generative_user): + if generative_user.is_anonymous(): + return False + + if generative_user.is_superuser: + return True + + if Course.objects.filter(teachers=generative_user).count(): + return True + + return False + + @staticmethod + def generate_invite(generated_by, group, size=7): + invite = Invite() + invite.generated_by = generated_by + invite.group = group + key = Invite._id_generator(size) + for _ in xrange(1000): + try: + if Invite.objects.filter(key=key).count(): + key = Invite._id_generator(size) + else: + invite.key = key + invite.save() + return invite + except IntegrityError: + return Invite.generate_invite(generated_by, group, size) + + @staticmethod + def generate_invites(count, generated_by, group, size=7): + for _ in xrange(count): + yield Invite.generate_invite(generated_by, group, size) + + @staticmethod + def _id_generator(size=7, chars=string.ascii_letters + string.digits): + return ''.join(random.choice(chars) for x in range(size)) diff --git a/pool/shard002/Python/0026744_views.py b/pool/shard002/Python/0026744_views.py new file mode 100644 index 0000000000000000000000000000000000000000..c60c6ff061c962d1f1cd854b1be4dfae9d2c3133 --- /dev/null +++ b/pool/shard002/Python/0026744_views.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- + +from django.shortcuts import render +from blog.models import BlogPost +from django.template import loader, Context +from django.http import HttpResponse +from ExpPH.utils.BaseUtils import isLocalEnvironment +import ExpPH.conf.Consts as ECC + +''' 博客主页 ''' +def bolgPage(request): + blogs = BlogPost.objects # 从数据库提取所有blog记录 + posts = blogs.all() + + # 提取需要显示的页面模板 + template = loader.get_template("BlogPage.html") + + # 把从数据库提取页面请求的记录,响应到页面显示 + title = "Welcome to Exp's Blog (Version:1.0.187.20140518 Beta)" + + # 首页地址 + homeURL = (isLocalEnvironment() and ECC.LOCAL_ROOT_URL or ECC.SAE_ROOT_URL) + + content = Context({'posts': posts, 'title': title, 'homeURL': homeURL}) + return HttpResponse(template.render(content)) + diff --git a/pool/shard002/Python/0026745_urls.py b/pool/shard002/Python/0026745_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..319d053c04a7e8d31cf326e4690711b71f4acaba --- /dev/null +++ b/pool/shard002/Python/0026745_urls.py @@ -0,0 +1,25 @@ +"""mymoviedb URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.8/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') +Including another URLconf + 1. Add an import: from blog import urls as blog_urls + 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) +""" +from django.conf.urls import include, url +from django.contrib import admin +from django.conf import settings +from django.conf.urls.static import static + +urlpatterns = [ + url(r'^admin/', include(admin.site.urls)), + url(r'^$', 'mymoviedb.views.index'), +] +#+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) diff --git a/pool/shard002/Python/0026747_write_labels.py b/pool/shard002/Python/0026747_write_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..04c110005fcec09849cbe3eaec0f27486a462b43 --- /dev/null +++ b/pool/shard002/Python/0026747_write_labels.py @@ -0,0 +1,56 @@ +""" +find GDS labels and write labels into a CSV file +""" + +import pathlib +import csv +import klayout.db as pya + +from pp import LAYER + + +def find_labels(gdspath, label_layer=LAYER.LABEL, prefix="opt_"): + """ finds labels and locations from a GDS file """ + # Load the layout + gdspath = str(gdspath) + layout = pya.Layout() + layout.read(gdspath) + + # Get the top cell and the units, and find out the index of the layer + topcell = layout.top_cell() + dbu = layout.dbu + layer = pya.LayerInfo(label_layer[0], label_layer[1]) + layer_index = layout.layer(layer) + + # Extract locations + iterator = topcell.begin_shapes_rec(layer_index) + + while not (iterator.at_end()): + shape, trans = iterator.shape(), iterator.trans() + iterator.next() + if shape.is_text(): + text = shape.text + if text.string.startswith(prefix): + transformed = text.transformed(trans) + yield text.string, transformed.x * dbu, transformed.y * dbu + + +def write_labels(gdspath, label_layer=LAYER.LABEL, csv_filename=None, prefix="opt_"): + """Load GDS mask and extracts the labels and coordinates from a GDS file""" + labels = list(find_labels(gdspath, label_layer=label_layer, prefix=prefix)) + + # Save the coordinates somewhere sensible + if csv_filename is None: + gdspath = pathlib.Path(gdspath) + csv_filename = gdspath.with_suffix(".csv") + with open(csv_filename, "w", newline="") as f: + writer = csv.writer(f) + writer.writerows(labels) + print(f"Wrote {csv_filename}") + + +if __name__ == "__main__": + from pp.config import CONFIG + + gdspath = CONFIG["samples_path"] / "mask" / "build" / "mask" / "sample.gds" + write_labels(gdspath) diff --git a/pool/shard002/Python/0026761_checkPingTime.py b/pool/shard002/Python/0026761_checkPingTime.py new file mode 100644 index 0000000000000000000000000000000000000000..53928c43914b54d98509ea4af14882ae805c096d --- /dev/null +++ b/pool/shard002/Python/0026761_checkPingTime.py @@ -0,0 +1,33 @@ +#!/usr/bin/python +''' + Check pingTime daemon + Nacho Mas January 2016 +''' + +import socket +import time +import datetime + + +HOST = 'cronostamper' # Symbolic name meaning all available interfaces +PORT = 5555 # Arbitrary non-privileged port + + + +i=0 +#now keep talking with the server +while True: + i=i+1 + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server_address = (HOST, PORT) + d=str(datetime.datetime.utcnow()) + sock.connect(server_address) + msg=sock.recv(1024) + dd=d.split()[1].split(":") + dmsg=msg.split()[1].split(":") + sd=float(dd[2])+float(dd[1])*60 + smsg=float(dmsg[2])+float(dmsg[1])*60 + print sd,smsg + sock.close() + time.sleep(0.01) + diff --git a/pool/shard002/Python/0026764_ticket.py b/pool/shard002/Python/0026764_ticket.py new file mode 100644 index 0000000000000000000000000000000000000000..5a7a5cde18b1ea07fcfa442e37ce10db9ba58423 --- /dev/null +++ b/pool/shard002/Python/0026764_ticket.py @@ -0,0 +1,58 @@ +import os +import sys + +from docutils import nodes +from docutils.parsers.rst import Directive + +""" +Example of a Sphinx Directive. +This is useful for for working with large blocks of text. Leaving here as a reference. +Roles are more useful for inline text, which is what we need for tickets. + +class Ticket(Directive): + required_arguments = 1 + def run(self): + ticket_url = "link text" + paragraph_node = nodes.paragraph(text=ticket_url) + return [paragraph_node] + +def setup(app): + app.add_directive("ticket", Ticket) + +""" + +# Custom role reference: https://doughellmann.com/blog/2010/05/09/defining-custom-roles-in-sphinx/ + +def make_link_node(rawtext, app, type, slug, options): + """Create a link to an HTCondor ticket. + + :param rawtext: Text being replaced with link node. + :param app: Sphinx application context + :param type: Link type (issue, changeset, etc.) + :param slug: ID of the ticket to link to + :param options: Options dictionary passed to role func. + """ + base = "https://htcondor-wiki.cs.wisc.edu/index.cgi/tktview?tn=" + ref = base + slug + # set_classes(options) + node = nodes.reference(rawtext, "(Ticket #" + slug + ")", refuri=ref, **options) + return node + +def ticket_role(name, rawtext, text, lineno, inliner, options={}, content=[]): + try: + ticket_id = int(text) + if ticket_id <= 1000: + raise ValueError + except ValueError: + msg = inliner.reporter.error( + 'HTCondor ticket number must be a number greater than or equal to 1000; ' + '"%s" is invalid.' % text, line=lineno) + prb = inliner.problematic(rawtext, rawtext, msg) + return [prb], [msg] + app = inliner.document.settings.env.app + node = make_link_node(rawtext, app, 'issue', str(ticket_id), options) + return [node], [] + +def setup(app): + app.add_role("ticket", ticket_role) + diff --git a/pool/shard002/Python/0026768_Rover.py b/pool/shard002/Python/0026768_Rover.py new file mode 100644 index 0000000000000000000000000000000000000000..9a11fe6feb8262a3af09c273542d04b22f8fcf8d --- /dev/null +++ b/pool/shard002/Python/0026768_Rover.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python + +import sys +import time +from PySide.QtCore import * +from PySide.QtGui import * +from PySide.QtDeclarative import * +from Controller import Controller +from ControllerThread import ControllerThread + +class Rover(QDeclarativeView): + + def __init__(self, parent=None): + ''' + Initialize the attributes class. + ''' + super(Rover, self).__init__(parent) + self.setWindowTitle("Robotic Control Interface") + self.set_default_values() + self.setSource(QUrl.fromLocalFile("Rover.qml")) + self.setResizeMode(QDeclarativeView.SizeRootObjectToView) + self.ro = self.rootObject() + + self.control = Controller() + self.control_thread = ControllerThread() + self.control_start = False + + def set_default_values(self): + ''' + Set the default values to start the GUI. + ''' + self.joystick = "" + self.bluetooth = "" + self.power = 0.0 + self.angle = 0.0 + self.rc = self.rootContext() + self.rc.setContextProperty("joystick", self.joystick) + self.rc.setContextProperty("bluetooth", self.bluetooth) + self.rc.setContextProperty("power", self.power) + self.rc.setContextProperty("angle", self.angle) + + def set_connection(self): + ''' + Display the devices selected for the communication. + ''' + joystick_list = self.control.get_joystick_list() + for element in joystick_list: + if "DragonRise" in element: + self.joystick = element + break + self.rc.setContextProperty("joystick", self.joystick) + + bluetooth_list = self.control.get_bluetooth_list() + for element in bluetooth_list: + if "CURIOSITY" in element: + self.bluetooth = element + break + self.rc.setContextProperty("bluetooth", self.bluetooth) + + def set_event_signal(self): + ''' + Define the GUI interactions with the system. + ''' + self.ro.connection.connect(self.__connect_hw) + self.ro.disconnection.connect(self.__disconnect_hw) + + def __connect_hw(self): + ''' + Connect to the CONTROL software. + ''' + if not self.control_start: + self.control_start = True + self.control.connect(self.joystick, self.bluetooth) + self.control_thread.start() + + def __disconnect_hw(self): + ''' + Disconnect from the CONTROL software. + ''' + self.control_thread.stop_communication() + time.sleep(1) + self.control.disconnect() + time.sleep(1) + sys.exit(0) + + def update(self, observer): + ''' + Method to update values in the GUI. + ''' + self.power = observer.power + self.rc.setContextProperty("power", self.power) + self.angle = observer.angle + self.rc.setContextProperty("angle", self.angle) + + +from Driving import Driving + +if __name__ == "__main__": + app = QApplication(sys.argv) + window = Rover() + updater = Driving() + updater.register_observer(window) + window.set_connection() + window.set_event_signal() + window.show() + sys.exit(app.exec_()) \ No newline at end of file diff --git a/pool/shard002/Python/0026772_loginbackends.py b/pool/shard002/Python/0026772_loginbackends.py new file mode 100644 index 0000000000000000000000000000000000000000..31f7f314a2e32b52553338027ada568a6ff6d542 --- /dev/null +++ b/pool/shard002/Python/0026772_loginbackends.py @@ -0,0 +1,165 @@ +import anydbm +from sqlalchemy import select, update, insert +from model import users +from hashlib import sha256 +from kana.util.timestamp import generate_datetimestamp + + +class Backend(object): + + def check_credentials(self, user, password): + raise NotImplementedError + + def add_credentials(self, user, password, username): + raise NotImplementedError + + def update_credentials(self, user, password, username): + raise NotImplementedError + +class SQLBackend(Backend): + + def set_engine(self, engine): + self.engine = engine + + def _hash(self, user, password, timestamp): + salt = timestamp + user + m = sha256() + m.update(salt + password) + for i in range(0, 4096): + hres = m.hexdigest() + m.update(hres) + + return m.hexdigest() + + def get_users(self): + qry = select([users]) + with self.engine.begin() as connection: + data = connection.execute(qry) + + if data is not None: + res = data.fetchall() + data.close() + return res + + def get_user_by_name(self, user): + qry = select([users]).where(users.c.user == user) + + res = None + + with self.engine.begin() as connection: + data = connection.execute(qry) + + if data is not None: + res = data.fetchone() + data.close() + return res + + def add_credentials(self, user, password, username): + """Add a user's information, including password, &c.. + + Args: + user (str): the user's username. + password (str): the user's + username (str): the user's display name (e.g. Stefan Edwards). + + Return: + bool. True means success, False unsucess. + + """ + try: + timestamp = generate_datetimestamp() + hpass = self._hash(user, password, timestamp) + ins = insert(users).values(user=user, + salt=timestamp, + password=hpass, + name=username) + self.engine.execute(ins) + return True + except: + return False + + def update_credentials(self, user, password, username): + """Update a user's information, including password, &c.. + + Args: + user (str): the user's username. + password (str): the user's + username (str): the user's display name (e.g. Stefan Edwards). + + Return: + bool. True means success, False unsucess. + + """ + + try: + timestamp = generate_datetimestamp() + hpass = self._hash(user, password, timestamp) + + upd = update(users).where(users.c.user == user).values( + salt=timestamp, + password=hpass, + name=username) + self.engine.execute(upd) + return True + except: + return False + + def check_credentials(self, user, password): + """A simple function to check a user's credentials against the database. + + Args: + user (str): the user's username. + password (str): the user's (unencrypted, unhashed) password. + + Returns: + int. The return code:: + + >= 0 -- Success, integer is the user's UID + -1 -- user not found or password does not match + + Checks the user's credentials against those stored in the database; + since this uses iterated & salted SHA256 to store the user's pass, + we have to retrieve the user's salt (generally a time-stamp string), + append the user's username, and then iterate through the hashing + process.""" + + conn = self.engine.connect() + query = select([users]).where(users.c.user == user) + res = conn.execute(query) + data = res.fetchone() + conn.close() + + if data: + timestamp = data['salt'] + hpass = self._hash(user, password, timestamp) + + if hpass.lower() == data['password']: + return data['id'] + else: + return -1 + else: + return -1 + + +class DummyBackend(Backend): + + def check_credentials(self, user, password): + return True + + +class FileBackend(Backend): + + def __init__(self, database="./data/users.db"): + self.database = anydbm.open(database) + + def check_credentials(self, user, password): + print ("FileBackend") + if self.database[user] == password: + return True + return False + + def __del__(self): + self.database.close() + + def __exit__(self): + self.databse.close() diff --git a/pool/shard002/Python/0026775_test_0093_iterative_post_validate.py b/pool/shard002/Python/0026775_test_0093_iterative_post_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..a9109666467f39b24410a650181b8d82e24757b2 --- /dev/null +++ b/pool/shard002/Python/0026775_test_0093_iterative_post_validate.py @@ -0,0 +1,69 @@ +import unittest + + +class Solution: + def restoreIpAddresses(self, s): + """ + :type s: str + :rtype: List[str] + """ + result = [] + slen = len(s) + # [0,p1) [p1,p2) [p2,p3) [p3,slen) + for p1 in range(1, 4): + for p2 in range(p1 + 1, p1 + 4): + for p3 in range(p2 + 1, p2 + 4): + l4 = slen - p3 + if l4 < 1 or l4 > 3: + continue + if p1 > 1 and s[0] == '0': + continue + l2 = p2 - p1 + if l2 > 1 and s[p1] == '0': + continue + l3 = p3 - p2 + if l3 > 1 and s[p2] == '0': + continue + if l4 > 1 and s[p3] == '0': + continue + s1 = s[0:p1] + b1 = int(s1) + if b1 > 255: + continue + s2 = s[p1:p2] + b2 = int(s2) + if b2 > 255: + continue + s3 = s[p2:p3] + b3 = int(s3) + if b3 > 255: + continue + s4 = s[p3:slen] + b4 = int(s4) + if b4 > 255: + continue + result.append(s1 + '.' + s2 + '.' + s3 + '.' + s4) + return result + + +class Test(unittest.TestCase): + def test(self): + self._test('25525511135', [ + '255.255.11.135', + '255.255.111.35', + ]) + + self._test('10999', [ + '10.9.9.9', + '1.0.99.9', + '1.0.9.99', + # Should not contain 1.9.9.9 + ]) + + def _test(self, s, expected): + actual = Solution().restoreIpAddresses(s) + self.assertCountEqual(expected, actual) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard002/Python/0026777_94-BinaryTreeInorderTraversal.py b/pool/shard002/Python/0026777_94-BinaryTreeInorderTraversal.py new file mode 100644 index 0000000000000000000000000000000000000000..63ff168ced735d3a6e72cfd68b05bcc32477fa69 --- /dev/null +++ b/pool/shard002/Python/0026777_94-BinaryTreeInorderTraversal.py @@ -0,0 +1,34 @@ +# 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 inorderTraversal(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ + + if root == None: + return [] + + stack = [] + p = root + out = [] + + while len(stack) > 0 or p != None: + # if p is not None, go to the left end + while p != None: + stack.append(p) + p = p.left + # set p to the frist element in stack, + # print, then go to the right child + if stack: + p = stack.pop() + out.append(p.val) + p = p.right + + return out diff --git a/pool/shard002/Python/0026778_teatime.py b/pool/shard002/Python/0026778_teatime.py new file mode 100644 index 0000000000000000000000000000000000000000..af9fee605619a27b8d87a6bb48842508e4fc6894 --- /dev/null +++ b/pool/shard002/Python/0026778_teatime.py @@ -0,0 +1,37 @@ +import sys +from PyQt4 import QtGui +from PyQt4 import QtCore + +from yapsy.IPlugin import IPlugin + +class TeaTime(IPlugin): + def __init__(self): + self.timer = QtTeaTime(None) + def name(self): + return "Tea Time" + def addAction(self,menu): + self.timer.setParent(menu) + self.timer.addAction(menu,self.name()) + + +class QtTeaTime(QtCore.QObject): + def __init__(self, parent=None): + QtCore.QObject.__init__(self, parent) + + def addAction(self,menu,name): + self.action = menu.addAction( name ) + self.action.triggered.connect( self.run ) + + def run(self): + value, ret = QtGui.QInputDialog.getInt( None, "Tea Time", "Time (min):", 4, 0, 60, 1 ) + + if ret : + self.action.setText( "Brewing Tea ..." ) + self.action.setEnabled(False) + print("Plugin TeaTimer: waiting for ", value * 60 * 1000 ) + QtCore.QTimer.singleShot( value * 60 * 1000, self.done ) + + def done(self): + self.action.setText( "Tea Time" ) + self.action.setEnabled(True) + QtGui.QMessageBox.information( None, 'Tea Time', 'mmmmmmmhh', QtGui.QMessageBox.Ok ) diff --git a/pool/shard002/Python/0026780_Controller.py b/pool/shard002/Python/0026780_Controller.py new file mode 100644 index 0000000000000000000000000000000000000000..aed4ca8ff7c5c4b7f8b54a1be9b51f34e8c70a20 --- /dev/null +++ b/pool/shard002/Python/0026780_Controller.py @@ -0,0 +1,118 @@ +""" +Module containing functions for every activity availiable in the CFA635 API +""" +from cfa635.API import API +import time + +class Controller: + """ + Class driving the LCD with easy to call functions + """ + + dev = None + backlight_set = 0 + backlight_current = 0 + led_callback = None + + KEY_UP = 0x01 + KEY_OK = 0x02 + KEY_STOP = 0x04 + KEY_LEFT = 0x08 + KEY_RIGHT = 0x10 + KEY_DOWN = 0x20 + + CURSOR_NO = 0x00 + CURSOR_BLINK_BLOCK = 0x01 + CURSOR_UNDER = 0x02 + CURSOR_BLINK_UNDER = 0x03 + CURSOR_INV_BLINK_UNDER = 0x04 + + def __init__ (self, dev): + self.dev = dev + self.api = API(dev) + return None + + def flush_key_input(self): + """ Take input from keypad and ignore + """ + if self.led_callback != None: + self.led_callback.update() + self.api.read_keypad() + + def wait_for_input(self, timeout): + """ Loops checking for input, + Takes timeout + returns True/False Did we get input. + """ + while True: + if self.led_callback != None: + self.led_callback.update() + time.sleep(0.05) + else: + time.sleep(0.1) + (now, _press, _release) = self.api.read_keypad() + if ord(now) != 0: + return True + timeout -= 1 + if timeout < 1: + return False + + def get_input(self, timeout): + """ Timeout limited input request. Returns keycode currently pressed. + """ + while True: + if self.led_callback != None: + self.led_callback.update() + time.sleep(0.05) + else: + time.sleep(0.1) + (now, _press, _release) = self.api.read_keypad() + if ord(now) != 0: + return (True, ord(now)) + timeout -= 1 + if timeout < 1: + return (False, None) + + def register_led_callback(self, callback): + """ + On setup, we need to capture a callback for the LEDs. + """ + self.led_callback = callback + + def sleep_wait_for_input(self): + """ Long slow wait for input. + To be used after screen has gone to sleep. + """ + while True: + if self.led_callback != None: + self.led_callback.update() + time.sleep(.24) + else: + time.sleep(.25) + (now, _press, _release) = self.api.read_keypad() + if ord(now) != 0: + return True + + def set_led (self, row, green, red): + """ Set a LED + """ + if red > 100 and green > 100: + raise Exception("Maximum LED value is 100") + if row > 3: + raise Exception("Row number greater than 3") + led = [[11, 12], [9, 10], [7, 8], [5, 6]] + self.api.set_gpio(led[row][0], green) + self.api.set_gpio(led[row][1], red) + + def go_to_sleep(self): + """ decrease backlight to zero + """ + self.backlight_set = self.backlight_current + while(self.backlight_current > 0): + self.api.set_backlight(self.backlight_current - 1) + + def wake_up(self): + """ return backlight to previous level + """ + while(self.backlight_current != self.backlight_set): + self.api.set_backlight(self.backlight_current + 1) diff --git a/pool/shard002/Python/0026785_init__.py b/pool/shard002/Python/0026785_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5bc6c823b4e70b600975561ddc497fe256af976 --- /dev/null +++ b/pool/shard002/Python/0026785_init__.py @@ -0,0 +1,14 @@ +from flask import Flask +app = Flask(__name__) +from app import views +from mpd import MPDClient + +c = MPDClient() +c.timeout = 10 +c.idletimeout = None +c.connect("localhost",6600) +c.random(0) +c.repeat(0) +c.consume(1) +#c.setvol(100) +c.close() diff --git a/pool/shard002/Python/0026787_telefe.py b/pool/shard002/Python/0026787_telefe.py new file mode 100644 index 0000000000000000000000000000000000000000..635a59c40f8961577f2cee9218f335aa47c2749d --- /dev/null +++ b/pool/shard002/Python/0026787_telefe.py @@ -0,0 +1,50 @@ +import logging +import re + +from streamlink.plugin import Plugin, pluginmatcher +from streamlink.plugin.api import useragents +from streamlink.stream import HLSStream, HTTPStream +from streamlink.utils.parse import parse_json + +log = logging.getLogger(__name__) + + +@pluginmatcher(re.compile( + r'https?://telefe\.com/.+' +)) +class Telefe(Plugin): + def _get_streams(self): + res = self.session.http.get(self.url, headers={'User-Agent': useragents.CHROME}) + video_search = res.text + video_search = video_search[video_search.index('{"top":{"view":"PlayerContainer","model":{'):] + video_search = video_search[: video_search.index('}]}}') + 4] + "}" + + video_url_found_hls = "" + video_url_found_http = "" + + json_video_search = parse_json(video_search) + json_video_search_sources = json_video_search["top"]["model"]["videos"][0]["sources"] + log.debug('Video ID found: {0}'.format(json_video_search["top"]["model"]["id"])) + for current_video_source in json_video_search_sources: + if "HLS" in current_video_source["type"]: + video_url_found_hls = "http://telefe.com" + current_video_source["url"] + log.debug("HLS content available") + if "HTTP" in current_video_source["type"]: + video_url_found_http = "http://telefe.com" + current_video_source["url"] + log.debug("HTTP content available") + + self.session.http.headers = { + 'Referer': self.url, + 'User-Agent': useragents.CHROME, + 'X-Requested-With': 'ShockwaveFlash/25.0.0.148' + } + + if video_url_found_hls: + hls_streams = HLSStream.parse_variant_playlist(self.session, video_url_found_hls) + yield from hls_streams.items() + + if video_url_found_http: + yield "http", HTTPStream(self.session, video_url_found_http) + + +__plugin__ = Telefe diff --git a/pool/shard002/Python/0026788_lyt.py b/pool/shard002/Python/0026788_lyt.py new file mode 100644 index 0000000000000000000000000000000000000000..2414f402d5b799aa5841316244e39a9eae686521 --- /dev/null +++ b/pool/shard002/Python/0026788_lyt.py @@ -0,0 +1,125 @@ +# This file was autogenerated from lyt.md. Please do not edit! +#!/usr/bin/python + +# Copyright (C) 2016 Adrien Lamarque + +# 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 . + +"""lyt is a literate programming tool, written in Python, that extracts fenced code blocks from Markdown documents. It is meant to be used as a preprocess tool before a conventional build. +""" +import re +import collections +import click +import sys +import os.path + +DEFAULT_EXT = "txt" +matching_extensions = { + 'python': 'py', + 'c++': 'cpp', + 'c': 'c', + 'c#': 'cs', + 'haskell': 'hs', + 'ruby': 'rb', + 'go': 'go', + 'rust': 'rs', + 'racket': 'rkt', +} + +DEFAULT_COMMENT_SYMBOL = "#" +comment_symbols = collections.defaultdict(lambda: DEFAULT_COMMENT_SYMBOL, { + 'python': '#', + 'c++': '//', + 'c': '//', + 'c#': '//', + 'haskell': '--', + 'ruby': '#', + 'go': '//', + 'rust': '//', + 'racket': ';', +}) + +e = click.echo + +code_open_re = re.compile(r'^`{3,}(?!.*`)|^~{3,}(?!.*~)', re.MULTILINE) # /^`{3,}(?!.*`)|^~{3,}(?!.*~)/ +code_close_re = re.compile(r'^(?:`{3,}|~{3,})(?= *$)', re.MULTILINE) # /^(?:`{3,}|~{3,})(?= *$)/ + +@click.command() +@click.argument("input_file", type=click.File('r')) +@click.option("--force", is_flag=True) + +def lyt(input_file, force): + """lyt extracts fenced code blocks from Markdown documents.""" + out = collections.defaultdict(str) + lines = input_file.read() + start_pos = 0 + + while True: + open_match = code_open_re.search(lines, start_pos) + if not open_match: + break + start_pos = open_match.end() + fence_char = lines[open_match.start()] + infostring_end_idx = lines.find("\n", open_match.end()) + infostring = lines[open_match.end():infostring_end_idx] + + if infostring: + lang = infostring.split()[0] + else: + lang = "unknown" + start_pos = infostring_end_idx + + found = False + while not found: + close_match = code_close_re.search(lines, start_pos) + if not close_match: + found = True + out[lang] += lines[start_pos:] + # Turns out it's valid to have a 'dangling' fenced block quote according to the CommonMark spec + # e("Mismatched fenced block quotes! Check that your Markdown is valid.") + # sys.exit(1) + + if lines[close_match.start()] == fence_char: + found = True + out[lang] += lines[start_pos+1:close_match.start()] + start_pos = close_match.end() + + lpy_ext_idx = input_file.name.rfind(".") + 1 + basename = input_file.name[:lpy_ext_idx] + + for (language, source) in out.items(): + language = language.lower() + if language in matching_extensions: + ext = matching_extensions[language] + else: + if language == "unknown": + e("WARNING! The following blocks didn't have an infostring specifying the language. They were aggregated together and will be written to a .%s file." % DEFAULT_EXT) + e(source) + ext = DEFAULT_EXT + else: + e("Couldn't find extension to use for language %s. Using the first three letters: %s" % (language, language[:3])) + ext = language[:3] + + output_filename = basename + ext + + if os.path.isfile(output_filename) and not force: + e("WARNING! The file %s already exists. To allow overwriting, re-launch lyt with the --force option." % output_filename) + else: + with open(output_filename, "w") as output_file: + output_file.write(comment_symbols[language] + " This file was autogenerated from %s. Please do not edit!\n" % input_file.name) + output_file.write(source) + e("Wrote %s." % output_filename) + +if __name__ == "__main__": + lyt() diff --git a/pool/shard002/Python/0026791_samtools.py b/pool/shard002/Python/0026791_samtools.py new file mode 100644 index 0000000000000000000000000000000000000000..ffbaa7db49c924db66a5ee0921b2f9431e59aeb5 --- /dev/null +++ b/pool/shard002/Python/0026791_samtools.py @@ -0,0 +1,112 @@ +## +# This file is an EasyBuild reciPY as per https://github.com/hpcugent/easybuild +# +# Copyright:: Copyright 2012-2016 Uni.Lu/LCSB, NTUA +# Authors:: Cedric Laczny , Fotis Georgatos , Kenneth Hoste +# License:: MIT/GPL +# $Id$ +# +# This work implements a part of the HPCBIOS project and is a component of the policy: +# http://hpcbios.readthedocs.org/en/latest/HPCBIOS_2012-94.html +## +""" +EasyBuild support for building SAMtools (SAM - Sequence Alignment/Map), implemented as an easyblock + +@author: Cedric Laczny (Uni.Lu) +@author: Fotis Georgatos (Uni.Lu) +@author: Kenneth Hoste (Ghent University) +""" +import os +import shutil +import stat +from distutils.version import LooseVersion + +from easybuild.easyblocks.generic.configuremake import ConfigureMake +from easybuild.tools.build_log import EasyBuildError +from easybuild.tools.filetools import adjust_permissions + +class EB_SAMtools(ConfigureMake): + """ + Support for building SAMtools; SAM (Sequence Alignment/Map) format + is a generic format for storing large nucleotide sequence alignments. + """ + + def __init__(self, *args, **kwargs): + """Define lists of files to install.""" + super(EB_SAMtools, self).__init__(*args, **kwargs) + + self.bin_files = ["misc/blast2sam.pl", + "misc/bowtie2sam.pl", "misc/export2sam.pl", "misc/interpolate_sam.pl", + "misc/novo2sam.pl", "misc/psl2sam.pl", "misc/sam2vcf.pl", "misc/samtools.pl", + "misc/soap2sam.pl", "misc/varfilter.py", "misc/wgsim_eval.pl", + "misc/zoom2sam.pl", "misc/md5sum-lite", "misc/md5fa", "misc/maq2sam-short", + "misc/maq2sam-long", "misc/wgsim", "samtools"] + + self.include_files = ["bam.h", "bam2bcf.h", "bam_endian.h", "errmod.h", + "kprobaln.h", "sam.h", "sam_header.h", "sample.h"] + + if LooseVersion(self.version) <= LooseVersion('0.1.18'): + # seqtk is no longer there in v0.1.19 + self.bin_files += ["misc/seqtk"] + elif LooseVersion(self.version) >= LooseVersion('0.1.19'): + # new tools in v0.1.19 + self.bin_files += ["misc/ace2sam", "misc/r2plot.lua", + "misc/vcfutils.lua"] + + if LooseVersion(self.version) >= LooseVersion('0.1.19') and LooseVersion(self.version) < LooseVersion('1.0'): + self.bin_files += ["misc/bamcheck", "misc/plot-bamcheck"] + + if LooseVersion(self.version) < LooseVersion('1.0'): + self.bin_files += ["bcftools/vcfutils.pl", "bcftools/bcftools"] + self.include_files += [ "bgzf.h", "faidx.h", "khash.h", "klist.h", "knetfile.h", "razf.h", + "kseq.h", "ksort.h", "kstring.h"] + elif LooseVersion(self.version) >= LooseVersion('1.0'): + self.bin_files += ["misc/plot-bamstats","misc/seq_cache_populate.pl"] + + if LooseVersion(self.version) < LooseVersion('1.2'): + # kaln aligner removed in 1.2 (commit 19c9f6) + self.include_files += ["kaln.h"] + + self.lib_files = ["libbam.a"] + + def configure_step(self): + """ + No configure + """ + pass + + def install_step(self): + """ + Install by copying files to install dir + """ + + for (srcdir, dest, files) in [ + (self.cfg['start_dir'], 'bin', self.bin_files), + (self.cfg['start_dir'], 'lib', self.lib_files), + (self.cfg['start_dir'], 'include/bam', self.include_files) + ]: + + destdir = os.path.join(self.installdir, dest) + srcfile = None + try: + os.makedirs(destdir) + for filename in files: + srcfile = os.path.join(srcdir, filename) + shutil.copy2(srcfile, destdir) + except OSError, err: + raise EasyBuildError("Copying %s to installation dir %s failed: %s", srcfile, destdir, err) + + # fix permissions so ownwer group and others have R-X + adjust_permissions(self.installdir, stat.S_IRGRP|stat.S_IXGRP|stat.S_IROTH|stat.S_IXOTH, add=True, recursive=True) + + def sanity_check_step(self): + """Custom sanity check for SAMtools.""" + + custom_paths = { + 'files': ['bin/%s' % x for x in [f.split('/')[-1] for f in self.bin_files]] + + ['lib/%s' % x for x in self.lib_files] + + ['include/bam/%s' % x for x in self.include_files], + 'dirs': [] + } + + super(EB_SAMtools, self).sanity_check_step(custom_paths=custom_paths) diff --git a/pool/shard002/Python/0026823_cloudkms_v1_generated_key_management_service_mac_verify_sync.py b/pool/shard002/Python/0026823_cloudkms_v1_generated_key_management_service_mac_verify_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..c003949343d003e56c7178520e041951a9a0215c --- /dev/null +++ b/pool/shard002/Python/0026823_cloudkms_v1_generated_key_management_service_mac_verify_sync.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MacVerify +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_MacVerify_sync] +from google.cloud import kms_v1 + + +def sample_mac_verify(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.MacVerifyRequest( + name="name_value", + data=b'data_blob', + mac=b'mac_blob', + ) + + # Make the request + response = client.mac_verify(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_MacVerify_sync] diff --git a/pool/shard002/Python/0026824_test20_tag_alias.py b/pool/shard002/Python/0026824_test20_tag_alias.py new file mode 100644 index 0000000000000000000000000000000000000000..3509e841cd556209a9444c5a11934445c056ff67 --- /dev/null +++ b/pool/shard002/Python/0026824_test20_tag_alias.py @@ -0,0 +1,18 @@ +from test_base import TestCase + +class Test_TagAlias(TestCase): + + def test_tag_alias(self): + self.open('/') + self.open_popup(1580459) + self.start_bookmark() + self.assertEqual(self.q('#pp-popup-bookmark-wrapper #input_tag').get_attribute('value'), '') + self.click(self.q('.pp-tag-association-toggle')) + self.click(self.q('#pp-popup-bookmark-wrapper section.work-tags-container .pp-tag-associate-button')) + btn = self.q('#pp-popup-bookmark-wrapper section.tag-cloud-container .pp-tag-associate-button') + tag = btn.get_attribute('data-pp-tag') + self.click(btn) + self.assertEqual(self.q('#pp-popup-bookmark-wrapper #input_tag').get_attribute('value'), tag) + self.open_popup(1580459) + self.start_bookmark() + self.assertEqual(self.q('#pp-popup-bookmark-wrapper #input_tag').get_attribute('value'), tag) diff --git a/pool/shard002/Python/0026826_anglicisms.py b/pool/shard002/Python/0026826_anglicisms.py new file mode 100644 index 0000000000000000000000000000000000000000..a52b55bad069c888b00554c3f84bd6d6b279f64e --- /dev/null +++ b/pool/shard002/Python/0026826_anglicisms.py @@ -0,0 +1,140 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# ++++++++++++++++++++++++++++++++++++++++++++++ +# Authors: +# +# Sebastian Spaar +# Dennis Ulmer +# +# Project: +# CrOssinG (CompaRing Of AngliciSmS IN German) +# +# ++++++++++++++++++++++++++++++++++++++++++++++ + +"""anglicisms.py: + +This module extracts anglicisms from the online wikipedia wictionary. +(Check it out here: https://www.wiktionary.org/) + +The program looks into the html-code and checks if an anglicisms has an own +entry in the wictionary. If so, it will search in it for a +german translation. + +""" + +#-------------------------------- Imports ------------------------------------- + +import urllib2 +import re + +from bs4 import BeautifulSoup as BS + +from scrn_out import w, wil, fl + +#----------------------------- Main functions --------------------------------- + +def getAnglicismsList(url): + """Extracts a list of anglicisms from a wiktionary page.""" + anglicisms_list_html = BS(urllib2.urlopen(url)) # Extract the html-code + # Extracting every relevant section from the html-code + sections = anglicisms_list_html.find_all("p") + wil("Extracting anglicisms from wictionary.", 30) + entries = [] # Array for anglicisms + + for section in sections: + # The many variants of seperators + section_ = re.split("( - | – | -|- |– )", str(section)) + for s in section_: + entries.append(s) + + entries = entries[3:len(entries)-1] # Using only the relevant parts + fl() + wil("Extracting anglicisms from wictionary..") + + for i in range(len(entries)-1, -1, -1): + if entries[i] in [" - ", "- ", " -", " – ", "– "]: + entries.pop(i) # Popping redundant matches + + fl() + wil("Extracting anglicisms from wictionary...Complete!", 30, "\n") + return entries + +def generateEntries(list, printErrors=True): + """Generates array of tuples (anglicism, wiktionary-link).""" + tuples = [] # Array for tuples (anglicism, wiktionary-link) + errors = [] + + for e in list: + percentage = list.index(e)*1.0/len(list)*100 + wil("Creating tuples of anglicisms and their wikilink -" + "%.2f%% complete" %(percentage), 60) + try: + anglicism = re.findall(">[0-9a-zA-Z-. äöüÄÖÜßé]+<", e) + if anglicism == []: + continue + # Extracting the anglicisms + anglicism = anglicism[0].replace("<", "").replace(">", "") + wikilink = "" + + if "(Seite nicht vorhanden)" not in str(e): + # Extracting the wikilink + wikilink = re.findall('=".+"\s', e)[0].replace('="', + "").replace('" ', "") + wikilink = "http://de.wiktionary.org" + wikilink + tuples.append((anglicism, wikilink)) + except Exception, ex: + errors.append((str(e), str(ex))) + continue + finally: + fl() + + if printErrors == True: + wil("The following errors occured:", 150, "\n") + for error in errors: + print "Error at entry: %s - %s" %(error[0], error[1]) + + wil("Creating tuples of anglicisms and their wikilinks...Complete!", + 30, "\n") + return tuples + +def lookUpTranslations(list, printErrors=True): + """Looks up the English translation of an anglicism.""" + # Array for tuples with format (anglzism, [translation 1, translation2]) + tuples = [] + + for e in list: + percentage = list.index(e)*1.0/len(list)*100 + wil("Looking up translations for %s - %.2f%% complete" + %(e[0].replace("ä", "ae").replace("é", "e"), percentage), 20) + if e[1] == "": # If there is no wikilink + fl() + continue + try: + # Extracting the html-code of wiktionary-page + r = urllib2.Request(e[1]) + html = BS(urllib2.urlopen(r)) + # If there are English translations + if len(re.findall("/wiki/Englisch.+<\/li>", str(html))) > 0: + translations = re.findall("/wiki/Englisch.+<\/li>", + unicode(html))[0] + translations = re.findall(">[0-9a-zA-Z-. äöüÄÖÜßé]+<", + translations) + for i in range(len(translations)-1, -1, -1): + if translations[i] == "> <" or \ + translations[i] == ">Englisch<": + translations.pop(i) # Popping redundant matches... + else: + # ...or just formatting the results + translations[i] = translations[i].replace(">", + "").replace("<", "") + else: + translations = [] # Default + tuples.append((e[0].decode('utf-8'), translations)) + except Exception, ex: + if printErrors: + print str(ex) + fl() + + wil("Looking up translations...Complete!%s\n" %(40* " ")) + return tuples \ No newline at end of file diff --git a/pool/shard002/Python/0026829_reader.py b/pool/shard002/Python/0026829_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..a177189c9c523ad56b2307ef3ff750d09873bfa3 --- /dev/null +++ b/pool/shard002/Python/0026829_reader.py @@ -0,0 +1,111 @@ +import logging +from rota.exclude import ExcludeMixin + + +class ReaderError(Exception): + def __init__(self, error, id=None): + self.error = error + self.id = id + + def __str__(self): + return "{0}; ID: {1}".format(self.error, self.id) + + +class Reader(ExcludeMixin): + """ A reader available for a mass + + Instance variables: + id -- the numeric ID of the reader + name -- The name of the reader (either full name, or surname) + names -- The names for the reader + date_format -- The date format used to parse exclusions + exclude -- A list of dates the reader cannot make + + A 'reader' may be a single person (in which case, only 'name' is required) + or may be multiple people (e.g. a family). In this case, the surname should + be specified for 'name', with individual names in 'names'. + + The 'exclude' variable is a list of dates that the reader is unavailable + for. The dates are passed in as strings and are parsed into date objects. + The dates should be in either the default format of 'DD/MM/YYYY', or the + desired format should be specified in the date_format parameter on + construction an object. The date_format parameter follows the rules for + strftime and strptime in the python documentation. + """ + + def __init__(self, id, data, date_format='%d/%m/%Y'): + """Initialise a reader object + + Arguments: + id -- the reader ID + data -- A dictonary containing the reader data (name, exclude, etc) + date_format -- Format of dates in the exclude list + """ + self.logger = logging.getLogger('rotaGenerator.Reader') + self.id = id + try: + ExcludeMixin.__init__(self, data['exclude'], date_format) + except KeyError: + ExcludeMixin.__init__(self, [], date_format) + + if 'name' not in data and 'names' not in data: + raise ReaderError('Reader must have a name and/or names', self.id) + + try: + self.name = data['name'] + except KeyError: + self.name = '' + + try: + self.names = data['names'] + except KeyError: + self.names = [] + + try: + for n in self.names: + if not n: + raise ReaderError('Empty name in names', self.id) + except TypeError as e: + raise ReaderError('Invalid names ({0})'.format(e), self.id) + + def __repr__(self): + return("{0}({1:d}, '{2}', {3!r}, {4!r})".format( + self.__class__.__name__, + self.id, + self.name, + self.names, + self.excludes_as_string())) + + def __str__(self): + string = '{0} - {1}'.format(self.id, self.name) + if not self.name: + string = '{0} - {1}'.format(self.id, str(self.names)) + + return string + + def get_name(self, slots): + """Get the name of this reader + + When a reader with multiple names has fewer names than slots, the list + of individual names is returned as a combined string. When the reader + has enough or more names, only the 'name' is returned. + + Arguments: + slots -- the number of slots to be filled + + Returns: + A string containing the name(s) of the reader and the number of slots + remaining. + """ + if self.names: + num_names = len(self.names) + if num_names < slots: + remaining = slots - len(self.names) + return ', '.join(self.names), remaining + elif num_names == slots: + return self.name, 0 + else: + self.logger.warn("More names than slots") + return self.name, 0 + else: + return self.name, slots - 1 diff --git a/pool/shard002/Python/0026833_collection.py b/pool/shard002/Python/0026833_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..9723e30984c796762d048648d5f6d8e8cf142a61 --- /dev/null +++ b/pool/shard002/Python/0026833_collection.py @@ -0,0 +1,105 @@ +#Copyright (C) 2008 Codethink Ltd +#Copyright (c) 2012 SUSE LINUX Products GmbH, Nuernberg, Germany. + +#This library is free software; you can redistribute it and/or +#modify it under the terms of the GNU Lesser 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 Lesser 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. + +from gi.repository import Atspi +from pyatspi.enum import * +from pyatspi.utils import * + +__all__ = [ + "Collection", + "SortOrder", + "MatchType", + "TreeTraversalType", + ] + +#------------------------------------------------------------------------------ + +class MatchType(Enum): + _enum_lookup = { + 0:'MATCH_INVALID', + 1:'MATCH_ALL', + 2:'MATCH_ANY', + 3:'MATCH_NONE', + 4:'MATCH_EMPTY', + 5:'MATCH_LAST_DEFINED', + } + +class SortOrder(Enum): + _enum_lookup = { + 0:'SORT_ORDER_INVALID', + 1:'SORT_ORDER_CANONICAL', + 2:'SORT_ORDER_FLOW', + 3:'SORT_ORDER_TAB', + 4:'SORT_ORDER_REVERSE_CANONICAL', + 5:'SORT_ORDER_REVERSE_FLOW', + 6:'SORT_ORDER_REVERSE_TAB', + 7:'SORT_ORDER_LAST_DEFINED', + } + +class TreeTraversalType(Enum): + _enum_lookup = { + 0:'TREE_RESTRICT_CHILDREN', + 1:'TREE_RESTRICT_SIBLING', + 2:'TREE_INORDER', + 3:'TREE_LAST_DEFINED', + } + +class Collection: + + MATCH_ALL = MatchType(1) + MATCH_ANY = MatchType(2) + MATCH_EMPTY = MatchType(4) + MATCH_INVALID = MatchType(0) + MATCH_LAST_DEFINED = MatchType(5) + MATCH_NONE = MatchType(3) + + SORT_ORDER_CANONICAL = SortOrder(1) + SORT_ORDER_FLOW = SortOrder(2) + SORT_ORDER_INVALID = SortOrder(0) + SORT_ORDER_LAST_DEFINED = SortOrder(7) + SORT_ORDER_REVERSE_CANONICAL = SortOrder(4) + SORT_ORDER_REVERSE_FLOW = SortOrder(5) + SORT_ORDER_REVERSE_TAB = SortOrder(6) + SORT_ORDER_TAB = SortOrder(3) + + TREE_INORDER = TreeTraversalType(2) + TREE_LAST_DEFINED = TreeTraversalType(3) + TREE_RESTRICT_CHILDREN = TreeTraversalType(0) + TREE_RESTRICT_SIBLING = TreeTraversalType(1) + + def __init__(self, obj): + self.obj = obj + + def isAncestorOf(self, object): + return Atspi.Collection.is_ancestor_of(self.obj) + + def createMatchRule(self, states, stateMatchType, attributes, attributeMatchType, roles, roleMatchType, interfaces, interfaceMatchType, invert): + attributes_hash = attributeListToHash(attributes) + return Atspi.MatchRule.new(states, stateMatchType, attributes_hash, attributeMatchType, roles, roleMatchType, interfaces, interfaceMatchType, invert) + + def freeMatchRule(self, rule): + pass + + def getMatches(self, rule, sortby, count, traverse): + return Atspi.Collection.get_matches(self.obj, rule, sortby, count, traverse) + + def getMatchesTo(self, current_object, rule, sortby, tree, recurse, count, traverse): + return Atspi.Collection.get_matches_to(self.obj, current_object, rule, sortby, tree, recurse, count, traverse) + + def getMatchesFrom(self, current_object, rule, sortby, tree, count, traverse): + return Atspi.Collection.get_matches_from(self.obj, current_object, rule, sortby, tree, count, traverse) + + def getActiveDescendant(self): + return Atspi.Collection.get_active_descendant(self.obj) diff --git a/pool/shard002/Python/0026834_test_server.py b/pool/shard002/Python/0026834_test_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5df16831aee06b85a8e0bdc6442307aad990c8b9 --- /dev/null +++ b/pool/shard002/Python/0026834_test_server.py @@ -0,0 +1,66 @@ +# -*- coding: utf-8 -*- +""" +Created on Sun Mar 1 12:36:56 2015 + +@author: rep +""" + +import json +import cherrypy + +import os +import logging + +#com_profile,shapes = census_parsing.run() +cur_dir = os.path.dirname(os.path.realpath(__file__)) +os.chdir('../front_end') +com_profile,shapes = 'Nothing','Nothing' +class HelloWorld(object): + def home(self): + page = '../front_end/home.html' + return open(page) + home.exposed = True + + def van_map(self): + page = '../front_end/van_map.html' + return open(page) + van_map.exposed = True + + def edmon_map(self): + page = '../front_end/edmon_map.html' + return open(page) + edmon_map.exposed = True + + def van_map_profiles(self): + return open(com_profile) + van_map_profiles.exposed = True + + def van_map_shapes(self): + return open(shapes) + van_map_shapes.exposed = True + + def edmon_map_profiles(self): + return open(com_profile) + edmon_map_profiles.exposed = True + + def edmon_map_shapes(self): + return open(shapes) + edmon_map_shapes.exposed = True +# + def about_team(self): + page = '../front_end/about_team.html' + return open(page) + + def about_app(self): + page = '../front_end/about_app.html' + return open(page) + + +#cherrypy.config.update(# Used to bind to public ip - not working +# {'server.socket_host': ' 132.216.233.223' } ) + + +cherrypy.quickstart(HelloWorld(),'/',{'/':{ + 'tools.staticdir.on': True, + 'tools.staticdir.dir': os.path.abspath(os.curdir) + }}) diff --git a/pool/shard002/Python/0026843_2newtonOptimization.py b/pool/shard002/Python/0026843_2newtonOptimization.py new file mode 100644 index 0000000000000000000000000000000000000000..38d935b281535e7855c72871753ed086cc8199d8 --- /dev/null +++ b/pool/shard002/Python/0026843_2newtonOptimization.py @@ -0,0 +1,21 @@ +import numpy as np + +def newton(Function, o0, dx=1e-6, tolerance=1e-6, steps=1000): + def F(x): + return eval(Function) + def out(s1, s2, s3): + print("{:>15}".format(s1), "{:>15}".format(s2), "{:>15}".format(s3)) + out("iterations", "optimum", "%rel. error") + out(0, o0, 100) + for i in range(1, steps): + first = (F(o0+dx) - F(o0-dx)) / (2*dx) + second = (F(o0+dx) - 2*F(o0) + F(o0-dx)) / (dx**2) + o = o0 - first/second + error = abs((o-o0)/o)*100 + out(i, round(o,6), round(error)) + o0 = o + if(error < tolerance): + break + return o + +o = newton("np.log(np.exp(x+3) + np.exp(-2*x+2))", 0) diff --git a/pool/shard002/Python/0026844_init__.py b/pool/shard002/Python/0026844_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67ca456821671f68192d87243b84fcc2fbcedd4a --- /dev/null +++ b/pool/shard002/Python/0026844_init__.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +# 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 . +""" +kallithea.model.__init__ +~~~~~~~~~~~~~~~~~~~~~~~~ + +The application's model objects + +This file was forked by the Kallithea project in July 2014. +Original author and date, and relevant copyright and licensing information is below: +:created_on: Nov 25, 2010 +:author: marcink +:copyright: (c) 2013 RhodeCode GmbH, and others. +:license: GPLv3, see LICENSE.md for more details. + + +:example: + + .. code-block:: python + + from paste.deploy import appconfig + from pylons import config + from sqlalchemy import engine_from_config + from kallithea.config.environment import load_environment + + conf = appconfig('config:development.ini', relative_to = './../../') + load_environment(conf.global_conf, conf.local_conf) + + engine = engine_from_config(config, 'sqlalchemy.') + init_model(engine) + # RUN YOUR CODE HERE + +""" + + +import logging +from kallithea.model import meta +from kallithea.lib.utils2 import safe_str, obfuscate_url_pw + +log = logging.getLogger(__name__) + + +def init_model(engine): + """ + Initializes db session, bind the engine with the metadata, + Call this before using any of the tables or classes in the model, + preferably once in application start + + :param engine: engine to bind to + """ + engine_str = obfuscate_url_pw(str(engine.url)) + log.info("initializing db for %s" % engine_str) + meta.Base.metadata.bind = engine + + +class BaseModel(object): + """ + Base Model for all Kallithea models, it adds sql alchemy session + into instance of model + + :param sa: If passed it reuses this session instead of creating a new one + """ + + cls = None # override in child class + + def __init__(self, sa=None): + if sa is not None: + self.sa = sa + else: + self.sa = meta.Session() + + def _get_instance(self, cls, instance, callback=None): + """ + Gets instance of given cls using some simple lookup mechanism. + + :param cls: class to fetch + :param instance: int or Instance + :param callback: callback to call if all lookups failed + """ + + if isinstance(instance, cls): + return instance + elif isinstance(instance, (int, long)) or safe_str(instance).isdigit(): + return cls.get(instance) + else: + if instance: + if callback is None: + raise Exception( + 'given object must be int, long or Instance of %s ' + 'got %s, no callback provided' % (cls, type(instance)) + ) + else: + return callback(instance) + + def _get_user(self, user): + """ + Helper method to get user by ID, or username fallback + + :param user: UserID, username, or User instance + """ + from kallithea.model.db import User + return self._get_instance(User, user, + callback=User.get_by_username) + + def _get_repo(self, repository): + """ + Helper method to get repository by ID, or repository name + + :param repository: RepoID, repository name or Repository Instance + """ + from kallithea.model.db import Repository + return self._get_instance(Repository, repository, + callback=Repository.get_by_repo_name) + + def _get_perm(self, permission): + """ + Helper method to get permission by ID, or permission name + + :param permission: PermissionID, permission_name or Permission instance + """ + from kallithea.model.db import Permission + return self._get_instance(Permission, permission, + callback=Permission.get_by_key) + + @classmethod + def get_all(cls): + """ + Returns all instances of what is defined in `cls` class variable + """ + return cls.cls.getAll() diff --git a/pool/shard002/Python/0026845_admin.py b/pool/shard002/Python/0026845_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..d72d502cdcad65ef145fb8e43128b8d240a5b7e9 --- /dev/null +++ b/pool/shard002/Python/0026845_admin.py @@ -0,0 +1,36 @@ +from django.contrib import admin +from home.models import * + + +class LanguageAdmin(admin.ModelAdmin): + list_display = ('id', 'name', 'text', ) + + +class MenuInfoInline(admin.StackedInline): + model = MenuInfo + extra = 3 + + +class MenuAdmin(admin.ModelAdmin): + list_display = ('code', 'sort', 'url', ) + inlines = [MenuInfoInline] + + +class SectionInline(admin.StackedInline): + model = SectionInfo + extra = 3 + + +class SectionAdmin(admin.ModelAdmin): + list_display = ('code', 'sort', 'basepage', ) + inlines = [SectionInline] + + +class BasePageAdmin(admin.ModelAdmin): + list_display = ('name', 'remark', ) + + +admin.site.register(BasePage, BasePageAdmin) +admin.site.register(Languages, LanguageAdmin) +admin.site.register(Menu, MenuAdmin) +admin.site.register(Section, SectionAdmin) \ No newline at end of file diff --git a/pool/shard002/Python/0026853_jpharvest.py b/pool/shard002/Python/0026853_jpharvest.py new file mode 100644 index 0000000000000000000000000000000000000000..c12b6cd10895365380abaef24600bdc9c19194c4 --- /dev/null +++ b/pool/shard002/Python/0026853_jpharvest.py @@ -0,0 +1,128 @@ +import logging +import sqlsoup + +from language_explorer import constants +from language_explorer.language_sources.base import AbstractLanguageSource + +logging.basicConfig(level=logging.DEBUG) + + +class JPHarvestAdapter(AbstractLanguageSource): + SOURCE_NAME = constants.JOSHUA_PROJECT_SOURCE_ABBREV + + def __init__(self, db_url): + self.db = sqlsoup.SQLSoup(db_url) + + def get_language_iso_keys(self): + """get a list of languages, with the most common key available in the db + + this might mean we can insert it straight into our db, but it might + need some processing if the available keys need translation to be a + key in our db. + + SELECT DISTINCT("tblLNG3Languages"."ROL3"), "Language" FROM + "tbllnkLNGtoPEOGEO", "tblPEO3PeopleGroups", "tblLNG3Languages" where + "tblPEO3PeopleGroups"."PeopleID3" = "tbllnkLNGtoPEOGEO"."PeopleID3" AND + "tbllnkLNGtoPEOGEO"."ROL3" = "tblLNG3Languages"."ROL3" AND + "tblPEO3PeopleGroups"."PeopleID2" = '100' and + "tbllnkLNGtoPEOGEO"."ROG3" = 'AS' + ORDER by "ROL3" + """ + # We need labels because both tables have PeopleID3 as the join key + # and sqlsoup needs labels to avoid ambiguity + pg_labels = self.db.with_labels(self.db.tblPEO3PeopleGroups) + j1 = self.db.join(self.db.tbllnkLNGtoPEOGEO, pg_labels, + self.db.tbllnkLNGtoPEOGEO.PeopleID3 == + pg_labels.tblPEO3PeopleGroups_PeopleID3, + isouter=True) + all_iso = set([row.ROL3 for row in j1.filter( + j1.ROG3 == "AS", + j1.tblPEO3PeopleGroups_PeopleID2 == 100).all()])\ + .difference(self.EXCLUDED_AU_LANGUAGES) + return sorted(list(all_iso)) + + def get_primary_name_for_iso(self, iso): + language = self.db.tblLNG3Languages.get(iso) + if language: + return language.Language + else: + return None + + def get_alternate_names_for_iso(self, iso): + return [l.LangAltName for l in + self.db.tblLNG6LanguageAlternateNames.filter( + self.db.tblLNG6LanguageAlternateNames.ROL3 == iso).all()] + + def get_dialects_for_iso(self, iso): + """Language ISO also appears in tblLNG4Dialects. Not sure whether we + want to duplicate it all (if indeed it is duplicated). Haven't + investigated tblLNG7DialectAlternateNames + """ + # For the momen + return [] + + def get_classification(self, iso): + """Can't be implemented. JPHarvest doesn't provide classification""" + return [] + + def get_L1_speaker_count_for_iso(self, iso): + # JoshuaProject does not have speaker count for some languages + # despite having language records for that language. + # => bzr, dif, gnr, nid, wkw, wrg, wrz + # All of these languages are 8b, 9 or 10 on EGIDS + # i.e. extinct, dormant or nearly extinct + # So will infer that there aren't any remaining L1 speakers and + # record that they have SPEAKER_COUNT_NONE_EXPECTED speakers + language = self.db.tblLNG3Languages.get(iso) + if language: + if language.WorldSpeakers: + return language.WorldSpeakers + else: + return constants.SPEAKER_COUNT_NONE_EXPECTED + else: + return constants.SPEAKER_COUNT_UNKNOWN + + def get_translation_info_for_iso(self, iso): + """Has additional information on top of ethnologue and findabible + e.g. mwp and rop have NT dates + Extra data is likely from the world christian database, at least + based on http://www.joshuaproject.net/data-sources.php + + Note that we only return the date associated with the largest body of + work. If we have a NT, there's no need to report on portions. + Some year values are ranges, some are single years and one (bdy) + is "yes" !!! + """ + d = {} + STATE = constants.TRANSLATION_STATE_STATE_KEY + YEAR = constants.TRANSLATION_STATE_YEAR_KEY + language = self.db.tblLNG3Languages.filter( + self.db.tblLNG3Languages.ROL3 == iso).first() + # If we don't know about this iso + if not language: + return {} + + bible_year = language.BibleYear + if bible_year: + d[STATE] = constants.TRANSLATION_STATE_WHOLE_BIBLE + d[YEAR] = int(bible_year.rpartition("-")[2]) + return d + nt_year = self.db.tblLNG3Languages.filter( + self.db.tblLNG3Languages.ROL3 == iso).first().NTYear + if nt_year: + d[STATE] = constants.TRANSLATION_STATE_NEW_TESTAMENT + d[YEAR] = int(nt_year.rpartition("-")[2]) + return d + portions_year = self.db.tblLNG3Languages.filter( + self.db.tblLNG3Languages.ROL3 == iso).first().PortionsYear + if portions_year: + d[STATE] = constants.TRANSLATION_STATE_PORTIONS + if portions_year == "Yes": # bdy + d[YEAR] = constants.TRANSLATION_STATE_POSITIVE_YEAR + else: + d[YEAR] = int(portions_year.rpartition("-")[2]) + + return d + d[STATE] = constants.TRANSLATION_STATE_NO_SCRIPTURE + d[YEAR] = constants.TRANSLATION_STATE_UNKNOWN_YEAR + return d diff --git a/pool/shard002/Python/0026854_mainpage.py b/pool/shard002/Python/0026854_mainpage.py new file mode 100644 index 0000000000000000000000000000000000000000..9fcbc742f14ac04a8d19b6694005a07263e224e4 --- /dev/null +++ b/pool/shard002/Python/0026854_mainpage.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from flask import Blueprint, request, current_app +from flask import render_template, redirect, abort +from flask import url_for, jsonify +__all__ = ['bp'] +bp = Blueprint('mainpage',__name__) + +@bp.route('/') +def home(): + return redirect("/account/login") \ No newline at end of file diff --git a/pool/shard002/Python/0026858_qb_test_ir.py b/pool/shard002/Python/0026858_qb_test_ir.py new file mode 100644 index 0000000000000000000000000000000000000000..1bc0f5bf478dddcf9498025b2ac6a87c5f4f3ed2 --- /dev/null +++ b/pool/shard002/Python/0026858_qb_test_ir.py @@ -0,0 +1,41 @@ +""" +Mike Kroutikov, (c) 2014 + +Test QuickBot IR sensors. + +Run this code on the BeagleBone side. + +It will display for about 30 seconds the current values of all five sensors. + +While this program runs, try putting an obstacle before each sensor. Unobstructed sensor should read +low value (e.g. 0). Placing palm of your hand at about 2 inches should cause large readings (300-700). + +--------------------------------- +Modified by hiankun. + +The display time had been enlongate to about 300 seconds for longer testing period. + +Also, the output had been changed from raw readings to centimeters. + +Note that the unit conversion to centimeter was not adquite, +and further tunning is necessary. + +""" +import Adafruit_BBIO.ADC as ADC +import time + +if __name__ == '__main__': + import config + + print "Testing IR sensors. Try putting hand in front of a sensor to see its value change" + + ADC.setup() + + for _ in range(600): + values = tuple(ADC.read_raw(pin) for pin in config.IR_PINS) + time.sleep(0.5) + # if the value is not available, assign -999 + distances = map(lambda x: 2076.0/(x-11.0) if (x != 11.0) else -999., values) + print '{:10.2f}{:10.2f}{:10.2f}{:10.2f}{:10.2f}'.format(*distances) + + print "Done" diff --git a/pool/shard002/Python/0026861_issue.py b/pool/shard002/Python/0026861_issue.py new file mode 100644 index 0000000000000000000000000000000000000000..a52eee93813fae9ffd61d25ff0aac5591d9d3b04 --- /dev/null +++ b/pool/shard002/Python/0026861_issue.py @@ -0,0 +1,227 @@ +""" +sentry.plugins.bases.issue +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. +:license: BSD, see LICENSE for more details. +""" +from __future__ import absolute_import + +from django import forms +from django.conf import settings +from django.utils.html import format_html +from social_auth.models import UserSocialAuth + +from sentry.models import GroupMeta, Activity +from sentry.plugins import Plugin +from sentry.utils.auth import get_auth_providers +from sentry.utils.http import absolute_uri +from sentry.utils.safe import safe_execute + + +class NewIssueForm(forms.Form): + title = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'span9'})) + description = forms.CharField(widget=forms.Textarea(attrs={'class': 'span9'})) + + +class IssueTrackingPlugin(Plugin): + # project_conf_form = BaseIssueOptionsForm + new_issue_form = NewIssueForm + + create_issue_template = 'sentry/plugins/bases/issue/create_issue.html' + not_configured_template = 'sentry/plugins/bases/issue/not_configured.html' + needs_auth_template = 'sentry/plugins/bases/issue/needs_auth.html' + auth_provider = None + + def _get_group_body(self, request, group, event, **kwargs): + result = [] + for interface in event.interfaces.itervalues(): + output = safe_execute(interface.to_string, event) + if output: + result.append(output) + return '\n\n'.join(result) + + def _get_group_description(self, request, group, event): + output = [ + absolute_uri(group.get_absolute_url()), + ] + body = self._get_group_body(request, group, event) + if body: + output.extend([ + '', + '```', + body, + '```', + ]) + return '\n'.join(output) + + def _get_group_title(self, request, group, event): + return event.error() + + def is_configured(self, request, project, **kwargs): + raise NotImplementedError + + def get_auth_for_user(self, user, **kwargs): + """ + Return a ``UserSocialAuth`` object for the given user based on this plugins ``auth_provider``. + """ + assert self.auth_provider, 'There is no auth provider configured for this plugin.' + + if not user.is_authenticated(): + return None + + try: + return UserSocialAuth.objects.filter(user=user, provider=self.auth_provider)[0] + except IndexError: + return None + + def needs_auth(self, request, project, **kwargs): + """ + Return ``True`` if the authenticated user needs to associate an auth service before + performing actions with this plugin. + """ + if self.auth_provider is None: + return False + + if not request.user.is_authenticated(): + return True + + return bool(not UserSocialAuth.objects.filter(user=request.user, provider=self.auth_provider).exists()) + + def get_new_issue_title(self, **kwargs): + """ + Return a string for the "Create new issue" action label. + """ + return 'Create %s Issue' % self.get_title() + + def get_new_issue_form(self, request, group, event, **kwargs): + """ + Return a Form for the "Create new issue" page. + """ + return self.new_issue_form(request.POST or None, initial=self.get_initial_form_data(request, group, event)) + + def get_issue_url(self, group, issue_id, **kwargs): + """ + Given an issue_id (string) return an absolute URL to the issue's details + page. + """ + raise NotImplementedError + + def get_issue_label(self, group, issue_id, **kwargs): + """ + Given an issue_id (string) return a string representing the issue. + + e.g. GitHub represents issues as GH-XXX + """ + return '#%s' % issue_id + + def create_issue(self, request, group, form_data, **kwargs): + """ + Creates the issue on the remote service and returns an issue ID. + """ + raise NotImplementedError + + def get_initial_form_data(self, request, group, event, **kwargs): + return { + 'description': self._get_group_description(request, group, event), + 'title': self._get_group_title(request, group, event), + } + + def has_auth_configured(self, **kwargs): + if not self.auth_provider: + return True + + return self.auth_provider in get_auth_providers() + + def view(self, request, group, **kwargs): + has_auth_configured = self.has_auth_configured() + if not (has_auth_configured and self.is_configured(project=group.project, request=request)): + if self.auth_provider: + required_auth_settings = settings.AUTH_PROVIDERS[self.auth_provider] + else: + required_auth_settings = None + + return self.render(self.not_configured_template, { + 'title': self.get_title(), + 'project': group.project, + 'has_auth_configured': has_auth_configured, + 'required_auth_settings': required_auth_settings, + }) + + if self.needs_auth(project=group.project, request=request): + return self.render(self.needs_auth_template, { + 'title': self.get_title(), + 'project': group.project, + }) + + if GroupMeta.objects.get_value(group, '%s:tid' % self.get_conf_key(), None): + return None + + prefix = self.get_conf_key() + event = group.get_latest_event() + + form = self.get_new_issue_form(request, group, event) + if form.is_valid(): + try: + issue_id = self.create_issue( + group=group, + form_data=form.cleaned_data, + request=request, + ) + except forms.ValidationError as e: + form.errors['__all__'] = [u'Error creating issue: %s' % e] + + if form.is_valid(): + GroupMeta.objects.set_value(group, '%s:tid' % prefix, issue_id) + + issue_information = { + 'title': form.cleaned_data['title'], + 'provider': self.get_title(), + 'location': self.get_issue_url(group, issue_id), + 'label': self.get_issue_label(group=group, issue_id=issue_id), + } + Activity.objects.create( + project=group.project, + group=group, + type=Activity.CREATE_ISSUE, + user=request.user, + data=issue_information, + ) + + return self.redirect(group.get_absolute_url()) + + context = { + 'form': form, + 'title': self.get_new_issue_title(), + } + + return self.render(self.create_issue_template, context) + + def actions(self, request, group, action_list, **kwargs): + if not self.is_configured(request=request, project=group.project): + return action_list + prefix = self.get_conf_key() + if not GroupMeta.objects.get_value(group, '%s:tid' % prefix, None): + action_list.append((self.get_new_issue_title(), self.get_url(group))) + return action_list + + def tags(self, request, group, tag_list, **kwargs): + if not self.is_configured(request=request, project=group.project): + return tag_list + + prefix = self.get_conf_key() + issue_id = GroupMeta.objects.get_value(group, '%s:tid' % prefix) + if not issue_id: + return tag_list + + tag_list.append(format_html('{}', + self.get_issue_url(group=group, issue_id=issue_id), + self.get_issue_label(group=group, issue_id=issue_id), + )) + + return tag_list + + def get_issue_doc_html(self, **kwargs): + return "" + +IssuePlugin = IssueTrackingPlugin diff --git a/pool/shard002/Python/0026863_tvsubtitles.py b/pool/shard002/Python/0026863_tvsubtitles.py new file mode 100644 index 0000000000000000000000000000000000000000..3f21928b0d94eb37d7b5860b6998418c1eb2878e --- /dev/null +++ b/pool/shard002/Python/0026863_tvsubtitles.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals +import io +import logging +import re +import zipfile +import babelfish +import bs4 +import requests +from . import Provider +from .. import __version__ +from ..cache import region, SHOW_EXPIRATION_TIME, EPISODE_EXPIRATION_TIME +from ..exceptions import ProviderError +from ..subtitle import Subtitle, fix_line_endings, compute_guess_properties_matches +from ..video import Episode + + +logger = logging.getLogger(__name__) +babelfish.language_converters.register('tvsubtitles = subliminal.converters.tvsubtitles:TVsubtitlesConverter') + + +class TVsubtitlesSubtitle(Subtitle): + provider_name = 'tvsubtitles' + + def __init__(self, language, series, season, episode, year, id, rip, release, page_link): # @ReservedAssignment + super(TVsubtitlesSubtitle, self).__init__(language, page_link=page_link) + self.series = series + self.season = season + self.episode = episode + self.year = year + self.id = id + self.rip = rip + self.release = release + + def compute_matches(self, video): + matches = set() + # series + if video.series and self.series == video.series: + matches.add('series') + # season + if video.season and self.season == video.season: + matches.add('season') + # episode + if video.episode and self.episode == video.episode: + matches.add('episode') + # year + if self.year == video.year: + matches.add('year') + # release_group + if video.release_group and self.release and video.release_group.lower() in self.release.lower(): + matches.add('release_group') + """ + # video_codec + if video.video_codec and self.release and (video.video_codec in self.release.lower() + or video.video_codec == 'h264' and 'x264' in self.release.lower()): + matches.add('video_codec') + # resolution + if video.resolution and self.rip and video.resolution in self.rip.lower(): + matches.add('resolution') + # format + if video.format and self.rip and video.format in self.rip.lower(): + matches.add('format') + """ + # we don't have the complete filename, so we need to guess the matches separately + # guess video_codec (videoCodec in guessit) + matches |= compute_guess_properties_matches(video, self.release, 'videoCodec') + # guess resolution (screenSize in guessit) + matches |= compute_guess_properties_matches(video, self.rip, 'screenSize') + # guess format + matches |= compute_guess_properties_matches(video, self.rip, 'format') + return matches + + +class TVsubtitlesProvider(Provider): + languages = {babelfish.Language('por', 'BR')} | {babelfish.Language(l) + for l in ['ara', 'bul', 'ces', 'dan', 'deu', 'ell', 'eng', 'fin', 'fra', 'hun', 'ita', 'jpn', 'kor', + 'nld', 'pol', 'por', 'ron', 'rus', 'spa', 'swe', 'tur', 'ukr', 'zho']} + video_types = (Episode,) + server = 'http://www.tvsubtitles.net' + episode_id_re = re.compile('^episode-\d+\.html$') + subtitle_re = re.compile('^\/subtitle-\d+\.html$') + link_re = re.compile('^(?P[A-Za-z0-9 \'.]+).*\((?P\d{4})-\d{4}\)$') + + def initialize(self): + self.session = requests.Session() + self.session.headers = {'User-Agent': 'Subliminal/%s' % __version__.split('-')[0]} + + def terminate(self): + self.session.close() + + def request(self, url, params=None, data=None, method='GET'): + """Make a `method` request on `url` with the given parameters + + :param string url: part of the URL to reach with the leading slash + :param dict params: params of the request + :param dict data: data of the request + :param string method: method of the request + :return: the response + :rtype: :class:`bs4.BeautifulSoup` + + """ + r = self.session.request(method, self.server + url, params=params, data=data, timeout=10) + if r.status_code != 200: + raise ProviderError('Request failed with status code %d' % r.status_code) + return bs4.BeautifulSoup(r.content, ['permissive']) + + @region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME) + def find_show_id(self, series, year=None): + """Find the show id from the `series` with optional `year` + + :param string series: series of the episode in lowercase + :param year: year of the series, if any + :type year: int or None + :return: the show id, if any + :rtype: int or None + + """ + data = {'q': series} + logger.debug('Searching series %r', data) + soup = self.request('/search.php', data=data, method='POST') + links = soup.select('div.left li div a[href^="/tvshow-"]') + if not links: + logger.info('Series %r not found', series) + return None + matched_links = [link for link in links if self.link_re.match(link.string)] + for link in matched_links: # first pass with exact match on series + match = self.link_re.match(link.string) + if match.group('series').lower().replace('.', ' ').strip() == series: + if year is not None and int(match.group('first_year')) != year: + continue + return int(link['href'][8:-5]) + for link in matched_links: # less selective second pass + match = self.link_re.match(link.string) + if match.group('series').lower().replace('.', ' ').strip().startswith(series): + if year is not None and int(match.group('first_year')) != year: + continue + return int(link['href'][8:-5]) + return None + + @region.cache_on_arguments(expiration_time=EPISODE_EXPIRATION_TIME) + def find_episode_ids(self, show_id, season): + """Find episode ids from the show id and the season + + :param int show_id: show id + :param int season: season of the episode + :return: episode ids per episode number + :rtype: dict + + """ + params = {'show_id': show_id, 'season': season} + logger.debug('Searching episodes %r', params) + soup = self.request('/tvshow-{show_id}-{season}.html'.format(**params)) + episode_ids = {} + for row in soup.select('table#table5 tr'): + if not row('a', href=self.episode_id_re): + continue + cells = row('td') + episode_ids[int(cells[0].string.split('x')[1])] = int(cells[1].a['href'][8:-5]) + return episode_ids + + def query(self, series, season, episode, year=None): + show_id = self.find_show_id(series.lower(), year) + if show_id is None: + return [] + episode_ids = self.find_episode_ids(show_id, season) + if episode not in episode_ids: + logger.info('Episode %d not found', episode) + return [] + params = {'episode_id': episode_ids[episode]} + logger.debug('Searching episode %r', params) + link = '/episode-{episode_id}.html'.format(**params) + soup = self.request(link) + return [TVsubtitlesSubtitle(babelfish.Language.fromtvsubtitles(row.h5.img['src'][13:-4]), series, season, + episode, year if year and show_id != self.find_show_id(series.lower()) else None, + int(row['href'][10:-5]), row.find('p', title='rip').text.strip() or None, + row.find('p', title='release').text.strip() or None, + self.server + '/subtitle-%d.html' % int(row['href'][10:-5])) + for row in soup('a', href=self.subtitle_re)] + + def list_subtitles(self, video, languages): + return [s for s in self.query(video.series, video.season, video.episode, video.year) if s.language in languages] + + def download_subtitle(self, subtitle): + r = self.session.get(self.server + '/download-{subtitle_id}.html'.format(subtitle_id=subtitle.id), + timeout=10) + if r.status_code != 200: + raise ProviderError('Request failed with status code %d' % r.status_code) + with zipfile.ZipFile(io.BytesIO(r.content)) as zf: + if len(zf.namelist()) > 1: + raise ProviderError('More than one file to unzip') + subtitle.content = fix_line_endings(zf.read(zf.namelist()[0])) diff --git a/pool/shard002/Python/0026865_cleanup.py b/pool/shard002/Python/0026865_cleanup.py new file mode 100644 index 0000000000000000000000000000000000000000..4f4842f3b279b7ced28698c9100d7ec2e253e17a --- /dev/null +++ b/pool/shard002/Python/0026865_cleanup.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: + +# Copyright 2014-2021 Florian Bruhin (The Compiler) +# +# This file is part of qutebrowser. +# +# qutebrowser 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. +# +# qutebrowser 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 qutebrowser. If not, see . + +"""Script to clean up the mess made by Python/setuptools/PyInstaller.""" + +import os +import os.path +import sys +import glob +import shutil +import fnmatch + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, + os.pardir)) + +from scripts import utils + + +recursive_lint = ('__pycache__', '*.pyc') +lint = ('build', 'dist', 'pkg/pkg', 'pkg/qutebrowser-*.pkg.tar.xz', 'pkg/src', + 'pkg/qutebrowser', 'qutebrowser.egg-info', 'setuptools-*.egg', + 'setuptools-*.zip', 'doc/qutebrowser.asciidoc', 'doc/*.html', + 'doc/qutebrowser.1', 'README.html', 'qutebrowser/html/doc') + + +def remove(path): + """Remove either a file or directory unless --dry-run is given.""" + if os.path.isdir(path): + print("rm -r '{}'".format(path)) + if '--dry-run' not in sys.argv: + shutil.rmtree(path) + else: + print("rm '{}'".format(path)) + if '--dry-run' not in sys.argv: + os.remove(path) + + +def main(): + """Clean up lint in the current dir.""" + utils.change_cwd() + for elem in lint: + for f in glob.glob(elem): + remove(f) + + for root, _dirs, _files in os.walk(os.getcwd()): + path = os.path.basename(root) + if any(fnmatch.fnmatch(path, e) for e in recursive_lint): + remove(root) + + +if __name__ == '__main__': + main() diff --git a/pool/shard002/Python/0026878_distrib.py b/pool/shard002/Python/0026878_distrib.py new file mode 100644 index 0000000000000000000000000000000000000000..4f0a993bb3bc3a83e814f3c6e09c81f3d8452889 --- /dev/null +++ b/pool/shard002/Python/0026878_distrib.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 + +import gen +import os + +tpuser = os.environ['TPUSER'] +tphost = os.environ['TPHOST'] + +works_cats, years = gen.load_data() +gen.gen_works(works_cats) +gen.gen_timeline(years) + +os.system('make html') +os.system('rsync -avz -e ssh output/* %s@%s:~/www/thomaspaine/' % (tpuser, tphost)) diff --git a/pool/shard002/Python/0026884_test_userparser.py b/pool/shard002/Python/0026884_test_userparser.py new file mode 100644 index 0000000000000000000000000000000000000000..ab62b8c327f7d8307b276a015963b6675b33d55b --- /dev/null +++ b/pool/shard002/Python/0026884_test_userparser.py @@ -0,0 +1,22 @@ +import unittest +import os.path + +import json + +from mock import sentinel + +from pyhy.api.registry import HyvesRegistry +from pyhy.api.jsonreader.userparser import UserParser + +class Test(unittest.TestCase): + def setUp(self): + self.r = HyvesRegistry(sentinel.connectionobject) + self.p = UserParser(self.r) + + def testParse(self): + datafile = os.path.join(os.path.split(__file__)[0], 'users.getByUsername_homoapi.data') + userjson = json.load(open(datafile))['user'][0] + user = self.p.parse(userjson) + + self.assertEqual(user, self.r.User('6f89a2f516034edc')) + self.assertEqual(user.url, 'http://homoapi.hyves.nl/') diff --git a/pool/shard002/Python/0026886_debug.py b/pool/shard002/Python/0026886_debug.py new file mode 100644 index 0000000000000000000000000000000000000000..7c2e710eb1fb0c136a885a70f811cfbc2b9a4639 --- /dev/null +++ b/pool/shard002/Python/0026886_debug.py @@ -0,0 +1,37 @@ +''' +Created on 8 Apr 2012 + +@author: sam +Adds debug capabilities to stdin/stdout - can type commands on stdin using soundblizzard.x interface and these will be eval'ed and outputted onto stdout +Performs this by adding watch onto mainloop for stdin so when data on stdin this is analysed +''' +import sys +from gi.repository import GObject +def oot(fd, condition): + '''takes line from fd using readline and evals this, returning result of eval and any exceptions''' + print('oot\n') + text = fd.readline() + sb = soundblizzard +# if text.startswith('int'): +# import code +# import readline +# import rlcompleter +# readline.parse_and_bind("tab: complete") +# code.InteractiveConsole(globals()).interact() +# return True + try: + global soundblizzard + global sb + print(eval(text)) + except Exception as inst: + print inst + pass + return True +#fd = sys.stdin.fileno() +#flags = fcntl.fcntl(fd, fcntl.F_GETFL) +#fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) +GObject.io_add_watch(sys.stdin, GObject.IO_IN|GObject.IO_HUP|GObject.IO_PRI, oot) + +if __name__ == '__main__': + loop = GObject.MainLoop() + loop.run() \ No newline at end of file diff --git a/pool/shard002/Python/0026889_package.py b/pool/shard002/Python/0026889_package.py new file mode 100644 index 0000000000000000000000000000000000000000..65f9ba1090aad5eacf88e6ede8ace01a61cff3b6 --- /dev/null +++ b/pool/shard002/Python/0026889_package.py @@ -0,0 +1,111 @@ +############################################################################## +# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. +# Produced at the Lawrence Livermore National Laboratory. +# +# This file is part of Spack. +# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. +# LLNL-CODE-647188 +# +# For details, see https://github.com/llnl/spack +# Please also see the NOTICE and LICENSE files for our notice and the LGPL. +# +# This program 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 2.1, February 1999. +# +# 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 terms and +# conditions of 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +############################################################################## +from spack import * +import glob +import os + + +class Vizglow(Package): + """VizGlow software tool is used for high-fidelity multi-dimensional + modeling of non-equilibrium plasma discharges. + + Note: VizGlow is licensed software. You will need to create an account on + the EsgeeTech homepage and download VizGlow yourself. Spack will search + your current directory for a file of this format. Alternatively, add this + file to a mirror so that Spack can find it. For instructions on how to + set up a mirror, see http://spack.readthedocs.io/en/latest/mirrors.html""" + + homepage = "http://esgeetech.com/products/vizglow-plasma-modeling/" + + version('2.2alpha20', '2bef890c66f3a44aaf96f7c96788c89e', expand=False, + url="file://{0}/VizGlow_v2.2alpha20-Linux-x86_64-R09December2016-Install".format(os.getcwd())) + version('2.2alpha17', '1de268564363e0ee86f9ffff1c3b82e1', expand=False, + url="file://{0}/VizGlow_v2.2alpha17-R21November2016-Linux-x86_64-Install".format(os.getcwd())) + version('2.2alpha15', 'be2b5044f30f2b2c3bbe87a0037bf228', expand=False, + url="file://{0}/VizGlow_v2.2alpha15-Linux-x86_64-R31October2016-Install".format(os.getcwd())) + + # depends_on('mesa') # TODO: mesa build doesn't work for me + depends_on('zlib') + depends_on('freetype') + depends_on('fontconfig') + depends_on('libxrender') + depends_on('xterm') + # Can't get mozjs to build, packagekit -> polkit -> mozjs + # depends_on('packagekit+gtk') + depends_on('libcanberra+gtk') + + # Licensing + license_required = True + license_comment = '#' + license_files = ['esgeelm.lic'] + license_vars = ['ESGEE_LICENSE_FILE'] + + def configure(self, prefix): + # Dictionary of responses + responses = { + 'CreateDesktopShortcut': 'No', + 'CreateQuickLaunchShortcut': 'No', + 'InstallDir': prefix + } + + # Write response file + with open('spack-responses.txt', 'w') as response_file: + for key in responses: + response_file.write('{0}: {1}\n'.format(key, responses[key])) + + def install(self, spec, prefix): + self.configure(prefix) + + installer = glob.glob('VizGlow*Install')[0] + + chmod = which('chmod') + chmod('+x', installer) + + installer = Executable(installer) + installer('--mode', 'silent', '--response-file', 'spack-responses.txt') + + self.filter_ld_library_path(spec, prefix) + + def filter_ld_library_path(self, spec, prefix): + """Run after install to inject dependencies into LD_LIBRARY_PATH. + + If we don't do this, the run files will clear the LD_LIBRARY_PATH. + Since the installer is a binary file, we have no means of specifying + an RPATH to use.""" + + files = glob.glob(prefix + '/binaries/*.run') + + ld_library_path = ':'.join([ + spec['zlib'].prefix.lib, + spec['freetype'].prefix.lib, + spec['fontconfig'].prefix.lib, + spec['libxrender'].prefix.lib, + spec['libcanberra'].prefix.lib + ]) + + for runfile in files: + filter_file('(export LD_LIBRARY_PATH=)$', + r'\1{0}'.format(ld_library_path), + runfile) diff --git a/pool/shard002/Python/0026890_test_outputs.py b/pool/shard002/Python/0026890_test_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..6f4247698cb774a02c1b91f392d2e69cde3376a9 --- /dev/null +++ b/pool/shard002/Python/0026890_test_outputs.py @@ -0,0 +1,60 @@ +#!/usr/bin/python + +import unittest + +from scaffold.cf.stack.elements import Outputs + + +class TestOutputs(unittest.TestCase): + + def setUp(self): + def mock_stack(): 0 + mock_stack.outputs = [ + {'OutputKey': 'StartsWithOne', + 'OutputValue': 'StartsWithOneValue'}, + {'OutputKey': 'StartsWithTwo', + 'OutputValue': 'StartsWithTwoValue'}, + {'OutputKey': 'OneWithEnds', + 'OutputValue': 'OneWithEndsValue'}, + {'OutputKey': 'TwoWithEnds', + 'OutputValue': 'TwoWithEndsValue'} + ] + self.outputs = Outputs(mock_stack) + + def test_len(self): + self.assertEqual(4, len(self.outputs)) + + def test_getitem(self): + self.assertEquals('StartsWithOneValue', self.outputs['StartsWithOne']) + + def test_getitem_nokey(self): + with self.assertRaises(KeyError): + self.outputs['Blah'] + + def test_key_filter(self): + results = self.outputs.keys(lambda k: k.startswith('Starts')) + self.assertEqual(['StartsWithOne', 'StartsWithTwo'], results) + + def test_all_keys(self): + results = self.outputs.keys() + self.assertEqual(4, len(results)) + + def test_value_filter(self): + results = self.outputs.values(lambda v: v.endswith('Ends')) + self.assertEqual(['OneWithEndsValue', 'TwoWithEndsValue'], results) + + def test_all_values(self): + results = self.outputs.values() + self.assertEqual(4, len(results)) + + def test_first(self): + result = self.outputs.first(lambda k: k.endswith('Ends')) + self.assertEqual('OneWithEndsValue', result) + + def test_iter(self): + count = 0 + for k in self.outputs: + self.assertTrue('With' in k) + self.assertFalse('Value' in k) + count += 1 + self.assertEqual(4, count) diff --git a/pool/shard002/Python/0026892_check_assets.py b/pool/shard002/Python/0026892_check_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..4f4df82e0fafcd101c1e30ad42af2396f41f2606 --- /dev/null +++ b/pool/shard002/Python/0026892_check_assets.py @@ -0,0 +1,13 @@ +from . import RoundwareCommand + +class Command(RoundwareCommand): + args = '' + help = 'Checks that Assets exist as files in the media directory' + + def handle(self, *args, **options): + self.stdout.write("Checking all Roundware Assets") + + (found, not_found) = self.check_assets() + + self.stdout.write("Assets found: %s" % len(found)) + self.stdout.write("Assets missing: %s" % len(not_found)) diff --git a/pool/shard002/Python/0026897_test_representation_csv.py b/pool/shard002/Python/0026897_test_representation_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..6cabc30b24e4c2316171b5421747497cdeee3d6a --- /dev/null +++ b/pool/shard002/Python/0026897_test_representation_csv.py @@ -0,0 +1,86 @@ +from entry import Entry +from entry.representations.csv import content_type + + +def test_csv_content_type(): + assert content_type == "text/csv; charset=utf-8" + + +def test_empty_entry_as_csv(): + entry = Entry() + data = entry.csv + assert data == '' + + +def test_empty_entry_from_csv(): + entry = Entry() + entry.csv = ('') + assert entry.csv == ('') + + +def test_simple_as_csv(): + entry = Entry() + entry.a = "A value" + data = entry.csv + assert data == ( + '"a"\r\n' + '"A value"\r\n' + ) + + +def test_ignore_private_as_csv(): + entry = Entry() + entry._zero = "to be removed" + entry.one = "one value" + entry._two = "should be removed" + entry.two = "two value" + entry._three = "three" + + data = entry.csv + assert data == ( + '"one","two"\r\n' + '"one value","two value"\r\n' + ) + + +def test_postaladdress_as_csv(): + entry = Entry() + entry.streetAddress = "Aviation House, 125 Kingsway" + entry.addressLocality = "Holborn" + entry.addressRegion = "London" + entry.postcode = "WC2B 6NH" + entry.addressCountry = "GB" + + data = entry.csv + assert data == ( + '"addressCountry","addressLocality","addressRegion","postcode","streetAddress"\r\n' # NOQA + '"GB","Holborn","London","WC2B 6NH","Aviation House, 125 Kingsway"\r\n' # NOQA + ) + + +def test_postaladdress_from_csv(): + entry = Entry() + entry.csv = ( + '"addressCountry","addressLocality","addressRegion","postcode","streetAddress"\r\n' # NOQA + '"GB","Holborn","London","WC2B 6NH","Aviation House, 125 Kingsway"\r\n' # NOQA + ) + + assert entry.streetAddress == "Aviation House, 125 Kingsway" + assert entry.addressLocality == "Holborn" + assert entry.addressRegion == "London" + assert entry.postcode == "WC2B 6NH" + assert entry.addressCountry == "GB" + + +def test_trim_csv_headings(): + entry = Entry() + entry.csv = ( + '" addressCountry","addressLocality "," addressRegion","postcode"," streetAddress"\r\n' # NOQA + '"GB","Holborn","London","WC2B 6NH","Aviation House, 125 Kingsway"\r\n' # NOQA + ) + + assert entry.streetAddress == "Aviation House, 125 Kingsway" + assert entry.addressLocality == "Holborn" + assert entry.addressRegion == "London" + assert entry.postcode == "WC2B 6NH" + assert entry.addressCountry == "GB" diff --git a/pool/shard002/Python/0026904_UserController.py b/pool/shard002/Python/0026904_UserController.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd3a3a61244a00331f5339876628d44c5a0c872 --- /dev/null +++ b/pool/shard002/Python/0026904_UserController.py @@ -0,0 +1,57 @@ +import sys +import json +from flask import Blueprint, request +from Controller.API import Controllers +from Model.Gateway.UserGateway import UserGateway +from Model.Object.DataTransferObject import DataTransferObject + +UserController = Blueprint('UserController', __name__) + +#Get All Serves +@UserController.route('/api/Users', methods=['GET']) +def getServers(): + return json.dumps(UserGateway().getAllUsers(), default=Controllers.default) + +#Get Server based on ID +@UserController.route('/api/Users/View/', methods=['GET']) +def getServer(ID): + if ID is None: + abort(404) + else: + return json.dumps(UserGateway().getServer(ID), default=Controllers.default) + +@UserController.route('/api/Users/Create/', methods=['POST']) +def createServer(): + ServerDTO = DataTransferObject() + ServerDTO.Name = request.form['name'] + ServerDTO.ID = 0 + ServerDTO.Description = request.form['description'] + ServerDTO.HostName = request.form['host'] + ServerDTO.Port = request.form['port'] + ServerDTO.Schema = request.form['schema'] + ServerDTO.UserName = request.form['user'] + ServerDTO.Password = request.form['password'] + return json.dumps(UserGateway().addServer(ServerDTO), default=Controllers.default) + +@UserController.route('/api/Users/Update/', methods=['POST']) +def updateServer(ID): + if ID is None: + abort(404) + else: + ServerDTO = DataTransferObject() + ServerDTO.ID = ID + ServerDTO.Name = request.form['name'] + ServerDTO.Description = request.form['description'] + ServerDTO.HostName = request.form['host'] + ServerDTO.Schema = request.form['schema'] + ServerDTO.Port = request.form['port'] + ServerDTO.UserName = request.form['user'] + ServerDTO.Password = request.form['password'] + return json.dumps(UserGateway().modifyServer(ServerDTO), default=Controllers.default) + +@UserController.route('/api/Users/Delete/', methods=['POST']) +def deleteServer(ID): + if ID is None: + abort(404) + else: + return json.dumps(UserGateway().deleteServer(ID), default=Controllers.default) diff --git a/pool/shard002/Python/0026911_aggregate.py b/pool/shard002/Python/0026911_aggregate.py new file mode 100644 index 0000000000000000000000000000000000000000..0b6faf0056fb4d2eaf4cdf442668af90bf84eb0b --- /dev/null +++ b/pool/shard002/Python/0026911_aggregate.py @@ -0,0 +1,108 @@ +import csv +import itertools +import argparse +import importlib +import sys + +from csvgroup.common import dump_as_csv + + +def cast_to_type(type, values): + return [type(value) for value in values if value] + + +def aggregate(function, values, type): + cast_values = cast_to_type(type, values) + + return function(cast_values) if cast_values else None + + +def get_values(column, items): + return [item.get(column) for item in items] + + +def process(items, group, columns, function, type): + def key(item): + return [item.get(column) for column in group] + + def groups(items, key): + return ( + (group_key, list(generator)) + for group_key, generator in itertools.groupby( + sorted(items, key=key), + key + ) + ) + + fieldnames = group + columns + + yield fieldnames + + for group_key, group_items in groups(items, key): + yield ( + group_key + [ + aggregate( + function, + get_values(column, group_items), + type + ) + for column in columns + ] + ) + + +def arguments(): + parser = argparse.ArgumentParser( + description="Perform group-by aggregation on CSV files" + ) + parser.add_argument( + "--group", + "-g", + help="list of columns to group by, separated by comma") + parser.add_argument( + "--import-module", + "-i", + help="module to import for the operation") + parser.add_argument( + "--type", + "-t", + default="float", + help="type of columns to aggregate (default: float)") + parser.add_argument( + "columns", + help="list of columns to perform aggregation on, separated by comma") + parser.add_argument( + "function", + help=("Python function that performs aggregation (e.g., 'sum' " + + "or 'lambda v: 1. * sum(v) / len(v)')")) + + return parser.parse_args() + + +def main(): + args = arguments() + + environment = dict() + + if args.import_module: + module = importlib.import_module(args.import_module) + environment[module.__name__] = module + + group = args.group.split(",") if args.group else [] + columns = args.columns.split(",") + function = eval(args.function, environment) + type = eval(args.type, environment) + + dump_as_csv( + process( + csv.DictReader(sys.stdin), + group, + columns, + function, + type + ) + ) + + +if __name__ == "__main__": + main() diff --git a/pool/shard002/Python/0026913_edittool.py b/pool/shard002/Python/0026913_edittool.py new file mode 100644 index 0000000000000000000000000000000000000000..236f7340ed04d662720adb72f1bbc4d980c177ab --- /dev/null +++ b/pool/shard002/Python/0026913_edittool.py @@ -0,0 +1,107 @@ +from PyQt4.QtCore import pyqtSignal +from PyQt4.QtGui import QCursor, QPixmap, QColor +from qgis.core import (QgsRectangle, QgsTolerance, + QgsFeatureRequest, QgsFeature, + QgsVectorLayer) +from qgis.gui import QgsMapTool, QgsRubberBand +from qmap.listfeatureform import ListFeaturesForm +from maptool import MapTool + +class EditTool(MapTool): + """ + Inspection tool which copies the feature to a new layer + and copies selected data from the underlying feature. + """ + + finished = pyqtSignal(QgsVectorLayer, QgsFeature) + + def __init__(self, canvas, layers, snapradius = 2): + MapTool.__init__(self, canvas, layers) + self.canvas = canvas + self.radius = snapradius + + self.band = QgsRubberBand(self.canvas) + self.band.setColor(QColor.fromRgb(224,162,16)) + self.band.setWidth(3) + + self.cursor = QCursor(QPixmap(["16 16 3 1", + " c None", + ". c #FF0000", + "+ c #FFFFFF", + " ", + " +.+ ", + " ++.++ ", + " +.....+ ", + " +. .+ ", + " +. . .+ ", + " +. . .+ ", + " ++. . .++", + " ... ...+... ...", + " ++. . .++", + " +. . .+ ", + " +. . .+ ", + " ++. .+ ", + " ++.....+ ", + " ++.++ ", + " +.+ "])) + + def getFeatures(self, point): + searchRadius = (QgsTolerance.toleranceInMapUnits( self.radius, self.layers[0], + self.canvas.mapRenderer(), + QgsTolerance.Pixels)) + point = self.toMapCoordinates(point) + + rect = QgsRectangle() + rect.setXMinimum(point.x() - searchRadius) + rect.setXMaximum(point.x() + searchRadius) + rect.setYMinimum(point.y() - searchRadius) + rect.setYMaximum(point.y() + searchRadius) + + rq = QgsFeatureRequest().setFilterRect(rect) + + self.band.reset() + for layer in self.layers: + rq = QgsFeatureRequest().setFilterRect(rect) + for feature in layer.getFeatures(rq): + if feature.isValid(): + yield feature, layer + + def canvasMoveEvent(self, event): + for feature, _ in self.getFeatures(point = event.pos()): + self.band.addGeometry(feature.geometry(), None) + + def canvasReleaseEvent(self, event): + features = list(self.getFeatures(point = event.pos())) + + if len(features) == 1: + feature = features[0] + self.finished.emit(feature[1], feature[0]) + elif len(features) > 0: + listUi = ListFeaturesForm() + listUi.loadFeatureList(features) + listUi.openFeatureForm.connect(self.finished) + listUi.exec_() + + def activate(self): + """ + Set the tool as the active tool in the canvas. + + @note: Should be moved out into qmap.py + and just expose a cursor to be used + """ + self.canvas.setCursor(self.cursor) + + def deactivate(self): + """ + Deactive the tool. + """ + pass + + def isZoomTool(self): + return False + + def isTransient(self): + return False + + def isEditTool(self): + return True \ No newline at end of file diff --git a/pool/shard002/Python/0026914_build_webkit.py b/pool/shard002/Python/0026914_build_webkit.py new file mode 100644 index 0000000000000000000000000000000000000000..e05f664b7a2bd002b804df04888bfdd40833153a --- /dev/null +++ b/pool/shard002/Python/0026914_build_webkit.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python +# Copyright 2019 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 argparse +import os +import subprocess +import sys + +def main(): + description = 'Invokes build-webkit with the given options.' + parser = argparse.ArgumentParser(description=description) + parser.add_argument('--output_dir', + help='Output directory for build products.') + parser.add_argument('--ios_simulator', action='store_true', default=False, + help='Use "iphoneos" SDK instead of "macos".') + parser.add_argument('--asan', action='store_true', default=False, + help='Make Asan build.') + parser.add_argument('--clean', action='store_true', default=False, + help='Clean output directory before building.') + parser.add_argument('--debug', action='store_true', default=False, + help='Make debug build.') + parser.add_argument('-j', + help='Number of parallel jobs to run.') + (opts, extra_args) = parser.parse_known_args() + + output_dir = opts.output_dir + if not output_dir: + # Use a default that matches what ninja uses. + platform_dir = 'iOS' if opts.ios_simulator else 'macOS' + output_dir = os.path.realpath(os.path.join( + os.path.dirname(__file__), + '../../..', + 'out', 'Debug-iphonesimulator', 'obj', + 'ios', 'third_party', 'webkit', platform_dir)); + + command = ['src/Tools/Scripts/build-webkit'] + + if opts.ios_simulator: + command.append('--ios-simulator') + + if opts.debug: + command.append('--debug') + + if opts.j: + command.extend(['-jobs', opts.j]) + command.extend(extra_args) + + env = { + 'WEBKIT_OUTPUTDIR': output_dir, + # Needed for /bin/mkdir, /usr/bin/copypng, and /usr/sbin/sysctl. + 'PATH': '/bin:/usr/bin:/usr/sbin', + } + cwd = os.path.dirname(os.path.realpath(__file__)) + + if opts.clean: + clean_command = ['src/Tools/Scripts/clean-webkit'] + proc = subprocess.Popen(clean_command, cwd=cwd, env=env) + proc.communicate() + + if opts.asan: + config_command = ['src/Tools/Scripts/set-webkit-configuration', '--asan'] + if opts.debug: + config_command.append('--debug') + proc = subprocess.Popen(config_command, cwd=cwd, env=env) + proc.communicate() + if proc.returncode: + return proc.returncode + + # Enable rewriting WK_API_AVAILABLE() -> API_AVAILABLE(). + if opts.ios_simulator: + command.append('WK_FRAMEWORK_HEADER_POSTPROCESSING_DISABLED=NO') + + proc = subprocess.Popen(command, cwd=cwd, env=env) + proc.communicate() + return proc.returncode + +if __name__ == '__main__': + sys.exit(main()) diff --git a/pool/shard002/Python/0026915_Hello_world.py b/pool/shard002/Python/0026915_Hello_world.py new file mode 100644 index 0000000000000000000000000000000000000000..ab7270e4d117c2195c809582caa56871b890a2d6 --- /dev/null +++ b/pool/shard002/Python/0026915_Hello_world.py @@ -0,0 +1,31 @@ +from tkinter import * + + +class Application(Frame): + def say_hi(self): + print("hi there, everyone!") + + def createWidgets(self): + self.QUIT = Button(self) + self.QUIT["text"] = "QUIT" + self.QUIT["fg"] = "red" + self.QUIT["command"] = self.quit + + self.QUIT.pack({"side": "left"}) + + self.hi_there = Button(self) + self.hi_there["text"] = "Hello", + self.hi_there["command"] = self.say_hi + + self.hi_there.pack({"side": "left"}) + + def __init__(self, master=None): + Frame.__init__(self, master) + self.pack() + self.createWidgets() + + +root = Tk() +app = Application(master=root) +app.mainloop() +root.destroy() diff --git a/pool/shard002/Python/0026918_genre_maker.py b/pool/shard002/Python/0026918_genre_maker.py new file mode 100644 index 0000000000000000000000000000000000000000..c5264a66222eddae4803586566a10409c2d576ac --- /dev/null +++ b/pool/shard002/Python/0026918_genre_maker.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +import os +from knowledge.reader import data + + +if __name__ == '__main__': + BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + save_file = os.path.join(BASE_DIR, 'words/genre.txt') + genre = [] + for dic in data.values(): + synonyms = list(dic.keys())[0].split(',') + genre.extend(synonyms) + + with open(save_file, 'w') as f: + f.write('\n'.join(set(genre))) \ No newline at end of file diff --git a/pool/shard002/Python/0026923_bn.py b/pool/shard002/Python/0026923_bn.py new file mode 100644 index 0000000000000000000000000000000000000000..15def96314443e9da909754a508a59e1635b93e0 --- /dev/null +++ b/pool/shard002/Python/0026923_bn.py @@ -0,0 +1,272 @@ +"""Implements the batch normalization training graph transform. + +Specifically, this module contains the implementation for the +transformation of a batch-normalized inference graph into training graph, +which uses minibatch statistics in place of population statistics. + +""" +import collections +import contextlib +from functools import partial + +import theano +from toolz import isdistinct + +from ..roles import BATCH_NORM_OFFSET, BATCH_NORM_DIVISOR, INPUT, OUTPUT +from ..utils import find_bricks + + +def _training_mode_application_calls(application_calls): + """Filter for application calls made in 'training mode'.""" + from ..bricks import BatchNormalization + out = [] + for app_call in application_calls: + assert isinstance(app_call.application.brick, BatchNormalization) + assert app_call.application.application == BatchNormalization.apply + if app_call.metadata.get('training_mode', False): + out.append(app_call) + return out + + +@contextlib.contextmanager +def batch_normalization(*bricks): + r"""Context manager to run batch normalization in "training mode". + + Parameters + ---------- + \*bricks + One or more bricks which will be inspected for descendant + instances of :class:`~blocks.bricks.BatchNormalization`. + + Notes + ----- + Graph replacement using :func:`apply_batch_normalization`, while + elegant, can lead to Theano graphs that are quite large and result + in very slow compiles. This provides an alternative mechanism for + building the batch normalized training graph. It can be somewhat + less convenient as it requires building the graph twice if one + wishes to monitor the output of the inference graph during training. + + Examples + -------- + First, we'll create a :class:`~blocks.bricks.BatchNormalizedMLP`. + + >>> import theano + >>> from blocks.bricks import BatchNormalizedMLP, Tanh + >>> from blocks.initialization import Constant, IsotropicGaussian + >>> mlp = BatchNormalizedMLP([Tanh(), Tanh()], [4, 5, 6], + ... weights_init=IsotropicGaussian(0.1), + ... biases_init=Constant(0)) + >>> mlp.initialize() + + Now, we'll construct an output variable as we would normally. This + is getting normalized by the *population* statistics, which by + default are initialized to 0 (mean) and 1 (standard deviation), + respectively. + + >>> x = theano.tensor.matrix() + >>> y = mlp.apply(x) + + And now, to construct an output with batch normalization enabled, + i.e. normalizing pre-activations using per-minibatch statistics, we + simply make a similar call inside of a `with` statement: + + >>> with batch_normalization(mlp): + ... y_bn = mlp.apply(x) + + Let's verify that these two graphs behave differently on the + same data: + + >>> import numpy + >>> data = numpy.arange(12, dtype=theano.config.floatX).reshape(3, 4) + >>> inf_y = y.eval({x: data}) + >>> trn_y = y_bn.eval({x: data}) + >>> numpy.allclose(inf_y, trn_y) + False + + """ + # Avoid circular imports. + from blocks.bricks import BatchNormalization + + bn = find_bricks(bricks, lambda b: isinstance(b, BatchNormalization)) + # Can't use either nested() (deprecated) nor ExitStack (not available + # on Python 2.7). Well, that sucks. + try: + for brick in bn: + brick.__enter__() + yield + finally: + for brick in bn[::-1]: + brick.__exit__() + + +def apply_batch_normalization(computation_graph): + """Transform a graph into a batch-normalized training graph. + + Parameters + ---------- + computation_graph : :class:`~blocks.graph.ComputationGraph` + The computation graph containing :class:`BatchNormalization` + brick applications. + + Returns + ------- + batch_normed_graph : :class:`~blocks.graph.ComputationGraph` + The computation graph, with :class:`BatchNormalization` + applications transformed to use minibatch statistics instead + of accumulated population statistics. + + See Also + -------- + :func:`batch_normalization`, for an alternative method to produce + batch normalized graphs. + + Examples + -------- + First, we'll create a :class:`~blocks.bricks.BatchNormalizedMLP`. + + >>> import theano + >>> from blocks.bricks import BatchNormalizedMLP, Tanh + >>> from blocks.initialization import Constant, IsotropicGaussian + >>> mlp = BatchNormalizedMLP([Tanh(), Tanh()], [4, 5, 6], + ... weights_init=IsotropicGaussian(0.1), + ... biases_init=Constant(0)) + >>> mlp.initialize() + + Now, we'll construct an output variable as we would normally. This + is getting normalized by the *population* statistics, which by + default are initialized to 0 (mean) and 1 (standard deviation), + respectively. + + >>> x = theano.tensor.matrix() + >>> y = mlp.apply(x) + + Finally, we'll create a :class:`~blocks.graph.ComputationGraph` + and transform it to switch to minibatch standardization: + + >>> from blocks.graph import ComputationGraph + >>> cg = apply_batch_normalization(ComputationGraph([y])) + >>> y_bn = cg.outputs[0] + + Let's verify that these two graphs behave differently on the + same data: + + >>> import numpy + >>> data = numpy.arange(12, dtype=theano.config.floatX).reshape(3, 4) + >>> inf_y = y.eval({x: data}) + >>> trn_y = y_bn.eval({x: data}) + >>> numpy.allclose(inf_y, trn_y) + False + + """ + # Avoid circular imports. + from blocks.bricks import BatchNormalization + from ..filter import VariableFilter, get_application_call + + # Create filters for variables involved in a batch normalization brick + # application. + def make_variable_filter(role): + return VariableFilter(bricks=[BatchNormalization], roles=[role]) + + # Group inputs and outputs into dicts indexed by application call. + def get_app_call_dict(variable_filter): + return collections.OrderedDict((get_application_call(v), v) for v in + variable_filter(computation_graph)) + + # Compose these two so that we get 4 dicts, grouped by application + # call, of different variable roles involved in BatchNormalization. + inputs, outputs, means, stdevs = map(get_app_call_dict, + map(make_variable_filter, + [INPUT, OUTPUT, BATCH_NORM_OFFSET, + BATCH_NORM_DIVISOR])) + + assert len(set([len(inputs), len(outputs), len(means), len(stdevs)])) == 1 + + # Remove any ApplicationCalls that were not generated by apply(), or + # were generated by an apply() while already in training mode. + app_calls = inputs.keys() + remove = _training_mode_application_calls(app_calls) + for app_call in app_calls: + if app_call in remove: + for mapping in (inputs, outputs, means, stdevs): + del mapping[app_call] + + replacements = [] + for app_call in inputs: + old_output = outputs[app_call] + # Get rid of the copy made on the way into the original apply. + op = inputs[app_call].owner.op + assert (isinstance(op, theano.tensor.Elemwise) and + isinstance(op.scalar_op, theano.scalar.basic.Identity)) + unpacked = inputs[app_call].owner.inputs[0] + with app_call.application.brick: + new_output = app_call.application.brick.apply(unpacked) + new_app_call = get_application_call(new_output) + assert new_app_call.metadata['training_mode'] + replacements.append((old_output, new_output)) + return computation_graph.replace(replacements) + + +def get_batch_normalization_updates(training_graph, allow_duplicates=False): + """Extract correspondences for learning BN population statistics. + + Parameters + ---------- + training_graph : :class:`~blocks.graph.ComputationGraph` + A graph of expressions wherein "training mode" batch normalization + is taking place. + allow_duplicates : bool, optional + If `True`, allow multiple training-mode application calls from the + same :class:`~blocks.bricks.BatchNormalization` instance, and + return pairs corresponding to all of them. It's then the user's + responsibility to do something sensible to resolve the duplicates. + + Returns + ------- + update_pairs : list of tuples + A list of 2-tuples where the first element of each tuple is the + shared variable containing a "population" mean or standard + deviation, and the second is a Theano variable for the + corresponding statistics on a minibatch. Note that multiple + applications of a single :class:`blocks.bricks.BatchNormalization` + may appear in the graph, and therefore (if `allow_duplicates` is + True) a single population variable may map to several different + minibatch variables, and appear multiple times in this mapping. + This can happen in recurrent models, siamese networks or other + models that reuse pathways. + + Notes + ----- + Used in their raw form, these updates will simply overwrite the + population statistics with the minibatch statistics at every gradient + step. You will probably want to transform these pairs into something + more sensible, such as keeping a moving average of minibatch values, + or accumulating an average over the entire training set once every few + epochs. + + """ + from ..bricks import BatchNormalization + from ..filter import VariableFilter, get_application_call + var_filter = VariableFilter(bricks=[BatchNormalization], roles=[OUTPUT]) + all_app_calls = map(get_application_call, var_filter(training_graph)) + train_app_calls = _training_mode_application_calls(all_app_calls) + if len(train_app_calls) == 0: + raise ValueError("no training mode BatchNormalization " + "applications found in graph") + bricks = [c.application.brick for c in train_app_calls] + + if not allow_duplicates and not isdistinct(bricks): + raise ValueError('multiple applications of the same ' + 'BatchNormalization brick; pass allow_duplicates ' + '= True to override this check') + + def extract_pair(brick_attribute, metadata_key, app_call): + return (getattr(app_call.application.brick, brick_attribute), + app_call.metadata[metadata_key]) + + mean_pair = partial(extract_pair, 'population_mean', 'offset') + stdev_pair = partial(extract_pair, 'population_stdev', 'divisor') + return sum([[mean_pair(a), stdev_pair(a)] + if not a.application.brick.mean_only + else [mean_pair(a)] + for a in train_app_calls], []) diff --git a/pool/shard002/Python/0026939_generic_ops.py b/pool/shard002/Python/0026939_generic_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..6b7cb369e021fae4833f609d6748040266bcae9a --- /dev/null +++ b/pool/shard002/Python/0026939_generic_ops.py @@ -0,0 +1,16 @@ +import numpy as np +from . import Differentiable + +class Blank(Differentiable): + # Creates a custom kayak node on-the-fly with compute_grad and/or local_grad + # functions passed in as arguments + def __init__(self, args=[], compute_value=None, local_grad=None): + super(Blank, self).__init__(args) + self.compute_value_fun = compute_value + self.local_grad_fun = local_grad + + def _compute_value(self): + return self.compute_value_fun(self._parents) + + def _local_grad(self, parent, d_out_d_self): + return self.local_grad_fun(self._parents, parent, d_out_d_self) diff --git a/pool/shard002/Python/0026940_t_solution_array.py b/pool/shard002/Python/0026940_t_solution_array.py new file mode 100644 index 0000000000000000000000000000000000000000..7304bc571caaf86fb41fe7698172dbab0014404d --- /dev/null +++ b/pool/shard002/Python/0026940_t_solution_array.py @@ -0,0 +1,126 @@ +"""Tests for SolutionArray class""" +import unittest +import numpy as np +from gpkit import Variable, VectorVariable, Model, SignomialsEnabled +import gpkit +from gpkit.solution_array import var_table +from gpkit.varkey import VarKey +from gpkit.small_classes import Strings, Quantity + + +class TestSolutionArray(unittest.TestCase): + """Unit tests for the SolutionArray class""" + + def test_call(self): + A = Variable('A', '-', 'Test Variable') + prob = Model(A, [A >= 1]) + sol = prob.solve(verbosity=0) + self.assertAlmostEqual(sol(A), 1.0, 8) + + def test_call_units(self): + # test from issue541 + x = Variable("x", 10, "ft") + y = Variable("y", "m") + m = Model(y, [y >= x]) + sol = m.solve(verbosity=0) + self.assertAlmostEqual(sol("y")/sol("x"), 1.0, 6) + self.assertAlmostEqual(sol(x)/sol(y), 1.0, 6) + + def test_call_vector(self): + n = 5 + x = VectorVariable(n, 'x') + prob = Model(sum(x), [x >= 2.5]) + sol = prob.solve(verbosity=0) + solx = sol(x) + self.assertEqual(type(solx), Quantity) + self.assertEqual(type(sol["variables"][x]), np.ndarray) + self.assertEqual(solx.shape, (n,)) + for i in range(n): + self.assertAlmostEqual(solx[i], 2.5, places=4) + + def test_subinto(self): + Nsweep = 20 + Pvals = np.linspace(13, 24, Nsweep) + H_max = Variable("H_max", 10, "m", "Length") + A_min = Variable("A_min", 10, "m^2", "Area") + P_max = Variable("P", Pvals, "m", "Perimeter") + H = Variable("H", "m", "Length") + W = Variable("W", "m", "Width") + m = Model(12/(W*H**3), + [H <= H_max, + H*W >= A_min, + P_max >= 2*H + 2*W]) + sol = m.solve(verbosity=0) + Psol = sol.subinto(P_max) + self.assertEqual(len(Psol), Nsweep) + self.assertAlmostEqual(0*gpkit.ureg.m, + np.max(np.abs(Pvals*gpkit.ureg.m - Psol))) + self.assertAlmostEqual(0*gpkit.ureg.m, + np.max(np.abs(Psol - sol(P_max)))) + + def test_table(self): + x = Variable('x') + gp = Model(x, [x >= 12]) + sol = gp.solve(verbosity=0) + tab = sol.table() + self.assertTrue(isinstance(tab, Strings)) + + def test_units_sub(self): + # issue 809 + T = Variable("T", "N", "thrust") + Tmin = Variable("T_{min}", "N", "minimum thrust") + m = Model(T, [T >= Tmin]) + tminsub = 1000 * gpkit.ureg.lbf + m.substitutions.update({Tmin: tminsub}) + sol = m.solve(verbosity=0) + self.assertAlmostEqual(sol(Tmin), tminsub) + self.assertFalse( + "1000N" in + sol.table().replace(" ", "").replace("[", "").replace("]", "")) + + def test_key_options(self): + # issue 993 + x = Variable("x") + y = Variable("y") + with SignomialsEnabled(): + m = Model(y, [y + 6*x >= 13 + x**2]) + msol = m.localsolve(verbosity=0) + spsol = m.sp().localsolve(verbosity=0) # pylint: disable=no-member + gpsol = m.program.gps[-1].solve(verbosity=0) + self.assertEqual(msol(x), msol("x")) + self.assertEqual(spsol(x), spsol("x")) + self.assertEqual(gpsol(x), gpsol("x")) + self.assertEqual(msol(x), spsol(x)) + self.assertEqual(msol(x), gpsol(x)) + + +class TestResultsTable(unittest.TestCase): + """TestCase for var_table()""" + + def test_nan_printing(self): + """Test that solution prints when it contains nans""" + x = VarKey(name='x') + data = {x: np.array([np.nan, 1, 1, 1, 1])} + title = "Free variables" + printstr = "\n".join(var_table(data, title)) + self.assertTrue(" - " in printstr) # nan is printed as " - " + self.assertTrue(title in printstr) + + def test_result_access(self): + x = Variable("x") + y = Variable("y") + with SignomialsEnabled(): + sig = (y + 6*x >= 13 + x**2) + m = Model(y, [sig]) + sol = m.localsolve(verbosity=0) + self.assertTrue(all([isinstance(gp.result.table(), Strings) + for gp in m.program.gps])) + self.assertAlmostEqual(sol["cost"]/4.0, 1.0, 5) + self.assertAlmostEqual(sol("x")/3.0, 1.0, 3) + +TESTS = [TestSolutionArray, TestResultsTable] + +if __name__ == "__main__": # pragma: no cover + # pylint: disable=wrong-import-position + from gpkit.tests.helpers import run_tests + run_tests(TESTS) diff --git a/pool/shard002/Python/0026946_config.py b/pool/shard002/Python/0026946_config.py new file mode 100644 index 0000000000000000000000000000000000000000..cd100c830433e62f8c1ba9402299f68acf2b4319 --- /dev/null +++ b/pool/shard002/Python/0026946_config.py @@ -0,0 +1,165 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +''' +@date: 2016-08-25 +@author: Heysion Yuan +@copyright: 2016, Heysion Yuan +@license: GPLv3 +''' +import os.path +import sys +import argparse + +from ConfigParser import ConfigParser +from error import ConfigError + + +def str2bool(r): + return r == "True" + +def str2int(r): + return int(r) + +class DaemonConfig(object): + def __new__(cls,*args,**kw): + if not hasattr(cls,"_instance"): + orig = super(DaemonConfig, cls) + cls._instace = orig.__new__(cls, *args, **kw) + return cls._instace + + def update_options(self,dabargs): + """process options from command line and config file""" + parser = argparse.ArgumentParser("[option]",description="daemon options from command line and config file") + parser.add_argument("-c", "--config", dest="config", + help="use alternate configuration file", metavar="FILE", + default="/etc/dab/daemon.conf") + + parser.add_argument("-p","--pid", dest="pidfile", + help="run pid file") + + parser.add_argument("-l","--log", dest="logfile", + help="daemon log file") + + parser.add_argument("-v", "--verbose", action="store_true", default=False, + help="show verbose output") + + parser.add_argument("-d", "--debug", dest="debug", action="store_true", + help="show debug output",default=False) + + + parser.add_argument("--fg", dest="foreground", + action="store_true", default=False, + help="run in foreground") + parser.add_argument("--forcelock", dest="forcelock", + action="store_true", default=False, + help="force lock for exclusive session") + + parser.add_argument("--appname", help="specify appname") + parser.add_argument("--username", help="specify user") + parser.add_argument("--password", help="specify password") + + parser.add_argument("--maxjobs", type=int, help="Specify maxjobs") + parser.add_argument("--sleeptime", type=int, help="Specify the polling interval") + parser.add_argument("--server", help="url for server api") + parser.add_argument("--topurl", help="Specify topurl") + + parser.add_argument("--topdir", help="Specify topdir") + parser.add_argument("--workdir", help="Specify workdir") + parser.add_argument("--arches", help="Specify arches") + + + options = parser.parse_args(args=dabargs) + # load config + if options.config: + if os.path.exists(options.config): + self.config = options.config + else: + raise ConfigError("not found config %s"%(config)) + self.confp = ConfigParser() + self.confp.read(self.config) + if not self.confp.has_section("daemon"): + raise ConfigError("not found service section") + + for key ,value in self.confp.items("daemon"): + if not getattr(self, key, None): + setattr(self, key, value) + #merge options to config + opt_list = vars(options) + for key in opt_list.keys(): + if opt_list[key]: + setattr(self, key, opt_list[key]) + if not isinstance(self.maxjobs, int): + self.maxjobs = int(self.maxjobs) + if not isinstance(self.sleeptime, int): + self.sleeptime = int(self.sleeptime) + if not isinstance(self.debug, bool): + self.debug = str2bool(self.debug) + if not isinstance(self.foreground, bool): + self.foreground = str2bool(self.foreground) + if not isinstance(self.forcelock, bool): + self.forcelock = str2bool(self.forcelock) + if not isinstance(self.verbose, bool): + self.verbose = str2bool(self.verbose) + +class DabsvConfig(object): + def __new__(cls,*args,**kw): + if not hasattr(cls,"_instance"): + orig = super(DabsvConfig, cls) + cls._instace = orig.__new__(cls, *args, **kw) + return cls._instace + + def update_options(self,dabargs): + """process options from command line and config file""" + parser = argparse.ArgumentParser("[option]",description="service options from command line and config file") + parser.add_argument("-c", "--config", dest="config", + help="use alternate configuration file", metavar="FILE", + default="/etc/dab/dabsv.conf") + + parser.add_argument("-d", "--debug", dest="debug", action="store_true", + help="show debug output", + default=False) + + parser.add_argument("--dbtype", help="database type") + parser.add_argument("--dbhost", help="database host ip") + parser.add_argument("--dbport", help="database host port",type=int) + parser.add_argument("--dbuname", help="database username") + parser.add_argument("--dbpasswd", help="database password") + + options = parser.parse_args(args=dabargs) + # load config + if options.config: + if os.path.exists(options.config): + self.config = options.config + else: + raise ConfigError("not found config %s"%(config)) + self.confp = ConfigParser() + self.confp.read(self.config) + if not self.confp.has_section("service"): + raise ConfigError("not found service section") + + for key ,value in self.confp.items("service"): + if not getattr(self, key, None): + setattr(self, key, value) + #merge options to config + opt_list = vars(options) + for key in opt_list.keys(): + if opt_list[key]: + setattr(self, key, opt_list[key]) + if not isinstance(self.dbport, int): + self.dbport = int(self.dbport) + if not isinstance(self.debug, bool): + self.debug = str2bool(self.debug) + # if options.debug: + # self.debug = options.debug + # if options.dbtype.lower() in "sqlite": + # pass + pass + +if __name__ == "__main__": + opt = DaemonConfig() + #print sys.argv + opt.update_options(sys.argv[1:]) + print(opt.__dict__) + + + diff --git a/pool/shard002/Python/0026948_test_utils.py b/pool/shard002/Python/0026948_test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f30b1ff294a939e5ed72b8809c853cbe348acfd7 --- /dev/null +++ b/pool/shard002/Python/0026948_test_utils.py @@ -0,0 +1,113 @@ +import sys +import click + + +def test_echo(runner): + with runner.isolation() as out: + click.echo(u'\N{SNOWMAN}') + click.echo(b'\x44\x44') + click.echo(42, nl=False) + click.echo(b'a', nl=False) + click.echo('\x1b[31mx\x1b[39m', nl=False) + bytes = out.getvalue() + assert bytes == b'\xe2\x98\x83\nDD\n42ax' + + # If we are in Python 2, we expect that writing bytes into a string io + # does not do anything crazy. In Python 3 + if sys.version_info[0] == 2: + import StringIO + sys.stdout = x = StringIO.StringIO() + try: + click.echo('\xf6') + finally: + sys.stdout = sys.__stdout__ + assert x.getvalue() == '\xf6\n' + + # And in any case, if wrapped, we expect bytes to survive. + @click.command() + def cli(): + click.echo(b'\xf6') + result = runner.invoke(cli, []) + assert result.output_bytes == b'\xf6\n' + + # Ensure we do not strip for bytes. + with runner.isolation() as out: + click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False) + assert out.getvalue() == b'\x1b[31mx\x1b[39m' + + +def test_styling(): + examples = [ + ('x', dict(fg='black'), '\x1b[30mx\x1b[0m'), + ('x', dict(fg='red'), '\x1b[31mx\x1b[0m'), + ('x', dict(fg='green'), '\x1b[32mx\x1b[0m'), + ('x', dict(fg='yellow'), '\x1b[33mx\x1b[0m'), + ('x', dict(fg='blue'), '\x1b[34mx\x1b[0m'), + ('x', dict(fg='magenta'), '\x1b[35mx\x1b[0m'), + ('x', dict(fg='cyan'), '\x1b[36mx\x1b[0m'), + ('x', dict(fg='white'), '\x1b[37mx\x1b[0m'), + ('x', dict(bg='black'), '\x1b[40mx\x1b[0m'), + ('x', dict(bg='red'), '\x1b[41mx\x1b[0m'), + ('x', dict(bg='green'), '\x1b[42mx\x1b[0m'), + ('x', dict(bg='yellow'), '\x1b[43mx\x1b[0m'), + ('x', dict(bg='blue'), '\x1b[44mx\x1b[0m'), + ('x', dict(bg='magenta'), '\x1b[45mx\x1b[0m'), + ('x', dict(bg='cyan'), '\x1b[46mx\x1b[0m'), + ('x', dict(bg='white'), '\x1b[47mx\x1b[0m'), + ('foo bar', dict(blink=True), '\x1b[5mfoo bar\x1b[0m'), + ('foo bar', dict(underline=True), '\x1b[4mfoo bar\x1b[0m'), + ('foo bar', dict(bold=True), '\x1b[1mfoo bar\x1b[0m'), + ('foo bar', dict(dim=True), '\x1b[2mfoo bar\x1b[0m'), + ] + for text, styles, ref in examples: + assert click.style(text, **styles) == ref + assert click.unstyle(ref) == text + + +def test_filename_formatting(): + assert click.format_filename(b'foo.txt') == 'foo.txt' + assert click.format_filename(b'/x/foo.txt') == '/x/foo.txt' + assert click.format_filename(u'/x/foo.txt') == '/x/foo.txt' + assert click.format_filename(u'/x/foo.txt', shorten=True) == 'foo.txt' + assert click.format_filename(b'/x/foo\xff.txt', shorten=True) \ + == u'foo\ufffd.txt' + + +def test_prompts(runner): + @click.command() + def test(): + if click.confirm('Foo'): + click.echo('yes!') + else: + click.echo('no :(') + + result = runner.invoke(test, input='y\n') + assert not result.exception + assert result.output == 'Foo [y/N]: y\nyes!\n' + + result = runner.invoke(test, input='\n') + assert not result.exception + assert result.output == 'Foo [y/N]: \nno :(\n' + + result = runner.invoke(test, input='n\n') + assert not result.exception + assert result.output == 'Foo [y/N]: n\nno :(\n' + + @click.command() + def test_no(): + if click.confirm('Foo', default=True): + click.echo('yes!') + else: + click.echo('no :(') + + result = runner.invoke(test_no, input='y\n') + assert not result.exception + assert result.output == 'Foo [Y/n]: y\nyes!\n' + + result = runner.invoke(test_no, input='\n') + assert not result.exception + assert result.output == 'Foo [Y/n]: \nyes!\n' + + result = runner.invoke(test_no, input='n\n') + assert not result.exception + assert result.output == 'Foo [Y/n]: n\nno :(\n' diff --git a/pool/shard002/Python/0026951_pnacl-strip.py b/pool/shard002/Python/0026951_pnacl-strip.py new file mode 100644 index 0000000000000000000000000000000000000000..94aa53d2424098946ab490531de82528ed71860a --- /dev/null +++ b/pool/shard002/Python/0026951_pnacl-strip.py @@ -0,0 +1,72 @@ +#!/usr/bin/python +# Copyright (c) 2012 The Native Client Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +# +# IMPORTANT NOTE: If you make local mods to this file, you must run: +# % pnacl/build.sh driver +# in order for them to take effect in the scons build. This command +# updates the copy in the toolchain/ tree. +# + +import driver_tools +import pathtools +from driver_env import env +from driver_log import Log + +EXTRA_ENV = { + 'INPUTS' : '', + 'OUTPUT' : '', + 'MODE' : 'all', + 'DO_WRAP' : '1', + + 'OPT_FLAGS_all' : '-disable-opt --strip', + 'OPT_FLAGS_debug' : '-disable-opt --strip-debug', + 'STRIP_FLAGS_all' : '-s', + 'STRIP_FLAGS_debug' : '-S', + + 'OPT_FLAGS' : '${OPT_FLAGS_%MODE%}', + 'STRIP_FLAGS' : '${STRIP_FLAGS_%MODE%}', + + 'RUN_OPT' : '${LLVM_OPT} ${OPT_FLAGS} ${input} -o ${output}', + 'RUN_STRIP' : '${STRIP} ${STRIP_FLAGS} ${input} -o ${output}', +} + +StripPatterns = [ + ( ('-o','(.*)'), "env.set('OUTPUT', pathtools.normalize($0))"), + ( ('-o','(.*)'), "env.set('OUTPUT', pathtools.normalize($0))"), + ( '--strip-all', "env.set('MODE', 'all')"), + ( '-s', "env.set('MODE', 'all')"), + + ( '--do-not-wrap', "env.set('DO_WRAP', '0')"), + + ( '--strip-debug', "env.set('MODE', 'debug')"), + ( '-S', "env.set('MODE', 'debug')"), + ( '(-.*)', driver_tools.UnrecognizedOption), + + ( '(.*)', "env.append('INPUTS', pathtools.normalize($0))"), +] + +def main(argv): + env.update(EXTRA_ENV) + driver_tools.ParseArgs(argv, StripPatterns) + inputs = env.get('INPUTS') + output = env.getone('OUTPUT') + + if len(inputs) > 1 and output != '': + Log.Fatal('Cannot have -o with multiple inputs') + + for f in inputs: + if output != '': + f_output = output + else: + f_output = f + if driver_tools.IsBitcode(f): + driver_tools.RunWithEnv('${RUN_OPT}', input=f, output=f_output) + if env.getbool('DO_WRAP'): + driver_tools.WrapBitcode(f_output) + elif driver_tools.IsELF(f): + driver_tools.RunWithEnv('${RUN_STRIP}', input=f, output=f_output) + else: + Log.Fatal('%s: File is neither ELF nor bitcode', pathtools.touser(f)) + return 0 diff --git a/pool/shard002/Python/0026955_compat_tests.py b/pool/shard002/Python/0026955_compat_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..97157c9d849ee5c3e143148a81f4948779ee6d54 --- /dev/null +++ b/pool/shard002/Python/0026955_compat_tests.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +import datetime +from six.moves import cStringIO + +from django.test import TestCase + +from oscar.core.compat import UnicodeCSVWriter + + +class TestUnicodeCSVWriter(TestCase): + + def test_can_write_different_values(self): + writer = UnicodeCSVWriter(open_file=cStringIO()) + s = u'ünįcodē' + class unicodeobj(object): + def __str__(self): + return s + def __unicode__(self): + return s + rows = [[s, unicodeobj(), 123, datetime.date.today()], ] + writer.writerows(rows) + self.assertRaises(TypeError, writer.writerows, [object()]) diff --git a/pool/shard002/Python/0026967_dpad.py b/pool/shard002/Python/0026967_dpad.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d7188cf1ac691731f23124090735d8b12decfe --- /dev/null +++ b/pool/shard002/Python/0026967_dpad.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +"""dpad.py: Directional pad.""" + +import math + +from kivy.clock import Clock +from kivy.graphics import Color, Rectangle +from kivy.uix.widget import Widget + +__author__ = "Victor RENÉ" +__copyright__ = "Copyright 2014, Kivy widget library" +__license__ = "MIT" +__version__ = "1.0" +__maintainer__ = "Victor RENÉ" +__email__ = "victor-rene.dev@outlook.com" +__status__ = "Production" + + +class Dpad(Widget): + + def __init__(self, **kw): + super(Dpad, self).__init__(**kw) + self.listeners = [] + self.thresholds = [(.3, .5), (.7, 1)] + self.input = [0, 0] + self.last_touch = None + with self.canvas.before: + Color(1, 1, 1, 1) + self.rect = Rectangle(pos=self.pos, size=self.size, source='img/dpad.png') + self.bind(pos=self._update_rect) + self.bind(size=self._update_rect) + self.polling = kw['polling'] if 'polling' in kw else .01 + Clock.schedule_interval(self.send_input, self.polling) + + def _update_rect(self, *args): + self.rect.pos = self.pos + self.rect.size = self.size + + def on_touch_down(self, touch): + self.handle_touch(touch) + + def on_touch_move(self, touch): + self.handle_touch(touch) + + def handle_touch(self, touch): + if self.collide_point(touch.x, touch.y): + self.last_touch = touch + dx = (touch.x - self.x - self.width / 2) / self.width * 2 + dy = (touch.y - self.y - self.height / 2) / self.height * 2 + dist = math.sqrt(dx * dx + dy * dy) + angle = math.atan2(dy, dx) + self.input = [0, 0] + for t in self.thresholds: + if dist > t[0]: + self.input[0] = t[1] * math.cos(angle) + self.input[1] = t[1] * math.sin(angle) + + def on_touch_up(self, touch): + if self.last_touch == touch: + self.input = [0, 0] + + def notify(self, event_name, *args, **kw): + for listener in self.listeners: + if event_name in listener.handlers: + getattr(listener, event_name)(*args, **kw) + + def send_input(self, dt): + self.notify('dpad_input', input=self.input) \ No newline at end of file diff --git a/pool/shard002/Python/0026970_sarsatilestorage.py b/pool/shard002/Python/0026970_sarsatilestorage.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb5a834f38b921b170301de63be7325861320c4 --- /dev/null +++ b/pool/shard002/Python/0026970_sarsatilestorage.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +""" +File that stores the learning results + +@author: Felipe Leno +""" + +from sarsatile import SARSATile +class SARSATileStorage(SARSATile): + + storagePath = None + visitTable = None + qTableFile = 'QTable.txt' + visitFile = 'VisitTable.txt' + + def __init__(self, epsilon=0.1, alpha=0.1, gamma=0.9, decayRate=0.9, seed=12345, port=12345, + lowerBoundVariables=-1, upperBoundVariables=+1, tilesNumber=10,tileWidth=0.5,serverPath = "/home/leno/HFO/bin/", + storagePath="agentData/"): + super(SARSATileStorage, self).__init__(epsilon=epsilon, alpha=alpha, gamma=gamma, + decayRate=decayRate,seed=seed, port=port, serverPath=serverPath) + self.storagePath = storagePath + self.visitTable = {} + + def finish_training(self): + fileToWrite = self.storagePath + self.qTableFile + + import cPickle + #Stores the Q-table for posterior reuse + with open(fileToWrite,"wb") as qFile: + cPickle.dump(self.qTable, qFile) + #Stores number of visits per state + fileToWrite = self.storagePath + self.visitFile + with open(fileToWrite,"wb") as qFile: + cPickle.dump(self.visitTable, qFile) + + + def step(self, state, action): + """Modifies the default step action just to include a state visit counter""" + if self.exploring: + processedState = self.quantize_features(state) + self.visitTable[processedState] = self.visitTable.get(processedState,0.0) + 1 + return super(SARSATileStorage, self).step(state,action) diff --git a/pool/shard002/Python/0026973_helpers.py b/pool/shard002/Python/0026973_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ad36fb4e339760f9a68471dce44b6886c3a0e4af --- /dev/null +++ b/pool/shard002/Python/0026973_helpers.py @@ -0,0 +1,149 @@ +"""Helpers to deal with Cast devices.""" +from __future__ import annotations + +from typing import Optional + +import attr +from pychromecast import dial +from pychromecast.const import CAST_TYPE_GROUP +from pychromecast.models import CastInfo + + +@attr.s(slots=True, frozen=True) +class ChromecastInfo: + """Class to hold all data about a chromecast for creating connections. + + This also has the same attributes as the mDNS fields by zeroconf. + """ + + cast_info: CastInfo = attr.ib() + is_dynamic_group = attr.ib(type=Optional[bool], default=None) + + @property + def friendly_name(self) -> str: + """Return the UUID.""" + return self.cast_info.friendly_name + + @property + def is_audio_group(self) -> bool: + """Return if the cast is an audio group.""" + return self.cast_info.cast_type == CAST_TYPE_GROUP + + @property + def uuid(self) -> bool: + """Return the UUID.""" + return self.cast_info.uuid + + def fill_out_missing_chromecast_info(self) -> ChromecastInfo: + """Return a new ChromecastInfo object with missing attributes filled in. + + Uses blocking HTTP / HTTPS. + """ + if not self.is_audio_group or self.is_dynamic_group is not None: + # We have all information, no need to check HTTP API. + return self + + # Fill out missing group information via HTTP API. + is_dynamic_group = False + http_group_status = None + http_group_status = dial.get_multizone_status( + None, + services=self.cast_info.services, + zconf=ChromeCastZeroconf.get_zeroconf(), + ) + if http_group_status is not None: + is_dynamic_group = any( + g.uuid == self.cast_info.uuid for g in http_group_status.dynamic_groups + ) + + return ChromecastInfo( + cast_info=self.cast_info, + is_dynamic_group=is_dynamic_group, + ) + + +class ChromeCastZeroconf: + """Class to hold a zeroconf instance.""" + + __zconf = None + + @classmethod + def set_zeroconf(cls, zconf): + """Set zeroconf.""" + cls.__zconf = zconf + + @classmethod + def get_zeroconf(cls): + """Get zeroconf.""" + return cls.__zconf + + +class CastStatusListener: + """Helper class to handle pychromecast status callbacks. + + Necessary because a CastDevice entity or dynamic group can create a new + socket client and therefore callbacks from multiple chromecast connections can + potentially arrive. This class allows invalidating past chromecast objects. + """ + + def __init__(self, cast_device, chromecast, mz_mgr, mz_only=False): + """Initialize the status listener.""" + self._cast_device = cast_device + self._uuid = chromecast.uuid + self._valid = True + self._mz_mgr = mz_mgr + + if cast_device._cast_info.is_audio_group: + self._mz_mgr.add_multizone(chromecast) + if mz_only: + return + + chromecast.register_status_listener(self) + chromecast.socket_client.media_controller.register_status_listener(self) + chromecast.register_connection_listener(self) + if not cast_device._cast_info.is_audio_group: + self._mz_mgr.register_listener(chromecast.uuid, self) + + def new_cast_status(self, cast_status): + """Handle reception of a new CastStatus.""" + if self._valid: + self._cast_device.new_cast_status(cast_status) + + def new_media_status(self, media_status): + """Handle reception of a new MediaStatus.""" + if self._valid: + self._cast_device.new_media_status(media_status) + + def new_connection_status(self, connection_status): + """Handle reception of a new ConnectionStatus.""" + if self._valid: + self._cast_device.new_connection_status(connection_status) + + @staticmethod + def added_to_multizone(group_uuid): + """Handle the cast added to a group.""" + + def removed_from_multizone(self, group_uuid): + """Handle the cast removed from a group.""" + if self._valid: + self._cast_device.multizone_new_media_status(group_uuid, None) + + def multizone_new_cast_status(self, group_uuid, cast_status): + """Handle reception of a new CastStatus for a group.""" + + def multizone_new_media_status(self, group_uuid, media_status): + """Handle reception of a new MediaStatus for a group.""" + if self._valid: + self._cast_device.multizone_new_media_status(group_uuid, media_status) + + def invalidate(self): + """Invalidate this status listener. + + All following callbacks won't be forwarded. + """ + # pylint: disable=protected-access + if self._cast_device._cast_info.is_audio_group: + self._mz_mgr.remove_multizone(self._uuid) + else: + self._mz_mgr.deregister_listener(self._uuid, self) + self._valid = False diff --git a/pool/shard002/Python/0026975_test_player.py b/pool/shard002/Python/0026975_test_player.py new file mode 100644 index 0000000000000000000000000000000000000000..6115b92c22e4e57b7b1f24a71561812a6aa8e045 --- /dev/null +++ b/pool/shard002/Python/0026975_test_player.py @@ -0,0 +1,70 @@ +# This file is part of beets. +# Copyright 2015, Adrian Sampson. +# +# 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. + +"""Tests for BPD and music playing. +""" +from __future__ import (division, absolute_import, print_function, + unicode_literals) + +from test._common import unittest +from beetsplug import bpd + + +class CommandParseTest(unittest.TestCase): + def test_no_args(self): + s = r'command' + c = bpd.Command(s) + self.assertEqual(c.name, u'command') + self.assertEqual(c.args, []) + + def test_one_unquoted_arg(self): + s = r'command hello' + c = bpd.Command(s) + self.assertEqual(c.name, u'command') + self.assertEqual(c.args, [u'hello']) + + def test_two_unquoted_args(self): + s = r'command hello there' + c = bpd.Command(s) + self.assertEqual(c.name, u'command') + self.assertEqual(c.args, [u'hello', u'there']) + + def test_one_quoted_arg(self): + s = r'command "hello there"' + c = bpd.Command(s) + self.assertEqual(c.name, u'command') + self.assertEqual(c.args, [u'hello there']) + + def test_heterogenous_args(self): + s = r'command "hello there" sir' + c = bpd.Command(s) + self.assertEqual(c.name, u'command') + self.assertEqual(c.args, [u'hello there', u'sir']) + + def test_quote_in_arg(self): + s = r'command "hello \" there"' + c = bpd.Command(s) + self.assertEqual(c.args, [u'hello " there']) + + def test_backslash_in_arg(self): + s = r'command "hello \\ there"' + c = bpd.Command(s) + self.assertEqual(c.args, [u'hello \ there']) + + +def suite(): + return unittest.TestLoader().loadTestsFromName(__name__) + +if __name__ == b'__main__': + unittest.main(defaultTest='suite') diff --git a/pool/shard002/Python/0026980_commands.py b/pool/shard002/Python/0026980_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..8a0173e2bb85d4d46776a4cf0b6cc909ab4b3f36 --- /dev/null +++ b/pool/shard002/Python/0026980_commands.py @@ -0,0 +1,157 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# Copyright 2012, Nachi Ueno, NTT MCL, Inc. +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from cliff import lister +from neutronclient.common import utils +from neutronclient.neutron import v2_0 as client +from neutronclient.neutron.v2_0 import port + +from neutron.openstack.common import log as logging + + +class ProbeCommand(client.NeutronCommand): + log = logging.getLogger(__name__ + '.ProbeCommand') + + def get_debug_agent(self): + return self.app.debug_agent + + def run(self, parsed_args): + self.log.debug('run(%s)', parsed_args) + self.log.info(_('Unimplemented commands')) + + +class CreateProbe(ProbeCommand): + """Create probe port and interface, then plug it in.""" + + log = logging.getLogger(__name__ + '.CreateProbe') + + def get_parser(self, prog_name): + parser = super(CreateProbe, self).get_parser(prog_name) + parser.add_argument( + 'id', metavar='network_id', + help=_('ID of network to probe')) + parser.add_argument( + '--device-owner', + default='network', choices=['network', 'compute'], + help=_('Owner type of the device: network/compute')) + return parser + + def run(self, parsed_args): + self.log.debug('run(%s)' % parsed_args) + debug_agent = self.get_debug_agent() + probe_port = debug_agent.create_probe(parsed_args.id, + parsed_args.device_owner) + self.log.info(_('Probe created : %s '), probe_port.id) + + +class DeleteProbe(ProbeCommand): + """Delete probe - delete port then uplug.""" + + log = logging.getLogger(__name__ + '.DeleteProbe') + + def get_parser(self, prog_name): + parser = super(DeleteProbe, self).get_parser(prog_name) + parser.add_argument( + 'id', metavar='port_id', + help=_('ID of probe port to delete')) + return parser + + def run(self, parsed_args): + self.log.debug('run(%s)' % parsed_args) + debug_agent = self.get_debug_agent() + debug_agent.delete_probe(parsed_args.id) + self.log.info(_('Probe %s deleted'), parsed_args.id) + + +class ListProbe(client.NeutronCommand, lister.Lister): + """List probes.""" + + log = logging.getLogger(__name__ + '.ListProbe') + _formatters = {'fixed_ips': port._format_fixed_ips, } + + def get_debug_agent(self): + return self.app.debug_agent + + def get_data(self, parsed_args): + + debug_agent = self.get_debug_agent() + info = debug_agent.list_probes() + columns = len(info) > 0 and sorted(info[0].keys()) or [] + return (columns, (utils.get_item_properties( + s, columns, formatters=self._formatters, ) + for s in info), ) + + +class ClearProbe(ProbeCommand): + """Clear All probes.""" + + log = logging.getLogger(__name__ + '.ClearProbe') + + def run(self, parsed_args): + self.log.debug('run(%s)' % parsed_args) + debug_agent = self.get_debug_agent() + debug_agent.clear_probe() + self.log.info(_('All Probes deleted ')) + + +class ExecProbe(ProbeCommand): + """Exec commands on the namespace of the probe.""" + + log = logging.getLogger(__name__ + '.ExecProbe') + + def get_parser(self, prog_name): + parser = super(ExecProbe, self).get_parser(prog_name) + parser.add_argument( + 'id', metavar='port_id', + help=_('ID of probe port to execute command')) + parser.add_argument( + 'command', metavar='command', + nargs='?', + default=None, + help=_('Command to execute')) + return parser + + def run(self, parsed_args): + self.log.debug('run(%s)' % parsed_args) + debug_agent = self.get_debug_agent() + result = debug_agent.exec_command(parsed_args.id, parsed_args.command) + self.app.stdout.write(result + '\n') + + +class PingAll(ProbeCommand): + """Ping all fixed_ip.""" + + log = logging.getLogger(__name__ + '.ExecProbe') + + def get_parser(self, prog_name): + parser = super(PingAll, self).get_parser(prog_name) + parser.add_argument( + '--timeout', metavar='', + default=10, + help=_('Ping timeout')) + parser.add_argument( + '--id', metavar='network_id', + default=None, + help=_('ID of network')) + return parser + + def run(self, parsed_args): + self.log.debug('run(%s)' % parsed_args) + debug_agent = self.get_debug_agent() + result = debug_agent.ping_all(parsed_args.id, + timeout=parsed_args.timeout) + self.app.stdout.write(result + '\n') diff --git a/pool/shard002/Python/0026983_test_resource_group.py b/pool/shard002/Python/0026983_test_resource_group.py new file mode 100644 index 0000000000000000000000000000000000000000..89cd533786b997ed4584a409da1214ab8efe14e4 --- /dev/null +++ b/pool/shard002/Python/0026983_test_resource_group.py @@ -0,0 +1,213 @@ +# vim: tabstop=4 shiftwidth=4 softtabstop=4 + +# +# 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 copy + +from heat.common import exception +from heat.engine import resource +from heat.engine import scheduler +from heat.engine.resources import resource_group +from heat.tests import common +from heat.tests import generic_resource +from heat.tests import utils + +template = { + "heat_template_version": "2013-05-23", + "resources": { + "group1": { + "type": "OS::Heat::ResourceGroup", + "properties": { + "count": 2, + "resource_def": { + "type": "dummy.resource", + "properties": { + "Foo": "Bar" + } + } + } + } + } +} + +template2 = { + "heat_template_version": "2013-05-23", + "resources": { + "dummy": { + "type": "dummy.resource", + "properties": { + "Foo": "baz" + } + }, + "group1": { + "type": "OS::Heat::ResourceGroup", + "properties": { + "count": 2, + "resource_def": { + "type": "dummy.resource", + "properties": { + "Foo": {"get_attr": ["dummy", "Foo"]} + } + } + } + } + } +} + + +class ResourceWithPropsAndId(generic_resource.ResourceWithProps): + + def FnGetRefId(self): + return "ID-%s" % self.name + + +class ResourceGroupTest(common.HeatTestCase): + + def setUp(self): + common.HeatTestCase.setUp(self) + resource._register_class("dummy.resource", + ResourceWithPropsAndId) + utils.setup_dummy_db() + + def test_assemble_nested(self): + """ + Tests that the nested stack that implements the group is created + appropriately based on properties. + """ + stack = utils.parse_stack(template) + snip = stack.t['Resources']['group1'] + resg = resource_group.ResourceGroup('test', snip, stack) + templ = { + "heat_template_version": "2013-05-23", + "resources": { + "0": { + "type": "dummy.resource", + "properties": { + "Foo": "Bar" + } + }, + "1": { + "type": "dummy.resource", + "properties": { + "Foo": "Bar" + } + }, + "2": { + "type": "dummy.resource", + "properties": { + "Foo": "Bar" + } + } + } + } + + self.assertEqual(templ, resg._assemble_nested(3)) + + def test_assemble_nested_include(self): + templ = copy.deepcopy(template) + res_def = templ["resources"]["group1"]["properties"]['resource_def'] + res_def['properties']['Foo'] = None + stack = utils.parse_stack(templ) + snip = stack.t['Resources']['group1'] + resg = resource_group.ResourceGroup('test', snip, stack) + expect = { + "heat_template_version": "2013-05-23", + "resources": { + "0": { + "type": "dummy.resource", + "properties": {} + } + } + } + self.assertEqual(expect, resg._assemble_nested(1)) + expect['resources']["0"]['properties'] = {"Foo": None} + self.assertEqual(expect, resg._assemble_nested(1, include_all=True)) + + def test_invalid_res_type(self): + """Test that error raised for unknown resource type.""" + tmp = copy.deepcopy(template) + grp_props = tmp['resources']['group1']['properties'] + grp_props['resource_def']['type'] = "idontexist" + stack = utils.parse_stack(tmp) + snip = stack.t['Resources']['group1'] + resg = resource_group.ResourceGroup('test', snip, stack) + exc = self.assertRaises(exception.StackValidationFailed, + resg.validate) + self.assertIn('Unknown resource Type', str(exc)) + + def test_reference_attr(self): + stack = utils.parse_stack(template2) + snip = stack.t['Resources']['group1'] + resgrp = resource_group.ResourceGroup('test', snip, stack) + self.assertIsNone(resgrp.validate()) + + @utils.stack_delete_after + def test_delete(self): + """Test basic delete.""" + resg = self._create_dummy_stack() + self.assertIsNotNone(resg.nested()) + scheduler.TaskRunner(resg.delete)() + self.assertEqual((resg.DELETE, resg.COMPLETE), resg.nested().state) + self.assertEqual((resg.DELETE, resg.COMPLETE), resg.state) + + @utils.stack_delete_after + def test_update(self): + """Test basic update.""" + resg = self._create_dummy_stack() + new_snip = copy.deepcopy(resg.t) + new_snip['Properties']['count'] = 3 + scheduler.TaskRunner(resg.update, new_snip)() + self.stack = resg.nested() + self.assertEqual((resg.UPDATE, resg.COMPLETE), resg.state) + self.assertEqual((resg.UPDATE, resg.COMPLETE), resg.nested().state) + self.assertEqual(3, len(resg.nested())) + + @utils.stack_delete_after + def test_aggregate_attribs(self): + """ + Test attribute aggregation and that we mimic the nested resource's + attributes. + """ + resg = self._create_dummy_stack() + expected = ['0', '1'] + self.assertEqual(expected, resg.FnGetAtt('foo')) + self.assertEqual(expected, resg.FnGetAtt('Foo')) + + @utils.stack_delete_after + def test_aggregate_refs(self): + """ + Test resource id aggregation + """ + resg = self._create_dummy_stack() + expected = ['ID-0', 'ID-1'] + self.assertEqual(expected, resg.FnGetAtt("refs")) + + @utils.stack_delete_after + def test_index_refs(self): + """Tests getting ids of individual resources.""" + resg = self._create_dummy_stack() + self.assertEqual("ID-0", resg.FnGetAtt('resource.0')) + self.assertEqual("ID-1", resg.FnGetAtt('resource.1')) + self.assertRaises(exception.InvalidTemplateAttribute, resg.FnGetAtt, + 'resource.2') + + def _create_dummy_stack(self): + stack = utils.parse_stack(template) + snip = stack.t['Resources']['group1'] + resg = resource_group.ResourceGroup('test', snip, stack) + scheduler.TaskRunner(resg.create)() + self.stack = resg.nested() + self.assertEqual(2, len(resg.nested())) + self.assertEqual((resg.CREATE, resg.COMPLETE), resg.state) + return resg diff --git a/pool/shard003/C/0064028_verstage.c b/pool/shard003/C/0064028_verstage.c new file mode 100644 index 0000000000000000000000000000000000000000..ab02bb150e8870c9fae59df75c9a6a12a0134059 --- /dev/null +++ b/pool/shard003/C/0064028_verstage.c @@ -0,0 +1,51 @@ +/* + * This file is part of the coreboot project. + * + * Copyright 2014 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. + * + * 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. + */ + +#include +#include +#include +#include +#include + +static const struct pad_config i2cpad[] = { + /* TPM I2C */ + PAD_CFG_SFIO(CAM_I2C_SCL, PINMUX_INPUT_ENABLE, I2C3), + PAD_CFG_SFIO(CAM_I2C_SDA, PINMUX_INPUT_ENABLE, I2C3), +}; + +static const struct pad_config spipad[] = { + /* EC on SPI1: mosi, miso, clk, cs */ + PAD_CFG_SFIO(ULPI_CLK, PINMUX_INPUT_ENABLE, SPI1), + PAD_CFG_SFIO(ULPI_DIR, PINMUX_INPUT_ENABLE, SPI1), + PAD_CFG_SFIO(ULPI_NXT, PINMUX_INPUT_ENABLE, SPI1), + PAD_CFG_SFIO(ULPI_STP, PINMUX_INPUT_ENABLE, SPI1), +}; + +static const struct funit_cfg funitcfgs[] = { + FUNIT_CFG(SBC1, CLK_M, 3000, spipad, ARRAY_SIZE(spipad)), + FUNIT_CFG(I2C3, PLLP, 400, i2cpad, ARRAY_SIZE(i2cpad)), +}; + +void verstage_mainboard_init(void) +{ + soc_configure_funits(funitcfgs, ARRAY_SIZE(funitcfgs)); + + /* TPM I2C bus */ + i2c_init(2); +} diff --git a/pool/shard003/C/0064031_pie.c b/pool/shard003/C/0064031_pie.c new file mode 100644 index 0000000000000000000000000000000000000000..695a38171d00d1f0cee49c3b13473b157527d2fc --- /dev/null +++ b/pool/shard003/C/0064031_pie.c @@ -0,0 +1,97 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later + * Copyright © 2020 VMware, Inc. */ + +#include + +#include "alloc-util.h" +#include "conf-parser.h" +#include "pie.h" +#include "netlink-util.h" +#include "parse-util.h" +#include "string-util.h" + +static int pie_fill_message(Link *link, QDisc *qdisc, sd_netlink_message *req) { + ProportionalIntegralControllerEnhanced *pie; + int r; + + assert(link); + assert(qdisc); + assert(req); + + pie = PIE(qdisc); + + r = sd_netlink_message_open_container_union(req, TCA_OPTIONS, "pie"); + if (r < 0) + return log_link_error_errno(link, r, "Could not open container TCA_OPTIONS: %m"); + + if (pie->packet_limit > 0) { + r = sd_netlink_message_append_u32(req, TCA_PIE_LIMIT, pie->packet_limit); + if (r < 0) + return log_link_error_errno(link, r, "Could not append TCA_PIE_PLIMIT attribute: %m"); + } + + r = sd_netlink_message_close_container(req); + if (r < 0) + return log_link_error_errno(link, r, "Could not close container TCA_OPTIONS: %m"); + + return 0; +} + +int config_parse_pie_packet_limit( + const char *unit, + const char *filename, + unsigned line, + const char *section, + unsigned section_line, + const char *lvalue, + int ltype, + const char *rvalue, + void *data, + void *userdata) { + + _cleanup_(qdisc_free_or_set_invalidp) QDisc *qdisc = NULL; + ProportionalIntegralControllerEnhanced *pie; + Network *network = data; + int r; + + assert(filename); + assert(lvalue); + assert(rvalue); + assert(data); + + r = qdisc_new_static(QDISC_KIND_PIE, network, filename, section_line, &qdisc); + if (r == -ENOMEM) + return log_oom(); + if (r < 0) { + log_syntax(unit, LOG_WARNING, filename, line, r, + "More than one kind of queueing discipline, ignoring assignment: %m"); + return 0; + } + + pie = PIE(qdisc); + + if (isempty(rvalue)) { + pie->packet_limit = 0; + + qdisc = NULL; + return 0; + } + + r = safe_atou32(rvalue, &pie->packet_limit); + if (r < 0) { + log_syntax(unit, LOG_WARNING, filename, line, r, + "Failed to parse '%s=', ignoring assignment: %s", + lvalue, rvalue); + return 0; + } + + qdisc = NULL; + + return 0; +} + +const QDiscVTable pie_vtable = { + .object_size = sizeof(ProportionalIntegralControllerEnhanced), + .tca_kind = "pie", + .fill_message = pie_fill_message, +}; diff --git a/pool/shard003/C/0064035_xoverlay.c b/pool/shard003/C/0064035_xoverlay.c new file mode 100644 index 0000000000000000000000000000000000000000..84858e9502b58288fab3dae40b06bbbc6a0440a6 --- /dev/null +++ b/pool/shard003/C/0064035_xoverlay.c @@ -0,0 +1,503 @@ +/* GStreamer X-based Overlay + * Copyright (C) 2003 Ronald Bultje + * + * x-overlay.c: X-based overlay interface design + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ +/** + * SECTION:gstxoverlay + * @short_description: Interface for setting/getting a Window on elements + * supporting it + * + * + * + * The XOverlay interface is used for 2 main purposes : + * + * + * + * To get a grab on the Window where the video sink element is going to render. + * This is achieved by either being informed about the Window identifier that + * the video sink element generated, or by forcing the video sink element to use + * a specific Window identifier for rendering. + * + * + * + * + * To force a redrawing of the latest video frame the video sink element + * displayed on the Window. Indeed if the #GstPipeline is in #GST_STATE_PAUSED + * state, moving the Window around will damage its content. Application + * developers will want to handle the Expose events themselves and force the + * video sink element to refresh the Window's content. + * + * + * + * + * + * Using the Window created by the video sink is probably the simplest scenario, + * in some cases, though, it might not be flexible enough for application + * developers if they need to catch events such as mouse moves and button + * clicks. + * + * + * Setting a specific Window identifier on the video sink element is the most + * flexible solution but it has some issues. Indeed the application needs to set + * its Window identifier at the right time to avoid internal Window creation + * from the video sink element. To solve this issue a #GstMessage is posted on + * the bus to inform the application that it should set the Window identifier + * immediately. Here is an example on how to do that correctly: + * |[ + * static GstBusSyncReply + * create_window (GstBus * bus, GstMessage * message, GstPipeline * pipeline) + * { + * // ignore anything but 'prepare-xwindow-id' element messages + * if (GST_MESSAGE_TYPE (message) != GST_MESSAGE_ELEMENT) + * return GST_BUS_PASS; + * + * if (!gst_structure_has_name (message->structure, "prepare-xwindow-id")) + * return GST_BUS_PASS; + * + * win = XCreateSimpleWindow (disp, root, 0, 0, 320, 240, 0, 0, 0); + * + * XSetWindowBackgroundPixmap (disp, win, None); + * + * XMapRaised (disp, win); + * + * XSync (disp, FALSE); + * + * gst_x_overlay_set_xwindow_id (GST_X_OVERLAY (GST_MESSAGE_SRC (message)), + * win); + * + * gst_message_unref (message); + * + * return GST_BUS_DROP; + * } + * ... + * int + * main (int argc, char **argv) + * { + * ... + * bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); + * gst_bus_set_sync_handler (bus, (GstBusSyncHandler) create_window, pipeline); + * ... + * } + * ]| + * + * + * + * Two basic usage scenarios + * + * There are two basic usage scenarios: in the simplest case, the application + * knows exactly what particular element is used for video output, which is + * usually the case when the application creates the videosink to use + * (e.g. #xvimagesink, #ximagesink, etc.) itself; in this case, the application + * can just create the videosink element, create and realize the window to + * render the video on and then call gst_x_overlay_set_xwindow_id() directly + * with the XID or native window handle, before starting up the pipeline. + * + * + * In the other and more common case, the application does not know in advance + * what GStreamer video sink element will be used for video output. This is + * usually the case when an element such as #autovideosink or #gconfvideosink + * is used. In this case, the video sink element itself is created + * asynchronously from a GStreamer streaming thread some time after the + * pipeline has been started up. When that happens, however, the video sink + * will need to know right then whether to render onto an already existing + * application window or whether to create its own window. This is when it + * posts a prepare-xwindow-id message, and that is also why this message needs + * to be handled in a sync bus handler which will be called from the streaming + * thread directly (because the video sink will need an answer right then). + * + * + * As response to the prepare-xwindow-id element message in the bus sync + * handler, the application may use gst_x_overlay_set_xwindow_id() to tell + * the video sink to render onto an existing window surface. At this point the + * application should already have obtained the window handle / XID, so it + * just needs to set it. It is generally not advisable to call any GUI toolkit + * functions or window system functions from the streaming thread in which the + * prepare-xwindow-id message is handled, because most GUI toolkits and + * windowing systems are not thread-safe at all and a lot of care would be + * required to co-ordinate the toolkit and window system calls of the + * different threads (Gtk+ users please note: prior to Gtk+ 2.18 + * GDK_WINDOW_XID() was just a simple structure access, so generally fine to do + * within the bus sync handler; this macro was changed to a function call in + * Gtk+ 2.18 and later, which is likely to cause problems when called from a + * sync handler; see below for a better approach without GDK_WINDOW_XID() + * used in the callback). + * + * + * + * GstXOverlay and Gtk+ + * + * |[ + * #include <gtk/gtk.h> + * #ifdef GDK_WINDOWING_X11 + * #include <gdk/gdkx.h> // for GDK_WINDOW_XID + * #endif + * ... + * static gulong video_window_xid = 0; + * ... + * static GstBusSyncReply + * bus_sync_handler (GstBus * bus, GstMessage * message, gpointer user_data) + * { + * // ignore anything but 'prepare-xwindow-id' element messages + * if (GST_MESSAGE_TYPE (message) != GST_MESSAGE_ELEMENT) + * return GST_BUS_PASS; + * if (!gst_structure_has_name (message->structure, "prepare-xwindow-id")) + * return GST_BUS_PASS; + * + * if (video_window_xid != 0) { + * GstXOverlay *xoverlay; + * + * // GST_MESSAGE_SRC (message) will be the video sink element + * xoverlay = GST_X_OVERLAY (GST_MESSAGE_SRC (message)); + * gst_x_overlay_set_xwindow_id (xoverlay, video_window_xid); + * } else { + * g_warning ("Should have obtained video_window_xid by now!"); + * } + * + * gst_message_unref (message); + * return GST_BUS_DROP; + * } + * ... + * static void + * video_widget_realize_cb (GtkWidget * widget, gpointer data) + * { + * #if GTK_CHECK_VERSION(2,18,0) + * // This is here just for pedagogical purposes, GDK_WINDOW_XID will call + * // it as well in newer Gtk versions + * if (!gdk_window_ensure_native (widget->window)) + * g_error ("Couldn't create native window needed for GstXOverlay!"); + * #endif + * + * #ifdef GDK_WINDOWING_X11 + * video_window_xid = GDK_WINDOW_XID (video_window->window); + * #endif + * } + * ... + * int + * main (int argc, char **argv) + * { + * GtkWidget *video_window; + * GtkWidget *app_window; + * ... + * app_window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + * ... + * video_window = gtk_drawing_area_new (); + * g_signal_connect (video_window, "realize", + * G_CALLBACK (video_widget_realize_cb), NULL); + * gtk_widget_set_double_buffered (video_window, FALSE); + * ... + * // usually the video_window will not be directly embedded into the + * // application window like this, but there will be many other widgets + * // and the video window will be embedded in one of them instead + * gtk_container_add (GTK_CONTAINER (ap_window), video_window); + * ... + * // show the GUI + * gtk_widget_show_all (app_window); + * + * // realize window now so that the video window gets created and we can + * // obtain its XID before the pipeline is started up and the videosink + * // asks for the XID of the window to render onto + * gtk_widget_realize (window); + * + * // we should have the XID now + * g_assert (video_window_xid != 0); + * ... + * // set up sync handler for setting the xid once the pipeline is started + * bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); + * gst_bus_set_sync_handler (bus, (GstBusSyncHandler) bus_sync_handler, NULL); + * gst_object_unref (bus); + * ... + * gst_element_set_state (pipeline, GST_STATE_PLAYING); + * ... + * } + * ]| + * + * + * + * GstXOverlay and Qt + * + * |[ + * #include <glib.h> + * #include <gst/gst.h> + * #include <gst/interfaces/xoverlay.h> + * + * #include <QApplication> + * #include <QTimer> + * #include <QWidget> + * + * int main(int argc, char *argv[]) + * { + * if (!g_thread_supported ()) + * g_thread_init (NULL); + * + * gst_init (&argc, &argv); + * QApplication app(argc, argv); + * app.connect(&app, SIGNAL(lastWindowClosed()), &app, SLOT(quit ())); + * + * // prepare the pipeline + * + * GstElement *pipeline = gst_pipeline_new ("xvoverlay"); + * GstElement *src = gst_element_factory_make ("videotestsrc", NULL); + * GstElement *sink = gst_element_factory_make ("xvimagesink", NULL); + * gst_bin_add_many (GST_BIN (pipeline), src, sink, NULL); + * gst_element_link (src, sink); + * + * // prepare the ui + * + * QWidget window; + * window.resize(320, 240); + * window.show(); + * + * WId xwinid = window.winId(); + * gst_x_overlay_set_xwindow_id (GST_X_OVERLAY (sink), xwinid); + * + * // run the pipeline + * + * GstStateChangeReturn sret = gst_element_set_state (pipeline, + * GST_STATE_PLAYING); + * if (sret == GST_STATE_CHANGE_FAILURE) { + * gst_element_set_state (pipeline, GST_STATE_NULL); + * gst_object_unref (pipeline); + * // Exit application + * QTimer::singleShot(0, QApplication::activeWindow(), SLOT(quit())); + * } + * + * int ret = app.exec(); + * + * window.hide(); + * gst_element_set_state (pipeline, GST_STATE_NULL); + * gst_object_unref (pipeline); + * + * return ret; + * } + * ]| + * + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "xoverlay.h" + +static void gst_x_overlay_base_init (gpointer g_class); + +GType +gst_x_overlay_get_type (void) +{ + static GType gst_x_overlay_type = 0; + + if (!gst_x_overlay_type) { + static const GTypeInfo gst_x_overlay_info = { + sizeof (GstXOverlayClass), + gst_x_overlay_base_init, + NULL, + NULL, + NULL, + NULL, + 0, + 0, + NULL, + }; + + gst_x_overlay_type = g_type_register_static (G_TYPE_INTERFACE, + "GstXOverlay", &gst_x_overlay_info, 0); + g_type_interface_add_prerequisite (gst_x_overlay_type, + GST_TYPE_IMPLEMENTS_INTERFACE); + } + + return gst_x_overlay_type; +} + +static void +gst_x_overlay_base_init (gpointer g_class) +{ + GstXOverlayClass *overlay_class = (GstXOverlayClass *) g_class; + + overlay_class->set_xwindow_id = NULL; +} + +/** + * gst_x_overlay_set_xwindow_id: + * @overlay: a #GstXOverlay to set the XWindow on. + * @xwindow_id: a #XID referencing the XWindow. + * + * This will call the video overlay's set_xwindow_id method. You should + * use this method to tell to a XOverlay to display video output to a + * specific XWindow. Passing 0 as the xwindow_id will tell the overlay to + * stop using that window and create an internal one. + */ +void +gst_x_overlay_set_xwindow_id (GstXOverlay * overlay, gulong xwindow_id) +{ + GstXOverlayClass *klass; + + g_return_if_fail (overlay != NULL); + g_return_if_fail (GST_IS_X_OVERLAY (overlay)); + + klass = GST_X_OVERLAY_GET_CLASS (overlay); + + if (klass->set_xwindow_id) { + klass->set_xwindow_id (overlay, xwindow_id); + } +} + +/** + * gst_x_overlay_got_xwindow_id: + * @overlay: a #GstXOverlay which got a XWindow. + * @xwindow_id: a #XID referencing the XWindow. + * + * This will post a "have-xwindow-id" element message on the bus. + * + * This function should only be used by video overlay plugin developers. + */ +void +gst_x_overlay_got_xwindow_id (GstXOverlay * overlay, gulong xwindow_id) +{ + GstStructure *s; + GstMessage *msg; + + g_return_if_fail (overlay != NULL); + g_return_if_fail (GST_IS_X_OVERLAY (overlay)); + + GST_LOG_OBJECT (GST_OBJECT (overlay), "xwindow_id = %lu", xwindow_id); + s = gst_structure_new ("have-xwindow-id", "xwindow-id", G_TYPE_ULONG, + xwindow_id, NULL); + msg = gst_message_new_element (GST_OBJECT (overlay), s); + gst_element_post_message (GST_ELEMENT (overlay), msg); +} + +/** + * gst_x_overlay_prepare_xwindow_id: + * @overlay: a #GstXOverlay which does not yet have an XWindow. + * + * This will post a "prepare-xwindow-id" element message on the bus + * to give applications an opportunity to call + * gst_x_overlay_set_xwindow_id() before a plugin creates its own + * window. + * + * This function should only be used by video overlay plugin developers. + */ +void +gst_x_overlay_prepare_xwindow_id (GstXOverlay * overlay) +{ + GstStructure *s; + GstMessage *msg; + + g_return_if_fail (overlay != NULL); + g_return_if_fail (GST_IS_X_OVERLAY (overlay)); + + GST_LOG_OBJECT (GST_OBJECT (overlay), "prepare xwindow_id"); + s = gst_structure_new ("prepare-xwindow-id", NULL); + msg = gst_message_new_element (GST_OBJECT (overlay), s); + gst_element_post_message (GST_ELEMENT (overlay), msg); +} + +/** + * gst_x_overlay_expose: + * @overlay: a #GstXOverlay to expose. + * + * Tell an overlay that it has been exposed. This will redraw the current frame + * in the drawable even if the pipeline is PAUSED. + */ +void +gst_x_overlay_expose (GstXOverlay * overlay) +{ + GstXOverlayClass *klass; + + g_return_if_fail (overlay != NULL); + g_return_if_fail (GST_IS_X_OVERLAY (overlay)); + + klass = GST_X_OVERLAY_GET_CLASS (overlay); + + if (klass->expose) { + klass->expose (overlay); + } +} + +/** + * gst_x_overlay_handle_events: + * @overlay: a #GstXOverlay to expose. + * @handle_events: a #gboolean indicating if events should be handled or not. + * + * Tell an overlay that it should handle events from the window system. These + * events are forwared upstream as navigation events. In some window system, + * events are not propagated in the window hierarchy if a client is listening + * for them. This method allows you to disable events handling completely + * from the XOverlay. + * + * Since: 0.10.12 + */ +void +gst_x_overlay_handle_events (GstXOverlay * overlay, gboolean handle_events) +{ + GstXOverlayClass *klass; + + g_return_if_fail (overlay != NULL); + g_return_if_fail (GST_IS_X_OVERLAY (overlay)); + + klass = GST_X_OVERLAY_GET_CLASS (overlay); + + if (klass->handle_events) { + klass->handle_events (overlay, handle_events); + } +} + +/** + * gst_x_overlay_set_render_rectangle: + * @overlay: a #GstXOverlay + * @x: the horizontal offset of the render area inside the window + * @y: the vertical offset of the render area inside the window + * @width: the width of the render area inside the window + * @height: the height of the render area inside the window + * + * Configure a subregion as a video target within the window set by + * gst_x_overlay_set_xwindow_id(). If this is not used or not supported + * the video will fill the area of the window set as the overlay to 100%. + * By specifying the rectangle, the video can be overlayed to a specific region + * of that window only. After setting the new rectangle one should call + * gst_x_overlay_expose() to force a redraw. To unset the region pass -1 for + * the @x, @y, @width, and @height parameters. + * + * This method is needed for non fullscreen video overlay in UI toolkits that + * do not support subwindows. + * + * Returns: %FALSE if not supported by the sink. + * + * Since: 0.10.29 + */ +gboolean +gst_x_overlay_set_render_rectangle (GstXOverlay * overlay, + gint x, gint y, gint width, gint height) +{ + GstXOverlayClass *klass; + + g_return_val_if_fail (overlay != NULL, FALSE); + g_return_val_if_fail (GST_IS_X_OVERLAY (overlay), FALSE); + g_return_val_if_fail ((x == -1 && y == -1 && width == -1 && height == -1) || + (x >= 0 && y >= 0 && width > 0 && height > 0), FALSE); + + klass = GST_X_OVERLAY_GET_CLASS (overlay); + + if (klass->set_render_rectangle) { + klass->set_render_rectangle (overlay, x, y, width, height); + return TRUE; + } + return FALSE; +} diff --git a/pool/shard003/C/0064036_pm_lpsp.c b/pool/shard003/C/0064036_pm_lpsp.c new file mode 100644 index 0000000000000000000000000000000000000000..f35785bb0dcad204f6859d54ddc3014ab2fdad87 --- /dev/null +++ b/pool/shard003/C/0064036_pm_lpsp.c @@ -0,0 +1,267 @@ +/* + * Copyright © 2013 Intel Corporation + * + * 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 (including the next + * paragraph) 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. + * + * Author: Paulo Zanoni + * + */ + +#include +#include +#include +#include + +#include "drmtest.h" +#include "igt_kms.h" +#include "intel_io.h" +#include "intel_chipset.h" + +/* We know that if we don't enable audio runtime PM, snd_hda_intel will never + * release its power well refcount, and we'll never reach the LPSP sate. OTOH + * there's no guarantee that it will release the power well if we enable runtime + * PM, but at least we can try. We don't have any assertions since the user may + * not even have snd_hda_intel loaded, which is not a problem. */ +static void disable_audio_runtime_pm(void) +{ + int fd; + + fd = open("/sys/module/snd_hda_intel/parameters/power_save", O_WRONLY); + if (fd >= 0) { + write(fd, "1\n", 2); + close(fd); + } + fd = open("/sys/bus/pci/devices/0000:00:03.0/power/control", O_WRONLY); + if (fd >= 0) { + write(fd, "auto\n", 5); + close(fd); + } + /* Give some time for it to react. */ + sleep(1); +} + +static bool supports_lpsp(uint32_t devid) +{ + return IS_HASWELL(devid) || IS_BROADWELL(devid); +} + +static bool lpsp_is_enabled(int drm_fd) +{ + uint32_t val; + + val = INREG(HSW_PWR_WELL_CTL2); + return !(val & HSW_PWR_WELL_STATE_ENABLED); +} + +/* The LPSP mode is all about an enabled pipe, but we expect to also be in the + * low power mode when no pipes are enabled, so do this check anyway. */ +static void screens_disabled_subtest(int drm_fd, drmModeResPtr drm_res) +{ + kmstest_unset_all_crtcs(drm_fd, drm_res); + igt_assert(lpsp_is_enabled(drm_fd)); +} + +static uint32_t create_fb(int drm_fd, int width, int height) +{ + struct igt_fb fb; + cairo_t *cr; + uint32_t buffer_id; + + buffer_id = igt_create_fb(drm_fd, width, height, DRM_FORMAT_XRGB8888, + I915_TILING_NONE, &fb); + cr = igt_get_cairo_ctx(drm_fd, &fb); + igt_paint_test_pattern(cr, width, height); + cairo_destroy(cr); + + return buffer_id; +} + +static void edp_subtest(int drm_fd, drmModeResPtr drm_res, + drmModeConnectorPtr *drm_connectors, uint32_t devid, + bool use_panel_fitter) +{ + int i, rc; + uint32_t connector_id = 0, crtc_id = 0, buffer_id = 0; + drmModeModeInfoPtr mode = NULL; + drmModeModeInfo std_1024_mode = { + .clock = 65000, + .hdisplay = 1024, + .hsync_start = 1048, + .hsync_end = 1184, + .htotal = 1344, + .vtotal = 806, + .hskew = 0, + .vdisplay = 768, + .vsync_start = 771, + .vsync_end = 777, + .vscan = 0, + .vrefresh = 60, + .flags = 0xA, + .type = 0x40, + .name = "Custom 1024x768", + }; + + kmstest_unset_all_crtcs(drm_fd, drm_res); + + for (i = 0; i < drm_res->count_connectors; i++) { + drmModeConnectorPtr c = drm_connectors[i]; + + if (c->connector_type != DRM_MODE_CONNECTOR_eDP) + continue; + if (c->connection != DRM_MODE_CONNECTED) + continue; + + if (!use_panel_fitter && c->count_modes) { + connector_id = c->connector_id; + mode = &c->modes[0]; + break; + } + if (use_panel_fitter) { + connector_id = c->connector_id; + + /* This is one of the modes Xorg creates for panels, so + * it should work just fine. Notice that Gens that + * support LPSP are too new for panels with native + * 1024x768 resolution, so this should force the panel + * fitter. */ + igt_assert(c->count_modes && + c->modes[0].hdisplay > 1024); + igt_assert(c->count_modes && + c->modes[0].vdisplay > 768); + mode = &std_1024_mode; + break; + } + } + igt_require(connector_id); + + crtc_id = drm_res->crtcs[0]; + buffer_id = create_fb(drm_fd, mode->hdisplay, mode->vdisplay); + + igt_assert(crtc_id); + igt_assert(buffer_id); + igt_assert(connector_id); + igt_assert(mode); + + rc = drmModeSetCrtc(drm_fd, crtc_id, buffer_id, 0, 0, &connector_id, 1, + mode); + igt_assert(rc == 0); + + if (use_panel_fitter) { + if (IS_HASWELL(devid)) + igt_assert(!lpsp_is_enabled(drm_fd)); + else + igt_assert(lpsp_is_enabled(drm_fd)); + } else { + igt_assert(lpsp_is_enabled(drm_fd)); + } +} + +static void non_edp_subtest(int drm_fd, drmModeResPtr drm_res, + drmModeConnectorPtr *drm_connectors) +{ + int i, rc; + uint32_t connector_id = 0, crtc_id = 0, buffer_id = 0; + drmModeModeInfoPtr mode = NULL; + + kmstest_unset_all_crtcs(drm_fd, drm_res); + + for (i = 0; i < drm_res->count_connectors; i++) { + drmModeConnectorPtr c = drm_connectors[i]; + + if (c->connector_type == DRM_MODE_CONNECTOR_eDP) + continue; + if (c->connection != DRM_MODE_CONNECTED) + continue; + + if (c->count_modes) { + connector_id = c->connector_id; + mode = &c->modes[0]; + break; + } + } + igt_require(connector_id); + + crtc_id = drm_res->crtcs[0]; + buffer_id = create_fb(drm_fd, mode->hdisplay, mode->vdisplay); + + igt_assert(crtc_id); + igt_assert(buffer_id); + igt_assert(connector_id); + igt_assert(mode); + + rc = drmModeSetCrtc(drm_fd, crtc_id, buffer_id, 0, 0, &connector_id, 1, + mode); + igt_assert(rc == 0); + + igt_assert(!lpsp_is_enabled(drm_fd)); +} + +#define MAX_CONNECTORS 32 + +int drm_fd; +uint32_t devid; +drmModeResPtr drm_res; +drmModeConnectorPtr drm_connectors[MAX_CONNECTORS]; + +igt_main +{ + igt_fixture { + int i; + + drm_fd = drm_open_any_master(); + igt_require(drm_fd >= 0); + + devid = intel_get_drm_devid(drm_fd); + + drm_res = drmModeGetResources(drm_fd); + igt_assert(drm_res->count_connectors <= MAX_CONNECTORS); + + for (i = 0; i < drm_res->count_connectors; i++) + drm_connectors[i] = drmModeGetConnector(drm_fd, + drm_res->connectors[i]); + + disable_audio_runtime_pm(); + + igt_require(supports_lpsp(devid)); + + intel_register_access_init(intel_get_pci_device(), 0); + + kmstest_set_vt_graphics_mode(); + } + + igt_subtest("screens-disabled") + screens_disabled_subtest(drm_fd, drm_res); + igt_subtest("edp-native") + edp_subtest(drm_fd, drm_res, drm_connectors, devid, false); + igt_subtest("edp-panel-fitter") + edp_subtest(drm_fd, drm_res, drm_connectors, devid, true); + igt_subtest("non-edp") + non_edp_subtest(drm_fd, drm_res, drm_connectors); + + igt_fixture { + int i; + + intel_register_access_fini(); + for (i = 0; i < drm_res->count_connectors; i++) + drmModeFreeConnector(drm_connectors[i]); + drmModeFreeResources(drm_res); + close(drm_fd); + } +} diff --git a/pool/shard003/C/0064038_gpio_dev_min.c b/pool/shard003/C/0064038_gpio_dev_min.c new file mode 100644 index 0000000000000000000000000000000000000000..a3ccea9b4ce2d2a47b6ff701ca458bc5721c9fef --- /dev/null +++ b/pool/shard003/C/0064038_gpio_dev_min.c @@ -0,0 +1,50 @@ +/* Copyright 2011; All Rights Reserved + * Please see http://www.coactionos.com/license.html for + * licensing information. + */ + +#include "hwpl/debug.h" +#include "hwpl/gpio.h" +#include "gpio_flags.h" +#include "hwpl/core.h" + + + +int hwpl_gpio_getattr(int port, void * ctl){ + gpio_attr_t * ctlp = (gpio_attr_t*)ctl; + //read the direction pin status + ctlp->output = gpio_get_dir(port); + ctlp->input = ~ctlp->output; + return 0; +} + +int hwpl_gpio_setattr(int port, void * ctl){ + gpio_attr_t * ctlp = (gpio_attr_t*)ctl; + + //set the input pins as input + gpio_clr_dir(port, ctlp->input); + + //set output pins as output + gpio_set_dir(port, ctlp->output); + + return 0; +} + +int hwpl_gpio_setmask(int port, void * ctl){ + gpio_set(port, (int)ctl); + return 0; +} + +int hwpl_gpio_clrmask(int port, void * ctl){ + gpio_clr(port, (int)ctl); + return 0; +} + +int hwpl_gpio_get(int port, void * ctl){ + return gpio_rd(port); +} + +int hwpl_gpio_set(int port, void * ctl){ + gpio_wr(port, (uint32_t)ctl); + return 0; +} diff --git a/pool/shard003/C/0064043_res_stasis_answer.c b/pool/shard003/C/0064043_res_stasis_answer.c new file mode 100644 index 0000000000000000000000000000000000000000..830de8015ccdae582a29e71bc6261f98336d53c4 --- /dev/null +++ b/pool/shard003/C/0064043_res_stasis_answer.c @@ -0,0 +1,79 @@ +/* + * Asterisk -- An open source telephony toolkit. + * + * Copyright (C) 2013, Digium, Inc. + * + * David M. Lee, II + * + * See http://www.asterisk.org for more information about + * the Asterisk project. Please do not directly contact + * any of the maintainers of this project for assistance; + * the project provides a web site, mailing lists and IRC + * channels for your use. + * + * This program is free software, distributed under the terms of + * the GNU General Public License Version 2. See the LICENSE file + * at the top of the source tree. + */ + +/*! \file + * + * \brief Stasis application control support. + * + * \author David M. Lee, II + */ + +/*** MODULEINFO + res_stasis + core + ***/ + +#include "asterisk.h" + +ASTERISK_REGISTER_FILE() + +#include "asterisk/module.h" +#include "asterisk/stasis_app_impl.h" + +static int app_control_answer(struct stasis_app_control *control, + struct ast_channel *chan, void *data) +{ + ast_debug(3, "%s: Answering\n", + stasis_app_control_get_channel_id(control)); + return ast_raw_answer(chan); +} + +int stasis_app_control_answer(struct stasis_app_control *control) +{ + int retval; + + ast_debug(3, "%s: Sending answer command\n", + stasis_app_control_get_channel_id(control)); + + retval = stasis_app_send_command(control, app_control_answer, NULL, NULL); + + if (retval != 0) { + ast_log(LOG_WARNING, "%s: Failed to answer channel\n", + stasis_app_control_get_channel_id(control)); + return -1; + } + + return 0; +} + +static int load_module(void) +{ + return AST_MODULE_LOAD_SUCCESS; +} + +static int unload_module(void) +{ + return 0; +} + +AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Stasis application answer support", + .support_level = AST_MODULE_SUPPORT_CORE, + .load = load_module, + .unload = unload_module, + .nonoptreq = "res_stasis" +); diff --git a/pool/shard003/C/0064052_dstore_quota_test.c b/pool/shard003/C/0064052_dstore_quota_test.c new file mode 100644 index 0000000000000000000000000000000000000000..f2cec778b88c82305390d864b1c657edc1dfe6fc --- /dev/null +++ b/pool/shard003/C/0064052_dstore_quota_test.c @@ -0,0 +1,115 @@ +/* + This file is part of GNUnet. + (C) 2006, 2008 Christian Grothoff (and other contributing authors) + + GNUnet 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. + + GNUnet 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 GNUnet; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. +*/ +/* + * @file applications/dstore/dstore_quota_test.c + * @brief Test for the dstore implementations. + * @author Nils Durner + */ + +#include "platform.h" +#include "gnunet_util.h" +#include "gnunet_protocols.h" +#include "gnunet_dstore_service.h" +#include "core.h" + +#define ASSERT(x) do { if (! (x)) { printf("Error at %s:%d\n", __FILE__, __LINE__); goto FAILURE;} } while (0) + +/** + * Quota is 1 MB. Each iteration of the test puts in about 1 MB of + * data. We do 10 iterations. Afterwards we check that the data from + * the first 5 iterations has all been discarded and that at least + * some of the data from the last iteration is still there. + */ +static int +test (GNUNET_Dstore_ServiceAPI * api) +{ + GNUNET_HashCode k; + GNUNET_HashCode n; + unsigned int i; + unsigned int j; + char buf[3200]; + + memset (buf, 1, sizeof (buf)); + memset (&k, 0, sizeof (GNUNET_HashCode)); + for (i = 0; i < 10; i++) + { + fprintf (stderr, "."); + GNUNET_hash (&k, sizeof (GNUNET_HashCode), &n); + for (j = i; j < sizeof (buf); j += 10) + { + buf[j] = i; + ASSERT (GNUNET_OK == api->put (&k, + i, + GNUNET_get_time () + + 30 * GNUNET_CRON_MINUTES, j, buf)); + ASSERT (0 != api->get (&k, i, NULL, NULL)); + } + k = n; + } + fprintf (stderr, "\n"); + memset (&k, 0, sizeof (GNUNET_HashCode)); + for (i = 0; i < 10; i++) + { + fprintf (stderr, "."); + GNUNET_hash (&k, sizeof (GNUNET_HashCode), &n); + if (i < 2) + ASSERT (0 == api->get (&k, i, NULL, NULL)); + if (i == 9) + ASSERT (0 != api->get (&k, i, NULL, NULL)); + k = n; + } + fprintf (stderr, "\n"); + return GNUNET_OK; +FAILURE: + return GNUNET_SYSERR; +} + +int +main (int argc, char *argv[]) +{ + GNUNET_Dstore_ServiceAPI *api; + int ok; + struct GNUNET_GC_Configuration *cfg; + struct GNUNET_CronManager *cron; + + GNUNET_disable_entropy_gathering (); + cfg = GNUNET_GC_create (); + if (-1 == GNUNET_GC_parse_configuration (cfg, "check.conf")) + { + GNUNET_GC_free (cfg); + return -1; + } + cron = GNUNET_cron_create (NULL); + GNUNET_CORE_init (NULL, cfg, cron, NULL); + api = GNUNET_CORE_request_service ("dstore"); + if (api != NULL) + { + ok = test (api); + GNUNET_CORE_release_service (api); + } + else + ok = GNUNET_SYSERR; + GNUNET_CORE_done (); + if (ok == GNUNET_SYSERR) + return 1; + return 0; +} + +/* end of dstore_quota_test.c */ diff --git a/pool/shard003/C/0064058_tpu_debug.c b/pool/shard003/C/0064058_tpu_debug.c new file mode 100644 index 0000000000000000000000000000000000000000..918cdedfd48097f5e9fe064ebe8fc1bab51334c1 --- /dev/null +++ b/pool/shard003/C/0064058_tpu_debug.c @@ -0,0 +1,138 @@ +/* Calypso TPU debugger, displays and decodes TPU instruction RAM */ + +/* (C) 2010 by Harald Welte + * + * All Rights Reserved + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 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 "msgb.h" + +/* TPU disassembler begin */ + +static const char *tpu_instr_name[] = { + [0] = "SLEEP", + [1] = "AT", + [2] = "OFFSET", + [3] = "SYNCHRO", + [4] = "MOVE", + [5] = "WAIT", + [6] = "UNDEFINED6", + [7] = "UNDEFINED7", +}; + +static const char *tpu_addr_name[0x1f] = { + [0] = "TSP_CTLR1", + [1] = "TSP_CTRL2", + [4] = "TSP_TX_1", + [3] = "TSP_TX_2", + [2] = "TSP_TX_3", + [5] = "TSP_TX_4", + [6] = "TSPACT_L", + [7] = "TSPACT_H", + [9] = "TSP_SET1", + [0xa] = "TSP_SET2", + [0xb] = "TSP_SET3", + [0x10] = "DSP_INT_PG", + [0x11] = "GAUGING_EN", +}; + +static uint8_t tpu_reg_cache[0x1f]; +static uint16_t tpu_qbit; + +static void tpu_show_instr(uint16_t tpu) +{ + uint16_t instr = tpu >> 13; + uint16_t param = tpu & 0x1fff; + uint16_t addr, data, bitlen; + uint32_t tsp_data; + + tpu_qbit++; + + printf("\t %04u %04x %s ", tpu_qbit, tpu, tpu_instr_name[instr]); + switch (instr) { + case 0: + tpu_qbit = 0; + default: + break; + case 1: + tpu_qbit = param; + printf("%u ", param); + break; + case 5: + tpu_qbit += param; + printf("%u ", param); + break; + case 2: + case 3: + printf("%u ", param); + break; + case 4: + addr = param & 0x1f; + data = param >> 5; + tpu_reg_cache[addr] = data; + printf("%10s=0x%04x ", tpu_addr_name[addr], data); + switch (addr) { + case 0: + bitlen = (data & 0x1f) + 1; + printf("DEV_IDX=%u, BITLEN=%u ", data >> 5, bitlen); + if (bitlen <= 8) { + tsp_data = tpu_reg_cache[4]; + printf(" TSP_DATA=0x%02x ", tsp_data); + } else if (bitlen <= 16) { + tsp_data = tpu_reg_cache[3]; + tsp_data |= tpu_reg_cache[4] << 8; + printf(" TSP_DATA=0x%04x ", tsp_data); + } else if (bitlen <= 24) { + tsp_data = tpu_reg_cache[2]; + tsp_data |= tpu_reg_cache[3] << 8; + tsp_data |= tpu_reg_cache[4] << 16; + printf(" TSP_DATA=0x%06x ", tsp_data); + } else { + tsp_data = tpu_reg_cache[5]; + tsp_data |= tpu_reg_cache[2] << 8; + tsp_data |= tpu_reg_cache[3] << 16; + tsp_data |= tpu_reg_cache[4] << 24; + printf(" TSP_DATA=0x%08x ", tsp_data); + } + break; + case 1: + if (data & 0x01) + printf("READ "); + if (data & 0x02) + printf("WRITE "); + break; + } + } + printf("\n"); +} + +void hdlc_tpudbg_cb(uint8_t dlci, struct msgb *msg) +{ + uint32_t *fn = (uint32_t *) msg->data; + uint16_t *tpu; + + printf("TPU FN %u\n", *fn); + for (tpu = (uint16_t *) (msg->data + 4); tpu < (uint16_t *) msg->tail; tpu++) + tpu_show_instr(*tpu); + + msgb_free(msg); +} diff --git a/pool/shard003/C/0064066_stb6000.c b/pool/shard003/C/0064066_stb6000.c new file mode 100644 index 0000000000000000000000000000000000000000..786b9eccde0097dea36016f9da607a69912600ef --- /dev/null +++ b/pool/shard003/C/0064066_stb6000.c @@ -0,0 +1,255 @@ + /* + Driver for ST STB6000 DVBS Silicon tuner + + Copyright (C) 2008 Igor M. Liplianin (liplianin@me.by) + + 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., 675 Mass Ave, Cambridge, MA 02139, USA. + + */ + +#include +#include +#include +#include + +#include "stb6000.h" + +static int debug; +#define dprintk(args...) \ + do { \ + if (debug) \ + printk(KERN_DEBUG "stb6000: " args); \ + } while (0) + +struct stb6000_priv { + /* i2c details */ + int i2c_address; + struct i2c_adapter *i2c; + u32 frequency; +}; + +static void stb6000_release(struct dvb_frontend *fe) +{ + kfree(fe->tuner_priv); + fe->tuner_priv = NULL; +} + +static int stb6000_sleep(struct dvb_frontend *fe) +{ + struct stb6000_priv *priv = fe->tuner_priv; + int ret; + u8 buf[] = { 10, 0 }; + struct i2c_msg msg = { + .addr = priv->i2c_address, + .flags = 0, + .buf = buf, + .len = 2 + }; + + dprintk("%s:\n", __func__); + + if (fe->ops.i2c_gate_ctrl) + fe->ops.i2c_gate_ctrl(fe, 1); + + ret = i2c_transfer(priv->i2c, &msg, 1); + if (ret != 1) + dprintk("%s: i2c error\n", __func__); + + if (fe->ops.i2c_gate_ctrl) + fe->ops.i2c_gate_ctrl(fe, 0); + + return (ret == 1) ? 0 : ret; +} + +static int stb6000_set_params(struct dvb_frontend *fe) +{ + struct dtv_frontend_properties *p = &fe->dtv_property_cache; + struct stb6000_priv *priv = fe->tuner_priv; + unsigned int n, m; + int ret; + u32 freq_mhz; + int bandwidth; + u8 buf[12]; + struct i2c_msg msg = { + .addr = priv->i2c_address, + .flags = 0, + .buf = buf, + .len = 12 + }; + + dprintk("%s:\n", __func__); + + freq_mhz = p->frequency / 1000; + bandwidth = p->symbol_rate / 1000000; + + if (bandwidth > 31) + bandwidth = 31; + + if ((freq_mhz > 949) && (freq_mhz < 2151)) { + buf[0] = 0x01; + buf[1] = 0xac; + if (freq_mhz < 1950) + buf[1] = 0xaa; + if (freq_mhz < 1800) + buf[1] = 0xa8; + if (freq_mhz < 1650) + buf[1] = 0xa6; + if (freq_mhz < 1530) + buf[1] = 0xa5; + if (freq_mhz < 1470) + buf[1] = 0xa4; + if (freq_mhz < 1370) + buf[1] = 0xa2; + if (freq_mhz < 1300) + buf[1] = 0xa1; + if (freq_mhz < 1200) + buf[1] = 0xa0; + if (freq_mhz < 1075) + buf[1] = 0xbc; + if (freq_mhz < 1000) + buf[1] = 0xba; + if (freq_mhz < 1075) { + n = freq_mhz / 8; /* vco=lo*4 */ + m = 2; + } else { + n = freq_mhz / 16; /* vco=lo*2 */ + m = 1; + } + buf[2] = n >> 1; + buf[3] = (unsigned char)(((n & 1) << 7) | + (m * freq_mhz - n * 16) | 0x60); + buf[4] = 0x04; + buf[5] = 0x0e; + + buf[6] = (unsigned char)(bandwidth); + + buf[7] = 0xd8; + buf[8] = 0xd0; + buf[9] = 0x50; + buf[10] = 0xeb; + buf[11] = 0x4f; + + if (fe->ops.i2c_gate_ctrl) + fe->ops.i2c_gate_ctrl(fe, 1); + + ret = i2c_transfer(priv->i2c, &msg, 1); + if (ret != 1) + dprintk("%s: i2c error\n", __func__); + + udelay(10); + if (fe->ops.i2c_gate_ctrl) + fe->ops.i2c_gate_ctrl(fe, 0); + + buf[0] = 0x07; + buf[1] = 0xdf; + buf[2] = 0xd0; + buf[3] = 0x50; + buf[4] = 0xfb; + msg.len = 5; + + if (fe->ops.i2c_gate_ctrl) + fe->ops.i2c_gate_ctrl(fe, 1); + + ret = i2c_transfer(priv->i2c, &msg, 1); + if (ret != 1) + dprintk("%s: i2c error\n", __func__); + + udelay(10); + if (fe->ops.i2c_gate_ctrl) + fe->ops.i2c_gate_ctrl(fe, 0); + + priv->frequency = freq_mhz * 1000; + + return (ret == 1) ? 0 : ret; + } + return -1; +} + +static int stb6000_get_frequency(struct dvb_frontend *fe, u32 *frequency) +{ + struct stb6000_priv *priv = fe->tuner_priv; + *frequency = priv->frequency; + return 0; +} + +static const struct dvb_tuner_ops stb6000_tuner_ops = { + .info = { + .name = "ST STB6000", + .frequency_min_hz = 950 * MHz, + .frequency_max_hz = 2150 * MHz + }, + .release = stb6000_release, + .sleep = stb6000_sleep, + .set_params = stb6000_set_params, + .get_frequency = stb6000_get_frequency, +}; + +struct dvb_frontend *stb6000_attach(struct dvb_frontend *fe, int addr, + struct i2c_adapter *i2c) +{ + struct stb6000_priv *priv = NULL; + u8 b0[] = { 0 }; + u8 b1[] = { 0, 0 }; + struct i2c_msg msg[2] = { + { + .addr = addr, + .flags = 0, + .buf = b0, + .len = 0 + }, { + .addr = addr, + .flags = I2C_M_RD, + .buf = b1, + .len = 2 + } + }; + int ret; + + dprintk("%s:\n", __func__); + + if (fe->ops.i2c_gate_ctrl) + fe->ops.i2c_gate_ctrl(fe, 1); + + /* is some i2c device here ? */ + ret = i2c_transfer(i2c, msg, 2); + if (fe->ops.i2c_gate_ctrl) + fe->ops.i2c_gate_ctrl(fe, 0); + + if (ret != 2) + return NULL; + + priv = kzalloc(sizeof(struct stb6000_priv), GFP_KERNEL); + if (priv == NULL) + return NULL; + + priv->i2c_address = addr; + priv->i2c = i2c; + + memcpy(&fe->ops.tuner_ops, &stb6000_tuner_ops, + sizeof(struct dvb_tuner_ops)); + + fe->tuner_priv = priv; + + return fe; +} +EXPORT_SYMBOL(stb6000_attach); + +module_param(debug, int, 0644); +MODULE_PARM_DESC(debug, "Turn on/off frontend debugging (default:off)."); + +MODULE_DESCRIPTION("DVB STB6000 driver"); +MODULE_AUTHOR("Igor M. Liplianin "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard003/C/0064085_sub16-sse2.c b/pool/shard003/C/0064085_sub16-sse2.c new file mode 100644 index 0000000000000000000000000000000000000000..61dcd4194ac12e6423501b92eb6d3286c072a843 --- /dev/null +++ b/pool/shard003/C/0064085_sub16-sse2.c @@ -0,0 +1,86 @@ +/* + * Copyright (c) Facebook, Inc. and its affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include + +#include + +void pytorch_u8maxpool_ukernel_sub16__sse2( + size_t n, + size_t ks, + size_t kc, + const uint8_t** input, + uint8_t* output, + size_t input_increment, + size_t output_increment, + const union pytorch_qnnp_u8_clamping_params params[RESTRICT_STATIC 1]) { + assert(n != 0); + assert(ks != 0); + assert(kc != 0); + assert(kc < 16); + + const __m128i voutput_max = + _mm_load_si128((const __m128i*)params->sse2.output_max); + const __m128i voutput_min = + _mm_load_si128((const __m128i*)params->sse2.output_min); + + do { + __m128i vmax = _mm_setzero_si128(); + + size_t m = ks; + do { + const uint8_t* i = *input++; + i += kc; + __m128i vi = vmax; + if (kc & 1) { + i -= 1; + vi = _mm_cvtsi32_si128(*i); + } + if (kc & 2) { + vi = _mm_slli_epi32(vi, 16); + i -= 2; + vi = _mm_insert_epi16(vi, *((const uint16_t*)i), 0); + } + if (kc & 4) { + i -= 4; + vi = _mm_unpacklo_epi32( + _mm_cvtsi32_si128((int)*((const uint32_t*)i)), vi); + } + if (kc & 8) { + i -= 8; + vi = _mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)i), vi); + } + vmax = _mm_max_epu8(vmax, vi); + } while (--m != 0); + input = (const uint8_t**)((uintptr_t)input + input_increment); + __m128i vout = _mm_max_epu8(_mm_min_epu8(vmax, voutput_max), voutput_min); + + if (kc & 8) { + _mm_storel_epi64((__m128i*)output, vout); + output += 8; + vout = _mm_unpackhi_epi64(vout, vout); + } + if (kc & 4) { + *((uint32_t*)output) = (uint32_t)_mm_cvtsi128_si32(vout); + output += 4; + vout = _mm_srli_epi64(vout, 32); + } + if (kc & 2) { + *((uint16_t*)output) = (uint16_t)_mm_extract_epi16(vout, 0); + output += 2; + vout = _mm_srli_epi32(vout, 16); + } + if (kc & 1) { + *((uint8_t*)output) = (uint8_t)_mm_cvtsi128_si32(vout); + output += 1; + } + output = (uint8_t*)((uintptr_t)output + output_increment); + } while (--n != 0); +} diff --git a/pool/shard003/C/0064087_int_quest.c b/pool/shard003/C/0064087_int_quest.c new file mode 100644 index 0000000000000000000000000000000000000000..1d64f48a385bd9391914cd4a8903f5b43e2e0cb1 --- /dev/null +++ b/pool/shard003/C/0064087_int_quest.c @@ -0,0 +1,306 @@ +// Copyright (c) Hercules Dev Team, licensed under GNU GPL. +// See the LICENSE file +// Portions Copyright (c) Athena Dev Teams + +#define HERCULES_CORE + +#include "int_quest.h" + +#include +#include +#include + +#include "char.h" +#include "inter.h" +#include "mapif.h" +#include "../common/db.h" +#include "../common/malloc.h" +#include "../common/mmo.h" +#include "../common/nullpo.h" +#include "../common/showmsg.h" +#include "../common/socket.h" +#include "../common/sql.h" +#include "../common/strlib.h" +#include "../common/timer.h" + +struct inter_quest_interface inter_quest_s; + +/** + * Loads the entire questlog for a character. + * + * @param char_id Character ID + * @param count Pointer to return the number of found entries. + * @return Array of found entries. It has *count entries, and it is care of the + * caller to aFree() it afterwards. + */ +struct quest *mapif_quests_fromsql(int char_id, int *count) +{ + struct quest *questlog = NULL; + struct quest tmp_quest; + SqlStmt *stmt; + StringBuf buf; + int i; + int sqlerror = SQL_SUCCESS; + + if (!count) + return NULL; + + stmt = SQL->StmtMalloc(inter->sql_handle); + if (stmt == NULL) { + SqlStmt_ShowDebug(stmt); + *count = 0; + return NULL; + } + + StrBuf->Init(&buf); + StrBuf->AppendStr(&buf, "SELECT `quest_id`, `state`, `time`"); + for (i = 0; i < MAX_QUEST_OBJECTIVES; i++) { + StrBuf->Printf(&buf, ", `count%d`", i+1); + } + StrBuf->Printf(&buf, " FROM `%s` WHERE `char_id`=?", quest_db); + + memset(&tmp_quest, 0, sizeof(struct quest)); + + if (SQL_ERROR == SQL->StmtPrepareStr(stmt, StrBuf->Value(&buf)) + || SQL_ERROR == SQL->StmtBindParam(stmt, 0, SQLDT_INT, &char_id, 0) + || SQL_ERROR == SQL->StmtExecute(stmt) + || SQL_ERROR == SQL->StmtBindColumn(stmt, 0, SQLDT_INT, &tmp_quest.quest_id, 0, NULL, NULL) + || SQL_ERROR == SQL->StmtBindColumn(stmt, 1, SQLDT_INT, &tmp_quest.state, 0, NULL, NULL) + || SQL_ERROR == SQL->StmtBindColumn(stmt, 2, SQLDT_UINT, &tmp_quest.time, 0, NULL, NULL) + ) { + sqlerror = SQL_ERROR; + } + + StrBuf->Destroy(&buf); + + for (i = 0; sqlerror != SQL_ERROR && i < MAX_QUEST_OBJECTIVES; i++) { // Stop on the first error + sqlerror = SQL->StmtBindColumn(stmt, 3+i, SQLDT_INT, &tmp_quest.count[i], 0, NULL, NULL); + } + + if (sqlerror == SQL_ERROR) { + SqlStmt_ShowDebug(stmt); + SQL->StmtFree(stmt); + *count = 0; + return NULL; + } + + *count = (int)SQL->StmtNumRows(stmt); + if (*count > 0) { + i = 0; + questlog = (struct quest *)aCalloc(*count, sizeof(struct quest)); + + while (SQL_SUCCESS == SQL->StmtNextRow(stmt)) { + if (i >= *count) // Sanity check, should never happen + break; + memcpy(&questlog[i++], &tmp_quest, sizeof(tmp_quest)); + } + if (i < *count) { + // Should never happen. Compact array + *count = i; + questlog = aRealloc(questlog, sizeof(struct quest)*i); + } + } + + SQL->StmtFree(stmt); + return questlog; +} + +/** + * Deletes a quest from a character's questlog. + * + * @param char_id Character ID + * @param quest_id Quest ID + * @return false in case of errors, true otherwise + */ +bool mapif_quest_delete(int char_id, int quest_id) +{ + if (SQL_ERROR == SQL->Query(inter->sql_handle, "DELETE FROM `%s` WHERE `quest_id` = '%d' AND `char_id` = '%d'", quest_db, quest_id, char_id)) { + Sql_ShowDebug(inter->sql_handle); + return false; + } + + return true; +} + +/** + * Adds a quest to a character's questlog. + * + * @param char_id Character ID + * @param qd Quest data + * @return false in case of errors, true otherwise + */ +bool mapif_quest_add(int char_id, struct quest qd) +{ + StringBuf buf; + int i; + + StrBuf->Init(&buf); + StrBuf->Printf(&buf, "INSERT INTO `%s`(`quest_id`, `char_id`, `state`, `time`", quest_db); + for (i = 0; i < MAX_QUEST_OBJECTIVES; i++) { + StrBuf->Printf(&buf, ", `count%d`", i+1); + } + StrBuf->Printf(&buf, ") VALUES ('%d', '%d', '%d', '%d'", qd.quest_id, char_id, qd.state, qd.time); + for (i = 0; i < MAX_QUEST_OBJECTIVES; i++) { + StrBuf->Printf(&buf, ", '%d'", qd.count[i]); + } + StrBuf->AppendStr(&buf, ")"); + if (SQL_ERROR == SQL->QueryStr(inter->sql_handle, StrBuf->Value(&buf))) { + Sql_ShowDebug(inter->sql_handle); + StrBuf->Destroy(&buf); + return false; + } + StrBuf->Destroy(&buf); + + return true; +} + +/** + * Updates a quest in a character's questlog. + * + * @param char_id Character ID + * @param qd Quest data + * @return false in case of errors, true otherwise + */ +bool mapif_quest_update(int char_id, struct quest qd) +{ + StringBuf buf; + int i; + + StrBuf->Init(&buf); + StrBuf->Printf(&buf, "UPDATE `%s` SET `state`='%d'", quest_db, qd.state); + for (i = 0; i < MAX_QUEST_OBJECTIVES; i++) { + StrBuf->Printf(&buf, ", `count%d`='%d'", i+1, qd.count[i]); + } + StrBuf->Printf(&buf, " WHERE `quest_id` = '%d' AND `char_id` = '%d'", qd.quest_id, char_id); + + if (SQL_ERROR == SQL->QueryStr(inter->sql_handle, StrBuf->Value(&buf))) { + Sql_ShowDebug(inter->sql_handle); + StrBuf->Destroy(&buf); + return false; + } + StrBuf->Destroy(&buf); + + return true; +} + +void mapif_quest_save_ack(int fd, int char_id, bool success) +{ + WFIFOHEAD(fd,7); + WFIFOW(fd,0) = 0x3861; + WFIFOL(fd,2) = char_id; + WFIFOB(fd,6) = success?1:0; + WFIFOSET(fd,7); +} + +/** + * Handles the save request from mapserver for a character's questlog. + * + * Received quests are saved, and an ack is sent back to the map server. + * + * @see inter_parse_frommap + */ +int mapif_parse_quest_save(int fd) +{ + int i, j, k, old_n, new_n = (RFIFOW(fd,2)-8)/sizeof(struct quest); + int char_id = RFIFOL(fd,4); + struct quest *old_qd = NULL, *new_qd = NULL; + bool success = true; + + if (new_n > 0) + new_qd = (struct quest*)RFIFOP(fd,8); + + old_qd = mapif->quests_fromsql(char_id, &old_n); + + for (i = 0; i < new_n; i++) { + ARR_FIND( 0, old_n, j, new_qd[i].quest_id == old_qd[j].quest_id ); + if (j < old_n) { + // Update existing quests + + // Only states and counts are changeable. + ARR_FIND( 0, MAX_QUEST_OBJECTIVES, k, new_qd[i].count[k] != old_qd[j].count[k] ); + if (k != MAX_QUEST_OBJECTIVES || new_qd[i].state != old_qd[j].state) + success &= mapif->quest_update(char_id, new_qd[i]); + + if (j < (--old_n)) { + // Compact array + memmove(&old_qd[j],&old_qd[j+1],sizeof(struct quest)*(old_n-j)); + memset(&old_qd[old_n], 0, sizeof(struct quest)); + } + } else { + // Add new quests + success &= mapif->quest_add(char_id, new_qd[i]); + } + } + + for (i = 0; i < old_n; i++) // Quests not in new_qd but in old_qd are to be erased. + success &= mapif->quest_delete(char_id, old_qd[i].quest_id); + + if (old_qd) + aFree(old_qd); + + // Send ack + mapif->quest_save_ack(fd, char_id, success); + + return 0; +} + +void mapif_send_quests(int fd, int char_id, struct quest *tmp_questlog, int num_quests) +{ + nullpo_retv(tmp_questlog); + WFIFOHEAD(fd,num_quests*sizeof(struct quest)+8); + WFIFOW(fd,0) = 0x3860; + WFIFOW(fd,2) = num_quests*sizeof(struct quest)+8; + WFIFOL(fd,4) = char_id; + + if (num_quests > 0) + memcpy(WFIFOP(fd,8), tmp_questlog, sizeof(struct quest)*num_quests); + + WFIFOSET(fd,num_quests*sizeof(struct quest)+8); +} + +/** + * Sends questlog to the map server + * + * Note: Completed quests (state == Q_COMPLETE) are guaranteed to be sent last + * and the map server relies on this behavior (once the first Q_COMPLETE quest, + * all of them are considered to be Q_COMPLETE) + * + * @see inter_parse_frommap + */ +int mapif_parse_quest_load(int fd) +{ + int char_id = RFIFOL(fd,2); + struct quest *tmp_questlog = NULL; + int num_quests; + + tmp_questlog = mapif->quests_fromsql(char_id, &num_quests); + mapif->send_quests(fd, char_id, tmp_questlog, num_quests); + + if (tmp_questlog) + aFree(tmp_questlog); + + return 0; +} + +/** + * Parses questlog related packets from the map server. + * + * @see inter_parse_frommap + */ +int inter_quest_parse_frommap(int fd) +{ + switch(RFIFOW(fd,0)) { + case 0x3060: mapif->parse_quest_load(fd); break; + case 0x3061: mapif->parse_quest_save(fd); break; + default: + return 0; + } + return 1; +} + +void inter_quest_defaults(void) +{ + inter_quest = &inter_quest_s; + + inter_quest->parse_frommap = inter_quest_parse_frommap; +} diff --git a/pool/shard003/C/0064094_src.c b/pool/shard003/C/0064094_src.c new file mode 100644 index 0000000000000000000000000000000000000000..1f3d0de521efc0c2632eb946a7a92a71aa19021d --- /dev/null +++ b/pool/shard003/C/0064094_src.c @@ -0,0 +1,124 @@ +/* + * Copyright 2011 Freescale Semiconductor, Inc. + * Copyright 2011 Linaro Ltd. + * + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include + +#define SRC_SCR 0x000 +#define SRC_SIMR 0x018 +#define SRC_GPR1 0x020 +#define BP_SRC_SCR_WARM_RESET_ENABLE 0 +#define BP_SRC_SCR_CORE1_RST 14 +#define BP_SRC_SCR_CORE1_ENABLE 22 +#define BP_SRC_SCR_VPU_RST 2 +#define BP_SRC_SCR_IPU1_RST 3 +#define BP_SRC_SCR_IPU2_RST 12 +#define BP_SRC_SIMR_VPU_MASK 1 +#define BP_SRC_SIMR_IPU1_MASK 2 +#define BP_SRC_SIMR_IPU2_MASK 4 + +static void __iomem *src_base; + +#ifndef CONFIG_SMP +#define cpu_logical_map(cpu) 0 +#endif + +void imx_reset_vpu(void) +{ + u32 val; + + /* mask interrupt due to vpu passed reset */ + val = readl_relaxed(src_base + SRC_SIMR); + val |= (1 << BP_SRC_SIMR_VPU_MASK); + writel_relaxed(val, src_base + SRC_SIMR); + + val = readl_relaxed(src_base + SRC_SCR); + val |= (1 << BP_SRC_SCR_VPU_RST); /* reset vpu */ + writel_relaxed(val, src_base + SRC_SCR); + while (readl_relaxed(src_base + SRC_SCR) & + (1 << BP_SRC_SCR_VPU_RST)) + ; +} + +void imx_reset_ipu(int ipu) +{ + u32 val; + u32 scr_off = ipu ? BP_SRC_SCR_IPU2_RST : BP_SRC_SCR_IPU1_RST; + u32 simr_off = ipu ? BP_SRC_SIMR_IPU2_MASK : BP_SRC_SIMR_IPU1_MASK; + + /* mask interrupt due to ipu passed reset */ + val = readl_relaxed(src_base + SRC_SIMR); + val |= (1 << simr_off); + writel_relaxed(val, src_base + SRC_SIMR); + + /* reset the IPU */ + val = readl_relaxed(src_base + SRC_SCR); + val |= (1 << scr_off); + writel_relaxed(val, src_base + SRC_SCR); + + while (readl_relaxed(src_base + SRC_SCR) & + (1 << scr_off)) + ; +} + +void imx_enable_cpu(int cpu, bool enable) +{ + u32 mask, val; + + cpu = cpu_logical_map(cpu); + mask = 1 << (BP_SRC_SCR_CORE1_ENABLE + cpu - 1); + val = readl_relaxed(src_base + SRC_SCR); + val = enable ? val | mask : val & ~mask; + writel_relaxed(val, src_base + SRC_SCR); +} + +void imx_set_cpu_jump(int cpu, void *jump_addr) +{ + cpu = cpu_logical_map(cpu); + writel_relaxed(BSYM(virt_to_phys(jump_addr)), + src_base + SRC_GPR1 + cpu * 8); +} + +void imx_src_prepare_restart(void) +{ + u32 val; + + /* clear enable bits of secondary cores */ + val = readl_relaxed(src_base + SRC_SCR); + val &= ~(0x7 << BP_SRC_SCR_CORE1_ENABLE); + writel_relaxed(val, src_base + SRC_SCR); + + /* clear persistent entry register of primary core */ + writel_relaxed(0, src_base + SRC_GPR1); +} + +void __init imx_src_init(void) +{ + struct device_node *np; + u32 val; + + np = of_find_compatible_node(NULL, NULL, "fsl,imx6q-src"); + src_base = of_iomap(np, 0); + WARN_ON(!src_base); + + /* + * force warm reset sources to generate cold reset + * for a more reliable restart + */ + val = readl_relaxed(src_base + SRC_SCR); + val &= ~(1 << BP_SRC_SCR_WARM_RESET_ENABLE); + writel_relaxed(val, src_base + SRC_SCR); +} diff --git a/pool/shard003/C/0064096_romstage.c b/pool/shard003/C/0064096_romstage.c new file mode 100644 index 0000000000000000000000000000000000000000..49c5528277f81b9847361eac868df022bc255eb8 --- /dev/null +++ b/pool/shard003/C/0064096_romstage.c @@ -0,0 +1,165 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2012 secunet Security Networks AG + * + * 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. + */ + +// __PRE_RAM__ means: use "unsigned" for device, not a struct. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "gpio.h" + +#define LPC_DEV PCI_DEV(0, 0x1f, 0) +#define MCH_DEV PCI_DEV(0, 0, 0) + + +static void early_lpc_setup(void) +{ + /* Set up SuperIO LPC forwards */ + + /* Configure serial IRQs.*/ + pci_write_config8(LPC_DEV, D31F0_SERIRQ_CNTL, 0xd0); + /* Map COMa on 0x3f8, COMb on 0x2f8. */ + pci_write_config16(LPC_DEV, D31F0_LPC_IODEC, 0x0010); + pci_write_config16(LPC_DEV, D31F0_LPC_EN, 0x3f0f); + pci_write_config32(LPC_DEV, D31F0_GEN1_DEC, 0x7c1601); + pci_write_config32(LPC_DEV, D31F0_GEN2_DEC, 0xc15e1); + pci_write_config32(LPC_DEV, D31F0_GEN3_DEC, 0x1c1681); +} + +void mainboard_romstage_entry(unsigned long bist) +{ + sysinfo_t sysinfo; + int s3resume = 0; + int cbmem_initted; + u16 reg16; + + /* basic northbridge setup, including MMCONF BAR */ + gm45_early_init(); + + if (bist == 0) + enable_lapic(); + + /* First, run everything needed for console output. */ + i82801ix_early_init(); + early_lpc_setup(); + console_init(); + printk(BIOS_DEBUG, "running main(bist = %lu)\n", bist); + + reg16 = pci_read_config16(LPC_DEV, D31F0_GEN_PMCON_3); + pci_write_config16(LPC_DEV, D31F0_GEN_PMCON_3, reg16); + if ((MCHBAR16(SSKPD_MCHBAR) == 0xCAFE) && !(reg16 & (1 << 9))) { + printk(BIOS_DEBUG, "soft reset detected, rebooting properly\n"); + gm45_early_reset(); + } + + setup_pch_gpios(&x200_gpio_map); + + /* ASPM related setting, set early by original BIOS. */ + DMIBAR16(0x204) &= ~(3 << 10); + + /* Check for S3 resume. */ + const u32 pm1_cnt = inl(DEFAULT_PMBASE + 0x04); + if (((pm1_cnt >> 10) & 7) == 5) { +#if CONFIG_HAVE_ACPI_RESUME + printk(BIOS_DEBUG, "Resume from S3 detected.\n"); + s3resume = 1; + /* Clear SLP_TYPE. This will break stage2 but + * we care for that when we get there. + */ + outl(pm1_cnt & ~(7 << 10), DEFAULT_PMBASE + 0x04); +#else + printk(BIOS_DEBUG, "Resume from S3 detected, but disabled.\n"); +#endif + } + + /* RAM initialization */ + enter_raminit_or_reset(); + memset(&sysinfo, 0, sizeof(sysinfo)); + sysinfo.spd_map[0] = 0x50; + sysinfo.spd_map[2] = 0x51; + sysinfo.enable_igd = 1; + sysinfo.enable_peg = 0; + get_gmch_info(&sysinfo); + raminit(&sysinfo, s3resume); + + const u32 deven = pci_read_config32(MCH_DEV, D0F0_DEVEN); + /* Disable D4F0 (unknown signal controller). */ + pci_write_config32(MCH_DEV, D0F0_DEVEN, deven & ~0x4000); + + init_pm(&sysinfo, 0); + + i82801ix_dmi_setup(); + gm45_late_init(sysinfo.stepping); + i82801ix_dmi_poll_vc1(); + + MCHBAR16(SSKPD_MCHBAR) = 0xCAFE; + /* Enable ethernet. */ + RCBA32(0x3414) &= ~0x20; + + RCBA32(0x0238) = 0x00543210; + RCBA32(0x0240) = 0x009c0b02; + RCBA32(0x0244) = 0x00a20b1a; + RCBA32(0x0248) = 0x005402cb; + RCBA32(0x0254) = 0x00470966; + RCBA32(0x0258) = 0x00470473; + RCBA32(0x0260) = 0x00e90825; + RCBA32(0x0278) = 0x00bc0efb; + RCBA32(0x027c) = 0x00c00f0b; + RCBA32(0x0280) = 0x00670000; + RCBA32(0x0284) = 0x006d0000; + RCBA32(0x0288) = 0x00600b4e; + RCBA32(0x1e10) = 0x00020800; + RCBA32(0x1e18) = 0x36ea00a0; + RCBA32(0x1e80) = 0x000c0801; + RCBA32(0x1e84) = 0x000200f0; + RCBA32(0x2028) = 0x04c8f95e; + RCBA32(0x202c) = 0x055c095e; + RCBA32(0x204c) = 0x001ffc00; + RCBA32(0x2050) = 0x00100fff; + RCBA32(0x2090) = 0x37000000; + RCBA32(0x20b0) = 0x0c000000; + RCBA32(0x20d0) = 0x09000000; + RCBA32(0x20f0) = 0x05000000; + RCBA32(0x3400) = 0x0000001c; + RCBA32(0x3410) = 0x00100461; + RCBA32(0x3414) = 0x00000000; + RCBA32(0x341c) = 0xbf4f001f; + RCBA32(0x3420) = 0x00000000; + RCBA32(0x3430) = 0x00000001; + + init_iommu(); + + /* FIXME: make a proper SMBUS mux support. */ + outl(inl(DEFAULT_GPIOBASE + 0x38) & ~0x400, DEFAULT_GPIOBASE + 0x38); + + cbmem_initted = !cbmem_recovery(s3resume); + + romstage_handoff_init(cbmem_initted && s3resume); + + printk(BIOS_SPEW, "exit main()\n"); +} diff --git a/pool/shard003/C/0064103_p2p_rput.c b/pool/shard003/C/0064103_p2p_rput.c new file mode 100644 index 0000000000000000000000000000000000000000..4e1ab1e53d61bf2a1d46fa5a803e8f0666609370 --- /dev/null +++ b/pool/shard003/C/0064103_p2p_rput.c @@ -0,0 +1,177 @@ +/*============================================================================== + * Program : p2p_rput + * Revision : 1.6 (2016-09-16) + * Author : Carlos Rosales Fernandez [carlos.rosales.fernandez(at)gmail.com] + *============================================================================== + * Copyright 2014 Carlos Rosales Fernandez and The University of Texas at Austin + * + * This code was originally written with support from the National Science + * Foundation under Grant #OCI-1134872 + * + * This file is part of the Performance Assessment Workbench (PAW). + * PAW is free software: you can redistribute it and/or modify it under the + * terms of the GNU GPL version 2 or (at your option) any later version. + * + * PAW 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 + * PAW, in the file COPYING.txt. If not, see . + *============================================================================== + * Test sustained MPI bandwidth using MPI-3 Rput/Wait calls. + *============================================================================*/ + +#include +#include +#include +#include +#include +#include "aux.h" +#include "aux_mpi.h" +#include "constants.h" + +int main(int argc, char **argv) +{ + FILE *fp, *fp2; + char testName[32] = "MPI_Rput", file1[64], file2[64]; + int dblSize, proc, nprocs, npairs, partner; + unsigned int i, j, k, size, localSize, NLOOP = NLOOP_MAX; + unsigned int smin = MIN_P2P_SIZE, smed = MED_P2P_SIZE, smax = MAX_P2P_SIZE; + double tScale = USEC, bwScale = MB_8; + double tStart, timeMin, timeMinGlobal, overhead, threshold_lo, threshold_hi; + double msgBytes, sizeBytes, localMax, UsedMem; + double tElapsed[NREPS], tElapsedGlobal[NREPS]; + double *A, *B; + MPI_Win win; + MPI_Status stat; + MPI_Request req; + + // Initialize parallel environment + MPI_Init(&argc, &argv); + MPI_Comm_size( MPI_COMM_WORLD, &nprocs ); + MPI_Comm_rank( MPI_COMM_WORLD, &proc ); + + // Test input parameters + if( nprocs%2 != 0 && proc == 0 ) + fatalError( "P2P test requires an even number of processors" ); + + // Check for user defined limits + checkEnvP2P( proc, &NLOOP, &smin, &smed, &smax ); + + // Initialize local variables + localMax = 0.0; + npairs = nprocs/2; + if( proc < npairs ) partner = proc + npairs; + if( proc >= npairs ) partner = proc - npairs; + UsedMem = (double)smax*(double)sizeof(double)*2.0; + + // Allocate and initialize arrays + srand( SEED ); + A = doubleVector( smax ); + B = doubleVector( smax ); + + // Open output file and write header + if( proc == 0 ){ + // Check timer overhead in seconds + timerTest( &overhead, &threshold_lo, &threshold_hi ); + // Open output files and write headers + sprintf( file1, "rput_time-np_%.4d.dat", nprocs ); + sprintf( file2, "rput_bw-np_%.4d.dat", nprocs ); + fp = fopen( file1, "a" ); + fp2 = fopen( file2, "a" ); + printHeaders( fp, fp2, testName, UsedMem, overhead, threshold_lo ); + } + + // Get type size + MPI_Type_size( MPI_DOUBLE, &dblSize ); + // Set up a window for RMA + MPI_Win_create( A, smax*dblSize, dblSize, MPI_INFO_NULL, MPI_COMM_WORLD, &win ); + MPI_Win_lock_all( 0, win ); + + //================================================================ + // Single loop with minimum size to verify that inner loop length + // is long enough for the timings to be accurate + //================================================================ + // Warmup with a medium size message + if( proc < npairs ){ + MPI_Rput( B, smed, MPI_DOUBLE, partner, 0, smed, MPI_DOUBLE, win, &req ); + MPI_Wait( &req, &stat ); + MPI_Win_flush_all( win ); + } + + // Test if current NLOOP is enough to capture fastest test cases + MPI_Barrier( MPI_COMM_WORLD ); + tStart = benchTimer(); + if( proc < npairs ){ + for(j = 0; j < NLOOP; j++){ + MPI_Rput( B, smin, MPI_DOUBLE, partner, 0, smin, MPI_DOUBLE, win, &req ); + MPI_Wait( &req, &stat ); + MPI_Win_flush_all( win ); + } + } + timeMin = benchTimer() - tStart; + MPI_Reduce( &timeMin, &timeMinGlobal, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD ); + if( proc == 0 ) resetInnerLoop( timeMinGlobal, threshold_lo, &NLOOP ); + MPI_Bcast( &NLOOP, 1, MPI_INT, 0, MPI_COMM_WORLD ); + + + //================================================================ + // Execute test for each requested size + //================================================================ + for( size = smin; size <= smax; size = size*2 ){ + + // Warmup with a medium size message + if( proc < npairs ){ + MPI_Rput( B, smed, MPI_DOUBLE, partner, 0, smed, MPI_DOUBLE, win, &req ); + MPI_Wait( &req, &stat ); + MPI_Win_flush_all( win ); + } + + // Repeat NREPS to collect statistics + for(i = 0; i < NREPS; i++){ + MPI_Barrier( MPI_COMM_WORLD ); + tStart = benchTimer(); + if( proc < npairs ){ + for(j = 0; j < NLOOP; j++){ + MPI_Rput( B, size, MPI_DOUBLE, partner, 0, size, MPI_DOUBLE, win, &req ); + MPI_Wait( &req, &stat ); + MPI_Win_flush_all( win ); + } + } + tElapsed[i] = benchTimer() - tStart; + } + MPI_Reduce( tElapsed, tElapsedGlobal, NREPS, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD ); + // Only task 0 needs to do the analysis of the collected data + if( proc == 0 ){ + // sizeBytes is size to write to file + // msgBytes is actual data exchanged on the wire + msgBytes = (double)size*(double)npairs*(double)dblSize; + sizeBytes = (double)size*(double)dblSize; + post_process( fp, fp2, threshold_hi, tElapsedGlobal, tScale, + bwScale, size*dblSize, sizeBytes, msgBytes, &NLOOP, + &localMax, &localSize ); + } + MPI_Bcast( &NLOOP, 1, MPI_INT, 0, MPI_COMM_WORLD ); + + } + MPI_Win_unlock_all( win ); + + MPI_Win_free( &win ); + MPI_Barrier( MPI_COMM_WORLD ); + free( A ); + free( B ); + + //================================================================ + // Print completion message, free memory and exit + //================================================================ + if( proc == 0 ){ + printSummary( fp2, testName, localMax, localSize ); + fclose( fp2 ); + fclose( fp ); + } + + MPI_Finalize(); + return 0; +} + diff --git a/pool/shard003/C/0064113_p80211req.c b/pool/shard003/C/0064113_p80211req.c new file mode 100644 index 0000000000000000000000000000000000000000..5c2b80164d990a7804735c3088a984308270ee3d --- /dev/null +++ b/pool/shard003/C/0064113_p80211req.c @@ -0,0 +1,239 @@ +/* src/p80211/p80211req.c +* +* Request/Indication/MacMgmt interface handling functions +* +* Copyright (C) 1999 AbsoluteValue Systems, Inc. All Rights Reserved. +* -------------------------------------------------------------------- +* +* linux-wlan +* +* The contents of this file are subject to the Mozilla Public +* License Version 1.1 (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.mozilla.org/MPL/ +* +* Software distributed under the License is distributed on an "AS +* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or +* implied. See the License for the specific language governing +* rights and limitations under the License. +* +* Alternatively, the contents of this file may be used under the +* terms of the GNU Public License version 2 (the "GPL"), in which +* case the provisions of the GPL are applicable instead of the +* above. If you wish to allow the use of your version of this file +* only under the terms of the GPL and not to allow others to use +* your version of this file under the MPL, indicate your decision +* by deleting the provisions above and replace them with the notice +* and other provisions required by the GPL. If you do not delete +* the provisions above, a recipient may use your version of this +* file under either the MPL or the GPL. +* +* -------------------------------------------------------------------- +* +* Inquiries regarding the linux-wlan Open Source project can be +* made directly to: +* +* AbsoluteValue Systems Inc. +* info@linux-wlan.com +* http://www.linux-wlan.com +* +* -------------------------------------------------------------------- +* +* Portions of the development of this software were funded by +* Intersil Corporation as part of PRISM(R) chipset product development. +* +* -------------------------------------------------------------------- +* +* This file contains the functions, types, and macros to support the +* MLME request interface that's implemented via the device ioctls. +* +* -------------------------------------------------------------------- +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "p80211types.h" +#include "p80211hdr.h" +#include "p80211mgmt.h" +#include "p80211conv.h" +#include "p80211msg.h" +#include "p80211netdev.h" +#include "p80211ioctl.h" +#include "p80211metadef.h" +#include "p80211metastruct.h" +#include "p80211req.h" + +static void p80211req_handlemsg(wlandevice_t *wlandev, struct p80211msg *msg); +static void p80211req_mibset_mibget(wlandevice_t *wlandev, + struct p80211msg_dot11req_mibget *mib_msg, + int isget); + +static void p80211req_handle_action(struct wlandevice *wlandev, u32 *data, + int isget, u32 flag) +{ + if (isget) { + if (wlandev->hostwep & flag) + *data = P80211ENUM_truth_true; + else + *data = P80211ENUM_truth_false; + } else { + wlandev->hostwep &= ~flag; + if (*data == P80211ENUM_truth_true) + wlandev->hostwep |= flag; + } +} + +/*---------------------------------------------------------------- +* p80211req_dorequest +* +* Handles an MLME request/confirm message. +* +* Arguments: +* wlandev WLAN device struct +* msgbuf Buffer containing a request message +* +* Returns: +* 0 on success, an errno otherwise +* +* Call context: +* Potentially blocks the caller, so it's a good idea to +* not call this function from an interrupt context. +----------------------------------------------------------------*/ +int p80211req_dorequest(wlandevice_t *wlandev, u8 *msgbuf) +{ + struct p80211msg *msg = (struct p80211msg *) msgbuf; + + /* Check to make sure the MSD is running */ + if (!((wlandev->msdstate == WLAN_MSD_HWPRESENT && + msg->msgcode == DIDmsg_lnxreq_ifstate) || + wlandev->msdstate == WLAN_MSD_RUNNING || + wlandev->msdstate == WLAN_MSD_FWLOAD)) { + return -ENODEV; + } + + /* Check Permissions */ + if (!capable(CAP_NET_ADMIN) && + (msg->msgcode != DIDmsg_dot11req_mibget)) { + netdev_err(wlandev->netdev, + "%s: only dot11req_mibget allowed for non-root.\n", + wlandev->name); + return -EPERM; + } + + /* Check for busy status */ + if (test_and_set_bit(1, &(wlandev->request_pending))) + return -EBUSY; + + /* Allow p80211 to look at msg and handle if desired. */ + /* So far, all p80211 msgs are immediate, no waitq/timer necessary */ + /* This may change. */ + p80211req_handlemsg(wlandev, msg); + + /* Pass it down to wlandev via wlandev->mlmerequest */ + if (wlandev->mlmerequest != NULL) + wlandev->mlmerequest(wlandev, msg); + + clear_bit(1, &(wlandev->request_pending)); + return 0; /* if result==0, msg->status still may contain an err */ +} + +/*---------------------------------------------------------------- +* p80211req_handlemsg +* +* p80211 message handler. Primarily looks for messages that +* belong to p80211 and then dispatches the appropriate response. +* TODO: we don't do anything yet. Once the linuxMIB is better +* defined we'll need a get/set handler. +* +* Arguments: +* wlandev WLAN device struct +* msg message structure +* +* Returns: +* nothing (any results are set in the status field of the msg) +* +* Call context: +* Process thread +----------------------------------------------------------------*/ +static void p80211req_handlemsg(wlandevice_t *wlandev, struct p80211msg *msg) +{ + switch (msg->msgcode) { + + case DIDmsg_lnxreq_hostwep:{ + struct p80211msg_lnxreq_hostwep *req = + (struct p80211msg_lnxreq_hostwep *) msg; + wlandev->hostwep &= + ~(HOSTWEP_DECRYPT | HOSTWEP_ENCRYPT); + if (req->decrypt.data == P80211ENUM_truth_true) + wlandev->hostwep |= HOSTWEP_DECRYPT; + if (req->encrypt.data == P80211ENUM_truth_true) + wlandev->hostwep |= HOSTWEP_ENCRYPT; + + break; + } + case DIDmsg_dot11req_mibget: + case DIDmsg_dot11req_mibset:{ + int isget = (msg->msgcode == DIDmsg_dot11req_mibget); + struct p80211msg_dot11req_mibget *mib_msg = + (struct p80211msg_dot11req_mibget *) msg; + p80211req_mibset_mibget(wlandev, mib_msg, isget); + break; + } + } /* switch msg->msgcode */ +} + +static void p80211req_mibset_mibget(wlandevice_t *wlandev, + struct p80211msg_dot11req_mibget *mib_msg, + int isget) +{ + p80211itemd_t *mibitem = (p80211itemd_t *) mib_msg->mibattribute.data; + p80211pstrd_t *pstr = (p80211pstrd_t *) mibitem->data; + u8 *key = mibitem->data + sizeof(p80211pstrd_t); + + switch (mibitem->did) { + case DIDmib_dot11smt_dot11WEPDefaultKeysTable_dot11WEPDefaultKey0: + case DIDmib_dot11smt_dot11WEPDefaultKeysTable_dot11WEPDefaultKey1: + case DIDmib_dot11smt_dot11WEPDefaultKeysTable_dot11WEPDefaultKey2: + case DIDmib_dot11smt_dot11WEPDefaultKeysTable_dot11WEPDefaultKey3: + if (!isget) + wep_change_key(wlandev, + P80211DID_ITEM(mibitem->did) - 1, + key, pstr->len); + break; + + case DIDmib_dot11smt_dot11PrivacyTable_dot11WEPDefaultKeyID:{ + u32 *data = (u32 *) mibitem->data; + + if (isget) { + *data = wlandev->hostwep & HOSTWEP_DEFAULTKEY_MASK; + } else { + wlandev->hostwep &= ~(HOSTWEP_DEFAULTKEY_MASK); + wlandev->hostwep |= (*data & HOSTWEP_DEFAULTKEY_MASK); + } + break; + } + case DIDmib_dot11smt_dot11PrivacyTable_dot11PrivacyInvoked:{ + u32 *data = (u32 *) mibitem->data; + + p80211req_handle_action(wlandev, data, isget, + HOSTWEP_PRIVACYINVOKED); + break; + } + case DIDmib_dot11smt_dot11PrivacyTable_dot11ExcludeUnencrypted:{ + u32 *data = (u32 *) mibitem->data; + + p80211req_handle_action(wlandev, data, isget, + HOSTWEP_EXCLUDEUNENCRYPTED); + break; + } + } +} diff --git a/pool/shard003/C/0064114_lpc_phy_smsc87x0.c b/pool/shard003/C/0064114_lpc_phy_smsc87x0.c new file mode 100644 index 0000000000000000000000000000000000000000..24c5ef724760774a66be4dd84e37b8853965d8f5 --- /dev/null +++ b/pool/shard003/C/0064114_lpc_phy_smsc87x0.c @@ -0,0 +1,270 @@ +/* + * @brief SMSC 87x0 simple PHY driver + * + * @note + * Copyright(C) NXP Semiconductors, 2012 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "chip.h" +#include "lpc_phy.h" + +/** @defgroup SMSC87X0_PHY BOARD: PHY status and control driver for the SMSC 87x0 + * @ingroup BOARD_PHY + * Various functions for controlling and monitoring the status of the + * SMSC 87x0 PHY. + * @{ + */ + +/* LAN8720 PHY register offsets */ +#define LAN8_BCR_REG 0x0 /*!< Basic Control Register */ +#define LAN8_BSR_REG 0x1 /*!< Basic Status Reg */ +#define LAN8_PHYID1_REG 0x2 /*!< PHY ID 1 Reg */ +#define LAN8_PHYID2_REG 0x3 /*!< PHY ID 2 Reg */ +#define LAN8_PHYSPLCTL_REG 0x1F/*!< PHY special control/status Reg */ + +/* LAN8720 BCR register definitions */ +#define LAN8_RESET (1 << 15) /*!< 1= S/W Reset */ +#define LAN8_LOOPBACK (1 << 14) /*!< 1=loopback Enabled */ +#define LAN8_SPEED_SELECT (1 << 13) /*!< 1=Select 100MBps */ +#define LAN8_AUTONEG (1 << 12) /*!< 1=Enable auto-negotiation */ +#define LAN8_POWER_DOWN (1 << 11) /*!< 1=Power down PHY */ +#define LAN8_ISOLATE (1 << 10) /*!< 1=Isolate PHY */ +#define LAN8_RESTART_AUTONEG (1 << 9) /*!< 1=Restart auto-negoatiation */ +#define LAN8_DUPLEX_MODE (1 << 8) /*!< 1=Full duplex mode */ + +/* LAN8720 BSR register definitions */ +#define LAN8_100BASE_T4 (1 << 15) /*!< T4 mode */ +#define LAN8_100BASE_TX_FD (1 << 14) /*!< 100MBps full duplex */ +#define LAN8_100BASE_TX_HD (1 << 13) /*!< 100MBps half duplex */ +#define LAN8_10BASE_T_FD (1 << 12) /*!< 100Bps full duplex */ +#define LAN8_10BASE_T_HD (1 << 11) /*!< 10MBps half duplex */ +#define LAN8_AUTONEG_COMP (1 << 5) /*!< Auto-negotation complete */ +#define LAN8_RMT_FAULT (1 << 4) /*!< Fault */ +#define LAN8_AUTONEG_ABILITY (1 << 3) /*!< Auto-negotation supported */ +#define LAN8_LINK_STATUS (1 << 2) /*!< 1=Link active */ +#define LAN8_JABBER_DETECT (1 << 1) /*!< Jabber detect */ +#define LAN8_EXTEND_CAPAB (1 << 0) /*!< Supports extended capabilities */ + +/* LAN8720 PHYSPLCTL status definitions */ +#define LAN8_SPEEDMASK (7 << 2) /*!< Speed and duplex mask */ +#define LAN8_SPEED100F (6 << 2) /*!< 100BT full duplex */ +#define LAN8_SPEED10F (5 << 2) /*!< 10BT full duplex */ +#define LAN8_SPEED100H (2 << 2) /*!< 100BT half duplex */ +#define LAN8_SPEED10H (1 << 2) /*!< 10BT half duplex */ + +/* LAN8720 PHY ID 1/2 register definitions */ +#define LAN8_PHYID1_OUI 0x0007 /*!< Expected PHY ID1 */ +#define LAN8_PHYID2_OUI 0xC0F0 /*!< Expected PHY ID2, except last 4 bits */ + +/* DP83848 PHY update flags */ +static uint32_t physts, olddphysts; + +/* PHY update counter for state machine */ +static int32_t phyustate; + +/* Pointer to delay function used for this driver */ +static p_msDelay_func_t pDelayMs; + +/* Write to the PHY. Will block for delays based on the pDelayMs function. Returns + true on success, or false on failure */ +static Status lpc_mii_write(uint8_t reg, uint16_t data) +{ + Status sts = ERROR; + int32_t mst = 250; + + /* Write value for register */ + Chip_ENET_StartMIIWrite(LPC_ETHERNET, reg, data); + + /* Wait for unbusy status */ + while (mst > 0) { + if (Chip_ENET_IsMIIBusy(LPC_ETHERNET)) { + mst--; + pDelayMs(1); + } + else { + mst = 0; + sts = SUCCESS; + } + } + + return sts; +} + +/* Read from the PHY. Will block for delays based on the pDelayMs function. Returns + true on success, or false on failure */ +static Status lpc_mii_read(uint8_t reg, uint16_t *data) +{ + Status sts = ERROR; + int32_t mst = 250; + + /* Start register read */ + Chip_ENET_StartMIIRead(LPC_ETHERNET, reg); + + /* Wait for unbusy status */ + while (mst > 0) { + if (!Chip_ENET_IsMIIBusy(LPC_ETHERNET)) { + mst = 0; + *data = Chip_ENET_ReadMIIData(LPC_ETHERNET); + sts = SUCCESS; + } + else { + mst--; + pDelayMs(1); + } + } + + return sts; +} + +/* Update PHY status from passed value */ +static void smsc_update_phy_sts(uint16_t linksts, uint16_t sdsts) +{ + /* Update link active status */ + if (linksts & LAN8_LINK_STATUS) { + physts |= PHY_LINK_CONNECTED; + } + else { + physts &= ~PHY_LINK_CONNECTED; + } + + switch (sdsts & LAN8_SPEEDMASK) { + case LAN8_SPEED100F: + default: + physts |= PHY_LINK_SPEED100; + physts |= PHY_LINK_FULLDUPLX; + break; + + case LAN8_SPEED10F: + physts &= ~PHY_LINK_SPEED100; + physts |= PHY_LINK_FULLDUPLX; + break; + + case LAN8_SPEED100H: + physts |= PHY_LINK_SPEED100; + physts &= ~PHY_LINK_FULLDUPLX; + break; + + case LAN8_SPEED10H: + physts &= ~PHY_LINK_SPEED100; + physts &= ~PHY_LINK_FULLDUPLX; + break; + } + + /* If the status has changed, indicate via change flag */ + if ((physts & (PHY_LINK_SPEED100 | PHY_LINK_FULLDUPLX | PHY_LINK_CONNECTED)) != + (olddphysts & (PHY_LINK_SPEED100 | PHY_LINK_FULLDUPLX | PHY_LINK_CONNECTED))) { + olddphysts = physts; + physts |= PHY_LINK_CHANGED; + } +} + +/* Initialize the SMSC 87x0 PHY */ +uint32_t lpc_phy_init(bool rmii, p_msDelay_func_t pDelayMsFunc) +{ + uint16_t tmp; + int32_t i; + + pDelayMs = pDelayMsFunc; + + /* Initial states for PHY status and state machine */ + olddphysts = physts = phyustate = 0; + + /* Only first read and write are checked for failure */ + /* Put the DP83848C in reset mode and wait for completion */ + if (lpc_mii_write(LAN8_BCR_REG, LAN8_RESET) != SUCCESS) { + return ERROR; + } + i = 400; + while (i > 0) { + pDelayMs(1); + if (lpc_mii_read(LAN8_BCR_REG, &tmp) != SUCCESS) { + return ERROR; + } + + if (!(tmp & (LAN8_RESET | LAN8_POWER_DOWN))) { + i = -1; + } + else { + i--; + } + } + /* Timeout? */ + if (i == 0) { + return ERROR; + } + + /* Setup link */ + lpc_mii_write(LAN8_BCR_REG, LAN8_AUTONEG); + + /* The link is not set active at this point, but will be detected + later */ + + return SUCCESS; +} + +/* Phy status update state machine */ +uint32_t lpcPHYStsPoll(void) +{ + static uint16_t sts; + + switch (phyustate) { + default: + case 0: + /* Read BMSR to clear faults */ + Chip_ENET_StartMIIRead(LPC_ETHERNET, LAN8_BSR_REG); + physts &= ~PHY_LINK_CHANGED; + physts = physts | PHY_LINK_BUSY; + phyustate = 1; + break; + + case 1: + /* Wait for read status state */ + if (!Chip_ENET_IsMIIBusy(LPC_ETHERNET)) { + /* Get PHY status with link state */ + sts = Chip_ENET_ReadMIIData(LPC_ETHERNET); + Chip_ENET_StartMIIRead(LPC_ETHERNET, LAN8_PHYSPLCTL_REG); + phyustate = 2; + } + break; + + case 2: + /* Wait for read status state */ + if (!Chip_ENET_IsMIIBusy(LPC_ETHERNET)) { + /* Update PHY status */ + physts &= ~PHY_LINK_BUSY; + smsc_update_phy_sts(sts, Chip_ENET_ReadMIIData(LPC_ETHERNET)); + phyustate = 0; + } + break; + } + + return physts; +} + +/** + * @} + */ diff --git a/pool/shard003/C/0064117_exutils.c b/pool/shard003/C/0064117_exutils.c new file mode 100644 index 0000000000000000000000000000000000000000..ec22f84df719f806b617137068d3c820748c0dfc --- /dev/null +++ b/pool/shard003/C/0064117_exutils.c @@ -0,0 +1,572 @@ +/****************************************************************************** + * + * Module Name: exutils - interpreter/scanner utilities + * + *****************************************************************************/ + +/****************************************************************************** + * + * 1. Copyright Notice + * + * Some or all of this work - Copyright (c) 1999 - 2016, Intel Corp. + * All rights reserved. + * + * 2. License + * + * 2.1. This is your license from Intel Corp. under its intellectual property + * rights. You may have additional license terms from the party that provided + * you this software, covering your right to use that party's intellectual + * property rights. + * + * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a + * copy of the source code appearing in this file ("Covered Code") an + * irrevocable, perpetual, worldwide license under Intel's copyrights in the + * base code distributed originally by Intel ("Original Intel Code") to copy, + * make derivatives, distribute, use and display any portion of the Covered + * Code in any form, with the right to sublicense such rights; and + * + * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent + * license (with the right to sublicense), under only those claims of Intel + * patents that are infringed by the Original Intel Code, to make, use, sell, + * offer to sell, and import the Covered Code and derivative works thereof + * solely to the minimum extent necessary to exercise the above copyright + * license, and in no event shall the patent license extend to any additions + * to or modifications of the Original Intel Code. No other license or right + * is granted directly or by implication, estoppel or otherwise; + * + * The above copyright and patent license is granted only if the following + * conditions are met: + * + * 3. Conditions + * + * 3.1. Redistribution of Source with Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification with rights to further distribute source must include + * the above Copyright Notice, the above License, this list of Conditions, + * and the following Disclaimer and Export Compliance provision. In addition, + * Licensee must cause all Covered Code to which Licensee contributes to + * contain a file documenting the changes Licensee made to create that Covered + * Code and the date of any change. Licensee must include in that file the + * documentation of any changes made by any predecessor Licensee. Licensee + * must include a prominent statement that the modification is derived, + * directly or indirectly, from Original Intel Code. + * + * 3.2. Redistribution of Source with no Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification without rights to further distribute source must + * include the following Disclaimer and Export Compliance provision in the + * documentation and/or other materials provided with distribution. In + * addition, Licensee may not authorize further sublicense of source of any + * portion of the Covered Code, and must include terms to the effect that the + * license from Licensee to its licensee is limited to the intellectual + * property embodied in the software Licensee provides to its licensee, and + * not to intellectual property embodied in modifications its licensee may + * make. + * + * 3.3. Redistribution of Executable. Redistribution in executable form of any + * substantial portion of the Covered Code or modification must reproduce the + * above Copyright Notice, and the following Disclaimer and Export Compliance + * provision in the documentation and/or other materials provided with the + * distribution. + * + * 3.4. Intel retains all right, title, and interest in and to the Original + * Intel Code. + * + * 3.5. Neither the name Intel nor any other trademark owned or controlled by + * Intel shall be used in advertising or otherwise to promote the sale, use or + * other dealings in products derived from or relating to the Covered Code + * without prior written authorization from Intel. + * + * 4. Disclaimer and Export Compliance + * + * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED + * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE + * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, + * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY + * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY + * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A + * PARTICULAR PURPOSE. + * + * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES + * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR + * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, + * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY + * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL + * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS + * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY + * LIMITED REMEDY. + * + * 4.3. Licensee shall not export, either directly or indirectly, any of this + * software or system incorporating such software without first obtaining any + * required license or other approval from the U. S. Department of Commerce or + * any other agency or department of the United States Government. In the + * event Licensee exports any such software from the United States or + * re-exports any such software from a foreign destination, Licensee shall + * ensure that the distribution and export/re-export of the software is in + * compliance with all laws, regulations, orders, or other restrictions of the + * U.S. Export Administration Regulations. Licensee agrees that neither it nor + * any of its subsidiaries will export/re-export any technical data, process, + * software, or service, directly or indirectly, to any country for which the + * United States government or any agency thereof requires an export license, + * other governmental approval, or letter of assurance, without first obtaining + * such license, approval or letter. + * + *****************************************************************************/ + +/* + * DEFINE_AML_GLOBALS is tested in amlcode.h + * to determine whether certain global names should be "defined" or only + * "declared" in the current compilation. This enhances maintainability + * by enabling a single header file to embody all knowledge of the names + * in question. + * + * Exactly one module of any executable should #define DEFINE_GLOBALS + * before #including the header files which use this convention. The + * names in question will be defined and initialized in that module, + * and declared as extern in all other modules which #include those + * header files. + */ + +#define DEFINE_AML_GLOBALS + +#include "acpi.h" +#include "accommon.h" +#include "acinterp.h" +#include "amlcode.h" + +#define _COMPONENT ACPI_EXECUTER + ACPI_MODULE_NAME ("exutils") + +/* Local prototypes */ + +static UINT32 +AcpiExDigitsNeeded ( + UINT64 Value, + UINT32 Base); + + +#ifndef ACPI_NO_METHOD_EXECUTION +/******************************************************************************* + * + * FUNCTION: AcpiExEnterInterpreter + * + * PARAMETERS: None + * + * RETURN: None + * + * DESCRIPTION: Enter the interpreter execution region. Failure to enter + * the interpreter region is a fatal system error. Used in + * conjunction with ExitInterpreter. + * + ******************************************************************************/ + +void +AcpiExEnterInterpreter ( + void) +{ + ACPI_STATUS Status; + + + ACPI_FUNCTION_TRACE (ExEnterInterpreter); + + + Status = AcpiUtAcquireMutex (ACPI_MTX_INTERPRETER); + if (ACPI_FAILURE (Status)) + { + ACPI_ERROR ((AE_INFO, "Could not acquire AML Interpreter mutex")); + } + + return_VOID; +} + + +/******************************************************************************* + * + * FUNCTION: AcpiExExitInterpreter + * + * PARAMETERS: None + * + * RETURN: None + * + * DESCRIPTION: Exit the interpreter execution region. This is the top level + * routine used to exit the interpreter when all processing has + * been completed, or when the method blocks. + * + * Cases where the interpreter is unlocked internally: + * 1) Method will be blocked on a Sleep() AML opcode + * 2) Method will be blocked on an Acquire() AML opcode + * 3) Method will be blocked on a Wait() AML opcode + * 4) Method will be blocked to acquire the global lock + * 5) Method will be blocked waiting to execute a serialized control + * method that is currently executing + * 6) About to invoke a user-installed opregion handler + * + ******************************************************************************/ + +void +AcpiExExitInterpreter ( + void) +{ + ACPI_STATUS Status; + + + ACPI_FUNCTION_TRACE (ExExitInterpreter); + + + Status = AcpiUtReleaseMutex (ACPI_MTX_INTERPRETER); + if (ACPI_FAILURE (Status)) + { + ACPI_ERROR ((AE_INFO, "Could not release AML Interpreter mutex")); + } + + return_VOID; +} + + +/******************************************************************************* + * + * FUNCTION: AcpiExTruncateFor32bitTable + * + * PARAMETERS: ObjDesc - Object to be truncated + * + * RETURN: TRUE if a truncation was performed, FALSE otherwise. + * + * DESCRIPTION: Truncate an ACPI Integer to 32 bits if the execution mode is + * 32-bit, as determined by the revision of the DSDT. + * + ******************************************************************************/ + +BOOLEAN +AcpiExTruncateFor32bitTable ( + ACPI_OPERAND_OBJECT *ObjDesc) +{ + + ACPI_FUNCTION_ENTRY (); + + + /* + * Object must be a valid number and we must be executing + * a control method. Object could be NS node for AML_INT_NAMEPATH_OP. + */ + if ((!ObjDesc) || + (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) != ACPI_DESC_TYPE_OPERAND) || + (ObjDesc->Common.Type != ACPI_TYPE_INTEGER)) + { + return (FALSE); + } + + if ((AcpiGbl_IntegerByteWidth == 4) && + (ObjDesc->Integer.Value > (UINT64) ACPI_UINT32_MAX)) + { + /* + * We are executing in a 32-bit ACPI table. Truncate + * the value to 32 bits by zeroing out the upper 32-bit field + */ + ObjDesc->Integer.Value &= (UINT64) ACPI_UINT32_MAX; + return (TRUE); + } + + return (FALSE); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiExAcquireGlobalLock + * + * PARAMETERS: FieldFlags - Flags with Lock rule: + * AlwaysLock or NeverLock + * + * RETURN: None + * + * DESCRIPTION: Obtain the ACPI hardware Global Lock, only if the field + * flags specifiy that it is to be obtained before field access. + * + ******************************************************************************/ + +void +AcpiExAcquireGlobalLock ( + UINT32 FieldFlags) +{ + ACPI_STATUS Status; + + + ACPI_FUNCTION_TRACE (ExAcquireGlobalLock); + + + /* Only use the lock if the AlwaysLock bit is set */ + + if (!(FieldFlags & AML_FIELD_LOCK_RULE_MASK)) + { + return_VOID; + } + + /* Attempt to get the global lock, wait forever */ + + Status = AcpiExAcquireMutexObject (ACPI_WAIT_FOREVER, + AcpiGbl_GlobalLockMutex, AcpiOsGetThreadId ()); + + if (ACPI_FAILURE (Status)) + { + ACPI_EXCEPTION ((AE_INFO, Status, + "Could not acquire Global Lock")); + } + + return_VOID; +} + + +/******************************************************************************* + * + * FUNCTION: AcpiExReleaseGlobalLock + * + * PARAMETERS: FieldFlags - Flags with Lock rule: + * AlwaysLock or NeverLock + * + * RETURN: None + * + * DESCRIPTION: Release the ACPI hardware Global Lock + * + ******************************************************************************/ + +void +AcpiExReleaseGlobalLock ( + UINT32 FieldFlags) +{ + ACPI_STATUS Status; + + + ACPI_FUNCTION_TRACE (ExReleaseGlobalLock); + + + /* Only use the lock if the AlwaysLock bit is set */ + + if (!(FieldFlags & AML_FIELD_LOCK_RULE_MASK)) + { + return_VOID; + } + + /* Release the global lock */ + + Status = AcpiExReleaseMutexObject (AcpiGbl_GlobalLockMutex); + if (ACPI_FAILURE (Status)) + { + /* Report the error, but there isn't much else we can do */ + + ACPI_EXCEPTION ((AE_INFO, Status, + "Could not release Global Lock")); + } + + return_VOID; +} + + +/******************************************************************************* + * + * FUNCTION: AcpiExDigitsNeeded + * + * PARAMETERS: Value - Value to be represented + * Base - Base of representation + * + * RETURN: The number of digits. + * + * DESCRIPTION: Calculate the number of digits needed to represent the Value + * in the given Base (Radix) + * + ******************************************************************************/ + +static UINT32 +AcpiExDigitsNeeded ( + UINT64 Value, + UINT32 Base) +{ + UINT32 NumDigits; + UINT64 CurrentValue; + + + ACPI_FUNCTION_TRACE (ExDigitsNeeded); + + + /* UINT64 is unsigned, so we don't worry about a '-' prefix */ + + if (Value == 0) + { + return_UINT32 (1); + } + + CurrentValue = Value; + NumDigits = 0; + + /* Count the digits in the requested base */ + + while (CurrentValue) + { + (void) AcpiUtShortDivide (CurrentValue, Base, &CurrentValue, NULL); + NumDigits++; + } + + return_UINT32 (NumDigits); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiExEisaIdToString + * + * PARAMETERS: OutString - Where to put the converted string (8 bytes) + * CompressedId - EISAID to be converted + * + * RETURN: None + * + * DESCRIPTION: Convert a numeric EISAID to string representation. Return + * buffer must be large enough to hold the string. The string + * returned is always exactly of length ACPI_EISAID_STRING_SIZE + * (includes null terminator). The EISAID is always 32 bits. + * + ******************************************************************************/ + +void +AcpiExEisaIdToString ( + char *OutString, + UINT64 CompressedId) +{ + UINT32 SwappedId; + + + ACPI_FUNCTION_ENTRY (); + + + /* The EISAID should be a 32-bit integer */ + + if (CompressedId > ACPI_UINT32_MAX) + { + ACPI_WARNING ((AE_INFO, + "Expected EISAID is larger than 32 bits: " + "0x%8.8X%8.8X, truncating", + ACPI_FORMAT_UINT64 (CompressedId))); + } + + /* Swap ID to big-endian to get contiguous bits */ + + SwappedId = AcpiUtDwordByteSwap ((UINT32) CompressedId); + + /* First 3 bytes are uppercase letters. Next 4 bytes are hexadecimal */ + + OutString[0] = (char) (0x40 + (((unsigned long) SwappedId >> 26) & 0x1F)); + OutString[1] = (char) (0x40 + ((SwappedId >> 21) & 0x1F)); + OutString[2] = (char) (0x40 + ((SwappedId >> 16) & 0x1F)); + OutString[3] = AcpiUtHexToAsciiChar ((UINT64) SwappedId, 12); + OutString[4] = AcpiUtHexToAsciiChar ((UINT64) SwappedId, 8); + OutString[5] = AcpiUtHexToAsciiChar ((UINT64) SwappedId, 4); + OutString[6] = AcpiUtHexToAsciiChar ((UINT64) SwappedId, 0); + OutString[7] = 0; +} + + +/******************************************************************************* + * + * FUNCTION: AcpiExIntegerToString + * + * PARAMETERS: OutString - Where to put the converted string. At least + * 21 bytes are needed to hold the largest + * possible 64-bit integer. + * Value - Value to be converted + * + * RETURN: Converted string in OutString + * + * DESCRIPTION: Convert a 64-bit integer to decimal string representation. + * Assumes string buffer is large enough to hold the string. The + * largest string is (ACPI_MAX64_DECIMAL_DIGITS + 1). + * + ******************************************************************************/ + +void +AcpiExIntegerToString ( + char *OutString, + UINT64 Value) +{ + UINT32 Count; + UINT32 DigitsNeeded; + UINT32 Remainder; + + + ACPI_FUNCTION_ENTRY (); + + + DigitsNeeded = AcpiExDigitsNeeded (Value, 10); + OutString[DigitsNeeded] = 0; + + for (Count = DigitsNeeded; Count > 0; Count--) + { + (void) AcpiUtShortDivide (Value, 10, &Value, &Remainder); + OutString[Count-1] = (char) ('0' + Remainder);\ + } +} + + +/******************************************************************************* + * + * FUNCTION: AcpiExPciClsToString + * + * PARAMETERS: OutString - Where to put the converted string (7 bytes) + * ClassCode - PCI class code to be converted (3 bytes) + * + * RETURN: Converted string in OutString + * + * DESCRIPTION: Convert 3-bytes PCI class code to string representation. + * Return buffer must be large enough to hold the string. The + * string returned is always exactly of length + * ACPI_PCICLS_STRING_SIZE (includes null terminator). + * + ******************************************************************************/ + +void +AcpiExPciClsToString ( + char *OutString, + UINT8 ClassCode[3]) +{ + + ACPI_FUNCTION_ENTRY (); + + + /* All 3 bytes are hexadecimal */ + + OutString[0] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[0], 4); + OutString[1] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[0], 0); + OutString[2] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[1], 4); + OutString[3] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[1], 0); + OutString[4] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[2], 4); + OutString[5] = AcpiUtHexToAsciiChar ((UINT64) ClassCode[2], 0); + OutString[6] = 0; +} + + +/******************************************************************************* + * + * FUNCTION: AcpiIsValidSpaceId + * + * PARAMETERS: SpaceId - ID to be validated + * + * RETURN: TRUE if SpaceId is a valid/supported ID. + * + * DESCRIPTION: Validate an operation region SpaceID. + * + ******************************************************************************/ + +BOOLEAN +AcpiIsValidSpaceId ( + UINT8 SpaceId) +{ + + if ((SpaceId >= ACPI_NUM_PREDEFINED_REGIONS) && + (SpaceId < ACPI_USER_REGION_BEGIN) && + (SpaceId != ACPI_ADR_SPACE_DATA_TABLE) && + (SpaceId != ACPI_ADR_SPACE_FIXED_HARDWARE)) + { + return (FALSE); + } + + return (TRUE); +} + +#endif diff --git a/pool/shard003/C/0064119_cmd_dfu.c b/pool/shard003/C/0064119_cmd_dfu.c new file mode 100644 index 0000000000000000000000000000000000000000..01d6b3a2d66b6a4780f8a479ff41ffd2a5bd601b --- /dev/null +++ b/pool/shard003/C/0064119_cmd_dfu.c @@ -0,0 +1,81 @@ +/* + * cmd_dfu.c -- dfu command + * + * Copyright (C) 2012 Samsung Electronics + * authors: Andrzej Pietrasiewicz + * Lukasz Majewski + * + * 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 + +static int do_dfu(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) +{ + const char *str_env; + char *s = "dfu"; + char *env_bkp; + int ret; + + if (argc < 3) + return CMD_RET_USAGE; + + str_env = getenv("dfu_alt_info"); + if (str_env == NULL) { + printf("%s: \"dfu_alt_info\" env variable not defined!\n", + __func__); + return CMD_RET_FAILURE; + } + + env_bkp = strdup(str_env); + ret = dfu_config_entities(env_bkp, argv[1], + (int)simple_strtoul(argv[2], NULL, 10)); + if (ret) + return CMD_RET_FAILURE; + + if (strcmp(argv[3], "list") == 0) { + dfu_show_entities(); + goto done; + } + + board_usb_init(); + g_dnl_register(s); + while (1) { + if (ctrlc()) + goto exit; + + usb_gadget_handle_interrupts(); + } +exit: + g_dnl_unregister(); +done: + dfu_free_entities(); + free(env_bkp); + + return CMD_RET_SUCCESS; +} + +U_BOOT_CMD(dfu, CONFIG_SYS_MAXARGS, 1, do_dfu, + "Device Firmware Upgrade", + " [list]\n" + " - device firmware upgrade on a device \n" + " attached to interface \n" + " [list] - list available alt settings" +); diff --git a/pool/shard003/C/0064120_SubjectAltName.c b/pool/shard003/C/0064120_SubjectAltName.c new file mode 100644 index 0000000000000000000000000000000000000000..2d955b8bf292fb83e0278c18b4923bc4c4707e1f --- /dev/null +++ b/pool/shard003/C/0064120_SubjectAltName.c @@ -0,0 +1,60 @@ +/* + * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) + * From ASN.1 module "PKIX1Implicit88" + * found in "asn1/rfc3280-PKIX1Implicit88.asn1" + * `asn1c -S asn1c/skeletons -pdu=all -pdu=Certificate -fwide-types` + */ + +#include "SubjectAltName.h" + +int +SubjectAltName_constraint(asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + size_t size; + + if(!sptr) { + ASN__CTFAIL(app_key, td, sptr, + "%s: value not given (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } + + /* Determine the number of elements */ + size = _A_CSEQUENCE_FROM_VOID(sptr)->count; + + if((size >= 1)) { + /* Perform validation of the inner elements */ + return td->op->check_constraints(td, sptr, ctfailcb, app_key); + } else { + ASN__CTFAIL(app_key, td, sptr, + "%s: constraint failed (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } +} + +/* + * This type is implemented using GeneralNames, + * so here we adjust the DEF accordingly. + */ +static const ber_tlv_tag_t asn_DEF_SubjectAltName_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_SubjectAltName = { + "SubjectAltName", + "SubjectAltName", + &asn_OP_SEQUENCE_OF, + SubjectAltName_constraint, + asn_DEF_SubjectAltName_tags_1, + sizeof(asn_DEF_SubjectAltName_tags_1) + /sizeof(asn_DEF_SubjectAltName_tags_1[0]), /* 1 */ + asn_DEF_SubjectAltName_tags_1, /* Same as above */ + sizeof(asn_DEF_SubjectAltName_tags_1) + /sizeof(asn_DEF_SubjectAltName_tags_1[0]), /* 1 */ + 0, /* No OER visible constraints */ + 0, /* No PER visible constraints */ + asn_MBR_GeneralNames_1, + 1, /* Single element */ + &asn_SPC_GeneralNames_specs_1 /* Additional specs */ +}; + diff --git a/pool/shard003/C/0064124_srtp-test-recv.c b/pool/shard003/C/0064124_srtp-test-recv.c new file mode 100644 index 0000000000000000000000000000000000000000..4648655d173555c0b1ac1fb5310f6627785827a9 --- /dev/null +++ b/pool/shard003/C/0064124_srtp-test-recv.c @@ -0,0 +1,172 @@ +/* + * Secure RTP with libgcrypt + * Copyright (C) 2007 Rémi Denis-Courmont + * + * 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 + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include +#include "srtp.h" + +#include +#include +#include + +#undef NDEBUG +#include + + +int main (void) +{ + static const char key[] = + "123456789ABCDEF0" "123456789ABCDEF0"; + static const char salt[] = + "1234567890" "1234567890" "12345678"; + int val; + srtp_session_t *sd, *se; + + /* Too big tag length */ + se = srtp_create (SRTP_ENCR_AES_CM, SRTP_AUTH_HMAC_SHA1, 21, + SRTP_PRF_AES_CM, 0); + assert (se == NULL); + + /* Too short tag length */ + se = srtp_create (SRTP_ENCR_AES_CM, SRTP_AUTH_HMAC_SHA1, 3, + SRTP_PRF_AES_CM, SRTP_RCC_MODE1); + assert (se == NULL); + + /* Initializes encryption and decryption contexts */ + se = srtp_create (SRTP_ENCR_AES_CM, SRTP_AUTH_HMAC_SHA1, 20, + SRTP_PRF_AES_CM, SRTP_RCC_MODE1); + assert (se != NULL); + + sd = srtp_create (SRTP_ENCR_AES_CM, SRTP_AUTH_HMAC_SHA1, 20, + SRTP_PRF_AES_CM, SRTP_RCC_MODE1); + assert (sd != NULL); + + srtp_setrcc_rate (se, 1); + srtp_setrcc_rate (sd, 1); + + val = srtp_setkeystring (se, key, salt); + assert (val == 0); + val = srtp_setkeystring (sd, key, salt); + assert (val == 0); + + uint8_t buf[1500], buf2[1500]; + size_t len; + + /* Invalid SRTP packet */ + len = 12; + memset (buf, 0, len); + val = srtp_send (se, buf, &len, sizeof (buf)); + assert (val == EINVAL); + + len = 32; + memset (buf, 0, len); + srtp_recv (sd, buf, &len); + assert (val == EINVAL); + + /* Too short packet */ + len = 11; + buf[0] = 0x80; + val = srtp_send (se, buf, &len, sizeof (buf)); + assert (val == EINVAL); + + len = 11; + val = srtp_recv (sd, buf, &len); + assert (val == EINVAL); + + /* Too short when taking tag into account */ + len = 31; + val = srtp_recv (sd, buf, &len); + assert (val == EINVAL); + + /* Too short when taking RTP extensions into account */ + len = 15; + buf[0] = 0x90; + val = srtp_send (se, buf, &len, sizeof (buf)); + assert (val == EINVAL); + + len = 16; + buf[0] = 0x90; + buf[15] = 1; + val = srtp_send (se, buf, &len, sizeof (buf)); + assert (val == EINVAL); + + /* Too small buffer (seq=1) */ + len = 20; + memset (buf, 0, len); + buf[0] = 0x80; + buf[3] = 1; + val = srtp_send (se, buf, &len, 39); + assert (val == ENOSPC); + assert (len == 40); + + len = 31; + val = srtp_recv (sd, buf, &len); + assert (val == EINVAL); + + /* OK (seq=3) */ + buf[0] = 0x80; + buf[3] = 3; + for (unsigned i = 0; i < 256; i++) + buf[i + 12] = i; + len = 0x10c; + val = srtp_send (se, buf, &len, 0x120); + assert (val == 0); + assert (len == 0x120); + + memcpy (buf2, buf, len); + val = srtp_recv (sd, buf2, &len); + assert (val == 0); + assert (len == 0x10c); + assert (!memcmp (buf2, "\x80\x00\x00\x03" "\x00\x00\x00\x00" + "\x00\x00\x00\x00", 12)); + for (unsigned i = 0; i < 256; i++) + assert (buf2[i + 12] == i); // test actual decryption + + /* Replay attack (seq=3) */ + len = 0x120; + val = srtp_recv (sd, buf, &len); + assert (val == EACCES); + assert (len == 0x10c); + + /* OK but late (seq=2) */ + buf[0] = 0x80; + buf[3] = 2; + val = srtp_send (se, buf, &len, 0x120); + assert (val == 0); + assert (len == 0x120); + + memcpy (buf2, buf, len); + val = srtp_recv (sd, buf2, &len); + assert (val == 0); + assert (len == 0x10c); + + /* Late replay attack (seq=3) */ + len = 0x120; + val = srtp_recv (sd, buf, &len); + assert (val == EACCES); + assert (len == 0x10c); + + srtp_destroy (se); + srtp_destroy (sd); + return 0; +} diff --git a/pool/shard003/C/0064127_gstburn.c b/pool/shard003/C/0064127_gstburn.c new file mode 100644 index 0000000000000000000000000000000000000000..ee448758456df650aaeab256add95287569e7c65 --- /dev/null +++ b/pool/shard003/C/0064127_gstburn.c @@ -0,0 +1,259 @@ +/* + * GStreamer + * Copyright (C) <2010-2015> Luis de Bethencourt + * + * Burn - curve adjustment video effect. + * Based on Pete Warden's FreeFrame plugin with the same name. + * + * 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. + * + * Alternatively, the contents of this file may be used under the + * GNU Lesser General Public License Version 2.1 (the "LGPL"), in + * which case the following provisions apply instead of the ones + * mentioned above: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library 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. + */ + +/** + * SECTION:element-burn + * + * Burn adjusts the colors of a video stream in realtime. + * + * + * Example launch line + * |[ + * gst-launch-1.0 -v videotestsrc ! burn ! videoconvert ! autovideosink + * ]| This pipeline shows the effect of burn on a test stream + * + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include + +#include "gstplugin.h" +#include "gstburn.h" + +#include "gstgaudieffectsorc.h" + +#define gst_burn_parent_class parent_class +G_DEFINE_TYPE (GstBurn, gst_burn, GST_TYPE_VIDEO_FILTER); + +GST_DEBUG_CATEGORY_STATIC (gst_burn_debug); +#define GST_CAT_DEFAULT gst_burn_debug + +#if G_BYTE_ORDER == G_LITTLE_ENDIAN +#define CAPS_STR GST_VIDEO_CAPS_MAKE ("{ BGRx, RGBx }") +#else +#define CAPS_STR GST_VIDEO_CAPS_MAKE ("{ xBGR, xRGB }") +#endif + +/* Filter signals and args. */ +enum +{ + LAST_SIGNAL +}; + +enum +{ + PROP_0 = 0, + PROP_ADJUSTMENT, +}; + +/* Initializations */ + +#define DEFAULT_ADJUSTMENT 175 + +/* The capabilities of the inputs and outputs. */ + +static GstStaticPadTemplate gst_burn_sink_template = +GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS (CAPS_STR) + ); + +static GstStaticPadTemplate gst_burn_src_template = +GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS (CAPS_STR) + ); + +static void gst_burn_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec); +static void gst_burn_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec); + +static void gst_burn_finalize (GObject * object); + +static GstFlowReturn gst_burn_transform_frame (GstVideoFilter * vfilter, + GstVideoFrame * in_frame, GstVideoFrame * out_frame); + +/* GObject vmethod implementations */ + +/* Initialize the burn's class. */ +static void +gst_burn_class_init (GstBurnClass * klass) +{ + GObjectClass *gobject_class = (GObjectClass *) klass; + GstElementClass *gstelement_class = (GstElementClass *) klass; + GstVideoFilterClass *vfilter_class = (GstVideoFilterClass *) klass; + + gst_element_class_set_static_metadata (gstelement_class, "Burn", + "Filter/Effect/Video", + "Burn adjusts the colors in the video signal.", + "Luis de Bethencourt "); + + gst_element_class_add_static_pad_template (gstelement_class, + &gst_burn_sink_template); + gst_element_class_add_static_pad_template (gstelement_class, + &gst_burn_src_template); + + gobject_class->set_property = gst_burn_set_property; + gobject_class->get_property = gst_burn_get_property; + gobject_class->finalize = gst_burn_finalize; + + g_object_class_install_property (gobject_class, PROP_ADJUSTMENT, + g_param_spec_uint ("adjustment", "Adjustment", + "Adjustment parameter", 0, 256, DEFAULT_ADJUSTMENT, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)); + + vfilter_class->transform_frame = GST_DEBUG_FUNCPTR (gst_burn_transform_frame); +} + +/* Initialize the element, + * instantiate pads and add them to element, + * set pad calback functions, and + * initialize instance structure. + */ +static void +gst_burn_init (GstBurn * filter) +{ + filter->adjustment = DEFAULT_ADJUSTMENT; +} + +static void +gst_burn_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstBurn *filter = GST_BURN (object); + + switch (prop_id) { + case PROP_ADJUSTMENT: + filter->adjustment = g_value_get_uint (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_burn_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec) +{ + GstBurn *filter = GST_BURN (object); + + GST_OBJECT_LOCK (filter); + switch (prop_id) { + case PROP_ADJUSTMENT: + g_value_set_uint (value, filter->adjustment); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } + GST_OBJECT_UNLOCK (filter); +} + +static void +gst_burn_finalize (GObject * object) +{ + G_OBJECT_CLASS (parent_class)->finalize (object); +} + +/* GstElement vmethod implementations */ + +/* Actual processing. */ +static GstFlowReturn +gst_burn_transform_frame (GstVideoFilter * vfilter, + GstVideoFrame * in_frame, GstVideoFrame * out_frame) +{ + GstBurn *filter = GST_BURN (vfilter); + gint video_size, adjustment; + guint32 *src, *dest; + GstClockTime timestamp; + gint64 stream_time; + + src = GST_VIDEO_FRAME_PLANE_DATA (in_frame, 0); + dest = GST_VIDEO_FRAME_PLANE_DATA (out_frame, 0); + + video_size = GST_VIDEO_FRAME_WIDTH (in_frame) * + GST_VIDEO_FRAME_HEIGHT (in_frame); + + /* GstController: update the properties */ + timestamp = GST_BUFFER_TIMESTAMP (in_frame->buffer); + stream_time = + gst_segment_to_stream_time (&GST_BASE_TRANSFORM (filter)->segment, + GST_FORMAT_TIME, timestamp); + + GST_DEBUG_OBJECT (filter, "sync to %" GST_TIME_FORMAT, + GST_TIME_ARGS (timestamp)); + + if (GST_CLOCK_TIME_IS_VALID (stream_time)) + gst_object_sync_values (GST_OBJECT (filter), stream_time); + + GST_OBJECT_LOCK (filter); + adjustment = filter->adjustment; + GST_OBJECT_UNLOCK (filter); + + /*** Now the image processing work.... ***/ + gaudi_orc_burn (dest, src, adjustment, video_size); + + return GST_FLOW_OK; +} + +/* Entry point to initialize the plug-in. + * Register the element factories and other features. */ +gboolean +gst_burn_plugin_init (GstPlugin * burn) +{ + /* debug category for fltering log messages */ + GST_DEBUG_CATEGORY_INIT (gst_burn_debug, "burn", 0, "Template burn"); + + return gst_element_register (burn, "burn", GST_RANK_NONE, GST_TYPE_BURN); +} diff --git a/pool/shard003/C/0064130_LeeBus.c b/pool/shard003/C/0064130_LeeBus.c new file mode 100644 index 0000000000000000000000000000000000000000..4dcca8908591b6b6bb5ca18cbc57f8d58455e7d2 --- /dev/null +++ b/pool/shard003/C/0064130_LeeBus.c @@ -0,0 +1,198 @@ +/* + * File: LeeBus.c + * Author: bquiroz + * + * Created on 15 de mayo de 2016, 10:07 PM + */ + +#include +//#include + +#define _XTAL_FREQ 32000000 // El reloj del pic corre a esta velocidad por default +#define RETRASO 100 + +#pragma config WDTE = OFF // Watchdog Timer Enable bits (WDT disabled; SWDTEN is ignored) +#pragma config FEXTOSC = OFF // FEXTOSC External Oscillator mode Selection bits (Oscillator not enabled) +//#pragma config RSTOSC = HFINT32 // Power-up default value for COSC bits (HFINTOSC with 2x PLL (32MHz)) + +int inRecibido; + +unsigned char chMsjRecibido[9]; +//unsigned char chBufferEnvio[8] ={0x30,0x31,0x32,0x33,0x34,0x35,0x36}; + +const unsigned char chAcciones[8] = {0b11000001,0b10000011,0b00000111,0b00001110,0b00011100,0b00111000,0b01110000,0b11100000}; + +const unsigned char chPatron01[9] = {0b11000001,0b10000011,0b00000111,0b00001110,0b00011100,0b00111000,0b01110000,0b11100000,0b00000000}; +const unsigned char chPatron02[9] = {0b10000011,0b11000001,0b11100000,0b01110000,0b00111000,0b00011100,0b00001110,0b00000111,0b00000000}; + +//const unsigned char chMsjAccion +//const unsigned char chMsj + +char UART_Init(const long int baudrate) +{ + unsigned int x; + x = (_XTAL_FREQ - baudrate*64)/(baudrate*64); + if(x>255) + { + x = (_XTAL_FREQ - baudrate*16)/(baudrate*16); + BRGH = 1; + } + if(x<256) + { + SPBRG = x; + SYNC = 0; + SPEN = 1; + TRISA0 = 1; + TRISA1 = 1; + CREN = 1; + TXEN = 1; + return 1; + } + return 0; +} + +char UART_TX_Empty() +{ + return TRMT; +} + +char UART_Data_Ready() +{ + return RCIF; +} + +char UART_Read() +{ + + while(!RCIF); + return RCREG; +} + +void UART_Read_Text(char *Output, unsigned int length) +{ + unsigned int i; + for( i=0;i> 5 )& 0b00000111 ; // Hacer 0 a partir del bit 4 queda lista la salida del RC + PORTA = chTempRA; + PORTC = chTempRC; +} + +void rutinaLED(unsigned char *chPatron) +{ + int i; + for( i = 0 ; chPatron[i] != 0b00000000 ; i++ ) + { + muestraPuerto( chPatron[i] ); + __delay_ms(90); + } +} + +void main() +{ + int i; + // Limpieza del Tri-estado, en cada etapa de la + // configuracion se cambiara el valor de este registro + TRISA = 0b00000000; + TRISC = 0b00000000; + +// ------------------------------------------------- + // Configuramos el UART + TRISCbits.TRISC4 = 0 ; // Se habilita el terminal RC4 como salida + TRISCbits.TRISC5 = 1 ; // Se habilita el terminal RC5 como entrada + RC4PPSbits.RC4PPS = 0b00010100; // Ajusta el pin RC5 como salida para TX - DS40001799A-page 141 + ANSELCbits.ANSC5 = 0; // Clear the ANSEL bit for the RX pin (if applicable) + RC4PPS = 0b00010100; // Ajusta el pin RC4 como salida para TX - DS40001799A-page 141 + + // Configuracion de la transmision + TX1STAbits.TXEN = 1; // Habilita el envio por el uart + TX1STAbits.SYNC = 0; // Modo asincrono + TX1STAbits.TX9 = 0; // Envia solo 8 bits + TX1STAbits.BRGH = 0; // Alta velocidad + BAUD1CONbits.BRG16 = 1; // Se usa el generador de BAUD de 16 bits + SPBRGbits.SP1BRGL = 191; // 10,417 kbaudios velocidad +// BAUD1CONbits.ABDEN = 1; // Auto-Baud Detect Enable bit +// BAUD1CONbits.ABDOVF = 1; + + // Configuracion de la recepcion + RC1STAbits.SPEN = 1; // Habilita la recepcion + RC1STAbits.CREN = 1; // Habilita la recepcion continua + +// ------------------------------------------------- + // Aviso que vamos al bucle principal - Enciende y apaga el RA4 + PORTA = 0b00110111; PORTC = 0b00001111; __delay_ms(1000); // 5 Second Delay + PORTA = 0b00000000; PORTC = 0b00001000; //__delay_ms(1000); // 5 Second Delay + +// ------------------------------------------------- + // Antes de entrar al bucle principal, habilitamos las interrupciones globales. + INTCONbits.GIE = 1; // Interrupciones globales activadas + INTCONbits.PEIE = 1; // Interrupciones de perifericos activadas + PIE1bits.RCIE = 1; // Se habilita notificacion de interrupcion por Rx + + inRecibido = 0; + + // El bucle principal + while(1) + { + PORTC = LATC | 0b00001000; + PORTC = LATC & 0b00001000; + PORTA = LATA & 0b00000000; + + inRecibido = 1; + for( i = 0 ; PIR1bits.RCIF && (i < 9); i++ ) + chMsjRecibido[i] = RC1REGbits.RC1REG; + + i++; + chMsjRecibido[i] = 0b00000000; + + if( inRecibido == 1) + { +// rutinaLED(chBufRecibido); + for( i = 0 ; chMsjRecibido[i] != 0b00000000 ; i++ ) + { + muestraPuerto(chMsjRecibido[i]); +// __delay_ms(600); + } + inRecibido = 0; + } + } +} diff --git a/pool/shard003/C/0064140_amd64-nat.c b/pool/shard003/C/0064140_amd64-nat.c new file mode 100644 index 0000000000000000000000000000000000000000..c641e89d0082c00d90fb54c7867f753f93fd03e8 --- /dev/null +++ b/pool/shard003/C/0064140_amd64-nat.c @@ -0,0 +1,161 @@ +/* Native-dependent code for AMD64. + + Copyright (C) 2003, 2004, 2007 Free Software Foundation, Inc. + + This file is part of GDB. + + 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 "defs.h" +#include "gdbarch.h" +#include "regcache.h" + +#include "gdb_assert.h" +#include "gdb_string.h" + +#include "i386-tdep.h" +#include "amd64-tdep.h" + +/* The following bits of code help with implementing debugging 32-bit + code natively on AMD64. The idea is to define two mappings between + the register number as used by GDB and the register set used by the + host to represent the general-purpose registers; one for 32-bit + code and one for 64-bit code. The mappings are specified by the + follwing variables and consist of an array of offsets within the + register set indexed by register number, and the number of + registers supported by the mapping. We don't need mappings for the + floating-point and SSE registers, since the difference between + 64-bit and 32-bit variants are negligable. The difference in the + number of SSE registers is already handled by the target code. */ + +/* General-purpose register mapping for native 32-bit code. */ +int *amd64_native_gregset32_reg_offset; +int amd64_native_gregset32_num_regs = I386_NUM_GREGS; + +/* General-purpose register mapping for native 64-bit code. */ +int *amd64_native_gregset64_reg_offset; +int amd64_native_gregset64_num_regs = AMD64_NUM_GREGS; + +/* Return the offset of REGNUM within the appropriate native + general-purpose register set. */ + +static int +amd64_native_gregset_reg_offset (int regnum) +{ + int *reg_offset = amd64_native_gregset64_reg_offset; + int num_regs = amd64_native_gregset64_num_regs; + + gdb_assert (regnum >= 0); + + if (gdbarch_ptr_bit (current_gdbarch) == 32) + { + reg_offset = amd64_native_gregset32_reg_offset; + num_regs = amd64_native_gregset32_num_regs; + } + + if (num_regs > gdbarch_num_regs (current_gdbarch)) + num_regs = gdbarch_num_regs (current_gdbarch); + + if (regnum < num_regs && regnum < gdbarch_num_regs (current_gdbarch)) + return reg_offset[regnum]; + + return -1; +} + +/* Return whether the native general-purpose register set supplies + register REGNUM. */ + +int +amd64_native_gregset_supplies_p (int regnum) +{ + return (amd64_native_gregset_reg_offset (regnum) != -1); +} + + +/* Supply register REGNUM, whose contents are stored in GREGS, to + REGCACHE. If REGNUM is -1, supply all appropriate registers. */ + +void +amd64_supply_native_gregset (struct regcache *regcache, + const void *gregs, int regnum) +{ + const char *regs = gregs; + struct gdbarch *gdbarch = get_regcache_arch (regcache); + int num_regs = amd64_native_gregset64_num_regs; + int i; + + if (gdbarch_ptr_bit (gdbarch) == 32) + num_regs = amd64_native_gregset32_num_regs; + + if (num_regs > gdbarch_num_regs (current_gdbarch)) + num_regs = gdbarch_num_regs (current_gdbarch); + + for (i = 0; i < num_regs; i++) + { + if (regnum == -1 || regnum == i) + { + int offset = amd64_native_gregset_reg_offset (i); + + if (offset != -1) + regcache_raw_supply (regcache, i, regs + offset); + } + } +} + +/* Collect register REGNUM from REGCACHE and store its contents in + GREGS. If REGNUM is -1, collect and store all appropriate + registers. */ + +void +amd64_collect_native_gregset (const struct regcache *regcache, + void *gregs, int regnum) +{ + char *regs = gregs; + struct gdbarch *gdbarch = get_regcache_arch (regcache); + int num_regs = amd64_native_gregset64_num_regs; + int i; + + if (gdbarch_ptr_bit (gdbarch) == 32) + { + num_regs = amd64_native_gregset32_num_regs; + + /* Make sure %eax, %ebx, %ecx, %edx, %esi, %edi, %ebp, %esp and + %eip get zero-extended to 64 bits. */ + for (i = 0; i <= I386_EIP_REGNUM; i++) + { + if (regnum == -1 || regnum == i) + memset (regs + amd64_native_gregset_reg_offset (i), 0, 8); + } + /* Ditto for %cs, %ss, %ds, %es, %fs, and %gs. */ + for (i = I386_CS_REGNUM; i <= I386_GS_REGNUM; i++) + { + if (regnum == -1 || regnum == i) + memset (regs + amd64_native_gregset_reg_offset (i), 0, 8); + } + } + + if (num_regs > gdbarch_num_regs (current_gdbarch)) + num_regs = gdbarch_num_regs (current_gdbarch); + + for (i = 0; i < num_regs; i++) + { + if (regnum == -1 || regnum == i) + { + int offset = amd64_native_gregset_reg_offset (i); + + if (offset != -1) + regcache_raw_collect (regcache, i, regs + offset); + } + } +} diff --git a/pool/shard003/C/0064146_timesynch.c b/pool/shard003/C/0064146_timesynch.c new file mode 100644 index 0000000000000000000000000000000000000000..349504f438fb925ad8792b411970eee3dfe9b19e --- /dev/null +++ b/pool/shard003/C/0064146_timesynch.c @@ -0,0 +1,275 @@ +/************************************************************************ + * IRC - Internet Relay Chat, timesynch.c + * (C) 2006 Bram Matthys (Syzop) + * + * 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 1, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + */ + +#include "struct.h" +#include "common.h" +#include "sys.h" +#include "numeric.h" +#include "msg.h" +#include "proto.h" +#include "channel.h" +#include "version.h" + +#if !defined(UNREAL_VERSION_TIME) + #error "YOU MUST RUN ./Config WHENEVER YOU ARE UPGRADING UNREAL!!!!" +#endif + +#include +#ifdef _WIN32 +#include +#endif +#include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif +#include +#include "h.h" +#include "inet.h" + +/* seconds from midnight Jan 1900 - 1970 */ +#if __STDC__ +#define TSDIFFERENCE 2208988800UL +#else +#define TSDIFFERENCE 2208988800 +#endif + +/* Maximum timeservers (which are sent in parallel). + * Currently defaults to 4, which is rightfully "low", since we don't + * want users to specify like 20 and flood the poor internet time servers. + */ +#define MAXTIMESERVERS 4 + +#define TSPKTLEN 48 + +static char tserr[512]; + +char *unreal_time_synch_error(void) +{ + return tserr; +} + +/* our "secret cookie". This is sent to the time server(s) and we check it + * in the response(s) we get. This is to make sure the reply is actually from + * the server we sent the request to, and not some kind of spoofidiot... + */ +static char tscookie[4]; + +char *ts_buildpacket(void) +{ +static char tspkt[TSPKTLEN]; +u_int32_t current; + + memset(tspkt, 0, sizeof(tspkt)); + /* bit 0-1: LI (00) + * bit 2-4: version number (4, which is: 100) + * bit 5-7: client mode (3, which is: 011) + * + * This comes down to 00100011, which is 0x23 + */ + tspkt[0] = 0x23; + /* rest is zero... */ + + /* Except the current timestamp: */ + current = htonl((u_int32_t)time(NULL)); + memcpy(tspkt+40, ¤t, 4); + + /* Our cookie... */ + tscookie[0] = getrandom8(); + tscookie[1] = getrandom8(); + tscookie[2] = getrandom8(); + tscookie[3] = getrandom8(); + memcpy(tspkt+44, tscookie, 4); + + return tspkt; +} + +time_t extracttime(const char *buf) +{ +unsigned long v; + + + + /* Verify cookie in originate timestamp */ + if (memcmp(buf+28, tscookie, 4)) + { + /* COOKIE MISMATCH !? */ + ircd_log(LOG_ERROR, "TimeSynch: Received invalid cookie from time server, this might indicate a security problem, or some faulty NTP implementation."); + return 0; + } + + + v = ((unsigned long)buf[40] << 24) | \ + ((unsigned long)buf[41] << 16) | \ + ((unsigned long)buf[42] << 8) | \ + ((unsigned long)buf[43]); + + if (v == 0) + { + ircd_log(LOG_ERROR, "TimeSynch: Zero timestamp received"); + return 0; + } + + v -= TSDIFFERENCE; + + if (v < 1147900561) + { + ircd_log(LOG_ERROR, "TimeSynch: Received timestamp in the (very) past from time server (ts=%lu)", v); + return 0; + } + + return (time_t)v; +} + + + +int unreal_time_synch(int timeout) +{ +int reply = 0; +char tmptimeservbuf[512], *p, *servname; +int s[MAXTIMESERVERS]; +int numservers = 0; +time_t start, now, t, offset; +struct sockaddr_in addr[MAXTIMESERVERS]; +int n, addrlen, i, highestfd = 0; +fd_set r; +struct timeval tv; +char buf[512], *buf_out; + + strlcpy(tmptimeservbuf, TIMESYNCH_SERVER, sizeof(tmptimeservbuf)); + + n = 0; + for (servname = strtoken(&p, tmptimeservbuf, ","); servname; servname = strtoken(&p, NULL, ",")) + { + s[n] = socket(AF_INET, SOCK_DGRAM, 0); /* always ipv4 */ + if (s[n] < 0) + { + ircsprintf(tserr, "unable to create socket: %s [%d]", STRERROR(ERRNO), (int)ERRNO); + goto end; + } + + highestfd = (highestfd < s[n]) ? s[n] : highestfd; /* adjust highestfd if needed */ + + memset(&addr[n], 0, sizeof(addr[n])); + addr[n].sin_family = AF_INET; + addr[n].sin_port = htons(123); + addr[n].sin_addr.s_addr = inet_addr(servname); + if (addr[n].sin_addr.s_addr == INADDR_NONE) + { + ircsprintf(tserr, "invalid timeserver IP '%s'", servname); + goto end; + } + + set_non_blocking(s[n], &me); + n++; + } + numservers = n; + + buf_out = ts_buildpacket(); + + /* Prepared... mass send.. */ + for (i = 0; i < numservers; i++) + { + n = sendto(s[i], buf_out, TSPKTLEN, 0, (struct sockaddr *)&addr[i], sizeof(struct sockaddr_in)); + if (n < 0) + ircd_log(LOG_ERROR, "TimeSync: WARNING: Was unable to send message to server #%d...", i); + } + + + + start = time(NULL); /* yes, indeed.. not TStime() here.. that is correct */ + + while(1) + { + now = time(NULL); + if (start + timeout <= now) + { + strcpy(tserr, "Timeout"); + goto end; + } + + FD_ZERO(&r); + for (i = 0; i < numservers; i++) + FD_SET(s[i], &r); + + memset(&tv, 0, sizeof(tv)); + + tv.tv_sec = timeout - (now - start); + + n = select(highestfd+1, &r, NULL, NULL, &tv); + if (n < 0) + { + /* select error == teh bad.. */ + ircsprintf(tserr, "select() error: %s [%d]", STRERROR(ERRNO), (int)ERRNO); + goto end; + } + + for (i = 0; i < numservers; i++) + { + if (FD_ISSET(s[i], &r)) + { + n = recv(s[i], buf, sizeof(buf), 0); +#ifndef _WIN32 + if ((n < 0) && (errno != EINPROGRESS)) +#else + if ((n < 0) && + (WSAGetLastError() != WSAEINPROGRESS) && + (WSAGetLastError() != WSAEWOULDBLOCK)) +#endif + { + /* Some kind of error.. uh ok... */ + continue; + } + + /* succes... check size */ + if (n >= 48) + { + t = extracttime(buf); + if (t != 0) + goto gotit; + } else { + ircd_log(LOG_ERROR, "TimeSynch: Odd short packet from time server received (len=%d)", n); + } + } + } + } /* while */ + +gotit: + /* Got time */ + now = time(NULL); + offset = t - now; + + ircd_log(LOG_ERROR, "TIME SYNCH: timeserver=%ld, our=%ld, offset = %ld [old offset: %ld]\n", + (long)t, (long)now, (long)offset, (long)TSoffset); + + TSoffset = offset; + + reply = 1; + +end: + for (i = 0; i < numservers; i++) + CLOSE_SOCK(s[i]); + + return reply; +} diff --git a/pool/shard003/C/0064148_vnc-jobs-sync.c b/pool/shard003/C/0064148_vnc-jobs-sync.c new file mode 100644 index 0000000000000000000000000000000000000000..49b77afcc9489d7030b24723aa6483bf6e628e1b --- /dev/null +++ b/pool/shard003/C/0064148_vnc-jobs-sync.c @@ -0,0 +1,73 @@ +/* + * QEMU VNC display driver + * + * Copyright (C) 2006 Anthony Liguori + * Copyright (C) 2006 Fabrice Bellard + * Copyright (C) 2009 Red Hat, Inc + * Copyright (C) 2010 Corentin Chary + * + * 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 "vnc.h" +#include "vnc-jobs.h" + +void vnc_jobs_clear(VncState *vs) +{ +} + +void vnc_jobs_join(VncState *vs) +{ +} + +VncJob *vnc_job_new(VncState *vs) +{ + vs->job.vs = vs; + vs->job.rectangles = 0; + + vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE); + vnc_write_u8(vs, 0); + vs->job.saved_offset = vs->output.offset; + vnc_write_u16(vs, 0); + return &vs->job; +} + +void vnc_job_push(VncJob *job) +{ + VncState *vs = job->vs; + + vs->output.buffer[job->saved_offset] = (job->rectangles >> 8) & 0xFF; + vs->output.buffer[job->saved_offset + 1] = job->rectangles & 0xFF; + vnc_flush(job->vs); +} + +int vnc_job_add_rect(VncJob *job, int x, int y, int w, int h) +{ + int n; + + n = vnc_send_framebuffer_update(job->vs, x, y, w, h); + if (n >= 0) + job->rectangles += n; + return n; +} + +bool vnc_has_job(VncState *vs) +{ + return false; +} diff --git a/pool/shard003/C/0064149_MBMS-TCTF-Presence.c b/pool/shard003/C/0064149_MBMS-TCTF-Presence.c new file mode 100644 index 0000000000000000000000000000000000000000..9940c1714e5c3553461c2d97d7b9ece236a61830 --- /dev/null +++ b/pool/shard003/C/0064149_MBMS-TCTF-Presence.c @@ -0,0 +1,144 @@ +/* + * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) + * From ASN.1 module "InformationElements" + * found in "../asn/InformationElements.asn" + * `asn1c -fcompound-names -fnative-types` + */ + +#include "MBMS-TCTF-Presence.h" + +int +MBMS_TCTF_Presence_constraint(asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + /* Replace with underlying type checker */ + td->check_constraints = asn_DEF_NativeEnumerated.check_constraints; + return td->check_constraints(td, sptr, ctfailcb, app_key); +} + +/* + * This type is implemented using NativeEnumerated, + * so here we adjust the DEF accordingly. + */ +static void +MBMS_TCTF_Presence_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { + td->free_struct = asn_DEF_NativeEnumerated.free_struct; + td->print_struct = asn_DEF_NativeEnumerated.print_struct; + td->ber_decoder = asn_DEF_NativeEnumerated.ber_decoder; + td->der_encoder = asn_DEF_NativeEnumerated.der_encoder; + td->xer_decoder = asn_DEF_NativeEnumerated.xer_decoder; + td->xer_encoder = asn_DEF_NativeEnumerated.xer_encoder; + td->uper_decoder = asn_DEF_NativeEnumerated.uper_decoder; + td->uper_encoder = asn_DEF_NativeEnumerated.uper_encoder; + if(!td->per_constraints) + td->per_constraints = asn_DEF_NativeEnumerated.per_constraints; + td->elements = asn_DEF_NativeEnumerated.elements; + td->elements_count = asn_DEF_NativeEnumerated.elements_count; + /* td->specifics = asn_DEF_NativeEnumerated.specifics; // Defined explicitly */ +} + +void +MBMS_TCTF_Presence_free(asn_TYPE_descriptor_t *td, + void *struct_ptr, int contents_only) { + MBMS_TCTF_Presence_1_inherit_TYPE_descriptor(td); + td->free_struct(td, struct_ptr, contents_only); +} + +int +MBMS_TCTF_Presence_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, + int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { + MBMS_TCTF_Presence_1_inherit_TYPE_descriptor(td); + return td->print_struct(td, struct_ptr, ilevel, cb, app_key); +} + +asn_dec_rval_t +MBMS_TCTF_Presence_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + void **structure, const void *bufptr, size_t size, int tag_mode) { + MBMS_TCTF_Presence_1_inherit_TYPE_descriptor(td); + return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); +} + +asn_enc_rval_t +MBMS_TCTF_Presence_encode_der(asn_TYPE_descriptor_t *td, + void *structure, int tag_mode, ber_tlv_tag_t tag, + asn_app_consume_bytes_f *cb, void *app_key) { + MBMS_TCTF_Presence_1_inherit_TYPE_descriptor(td); + return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); +} + +asn_dec_rval_t +MBMS_TCTF_Presence_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + void **structure, const char *opt_mname, const void *bufptr, size_t size) { + MBMS_TCTF_Presence_1_inherit_TYPE_descriptor(td); + return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); +} + +asn_enc_rval_t +MBMS_TCTF_Presence_encode_xer(asn_TYPE_descriptor_t *td, void *structure, + int ilevel, enum xer_encoder_flags_e flags, + asn_app_consume_bytes_f *cb, void *app_key) { + MBMS_TCTF_Presence_1_inherit_TYPE_descriptor(td); + return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); +} + +asn_dec_rval_t +MBMS_TCTF_Presence_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) { + MBMS_TCTF_Presence_1_inherit_TYPE_descriptor(td); + return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data); +} + +asn_enc_rval_t +MBMS_TCTF_Presence_encode_uper(asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, + void *structure, asn_per_outp_t *per_out) { + MBMS_TCTF_Presence_1_inherit_TYPE_descriptor(td); + return td->uper_encoder(td, constraints, structure, per_out); +} + +static asn_per_constraints_t asn_PER_type_MBMS_TCTF_Presence_constr_1 = { + { APC_CONSTRAINED, 0, 0, 0, 0 } /* (0..0) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +static asn_INTEGER_enum_map_t asn_MAP_MBMS_TCTF_Presence_value2enum_1[] = { + { 0, 5, "false" } +}; +static unsigned int asn_MAP_MBMS_TCTF_Presence_enum2value_1[] = { + 0 /* false(0) */ +}; +static asn_INTEGER_specifics_t asn_SPC_MBMS_TCTF_Presence_specs_1 = { + asn_MAP_MBMS_TCTF_Presence_value2enum_1, /* "tag" => N; sorted by tag */ + asn_MAP_MBMS_TCTF_Presence_enum2value_1, /* N => "tag"; sorted by N */ + 1, /* Number of elements in the maps */ + 0, /* Enumeration is not extensible */ + 1, /* Strict enumeration */ + 0, /* Native long size */ + 0 +}; +static ber_tlv_tag_t asn_DEF_MBMS_TCTF_Presence_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (10 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_MBMS_TCTF_Presence = { + "MBMS-TCTF-Presence", + "MBMS-TCTF-Presence", + MBMS_TCTF_Presence_free, + MBMS_TCTF_Presence_print, + MBMS_TCTF_Presence_constraint, + MBMS_TCTF_Presence_decode_ber, + MBMS_TCTF_Presence_encode_der, + MBMS_TCTF_Presence_decode_xer, + MBMS_TCTF_Presence_encode_xer, + MBMS_TCTF_Presence_decode_uper, + MBMS_TCTF_Presence_encode_uper, + 0, /* Use generic outmost tag fetcher */ + asn_DEF_MBMS_TCTF_Presence_tags_1, + sizeof(asn_DEF_MBMS_TCTF_Presence_tags_1) + /sizeof(asn_DEF_MBMS_TCTF_Presence_tags_1[0]), /* 1 */ + asn_DEF_MBMS_TCTF_Presence_tags_1, /* Same as above */ + sizeof(asn_DEF_MBMS_TCTF_Presence_tags_1) + /sizeof(asn_DEF_MBMS_TCTF_Presence_tags_1[0]), /* 1 */ + &asn_PER_type_MBMS_TCTF_Presence_constr_1, + 0, 0, /* Defined elsewhere */ + &asn_SPC_MBMS_TCTF_Presence_specs_1 /* Additional specs */ +}; + diff --git a/pool/shard003/C/0064154_pm_kernel.c b/pool/shard003/C/0064154_pm_kernel.c new file mode 100644 index 0000000000000000000000000000000000000000..b9e4e698aaca35acdbf8e0c30317a94f70b93aa3 --- /dev/null +++ b/pool/shard003/C/0064154_pm_kernel.c @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * 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 +#include +#include +#include + +#include + +int pm_kernel_create(pm_kernel_t **ker_out) { + pm_kernel_t *ker; + int error; + + if (!ker_out) + return 1; + + ker = calloc(1, sizeof(*ker)); + if (!ker) + return errno; + + ker->kpagecount_fd = open("/proc/kpagecount", O_RDONLY); + if (ker->kpagecount_fd < 0) { + error = errno; + free(ker); + return error; + } + + ker->kpageflags_fd = open("/proc/kpageflags", O_RDONLY); + if (ker->kpageflags_fd < 0) { + error = errno; + close(ker->kpagecount_fd); + free(ker); + return error; + } + + ker->pagesize = getpagesize(); + + *ker_out = ker; + + return 0; +} + +#define INIT_PIDS 20 +int pm_kernel_pids(pm_kernel_t *ker, pid_t **pids_out, size_t *len) { + DIR *proc; + struct dirent *dir; + pid_t pid, *pids, *new_pids; + size_t pids_count, pids_size; + int error; + + proc = opendir("/proc"); + if (!proc) + return errno; + + pids = malloc(INIT_PIDS * sizeof(pid_t)); + if (!pids) { + closedir(proc); + return errno; + } + pids_count = 0; pids_size = INIT_PIDS; + + while ((dir = readdir(proc))) { + if (sscanf(dir->d_name, "%d", &pid) < 1) + continue; + + if (pids_count >= pids_size) { + new_pids = realloc(pids, 2 * pids_size * sizeof(pid_t)); + if (!new_pids) { + error = errno; + free(pids); + closedir(proc); + return error; + } + pids = new_pids; + pids_size = 2 * pids_size; + } + + pids[pids_count] = pid; + + pids_count++; + } + + closedir(proc); + + new_pids = realloc(pids, pids_count * sizeof(pid_t)); + if (!new_pids) { + error = errno; + free(pids); + return error; + } + + *pids_out = new_pids; + *len = pids_count; + + return 0; +} + +int pm_kernel_count(pm_kernel_t *ker, uint64_t pfn, uint64_t *count_out) { + off64_t off; + + if (!ker || !count_out) + return -1; + + off = lseek64(ker->kpagecount_fd, pfn * sizeof(uint64_t), SEEK_SET); + if (off == (off_t)-1) + return errno; + if (read(ker->kpagecount_fd, count_out, sizeof(uint64_t)) < + (ssize_t)sizeof(uint64_t)) + return errno; + + return 0; +} + +int pm_kernel_flags(pm_kernel_t *ker, uint64_t pfn, uint64_t *flags_out) { + off64_t off; + + if (!ker || !flags_out) + return -1; + + off = lseek64(ker->kpageflags_fd, pfn * sizeof(uint64_t), SEEK_SET); + if (off == (off_t)-1) + return errno; + if (read(ker->kpageflags_fd, flags_out, sizeof(uint64_t)) < + (ssize_t)sizeof(uint64_t)) + return errno; + + return 0; +} + +int pm_kernel_destroy(pm_kernel_t *ker) { + if (!ker) + return -1; + + close(ker->kpagecount_fd); + close(ker->kpageflags_fd); + + free(ker); + + return 0; +} diff --git a/pool/shard003/C/0064161_lltoa.c b/pool/shard003/C/0064161_lltoa.c new file mode 100644 index 0000000000000000000000000000000000000000..112f562a7ceec65f0e8f455a205331d16c96f382 --- /dev/null +++ b/pool/shard003/C/0064161_lltoa.c @@ -0,0 +1,79 @@ +/**************************************************************************** +* +* Open Watcom Project +* +* Portions Copyright (c) 1983-2002 Sybase, Inc. All Rights Reserved. +* +* ======================================================================== +* +* This file contains Original Code and/or Modifications of Original +* Code as defined in and that are subject to the Sybase Open Watcom +* Public License version 1.0 (the 'License'). You may not use this file +* except in compliance with the License. BY USING THIS FILE YOU AGREE TO +* ALL TERMS AND CONDITIONS OF THE LICENSE. A copy of the License is +* provided with the Original Code and Modifications, and is also +* available at www.sybase.com/developer/opensource. +* +* The Original Code and all software distributed under the License are +* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER +* EXPRESS OR IMPLIED, AND SYBASE AND ALL CONTRIBUTORS HEREBY DISCLAIM +* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF +* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR +* NON-INFRINGEMENT. Please see the License for the specific language +* governing rights and limitations under the License. +* +* ======================================================================== +* +* Description: Long long integer to ascii routines +* +****************************************************************************/ + + +#include "variety.h" +#include "widechar.h" +#include "watcom.h" +#include "clibi64.h" +#include + +extern const char __based(__segname("_CODE")) __Alphabet[]; + +_WCRTLINK CHAR_TYPE *__F_NAME(__clib_ulltoa,__clib_wulltoa)( + unsigned __int64 value, + CHAR_TYPE *buffer, + unsigned radix ) + { + CHAR_TYPE *p = buffer; + char *q; + unsigned rem; + auto char buf[66]; // only holds ASCII so 'char' is OK + + buf[0] = '\0'; + q = &buf[1]; + do { + rem = value % radix; + value = value / radix; + *q = __Alphabet[ rem ]; + ++q; + } while( value ); + while( ( *p++ = (CHAR_TYPE)*--q ) ); + return( buffer ); + } + + +_WCRTLINK CHAR_TYPE *__F_NAME(__clib_lltoa,__clib_wlltoa)( + __int64 value, + CHAR_TYPE *buffer, + int radix ) + { + register CHAR_TYPE *p = buffer; + + if( radix == 10 ) { + if( value < 0 ) { + *p++ = '-'; + value = -value; + } + } + __F_NAME(__clib_ulltoa,__clib_wulltoa)( value, p, radix ); + return( buffer ); + } + diff --git a/pool/shard003/C/0064184_pxa2xx-flash.c b/pool/shard003/C/0064184_pxa2xx-flash.c new file mode 100644 index 0000000000000000000000000000000000000000..7d88346464923b1251bf2eeeec7bf7024ad8fc4f --- /dev/null +++ b/pool/shard003/C/0064184_pxa2xx-flash.c @@ -0,0 +1,170 @@ + + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +static void pxa2xx_map_inval_cache(struct map_info *map, unsigned long from, + ssize_t len) +{ + flush_ioremap_region(map->phys, map->cached, from, len); +} + +struct pxa2xx_flash_info { + struct mtd_partition *parts; + int nr_parts; + struct mtd_info *mtd; + struct map_info map; +}; + + +static const char *probes[] = { "RedBoot", "cmdlinepart", NULL }; + + +static int __init pxa2xx_flash_probe(struct platform_device *pdev) +{ + struct flash_platform_data *flash = pdev->dev.platform_data; + struct pxa2xx_flash_info *info; + struct mtd_partition *parts; + struct resource *res; + int ret = 0; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -ENODEV; + + info = kmalloc(sizeof(struct pxa2xx_flash_info), GFP_KERNEL); + if (!info) + return -ENOMEM; + + memset(info, 0, sizeof(struct pxa2xx_flash_info)); + info->map.name = (char *) flash->name; + info->map.bankwidth = flash->width; + info->map.phys = res->start; + info->map.size = res->end - res->start + 1; + info->parts = flash->parts; + info->nr_parts = flash->nr_parts; + + info->map.virt = ioremap(info->map.phys, info->map.size); + if (!info->map.virt) { + printk(KERN_WARNING "Failed to ioremap %s\n", + info->map.name); + return -ENOMEM; + } + info->map.cached = + ioremap_cached(info->map.phys, info->map.size); + if (!info->map.cached) + printk(KERN_WARNING "Failed to ioremap cached %s\n", + info->map.name); + info->map.inval_cache = pxa2xx_map_inval_cache; + simple_map_init(&info->map); + + printk(KERN_NOTICE + "Probing %s at physical address 0x%08lx" + " (%d-bit bankwidth)\n", + info->map.name, (unsigned long)info->map.phys, + info->map.bankwidth * 8); + + info->mtd = do_map_probe(flash->map_name, &info->map); + + if (!info->mtd) { + iounmap((void *)info->map.virt); + if (info->map.cached) + iounmap(info->map.cached); + return -EIO; + } + info->mtd->owner = THIS_MODULE; + +#ifdef CONFIG_MTD_PARTITIONS + ret = parse_mtd_partitions(info->mtd, probes, &parts, 0); + + if (ret > 0) { + info->nr_parts = ret; + info->parts = parts; + } +#endif + + if (info->nr_parts) { + add_mtd_partitions(info->mtd, info->parts, + info->nr_parts); + } else { + printk("Registering %s as whole device\n", + info->map.name); + add_mtd_device(info->mtd); + } + + platform_set_drvdata(pdev, info); + return 0; +} + +static int __devexit pxa2xx_flash_remove(struct platform_device *dev) +{ + struct pxa2xx_flash_info *info = platform_get_drvdata(dev); + + platform_set_drvdata(dev, NULL); + +#ifdef CONFIG_MTD_PARTITIONS + if (info->nr_parts) + del_mtd_partitions(info->mtd); + else +#endif + del_mtd_device(info->mtd); + + map_destroy(info->mtd); + iounmap(info->map.virt); + if (info->map.cached) + iounmap(info->map.cached); + kfree(info->parts); + kfree(info); + return 0; +} + +#ifdef CONFIG_PM +static void pxa2xx_flash_shutdown(struct platform_device *dev) +{ + struct pxa2xx_flash_info *info = platform_get_drvdata(dev); + + if (info && info->mtd->suspend(info->mtd) == 0) + info->mtd->resume(info->mtd); +} +#else +#define pxa2xx_flash_shutdown NULL +#endif + +static struct platform_driver pxa2xx_flash_driver = { + .driver = { + .name = "pxa2xx-flash", + .owner = THIS_MODULE, + }, + .probe = pxa2xx_flash_probe, + .remove = __devexit_p(pxa2xx_flash_remove), + .shutdown = pxa2xx_flash_shutdown, +}; + +static int __init init_pxa2xx_flash(void) +{ + return platform_driver_register(&pxa2xx_flash_driver); +} + +static void __exit cleanup_pxa2xx_flash(void) +{ + platform_driver_unregister(&pxa2xx_flash_driver); +} + +module_init(init_pxa2xx_flash); +module_exit(cleanup_pxa2xx_flash); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Nicolas Pitre "); +MODULE_DESCRIPTION("MTD map driver for Intel XScale PXA2xx"); diff --git a/pool/shard003/C/0064193_displist.c b/pool/shard003/C/0064193_displist.c new file mode 100644 index 0000000000000000000000000000000000000000..bdde7046454350c0fb4e9c856a8ea2a059a605bc --- /dev/null +++ b/pool/shard003/C/0064193_displist.c @@ -0,0 +1,274 @@ +//Copyright Paul Reiche, Fred Ford. 1992-2002 + +/* + * 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 "displist.h" +#include "libs/log.h" + +#ifdef QUEUE_TABLE +#define NULL_HANDLE NULL +#endif + +/* + * This file contains code for generic doubly linked lists. + * If QUEUE_TABLE is defined, each lists has its own preallocated + * pool of link structures. The size is specific on InitQueue(), + * and poses a hard limit on the number of elements in the list. + */ + +BOOLEAN +InitQueue (QUEUE *pq, COUNT num_elements, OBJ_SIZE size) +{ + SetHeadLink (pq, NULL_HANDLE); + SetTailLink (pq, NULL_HANDLE); + SetLinkSize (pq, size); +#ifndef QUEUE_TABLE + return (TRUE); +#else /* QUEUE_TABLE */ + SetFreeList (pq, NULL_HANDLE); +#if 0 + log_add (log_Debug, "InitQueue(): num_elements = %d (%d)", + num_elements, (BYTE)num_elements); +#endif + if (AllocQueueTab (pq, num_elements) != NULL) + { + do + FreeLink (pq, GetLinkAddr (pq, num_elements)); + while (--num_elements); + + return (TRUE); + } + + return (FALSE); +#endif /* QUEUE_TABLE */ +} + +BOOLEAN +UninitQueue (QUEUE *pq) +{ +#ifdef QUEUE_TABLE + SetHeadLink (pq, NULL_HANDLE); + SetTailLink (pq, NULL_HANDLE); + SetFreeList (pq, NULL_HANDLE); + FreeQueueTab (pq); + + return (TRUE); +#else /* !QUEUE_TABLE */ + HLINK hLink; + + while ((hLink = GetHeadLink (pq)) != NULL_HANDLE) + { + RemoveQueue (pq, hLink); + if (!FreeLink (pq, hLink)) + return (FALSE); + } + + return (TRUE); +#endif /* QUEUE_TABLE */ +} + +// Empty the queue. The elements linked to in the queue are unchanged. +void +ReinitQueue (QUEUE *pq) +{ + SetHeadLink (pq, NULL_HANDLE); + SetTailLink (pq, NULL_HANDLE); +#ifdef QUEUE_TABLE + { + COUNT num_elements; + + SetFreeList (pq, NULL_HANDLE); + + num_elements = SizeQueueTab (pq); + if (num_elements) + { + do + FreeLink (pq, GetLinkAddr (pq, num_elements)); + while (--num_elements); + } + } +#endif /* QUEUE_TABLE */ +} + +#ifdef QUEUE_TABLE +HLINK +AllocLink (QUEUE *pq) +{ + HLINK hLink; + + hLink = GetFreeList (pq); + if (hLink) + { + LINK *LinkPtr; + + LinkPtr = LockLink (pq, hLink); + SetFreeList (pq, _GetSuccLink (LinkPtr)); + UnlockLink (pq, hLink); + } + else + log_add (log_Debug, "AllocLink(): No more elements"); + + return (hLink); +} + +void +FreeLink (QUEUE *pq, HLINK hLink) +{ + LINK *LinkPtr; + + LinkPtr = LockLink (pq, hLink); + _SetSuccLink (LinkPtr, GetFreeList (pq)); + UnlockLink (pq, hLink); + + SetFreeList (pq, hLink); +} +#endif /* QUEUE_TABLE */ + +void +PutQueue (QUEUE *pq, HLINK hLink) +{ + LINK *LinkPtr; + + if (GetHeadLink (pq) == 0) + SetHeadLink (pq, hLink); + else + { + HLINK hTail; + LINK *lpTail; + + hTail = GetTailLink (pq); + lpTail = LockLink (pq, hTail); + _SetSuccLink (lpTail, hLink); + UnlockLink (pq, hTail); + } + + LinkPtr = LockLink (pq, hLink); + _SetPredLink (LinkPtr, GetTailLink (pq)); + _SetSuccLink (LinkPtr, NULL_HANDLE); + UnlockLink (pq, hLink); + + SetTailLink (pq, hLink); +} + +void +InsertQueue (QUEUE *pq, HLINK hLink, HLINK hRefLink) +{ + if (hRefLink == 0) + PutQueue (pq, hLink); + else + { + LINK *LinkPtr; + LINK *RefLinkPtr; + + LinkPtr = LockLink (pq, hLink); + RefLinkPtr = LockLink (pq, hRefLink); + _SetPredLink (LinkPtr, _GetPredLink (RefLinkPtr)); + _SetPredLink (RefLinkPtr, hLink); + _SetSuccLink (LinkPtr, hRefLink); + + if (GetHeadLink (pq) == hRefLink) + SetHeadLink (pq, hLink); + else + { + HLINK hPredLink; + LINK *PredLinkPtr; + + hPredLink = _GetPredLink (LinkPtr); + PredLinkPtr = LockLink (pq, hPredLink); + _SetSuccLink (PredLinkPtr, hLink); + UnlockLink (pq, hPredLink); + } + UnlockLink (pq, hRefLink); + UnlockLink (pq, hLink); + } +} + +void +RemoveQueue (QUEUE *pq, HLINK hLink) +{ + LINK *LinkPtr; + + LinkPtr = LockLink (pq, hLink); + if (GetHeadLink (pq) == hLink) + { + SetHeadLink (pq, _GetSuccLink (LinkPtr)); + } + else + { + HLINK hPredLink; + LINK *PredLinkPtr; + + hPredLink = _GetPredLink (LinkPtr); + PredLinkPtr = LockLink (pq, hPredLink); + _SetSuccLink (PredLinkPtr, _GetSuccLink (LinkPtr)); + UnlockLink (pq, hPredLink); + } + if (GetTailLink (pq) == hLink) + { + SetTailLink (pq, _GetPredLink (LinkPtr)); + } + else + { + HLINK hSuccLink, hPredLink; + LINK *SuccLinkPtr; + + hSuccLink = _GetSuccLink (LinkPtr); + SuccLinkPtr = LockLink (pq, hSuccLink); + hPredLink = _GetPredLink (LinkPtr); + _SetPredLink (SuccLinkPtr, hPredLink); + UnlockLink (pq, hSuccLink); + } + UnlockLink (pq, hLink); +} + +COUNT +CountLinks (QUEUE *pq) +{ + COUNT LinkCount; + HLINK hLink, hNextLink; + + LinkCount = 0; + for (hLink = GetHeadLink (pq); hLink; hLink = hNextLink) + { + LINK *LinkPtr; + + ++LinkCount; + + LinkPtr = LockLink (pq, hLink); + hNextLink = _GetSuccLink (LinkPtr); + UnlockLink (pq, hLink); + } + + return (LinkCount); +} + +void +ForAllLinks (QUEUE *pq, void (*callback)(LINK *, void *), void *arg) +{ + HLINK hLink, hNextLink; + + for (hLink = GetHeadLink (pq); hLink; hLink = hNextLink) + { + LINK *LinkPtr; + LinkPtr = LockLink (pq, hLink); + hNextLink = _GetSuccLink (LinkPtr); + (*callback) (LinkPtr, arg); + UnlockLink (pq, hLink); + } +} + + diff --git a/pool/shard003/C/0064198_cpu_x86_64.c b/pool/shard003/C/0064198_cpu_x86_64.c new file mode 100644 index 0000000000000000000000000000000000000000..5b63c0c767fcc2db8cb37a33d58b453f6fd9b72b --- /dev/null +++ b/pool/shard003/C/0064198_cpu_x86_64.c @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2015-2018 Contributors as noted in the AUTHORS file + * + * This file is part of Solo5, a sandboxed execution environment. + * + * 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 "bindings.h" + +static uint64_t cpu_gdt64[GDT_NUM_ENTRIES] ALIGN_64_BIT; + +/* + * The tender (hvt) or bootloader + bootstrap (virtio) starts us up with a + * bootstrap GDT which is "invisible" to the guest, init and switch to our own + * GDT. + * + * This is done primarily since we need to do LTR later in a predictable + * fashion. + */ +static void gdt_init(void) +{ + memset(cpu_gdt64, 0, sizeof(cpu_gdt64)); + cpu_gdt64[GDT_DESC_CODE] = GDT_DESC_CODE_VAL; + cpu_gdt64[GDT_DESC_DATA] = GDT_DESC_DATA_VAL; + + volatile struct gdtptr gdtptr; + gdtptr.limit = sizeof(cpu_gdt64) - 1; + gdtptr.base = (uint64_t)&cpu_gdt64; + __asm__ __volatile__("lgdt (%0)" :: "r" (&gdtptr)); + /* + * TODO: Technically we should reload all segment registers here, in + * practice this doesn't matter since the bootstrap GDT matches ours, for + * now. + */ +} + +static struct idt_gate_desc cpu_idt[IDT_NUM_ENTRIES] ALIGN_64_BIT; + +static void idt_fillgate(unsigned num, void *fun, unsigned ist) +{ + struct idt_gate_desc *desc = &cpu_idt[num]; + + /* + * All gates are interrupt gates, all handlers run with interrupts off. + */ + desc->offset_hi = (uint64_t)fun >> 16; + desc->offset_lo = (uint64_t)fun & 0xffff; + desc->selector = GDT_DESC_OFFSET(GDT_DESC_CODE); + desc->ist = ist; + desc->type = 0b1110; + desc->dpl = 0; + desc->p = 1; +} + +static void idt_init(void) +{ + /* + * Load trap vectors. All traps run on IST2 (cpu_trap_stack), except for + * the exceptions. + */ +#define FILL_TRAP_GATE(num, ist) extern void cpu_trap_##num(void); \ + idt_fillgate(num, cpu_trap_##num, ist) + FILL_TRAP_GATE(0, 2); + FILL_TRAP_GATE(1, 2); + FILL_TRAP_GATE(2, 3); /* #NMI runs on IST3 (cpu_nmi_stack) */ + FILL_TRAP_GATE(3, 2); + FILL_TRAP_GATE(4, 2); + FILL_TRAP_GATE(5, 2); + FILL_TRAP_GATE(6, 2); + FILL_TRAP_GATE(7, 2); + FILL_TRAP_GATE(8, 3); /* #DF runs on IST3 (cpu_nmi_stack) */ + FILL_TRAP_GATE(10, 2); + FILL_TRAP_GATE(11, 2); + FILL_TRAP_GATE(12, 2); + FILL_TRAP_GATE(13, 2); + FILL_TRAP_GATE(14, 2); + FILL_TRAP_GATE(16, 2); + FILL_TRAP_GATE(17, 2); + FILL_TRAP_GATE(18, 2); + FILL_TRAP_GATE(19, 2); + FILL_TRAP_GATE(20, 2); + + /* + * Load irq vectors. All irqs run on IST1 (cpu_intr_stack). + */ +#define FILL_IRQ_GATE(num, ist) extern void cpu_irq_##num(void); \ + idt_fillgate(32 + num, cpu_irq_##num, ist) + FILL_IRQ_GATE(0, 1); + FILL_IRQ_GATE(1, 1); + FILL_IRQ_GATE(2, 1); + FILL_IRQ_GATE(3, 1); + FILL_IRQ_GATE(4, 1); + FILL_IRQ_GATE(5, 1); + FILL_IRQ_GATE(6, 1); + FILL_IRQ_GATE(7, 1); + FILL_IRQ_GATE(8, 1); + FILL_IRQ_GATE(9, 1); + FILL_IRQ_GATE(10, 1); + FILL_IRQ_GATE(11, 1); + FILL_IRQ_GATE(12, 1); + FILL_IRQ_GATE(13, 1); + FILL_IRQ_GATE(14, 1); + FILL_IRQ_GATE(15, 1); + + volatile struct idtptr idtptr; + idtptr.limit = sizeof(cpu_idt) - 1; + idtptr.base = (uint64_t) &cpu_idt; + __asm__ __volatile__("lidt (%0)" :: "r" (&idtptr)); +} + +static struct tss cpu_tss; + +static char cpu_intr_stack[4096]; /* IST1 */ +static char cpu_trap_stack[4096]; /* IST2 */ +static char cpu_nmi_stack[4096]; /* IST3 */ + +static void tss_init(void) +{ + extern uint64_t cpu_gdt64[]; + struct tss_desc *td = (void *)&cpu_gdt64[GDT_DESC_TSS_LO]; + + cpu_tss.ist[0] = (uint64_t)&cpu_intr_stack[sizeof cpu_intr_stack]; + cpu_tss.ist[1] = (uint64_t)&cpu_trap_stack[sizeof cpu_trap_stack]; + cpu_tss.ist[2] = (uint64_t)&cpu_nmi_stack[sizeof cpu_nmi_stack]; + td->limit_lo = sizeof(cpu_tss); + td->base_lo = (uint64_t)&cpu_tss; + td->type = 0x9; + td->dpl = 0; + td->p = 1; + td->limit_hi = 0; + td->gran = 0; + td->base_hi = (uint64_t)&cpu_tss >> 24; + td->zero = 0; + + cc_barrier(); + __asm__ __volatile__("ltr %0" :: "r" ((unsigned short)(GDT_DESC_TSS_LO * 8))); +} + +void cpu_init(void) +{ + gdt_init(); + tss_init(); + idt_init(); +} + +static char *traps[32] = { + "#DE", "#DB", "#NMI", "#BP", "#OF", "#BR", "#UD", "#NM", "#DF", "#9", "#TS", + "#NP", "#SS", "#GP", "#PF", "#15", "#MF", "#AC", "#MC", "#XM", "#VE", "#21", + "#22", "#23", "#24", "#25", "#26", "#27", "#28", "#29", "#30", "#31" +}; + +void cpu_trap_handler(uint64_t num, struct trap_regs *regs) +{ + log(INFO, "Solo5: trap: type=%s ec=0x%lx rip=0x%lx rsp=0x%lx rflags=0x%lx\n", + traps[num], regs->ec, regs->rip, regs->rsp, regs->rflags); + if (num == 14) + log(INFO, "Solo5: trap: cr2=0x%lx\n", regs->cr2); + PANIC("Fatal trap", regs); +} + +/* keeps track of cpu_intr_disable() depth */ +int cpu_intr_depth = 1; + +void cpu_intr_disable(void) +{ + __asm__ __volatile__("cli"); + cpu_intr_depth++; +} + +void cpu_intr_enable(void) +{ + assert(cpu_intr_depth > 0); + + if (--cpu_intr_depth == 0) + __asm__ __volatile__("sti"); +} + +void cpu_halt(void) +{ + __asm__ __volatile__("cli; hlt"); + for(;;); +} diff --git a/pool/shard003/C/0064199_dntt.c b/pool/shard003/C/0064199_dntt.c new file mode 100644 index 0000000000000000000000000000000000000000..0695bd4010570e23e273a917b9fccc2fe7940440 --- /dev/null +++ b/pool/shard003/C/0064199_dntt.c @@ -0,0 +1,99 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* dntt.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: pgritsen +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2017/08/12 18:20:45 by pgritsen #+# #+# */ +/* Updated: 2017/08/12 18:20:46 by pgritsen ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "t.h" +#include "stack.h" +#include "t_opp.h" +#include + +void push_operands(char *str, int *from, t_stack **operands) +{ + if (str[*from] >= '0' && str[*from] <= '9') + { + c_push_front(operands, ft_atoi(str + *from)); + while (str[*from] >= '0' && str[*from] <= '9') + *from = *from + 1; + } +} + +void clear_operations(char *str, int from, t_stack **operands, + t_stack **operators) +{ + int num_tmp; + int act_it; + char opp_tmp; + + if ((act_it = found_action(str[from])) != -1) + { + while (get_priority(str[from]) <= + get_priority((char)c_get_data(*operators))) + { + opp_tmp = (char)c_shift_back_data(operators); + num_tmp = g_opp[found_action(opp_tmp)].action( + c_shift_back_data(operands), c_shift_back_data(operands)); + c_push_front(operands, num_tmp); + } + c_push_front(operators, (int)str[from]); + } +} + +void parentheses_detection(char *str, int *from, t_stack **operands) +{ + int parentheses_t_s; + int num_tmp; + int to_it; + + if (str[*from] == '(') + { + to_it = *from; + parentheses_t_s = 0; + while (str[++to_it]) + { + if (str[to_it] == '(') + parentheses_t_s++; + else if (str[to_it] == ')' && !parentheses_t_s) + break ; + else if (str[to_it] == ')') + parentheses_t_s--; + } + num_tmp = calculate(str, *from + 1, to_it); + c_push_front(operands, num_tmp); + *from = to_it; + } +} + +int calculate(char *str, int from, int to) +{ + t_stack *operands; + t_stack *operators; + char opp_tmp; + int num_tmp; + + operands = 0; + operators = 0; + while (str[from] && from < to) + { + push_operands(str, &from, &operands); + clear_operations(str, from, &operands, &operators); + parentheses_detection(str, &from, &operands); + from++; + } + opp_tmp = (char)c_shift_back_data(&operators); + while (opp_tmp) + { + num_tmp = g_opp[found_action(opp_tmp)].action( + c_shift_back_data(&operands), c_shift_back_data(&operands)); + c_push_front(&operands, num_tmp); + opp_tmp = (char)c_shift_back_data(&operators); + } + return (operands->data); +} diff --git a/pool/shard003/C/0064218_m_links.c b/pool/shard003/C/0064218_m_links.c new file mode 100644 index 0000000000000000000000000000000000000000..16a52d357b745526a9258bc7ed936a95331acbed --- /dev/null +++ b/pool/shard003/C/0064218_m_links.c @@ -0,0 +1,158 @@ +/* + * ircd-ratbox: A slightly useful ircd. + * m_links.c: Shows what servers are currently connected. + * + * Copyright (C) 1990 Jarkko Oikarinen and University of Oulu, Co Center + * Copyright (C) 1996-2002 Hybrid Development Team + * Copyright (C) 2002-2005 ircd-ratbox development team + * + * 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 "stdinc.h" +#include "client.h" +#include "match.h" +#include "ircd.h" +#include "numeric.h" +#include "s_serv.h" +#include "send.h" +#include "s_conf.h" +#include "msg.h" +#include "parse.h" +#include "modules.h" +#include "hook.h" +#include "scache.h" + +static int m_links(struct Client *, struct Client *, int, const char **); +static int mo_links(struct Client *, struct Client *, int, const char **); +static char * clean_string(char *dest, const unsigned char *src, size_t len); + +struct Message links_msgtab = { + "LINKS", 0, 0, 0, MFLG_SLOW, + {mg_unreg, {m_links, 0}, {mo_links, 0}, mg_ignore, mg_ignore, {mo_links, 0}} +}; + +int doing_links_hook; + +mapi_clist_av1 links_clist[] = { &links_msgtab, NULL }; +mapi_hlist_av1 links_hlist[] = { + { "doing_links", &doing_links_hook }, + { NULL, NULL } +}; + +DECLARE_MODULE_AV1(links, NULL, NULL, links_clist, links_hlist, NULL, "$Revision$"); + +/* + * m_links - LINKS message handler + * parv[1] = servername mask + * or + * parv[1] = server to query + * parv[2] = servername mask + */ +static int +m_links(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) +{ + if(ConfigServerHide.flatten_links && !IsExemptShide(source_p)) + scache_send_flattened_links(source_p); + else + mo_links(client_p, source_p, parc, parv); + + return 0; +} + +static int +mo_links(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) +{ + const char *mask = ""; + struct Client *target_p; + char clean_mask[2 * HOSTLEN + 4]; + hook_data hd; + + rb_dlink_node *ptr; + + if(parc > 2) { + if(strlen(parv[2]) > HOSTLEN) + return 0; + if(hunt_server(client_p, source_p, ":%s LINKS %s :%s", 1, parc, parv) + != HUNTED_ISME) + return 0; + + mask = parv[2]; + } else if(parc == 2) + mask = parv[1]; + + if(*mask) /* only necessary if there is a mask */ + mask = collapse(clean_string + (clean_mask, (const unsigned char *) mask, 2 * HOSTLEN)); + + hd.client = source_p; + hd.arg1 = mask; + hd.arg2 = NULL; + + call_hook(doing_links_hook, &hd); + + RB_DLINK_FOREACH(ptr, global_serv_list.head) { + target_p = ptr->data; + + if(*mask && !match(mask, target_p->name)) + continue; + + /* We just send the reply, as if theyre here theres either no SHIDE, + * or theyre an oper.. + */ + sendto_one_numeric(source_p, RPL_LINKS, form_str(RPL_LINKS), + target_p->name, target_p->servptr->name, + target_p->hopcount, + target_p->info[0] ? target_p->info : "(Unknown Location)"); + } + + sendto_one_numeric(source_p, RPL_ENDOFLINKS, form_str(RPL_ENDOFLINKS), + EmptyString(mask) ? "*" : mask); + + return 0; +} + +static char * +clean_string(char *dest, const unsigned char *src, size_t len) +{ + char *d = dest; + s_assert(0 != dest); + s_assert(0 != src); + + if(dest == NULL || src == NULL) + return NULL; + + while (*src && (len > 1)) { + if(*src & 0x80) { /* if high bit is set */ + *d++ = '.'; + --len; + if(len <= 1) + break; + } else if(!IsPrint(*src)) { /* if NOT printable */ + *d++ = '^'; + --len; + if(len <= 1) + break; + *d++ = 0x40 + *src; /* turn it into a printable */ + } else + *d++ = *src; + ++src; + --len; + } + *d = '\0'; + return dest; +} diff --git a/pool/shard003/C/0064219_eggsmclient-osx.c b/pool/shard003/C/0064219_eggsmclient-osx.c new file mode 100644 index 0000000000000000000000000000000000000000..e6fa37630757ac9f7d5884c1d6114a0453a401d0 --- /dev/null +++ b/pool/shard003/C/0064219_eggsmclient-osx.c @@ -0,0 +1,235 @@ +/* + * Copyright (C) 2007 Novell, Inc. + * Copyright (C) 2008 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 3 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +/* EggSMClientOSX + * + * For details on the OS X logout process, see: + * http://developer.apple.com/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/BootProcess.html#//apple_ref/doc/uid/20002130-114618 + * + * EggSMClientOSX registers for the kAEQuitApplication AppleEvent; the + * handler we register (quit_requested()) will be invoked from inside + * the quartz event-handling code (specifically, from inside + * [NSApplication nextEventMatchingMask]) when an AppleEvent arrives. + * We use AESuspendTheCurrentEvent() and AEResumeTheCurrentEvent() to + * allow asynchronous / non-main-loop-reentering processing of the + * quit request. (These are part of the Carbon framework; it doesn't + * seem to be possible to handle AppleEvents asynchronously from + * Cocoa.) + */ + +#include "config.h" + +#include "eggsmclient-private.h" +#include +#include +#include + +#define EGG_TYPE_SM_CLIENT_OSX (egg_sm_client_osx_get_type ()) +#define EGG_SM_CLIENT_OSX(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), EGG_TYPE_SM_CLIENT_OSX, EggSMClientOSX)) +#define EGG_SM_CLIENT_OSX_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), EGG_TYPE_SM_CLIENT_OSX, EggSMClientOSXClass)) +#define EGG_IS_SM_CLIENT_OSX(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), EGG_TYPE_SM_CLIENT_OSX)) +#define EGG_IS_SM_CLIENT_OSX_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), EGG_TYPE_SM_CLIENT_OSX)) +#define EGG_SM_CLIENT_OSX_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), EGG_TYPE_SM_CLIENT_OSX, EggSMClientOSXClass)) + +typedef struct _EggSMClientOSX EggSMClientOSX; +typedef struct _EggSMClientOSXClass EggSMClientOSXClass; + +struct _EggSMClientOSX { + EggSMClient parent; + + AppleEvent quit_event, quit_reply; + gboolean quit_requested, quitting; +}; + +struct _EggSMClientOSXClass +{ + EggSMClientClass parent_class; + +}; + +static void sm_client_osx_startup (EggSMClient *client, + const char *client_id); +static void sm_client_osx_will_quit (EggSMClient *client, + gboolean will_quit); +static gboolean sm_client_osx_end_session (EggSMClient *client, + EggSMClientEndStyle style, + gboolean request_confirmation); + +static pascal OSErr quit_requested (const AppleEvent *, AppleEvent *, long); + +G_DEFINE_TYPE (EggSMClientOSX, egg_sm_client_osx, EGG_TYPE_SM_CLIENT) + +static void +egg_sm_client_osx_init (EggSMClientOSX *osx) +{ + ; +} + +static void +egg_sm_client_osx_class_init (EggSMClientOSXClass *klass) +{ + EggSMClientClass *sm_client_class = EGG_SM_CLIENT_CLASS (klass); + + sm_client_class->startup = sm_client_osx_startup; + sm_client_class->will_quit = sm_client_osx_will_quit; + sm_client_class->end_session = sm_client_osx_end_session; +} + +EggSMClient * +egg_sm_client_osx_new (void) +{ + return g_object_new (EGG_TYPE_SM_CLIENT_OSX, NULL); +} + +static void +sm_client_osx_startup (EggSMClient *client, + const char *client_id) +{ + AEInstallEventHandler (kCoreEventClass, kAEQuitApplication, + NewAEEventHandlerUPP (quit_requested), + (long)GPOINTER_TO_SIZE (client), false); +} + +static gboolean +idle_quit_requested (gpointer client) +{ + egg_sm_client_quit_requested (client); + return FALSE; +} + +static pascal OSErr +quit_requested (const AppleEvent *aevt, AppleEvent *reply, long refcon) +{ + EggSMClient *client = GSIZE_TO_POINTER ((gsize)refcon); + EggSMClientOSX *osx = GSIZE_TO_POINTER ((gsize)refcon); + + g_return_val_if_fail (!osx->quit_requested, userCanceledErr); + + /* FIXME AEInteractWithUser? */ + + osx->quit_requested = TRUE; + AEDuplicateDesc (aevt, &osx->quit_event); + AEDuplicateDesc (reply, &osx->quit_reply); + AESuspendTheCurrentEvent (aevt); + + /* Don't emit the "quit_requested" signal immediately, since we're + * called from a weird point in the guts of gdkeventloop-quartz.c + */ + g_idle_add (idle_quit_requested, client); + return noErr; +} + +static pascal OSErr +quit_requested_resumed (const AppleEvent *aevt, AppleEvent *reply, long refcon) +{ + EggSMClientOSX *osx = GSIZE_TO_POINTER ((gsize)refcon); + + osx->quit_requested = FALSE; + return osx->quitting ? noErr : userCanceledErr; +} + +static gboolean +idle_will_quit (gpointer client) +{ + EggSMClientOSX *osx = (EggSMClientOSX *)client; + + /* Resume the event with a new handler that will return a value to + * the system. + */ + AEResumeTheCurrentEvent (&osx->quit_event, &osx->quit_reply, + NewAEEventHandlerUPP (quit_requested_resumed), + (long)GPOINTER_TO_SIZE (client)); + AEDisposeDesc (&osx->quit_event); + AEDisposeDesc (&osx->quit_reply); + + if (osx->quitting) + egg_sm_client_quit (client); + return FALSE; +} + +static void +sm_client_osx_will_quit (EggSMClient *client, + gboolean will_quit) +{ + EggSMClientOSX *osx = (EggSMClientOSX *)client; + + g_return_if_fail (osx->quit_requested); + + osx->quitting = will_quit; + + /* Finish in an idle handler since the caller might have called + * egg_sm_client_will_quit() from inside the "quit_requested" signal + * handler, but may not expect the "quit" signal to arrive during + * the _will_quit() call. + */ + g_idle_add (idle_will_quit, client); +} + +static gboolean +sm_client_osx_end_session (EggSMClient *client, + EggSMClientEndStyle style, + gboolean request_confirmation) +{ + static const ProcessSerialNumber loginwindow_psn = { 0, kSystemProcess }; + AppleEvent event = { typeNull, NULL }, reply = { typeNull, NULL }; + AEAddressDesc target; + AEEventID id; + OSErr err; + + switch (style) + { + case EGG_SM_CLIENT_END_SESSION_DEFAULT: + case EGG_SM_CLIENT_LOGOUT: + id = request_confirmation ? kAELogOut : kAEReallyLogOut; + break; + case EGG_SM_CLIENT_REBOOT: + id = request_confirmation ? kAEShowRestartDialog : kAERestart; + break; + case EGG_SM_CLIENT_SHUTDOWN: + id = request_confirmation ? kAEShowShutdownDialog : kAEShutDown; + break; + } + + err = AECreateDesc (typeProcessSerialNumber, &loginwindow_psn, + sizeof (loginwindow_psn), &target); + if (err != noErr) + { + g_warning ("Could not create descriptor for loginwindow: %d", err); + return FALSE; + } + + err = AECreateAppleEvent (kCoreEventClass, id, &target, + kAutoGenerateReturnID, kAnyTransactionID, + &event); + AEDisposeDesc (&target); + if (err != noErr) + { + g_warning ("Could not create logout AppleEvent: %d", err); + return FALSE; + } + + err = AESend (&event, &reply, kAENoReply, kAENormalPriority, + kAEDefaultTimeout, NULL, NULL); + AEDisposeDesc (&event); + if (err == noErr) + AEDisposeDesc (&reply); + + return err == noErr; +} diff --git a/pool/shard003/C/0064224_xtkbd.c b/pool/shard003/C/0064224_xtkbd.c new file mode 100644 index 0000000000000000000000000000000000000000..4c1c31642ef4657c427754d4be1e9bec219abb95 --- /dev/null +++ b/pool/shard003/C/0064224_xtkbd.c @@ -0,0 +1,171 @@ +/* + * $Id: xtkbd.c,v 1.11 2001/09/25 10:12:07 vojtech Exp $ + * + * Copyright (c) 1999-2001 Vojtech Pavlik + */ + +/* + * XT keyboard driver for Linux + */ + +/* + * 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 + * + * Should you need to contact me, the author, you can do so either by + * e-mail - mail your message to , or by paper mail: + * Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic + */ + +#include +#include +#include +#include +#include + +#define DRIVER_DESC "XT keyboard driver" + +MODULE_AUTHOR("Vojtech Pavlik "); +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_LICENSE("GPL"); + +#define XTKBD_EMUL0 0xe0 +#define XTKBD_EMUL1 0xe1 +#define XTKBD_KEY 0x7f +#define XTKBD_RELEASE 0x80 + +static unsigned char xtkbd_keycode[256] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, + 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 0, 0, 0, 87, 88, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 87, 88, 0, 0, 0, 0,110,111,103,108,105, + 106 +}; + +static char *xtkbd_name = "XT Keyboard"; + +struct xtkbd { + unsigned char keycode[256]; + struct input_dev dev; + struct serio *serio; + char phys[32]; +}; + +irqreturn_t xtkbd_interrupt(struct serio *serio, + unsigned char data, unsigned int flags, struct pt_regs *regs) +{ + struct xtkbd *xtkbd = serio->private; + + switch (data) { + case XTKBD_EMUL0: + case XTKBD_EMUL1: + break; + default: + + if (xtkbd->keycode[data & XTKBD_KEY]) { + input_regs(&xtkbd->dev, regs); + input_report_key(&xtkbd->dev, xtkbd->keycode[data & XTKBD_KEY], !(data & XTKBD_RELEASE)); + input_sync(&xtkbd->dev); + } else { + printk(KERN_WARNING "xtkbd.c: Unknown key (scancode %#x) %s.\n", + data & XTKBD_KEY, data & XTKBD_RELEASE ? "released" : "pressed"); + } + } + return IRQ_HANDLED; +} + +void xtkbd_connect(struct serio *serio, struct serio_driver *drv) +{ + struct xtkbd *xtkbd; + int i; + + if ((serio->type & SERIO_TYPE) != SERIO_XT) + return; + + if (!(xtkbd = kmalloc(sizeof(struct xtkbd), GFP_KERNEL))) + return; + + memset(xtkbd, 0, sizeof(struct xtkbd)); + + xtkbd->dev.evbit[0] = BIT(EV_KEY) | BIT(EV_REP); + + xtkbd->serio = serio; + + init_input_dev(&xtkbd->dev); + xtkbd->dev.keycode = xtkbd->keycode; + xtkbd->dev.keycodesize = sizeof(unsigned char); + xtkbd->dev.keycodemax = ARRAY_SIZE(xtkbd_keycode); + xtkbd->dev.private = xtkbd; + + serio->private = xtkbd; + + if (serio_open(serio, drv)) { + kfree(xtkbd); + return; + } + + memcpy(xtkbd->keycode, xtkbd_keycode, sizeof(xtkbd->keycode)); + for (i = 0; i < 255; i++) + set_bit(xtkbd->keycode[i], xtkbd->dev.keybit); + clear_bit(0, xtkbd->dev.keybit); + + sprintf(xtkbd->phys, "%s/input0", serio->phys); + + xtkbd->dev.name = xtkbd_name; + xtkbd->dev.phys = xtkbd->phys; + xtkbd->dev.id.bustype = BUS_XTKBD; + xtkbd->dev.id.vendor = 0x0001; + xtkbd->dev.id.product = 0x0001; + xtkbd->dev.id.version = 0x0100; + xtkbd->dev.dev = &serio->dev; + + input_register_device(&xtkbd->dev); + + printk(KERN_INFO "input: %s on %s\n", xtkbd_name, serio->phys); +} + +void xtkbd_disconnect(struct serio *serio) +{ + struct xtkbd *xtkbd = serio->private; + input_unregister_device(&xtkbd->dev); + serio_close(serio); + kfree(xtkbd); +} + +struct serio_driver xtkbd_drv = { + .driver = { + .name = "xtkbd", + }, + .description = DRIVER_DESC, + .interrupt = xtkbd_interrupt, + .connect = xtkbd_connect, + .disconnect = xtkbd_disconnect, +}; + +int __init xtkbd_init(void) +{ + serio_register_driver(&xtkbd_drv); + return 0; +} + +void __exit xtkbd_exit(void) +{ + serio_unregister_driver(&xtkbd_drv); +} + +module_init(xtkbd_init); +module_exit(xtkbd_exit); diff --git a/pool/shard003/C/0064229_test_compat_gtar.c b/pool/shard003/C/0064229_test_compat_gtar.c new file mode 100644 index 0000000000000000000000000000000000000000..3d5e456e56e6c9908fc6295ab5b5537b18900932 --- /dev/null +++ b/pool/shard003/C/0064229_test_compat_gtar.c @@ -0,0 +1,115 @@ +/*- + * Copyright (c) 2003-2007 Tim Kientzle + * 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(S) ``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(S) 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 "test.h" +__FBSDID("$FreeBSD: head/lib/libarchive/test/test_compat_gtar.c 189308 2009-03-03 17:02:51Z kientzle $"); + +/* + * Verify our ability to read sample files created by GNU tar. + * It should be easy to add any new sample files sent in by users + * to this collection of tests. + */ + +/* Copy this function for each test file and adjust it accordingly. */ + +/* + * test_compat_gtar_1.tgz exercises reading long filenames and + * symlink targets stored in the GNU tar format. + */ +static void +test_compat_gtar_1(void) +{ + char name[] = "test_compat_gtar_1.tar"; + struct archive_entry *ae; + struct archive *a; + int r; + + assert((a = archive_read_new()) != NULL); + assertEqualIntA(a, ARCHIVE_OK, archive_read_support_filter_all(a)); + assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a)); + extract_reference_file(name); + assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, name, 10240)); + + /* Read first entry. */ + assertEqualIntA(a, ARCHIVE_OK, r = archive_read_next_header(a, &ae)); + if (r != ARCHIVE_OK) { + archive_read_free(a); + return; + } + assertEqualString( + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890", + archive_entry_pathname(ae)); + assertEqualInt(1197179003, archive_entry_mtime(ae)); + assertEqualInt(1000, archive_entry_uid(ae)); + assertEqualString("tim", archive_entry_uname(ae)); + assertEqualInt(1000, archive_entry_gid(ae)); + assertEqualString("tim", archive_entry_gname(ae)); + assertEqualInt(0100644, archive_entry_mode(ae)); + + /* Read second entry. */ + assertEqualIntA(a, ARCHIVE_OK, r = archive_read_next_header(a, &ae)); + if (r != ARCHIVE_OK) { + archive_read_free(a); + return; + } + assertEqualString( + "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghij" + "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghij" + "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghij" + "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghij", + archive_entry_pathname(ae)); + assertEqualString( + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890", + archive_entry_symlink(ae)); + assertEqualInt(1197179043, archive_entry_mtime(ae)); + assertEqualInt(1000, archive_entry_uid(ae)); + assertEqualString("tim", archive_entry_uname(ae)); + assertEqualInt(1000, archive_entry_gid(ae)); + assertEqualString("tim", archive_entry_gname(ae)); + assertEqualInt(0120755, archive_entry_mode(ae)); + + /* Verify the end-of-archive. */ + assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); + + /* Verify that the format detection worked. */ + assertEqualInt(archive_filter_code(a, 0), ARCHIVE_FILTER_NONE); + assertEqualInt(archive_format(a), ARCHIVE_FORMAT_TAR_GNUTAR); + + assertEqualInt(ARCHIVE_OK, archive_read_close(a)); + assertEqualInt(ARCHIVE_OK, archive_read_free(a)); +} + + +DEFINE_TEST(test_compat_gtar) +{ + test_compat_gtar_1(); +} + + diff --git a/pool/shard003/C/0064240_tee_time_rtt.c b/pool/shard003/C/0064240_tee_time_rtt.c new file mode 100644 index 0000000000000000000000000000000000000000..ac8188c3da8fc35574881b1cba8b38edc52cb341 --- /dev/null +++ b/pool/shard003/C/0064240_tee_time_rtt.c @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2014, STMicroelectronics International N.V. + * 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 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. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define TEE_TIME_SHIFT 5 + +#define TEE_RTT0_HZ 32768UL + +#define TEE_RTT0_TICKS_PER_SECOND (TEE_RTT0_HZ) +#define TEE_RTT0_TICKS_PER_MINUTE (TEE_RTT0_TICKS_PER_SECOND * 60) +#define TEE_RTT0_TICKS_PER_HOUR (TEE_RTT0_TICKS_PER_MINUTE * 60) + +/* We'll receive one interrupt per hour */ +#define TEE_RTT0_WRAP_TICKS TEE_RTT0_TICKS_PER_HOUR + +#define TEE_RTT1_HZ 10UL +#define TEE_RTT1_WRAP_TICKS 0xffffffff + +/* + * Following is code example that could be used to activate time + * functionalities in TEE for arm32 + * +TEE_Result tee_time_init(void) +{ + - Disable timer and later change to 32kHz + IO(RTT0_CR) &= ~RTT_CR_EN; + + if (!(IO(RTT1_CR) & RTT_CR_EN)) { + IO(RTT1_IMSC) |= RTT_IMSC_IMSC; - disable interrupts + IO(RTT1_LR) = TEE_RTT1_WRAP_TICKS; - start the timer + + TEE_COMPILE_TIME_ASSERT(TEE_RTT1_HZ == TEE_TIME_BOOT_TICKS_HZ); + } + + return TEE_SUCCESS; +} + +uint32_t tee_time_get_boot_ticks(void) +{ + return TEE_RTT1_WRAP_TICKS - IO(RTT1_DR); +} + +uint32_t tee_time_get_boot_time_in_seconds(void) +{ + return tee_time_get_boot_ticks() / TEE_RTT1_HZ; +} +*/ + +static void tee_time_rtt0_init(void) +{ + static bool inited; /* initialized to false */ + + if (!inited) { + volatile uint32_t *cr = (uint32_t *)RTT0_CR; + volatile uint32_t *ctcr = (uint32_t *)RTT0_CTCR; + volatile uint32_t *lr = (uint32_t *)RTT0_LR; + volatile uint32_t *imsc = (uint32_t *)RTT0_IMSC; + + DMSG("tee_time_rtt0_init: First call may take a few secs"); + + /* + * Make sure timer is disabled. RTT_CR_EN is not accurate, + * enabling can be in progress too. Checking *ctcr takes + * care of that since updates to ctcr only propagates once + * timer really is disabled. + */ + while (*ctcr != 0 || (*cr & (RTT_CR_EN | RTT_CR_ENS)) != 0) { + *cr &= ~RTT_CR_EN; + *ctcr = 0; + } + + /* Change to 32kHz */ + *ctcr = 0; + + /* Enable interrupts on wrap */ + *imsc |= RTT_IMSC_IMSC; + + /* Start with the desired interrupt interval */ + *lr = TEE_RTT0_WRAP_TICKS; + + inited = true; + } +} + +/* + * Following is code example that could be used to activate time + * functionalities in TEE for arm32 + * +TEE_Result tee_time_stamp(uint32_t *stamp) +{ + tee_time_rtt0_init(); + + *stamp = IO(RTT0_DR); + + return TEE_SUCCESS; +} + +TEE_Result tee_time_get(uint32_t stamp, uint32_t *time) +{ + TEE_Result res; + uint32_t val; + + res = tee_time_stamp(&val); + if (res != TEE_SUCCESS) + return res; + + *time = (stamp - val) >> TEE_TIME_SHIFT; + + return TEE_SUCCESS; +} + +TEE_Result tee_time_secure_rtc_update(const void *time, uint32_t time_size) +{ + return TEE_SUCCESS; +} + +TEE_Result tee_time_secure_rtc_update_check(bool *ok) +{ + *ok = true; + return TEE_SUCCESS; +} +*/ + +static TEE_Result rtt_get_sys_time(TEE_Time *time) +{ + uint32_t wrap0; + uint32_t wrap; + uint32_t timer; + + tee_time_rtt0_init(); + + /* + * Reading wrap before and after we're reading DR to be able to + * detect if the timer wrapped while we where reading it. + */ + do { + wrap0 = tee_time_rtt0_wrap; + timer = TEE_RTT0_WRAP_TICKS - IO(RTT0_DR); + wrap = tee_time_rtt0_wrap; + } while (wrap0 != wrap); + + time->seconds = wrap * TEE_RTT0_WRAP_TICKS / TEE_RTT0_HZ + + timer / TEE_RTT0_HZ; + time->millis = + (timer % TEE_RTT0_HZ) / (TEE_RTT0_HZ / TEE_TIME_MILLIS_BASE); + + return TEE_SUCCESS; +} + +static const struct time_source rtt_time_source = { + .name = "rtt0", + .get_sys_time = rtt_get_sys_time, +}; + +REGISTER_TIME_SOURCE(rtt_time_source) diff --git a/pool/shard003/C/0064241_gss_export_sec_context.c b/pool/shard003/C/0064241_gss_export_sec_context.c new file mode 100644 index 0000000000000000000000000000000000000000..0fc19e2af735f9c0e703f8434255652caa7f8865 --- /dev/null +++ b/pool/shard003/C/0064241_gss_export_sec_context.c @@ -0,0 +1,77 @@ +/*- + * Copyright (c) 2005 Doug Rabson + * 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. + * + * $FreeBSD: src/lib/libgssapi/gss_export_sec_context.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ + */ + +#include "mech_locl.h" + +OM_uint32 GSSAPI_LIB_FUNCTION +gss_export_sec_context(OM_uint32 *minor_status, + gss_ctx_id_t *context_handle, + gss_buffer_t interprocess_token) +{ + OM_uint32 major_status; + struct _gss_context *ctx = (struct _gss_context *) *context_handle; + gssapi_mech_interface m = ctx->gc_mech; + gss_buffer_desc buf; + + _mg_buffer_zero(interprocess_token); + + major_status = m->gm_export_sec_context(minor_status, + &ctx->gc_ctx, &buf); + + if (major_status == GSS_S_COMPLETE) { + unsigned char *p; + + free(ctx); + *context_handle = GSS_C_NO_CONTEXT; + interprocess_token->length = buf.length + + 2 + m->gm_mech_oid.length; + interprocess_token->value = malloc(interprocess_token->length); + if (!interprocess_token->value) { + /* + * We are in trouble here - the context is + * already gone. This is allowed as long as we + * set the caller's context_handle to + * GSS_C_NO_CONTEXT, which we did above. + * Return GSS_S_FAILURE. + */ + _mg_buffer_zero(interprocess_token); + *minor_status = ENOMEM; + return (GSS_S_FAILURE); + } + p = interprocess_token->value; + p[0] = m->gm_mech_oid.length >> 8; + p[1] = m->gm_mech_oid.length; + memcpy(p + 2, m->gm_mech_oid.elements, m->gm_mech_oid.length); + memcpy(p + 2 + m->gm_mech_oid.length, buf.value, buf.length); + gss_release_buffer(minor_status, &buf); + } else { + _gss_mg_error(m, major_status, *minor_status); + } + + return (major_status); +} diff --git a/pool/shard003/C/0064245_crypt-sha512.c b/pool/shard003/C/0064245_crypt-sha512.c new file mode 100644 index 0000000000000000000000000000000000000000..59ae9708d137beacbd2e8e6b03ffbcfdcd740f33 --- /dev/null +++ b/pool/shard003/C/0064245_crypt-sha512.c @@ -0,0 +1,323 @@ +/* One way encryption based on the SHA512-based Unix crypt implementation. + * + * Written by Ulrich Drepper in 2007 [1]. + * Modified by Zack Weinberg in 2017, 2018. + * Composed by Björn Esser in 2018. + * Modified by Björn Esser in 2020. + * To the extent possible under law, the named authors have waived all + * copyright and related or neighboring rights to this work. + * + * See https://creativecommons.org/publicdomain/zero/1.0/ for further + * details. + * + * This file is a modified except from [2], lines 1403 up to 1676. + * + * [1] https://www.akkadia.org/drepper/sha-crypt.html + * [2] https://www.akkadia.org/drepper/SHA-crypt.txt + */ + +#include "crypt-port.h" +#include "alg-sha512.h" + +#include +#include +#include + +#if INCLUDE_sha512crypt + +/* Define our magic string to mark salt for SHA512 "encryption" + replacement. */ +static const char sha512_salt_prefix[] = "$6$"; + +/* Prefix for optional rounds specification. */ +static const char sha512_rounds_prefix[] = "rounds="; + +/* Maximum salt string length. */ +#define SALT_LEN_MAX 16 +/* Default number of rounds if not explicitly specified. */ +#define ROUNDS_DEFAULT 5000 +/* Minimum number of rounds. */ +#define ROUNDS_MIN 1000 +/* Maximum number of rounds. */ +#define ROUNDS_MAX 999999999 + +/* The maximum possible length of a SHA512-hashed password string, + including the terminating NUL character. Prefix (including its NUL) + + rounds tag ("rounds=$" = "rounds=\0") + strlen(ROUNDS_MAX) + + salt (up to SALT_LEN_MAX chars) + '$' + hash (86 chars). */ + +#define LENGTH_OF_NUMBER(n) (sizeof #n - 1) + +#define SHA512_HASH_LENGTH \ + (sizeof (sha512_salt_prefix) + sizeof (sha512_rounds_prefix) + \ + LENGTH_OF_NUMBER (ROUNDS_MAX) + SALT_LEN_MAX + 1 + 86) + +static_assert (SHA512_HASH_LENGTH <= CRYPT_OUTPUT_SIZE, + "CRYPT_OUTPUT_SIZE is too small for SHA512"); + +/* A sha512_buffer holds all of the sensitive intermediate data. */ +struct sha512_buffer +{ + SHA512_CTX ctx; + uint8_t result[64]; + uint8_t p_bytes[64]; + uint8_t s_bytes[64]; +}; + +static_assert (sizeof (struct sha512_buffer) <= ALG_SPECIFIC_SIZE, + "ALG_SPECIFIC_SIZE is too small for SHA512"); + + +/* Subroutine of _xcrypt_crypt_sha512crypt_rn: Feed CTX with LEN bytes of a + virtual byte sequence consisting of BLOCK repeated over and over + indefinitely. */ +static void +sha512_process_recycled_bytes (unsigned char block[64], size_t len, + SHA512_CTX *ctx) +{ + size_t cnt; + for (cnt = len; cnt >= 64; cnt -= 64) + SHA512_Update (ctx, block, 64); + SHA512_Update (ctx, block, cnt); +} + +void +crypt_sha512crypt_rn (const char *phrase, size_t phr_size, + const char *setting, size_t ARG_UNUSED (set_size), + uint8_t *output, size_t out_size, + void *scratch, size_t scr_size) +{ + /* This shouldn't ever happen, but... */ + if (out_size < SHA512_HASH_LENGTH + || scr_size < sizeof (struct sha512_buffer)) + { + errno = ERANGE; + return; + } + + struct sha512_buffer *buf = scratch; + SHA512_CTX *ctx = &buf->ctx; + uint8_t *result = buf->result; + uint8_t *p_bytes = buf->p_bytes; + uint8_t *s_bytes = buf->s_bytes; + char *cp = (char *)output; + const char *salt = setting; + + size_t salt_size; + size_t cnt; + /* Default number of rounds. */ + size_t rounds = ROUNDS_DEFAULT; + bool rounds_custom = false; + + /* Find beginning of salt string. The prefix should normally always + be present. Just in case it is not. */ + if (strncmp (sha512_salt_prefix, salt, sizeof (sha512_salt_prefix) - 1) == 0) + /* Skip salt prefix. */ + salt += sizeof (sha512_salt_prefix) - 1; + + if (strncmp (salt, sha512_rounds_prefix, sizeof (sha512_rounds_prefix) - 1) + == 0) + { + const char *num = salt + sizeof (sha512_rounds_prefix) - 1; + /* Do not allow an explicit setting of zero rounds, nor of the + default number of rounds, nor leading zeroes on the rounds. */ + if (!(*num >= '1' && *num <= '9')) + { + errno = EINVAL; + return; + } + + errno = 0; + char *endp; + rounds = strtoul (num, &endp, 10); + if (endp == num || *endp != '$' + || rounds < ROUNDS_MIN + || rounds > ROUNDS_MAX + || errno) + { + errno = EINVAL; + return; + } + salt = endp + 1; + rounds_custom = true; + } + + /* The salt ends at the next '$' or the end of the string. + Ensure ':' does not appear in the salt (it is used as a separator in /etc/passwd). + Also check for '\n', as in /etc/passwd the whole parameters of the user data must + be on a single line. */ + salt_size = strcspn (salt, "$:\n"); + if (!(salt[salt_size] == '$' || !salt[salt_size])) + { + errno = EINVAL; + return; + } + + /* Ensure we do not use more salt than SALT_LEN_MAX. */ + if (salt_size > SALT_LEN_MAX) + salt_size = SALT_LEN_MAX; + + /* Compute alternate SHA512 sum with input PHRASE, SALT, and PHRASE. The + final result will be added to the first context. */ + SHA512_Init (ctx); + + /* Add phrase. */ + SHA512_Update (ctx, phrase, phr_size); + + /* Add salt. */ + SHA512_Update (ctx, salt, salt_size); + + /* Add phrase again. */ + SHA512_Update (ctx, phrase, phr_size); + + /* Now get result of this (64 bytes) and add it to the other + context. */ + SHA512_Final (result, ctx); + + /* Prepare for the real work. */ + SHA512_Init (ctx); + + /* Add the phrase string. */ + SHA512_Update (ctx, phrase, phr_size); + + /* The last part is the salt string. This must be at most 8 + characters and it ends at the first `$' character (for + compatibility with existing implementations). */ + SHA512_Update (ctx, salt, salt_size); + + /* Add for any character in the phrase one byte of the alternate sum. */ + for (cnt = phr_size; cnt > 64; cnt -= 64) + SHA512_Update (ctx, result, 64); + SHA512_Update (ctx, result, cnt); + + /* Take the binary representation of the length of the phrase and for every + 1 add the alternate sum, for every 0 the phrase. */ + for (cnt = phr_size; cnt > 0; cnt >>= 1) + if ((cnt & 1) != 0) + SHA512_Update (ctx, result, 64); + else + SHA512_Update (ctx, phrase, phr_size); + + /* Create intermediate result. */ + SHA512_Final (result, ctx); + + /* Start computation of P byte sequence. */ + SHA512_Init (ctx); + + /* For every character in the password add the entire password. */ + for (cnt = 0; cnt < phr_size; ++cnt) + SHA512_Update (ctx, phrase, phr_size); + + /* Finish the digest. */ + SHA512_Final (p_bytes, ctx); + + /* Start computation of S byte sequence. */ + SHA512_Init (ctx); + + /* For every character in the password add the entire password. */ + for (cnt = 0; cnt < (size_t) 16 + (size_t) result[0]; ++cnt) + SHA512_Update (ctx, salt, salt_size); + + /* Finish the digest. */ + SHA512_Final (s_bytes, ctx); + + /* Repeatedly run the collected hash value through SHA512 to burn + CPU cycles. */ + for (cnt = 0; cnt < rounds; ++cnt) + { + /* New context. */ + SHA512_Init (ctx); + + /* Add phrase or last result. */ + if ((cnt & 1) != 0) + sha512_process_recycled_bytes (p_bytes, phr_size, ctx); + else + SHA512_Update (ctx, result, 64); + + /* Add salt for numbers not divisible by 3. */ + if (cnt % 3 != 0) + sha512_process_recycled_bytes (s_bytes, salt_size, ctx); + + /* Add phrase for numbers not divisible by 7. */ + if (cnt % 7 != 0) + sha512_process_recycled_bytes (p_bytes, phr_size, ctx); + + /* Add phrase or last result. */ + if ((cnt & 1) != 0) + SHA512_Update (ctx, result, 64); + else + sha512_process_recycled_bytes (p_bytes, phr_size, ctx); + + /* Create intermediate result. */ + SHA512_Final (result, ctx); + } + + /* Now we can construct the result string. It consists of four + parts, one of which is optional. We already know that buflen is + at least sha512_hash_length, therefore none of the string bashing + below can overflow the buffer. */ + + memcpy (cp, sha512_salt_prefix, sizeof (sha512_salt_prefix) - 1); + cp += sizeof (sha512_salt_prefix) - 1; + + if (rounds_custom) + { + int n = snprintf (cp, + SHA512_HASH_LENGTH - (sizeof (sha512_salt_prefix) - 1), + "%s%zu$", sha512_rounds_prefix, rounds); + cp += n; + } + + memcpy (cp, salt, salt_size); + cp += salt_size; + *cp++ = '$'; + +#define b64_from_24bit(B2, B1, B0, N) \ + do { \ + unsigned int w = ((((unsigned int)(B2)) << 16) | \ + (((unsigned int)(B1)) << 8) | \ + ((unsigned int)(B0))); \ + int n = (N); \ + while (n-- > 0) \ + { \ + *cp++ = b64t[w & 0x3f]; \ + w >>= 6; \ + } \ + } while (0) + + b64_from_24bit (result[0], result[21], result[42], 4); + b64_from_24bit (result[22], result[43], result[1], 4); + b64_from_24bit (result[44], result[2], result[23], 4); + b64_from_24bit (result[3], result[24], result[45], 4); + b64_from_24bit (result[25], result[46], result[4], 4); + b64_from_24bit (result[47], result[5], result[26], 4); + b64_from_24bit (result[6], result[27], result[48], 4); + b64_from_24bit (result[28], result[49], result[7], 4); + b64_from_24bit (result[50], result[8], result[29], 4); + b64_from_24bit (result[9], result[30], result[51], 4); + b64_from_24bit (result[31], result[52], result[10], 4); + b64_from_24bit (result[53], result[11], result[32], 4); + b64_from_24bit (result[12], result[33], result[54], 4); + b64_from_24bit (result[34], result[55], result[13], 4); + b64_from_24bit (result[56], result[14], result[35], 4); + b64_from_24bit (result[15], result[36], result[57], 4); + b64_from_24bit (result[37], result[58], result[16], 4); + b64_from_24bit (result[59], result[17], result[38], 4); + b64_from_24bit (result[18], result[39], result[60], 4); + b64_from_24bit (result[40], result[61], result[19], 4); + b64_from_24bit (result[62], result[20], result[41], 4); + b64_from_24bit (0, 0, result[63], 2); + + *cp = '\0'; +} + +void +gensalt_sha512crypt_rn (unsigned long count, + const uint8_t *rbytes, size_t nrbytes, + uint8_t *output, size_t output_size) +{ + gensalt_sha_rn ('6', SALT_LEN_MAX, ROUNDS_DEFAULT, ROUNDS_MIN, ROUNDS_MAX, + count, rbytes, nrbytes, output, output_size); +} + +#endif diff --git a/pool/shard003/C/0064246_thread_test.c b/pool/shard003/C/0064246_thread_test.c new file mode 100644 index 0000000000000000000000000000000000000000..bf0fb8ea2c0181d529ad624ebd0fb0b5a04757b2 --- /dev/null +++ b/pool/shard003/C/0064246_thread_test.c @@ -0,0 +1,248 @@ +/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; 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. + + 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 +#include +#include "mysql.h" +#include + +static my_bool version, verbose, tty_password= 0; +static uint thread_count,number_of_tests=1000,number_of_threads=2; +static pthread_cond_t COND_thread_count; +static pthread_mutex_t LOCK_thread_count; + +static char *database,*host,*user,*password,*unix_socket,*query; +uint tcp_port; + +#ifndef __WIN__ +void *test_thread(void *arg __attribute__((unused))) +#else +unsigned __stdcall test_thread(void *arg __attribute__((unused))) +#endif +{ + MYSQL *mysql; + uint count; + + mysql=mysql_init(NULL); + if (!mysql_real_connect(mysql,host,user,password,database,tcp_port, + unix_socket,0)) + { + fprintf(stderr,"Couldn't connect to engine!\n%s\n\n",mysql_error(mysql)); + perror(""); + goto end; + } + mysql.reconnect= 1; + if (verbose) { putchar('*'); fflush(stdout); } + for (count=0 ; count < number_of_tests ; count++) + { + MYSQL_RES *res; + if (mysql_query(mysql,query)) + { + fprintf(stderr,"Query failed (%s)\n",mysql_error(mysql)); + goto end; + } + if (!(res=mysql_store_result(mysql))) + { + fprintf(stderr,"Couldn't get result from %s\n", mysql_error(mysql)); + goto end; + } + mysql_free_result(res); + if (verbose) { putchar('.'); fflush(stdout); } + } +end: + if (verbose) { putchar('#'); fflush(stdout); } + mysql_close(mysql); + pthread_mutex_lock(&LOCK_thread_count); + thread_count--; + pthread_cond_signal(&COND_thread_count); /* Tell main we are ready */ + pthread_mutex_unlock(&LOCK_thread_count); + pthread_exit(0); + return 0; +} + + +static struct my_option my_long_options[] = +{ + {"help", '?', "Display this help and exit", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, + 0, 0, 0, 0, 0}, + {"database", 'D', "Database to use", &database, &database, + 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"host", 'h', "Connect to host", &host, &host, 0, GET_STR, + REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"password", 'p', + "Password to use when connecting to server. If password is not given it's asked from the tty.", + 0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0}, + {"user", 'u', "User for login if not current user", &user, + &user, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"version", 'V', "Output version information and exit", + 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"verbose", 'v', "Write some progress indicators", &verbose, + &verbose, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, + {"query", 'Q', "Query to execute in each threads", &query, + &query, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"port", 'P', "Port number to use for connection or 0 for default to, in " + "order of preference, my.cnf, $MYSQL_TCP_PORT, " +#if MYSQL_PORT_DEFAULT == 0 + "/etc/services, " +#endif + "built-in default (" STRINGIFY_ARG(MYSQL_PORT) ").", + &tcp_port, + &tcp_port, 0, GET_UINT, REQUIRED_ARG, MYSQL_PORT, 0, 0, 0, 0, 0}, + {"socket", 'S', "Socket file to use for connection", &unix_socket, + &unix_socket, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}, + {"test-count", 'c', "Run test count times (default %d)", + &number_of_tests, &number_of_tests, 0, GET_UINT, + REQUIRED_ARG, 1000, 0, 0, 0, 0, 0}, + {"thread-count", 't', "Number of threads to start", + &number_of_threads, &number_of_threads, 0, GET_UINT, + REQUIRED_ARG, 2, 0, 0, 0, 0, 0}, + { 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0} +}; + + +static const char *load_default_groups[]= +{ "client", "client-server", "client-mariadb", 0 }; + +static void usage() +{ + printf("Connection to a mysql server with multiple threads\n"); + if (version) + return; + puts("This software comes with ABSOLUTELY NO WARRANTY.\n"); + printf("Usage: %s [OPTIONS] [database]\n", my_progname); + + my_print_help(my_long_options); + print_defaults("my",load_default_groups); + my_print_variables(my_long_options); + printf("\nExample usage:\n\n\ +%s -Q 'select * from mysql.user' -c %d -t %d\n", + my_progname, number_of_tests, number_of_threads); +} + + +static my_bool +get_one_option(int optid, const struct my_option *opt __attribute__((unused)), + char *argument) +{ + switch (optid) { + case 'p': + if (argument) + { + my_free(password); + password= my_strdup(argument, MYF(MY_FAE)); + while (*argument) *argument++= 'x'; /* Destroy argument */ + } + else + tty_password= 1; + break; + case 'V': + version= 1; + usage(); + exit(0); + break; + case '?': + case 'I': /* Info */ + usage(); + exit(1); + break; + } + return 0; +} + + +static void get_options(int argc, char **argv) +{ + int ho_error; + + if ((ho_error= load_defaults("my",load_default_groups,&argc,&argv)) || + (ho_error= handle_options(&argc, &argv, my_long_options, get_one_option))) + exit(ho_error); + + free_defaults(argv); + if (tty_password) + password=get_tty_password(NullS); + return; +} + + +int main(int argc, char **argv) +{ + pthread_t tid; + pthread_attr_t thr_attr; + uint i; + int error; + MY_INIT(argv[0]); + get_options(argc,argv); + + if ((error=pthread_cond_init(&COND_thread_count,NULL))) + { + fprintf(stderr,"Got error: %d from pthread_cond_init (errno: %d)", + error,errno); + exit(1); + } + pthread_mutex_init(&LOCK_thread_count,MY_MUTEX_INIT_FAST); + + if ((error=pthread_attr_init(&thr_attr))) + { + fprintf(stderr,"Got error: %d from pthread_attr_init (errno: %d)", + error,errno); + exit(1); + } + if ((error=pthread_attr_setdetachstate(&thr_attr,PTHREAD_CREATE_DETACHED))) + { + fprintf(stderr, + "Got error: %d from pthread_attr_setdetachstate (errno: %d)", + error,errno); + exit(1); + } + + printf("Init ok. Creating %d threads\n",number_of_threads); + for (i=1 ; i <= number_of_threads ; i++) + { + int *param= &i; + + if (verbose) { putchar('+'); fflush(stdout); } + pthread_mutex_lock(&LOCK_thread_count); + if ((error=pthread_create(&tid,&thr_attr,test_thread,(void*) param))) + { + fprintf(stderr,"\nGot error: %d from pthread_create (errno: %d) when creating thread: %i\n", + error,errno,i); + pthread_mutex_unlock(&LOCK_thread_count); + exit(1); + } + thread_count++; + pthread_mutex_unlock(&LOCK_thread_count); + } + + printf("Waiting for threads to finnish\n"); + error=pthread_mutex_lock(&LOCK_thread_count); + while (thread_count) + { + if ((error=pthread_cond_wait(&COND_thread_count,&LOCK_thread_count))) + fprintf(stderr,"\nGot error: %d from pthread_cond_wait\n",error); + } + pthread_mutex_unlock(&LOCK_thread_count); + pthread_attr_destroy(&thr_attr); + printf("\nend\n"); + + my_end(0); + return 0; + + exit(0); + return 0; /* Keep some compilers happy */ +} + diff --git a/pool/shard003/C/0064262_read_16bit.c b/pool/shard003/C/0064262_read_16bit.c new file mode 100644 index 0000000000000000000000000000000000000000..5c2b042b1425a9b19be0004facac660d738986e3 --- /dev/null +++ b/pool/shard003/C/0064262_read_16bit.c @@ -0,0 +1,100 @@ +#include +#include +#include "mex.h" +#include + +/* + * Copyright (C) 2008, Robert Oostenveld, F.C. Donders Ccentre for Cognitive Neuroimaging + * Copyright (C) 2007, Peter Desain, Nijmegen Institute for Cognition and Information + * + * 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 + * + * + * $Id$ + */ + +void +mexFunction (int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[]) +{ + FILE *fp; + mxArray *dat; + double *dat_p; + char *filename; + short int *buf; + long int offset, numwords, fnlen, i, j, num, b1, b2, b3; + + if (nrhs != 3) + mexErrMsgTxt ("Invalid number of input arguments"); + + if (mxGetM(prhs[1])!=1 || mxGetN(prhs[1])!=1) + mexErrMsgTxt ("Invalid dimension for input argument 2"); + if (mxGetM(prhs[2])!=1 || mxGetN(prhs[2])!=1) + mexErrMsgTxt ("Invalid dimension for input argument 3"); + + /* get the filename */ + fnlen = mxGetN (prhs[0]); + filename = mxCalloc(fnlen+1, sizeof(char)); + mxGetString(prhs[0], filename, fnlen+1); + + /* get values and typecast to integer */ + offset = (long int)(mxGetScalar (prhs[1])); + numwords = (long int)(mxGetScalar (prhs[2])); + + /* + printf("filename = %s\n", filename); + printf("fnlen = %d\n", fnlen); + printf("offset = %d\n", offset); + printf("numwords = %d\n", numwords); + */ + + /* open the file and read the desired bytes */ + fp = fopen(filename, "rb"); + if (fp==NULL) + { + printf("error opening file: %s\n", filename); + return; + } + fseek(fp, offset, SEEK_SET); + + buf = mxCalloc(numwords, sizeof(short)); + num = fread(buf, sizeof(short), numwords, fp); + if (numprev = queue->next = queue; +} + +/* + * SHMQueueIsDetached -- TRUE if element is not currently + * in a queue. + */ +bool +SHMQueueIsDetached(SHM_QUEUE *queue) +{ + Assert(ShmemAddrIsValid(queue)); + return (queue->prev == NULL); +} + +/* + * SHMQueueElemInit -- clear an element's links + */ +void +SHMQueueElemInit(SHM_QUEUE *queue) +{ + Assert(ShmemAddrIsValid(queue)); + queue->prev = queue->next = NULL; +} + +/* + * SHMQueueDelete -- remove an element from the queue and + * close the links + */ +void +SHMQueueDelete(SHM_QUEUE *queue) +{ + SHM_QUEUE *nextElem = queue->next; + SHM_QUEUE *prevElem = queue->prev; + + Assert(ShmemAddrIsValid(queue)); + Assert(ShmemAddrIsValid(nextElem)); + Assert(ShmemAddrIsValid(prevElem)); + + prevElem->next = queue->next; + nextElem->prev = queue->prev; + + queue->prev = queue->next = NULL; +} + +/* + * SHMQueueInsertBefore -- put elem in queue before the given queue + * element. Inserting "before" the queue head puts the elem + * at the tail of the queue. + */ +void +SHMQueueInsertBefore(SHM_QUEUE *queue, SHM_QUEUE *elem) +{ + SHM_QUEUE *prevPtr = queue->prev; + + Assert(ShmemAddrIsValid(queue)); + Assert(ShmemAddrIsValid(elem)); + + elem->next = prevPtr->next; + elem->prev = queue->prev; + queue->prev = elem; + prevPtr->next = elem; +} + +/* + * SHMQueueInsertAfter -- put elem in queue after the given queue + * element. Inserting "after" the queue head puts the elem + * at the head of the queue. + */ +//#ifdef NOT_USED +void +SHMQueueInsertAfter(SHM_QUEUE *queue, SHM_QUEUE *elem) +{ + SHM_QUEUE *nextPtr = queue->next; + + Assert(ShmemAddrIsValid(queue)); + Assert(ShmemAddrIsValid(elem)); + + elem->prev = nextPtr->prev; + elem->next = queue->next; + queue->next = elem; + nextPtr->prev = elem; +} +//#endif /* NOT_USED */ + +/*-------------------- + * SHMQueueNext -- Get the next element from a queue + * + * To start the iteration, pass the queue head as both queue and curElem. + * Returns NULL if no more elements. + * + * Next element is at curElem->next. If SHMQueue is part of + * a larger structure, we want to return a pointer to the + * whole structure rather than a pointer to its SHMQueue field. + * For example, + * struct { + * int stuff; + * SHMQueue elem; + * } ELEMType; + * When this element is in a queue, prevElem->next points at struct.elem. + * We subtract linkOffset to get the correct start address of the structure. + * + * calls to SHMQueueNext should take these parameters: + * &(queueHead), &(queueHead), offsetof(ELEMType, elem) + * or + * &(queueHead), &(curElem->elem), offsetof(ELEMType, elem) + *-------------------- + */ +Pointer +SHMQueueNext(SHM_QUEUE *queue, SHM_QUEUE *curElem, Size linkOffset) +{ + SHM_QUEUE *elemPtr = curElem->next; + + Assert(ShmemAddrIsValid(curElem)); + + if (elemPtr == queue) /* back to the queue head? */ + return NULL; + + return (Pointer) (((char *) elemPtr) - linkOffset); +} + +/*-------------------- + * SHMQueuePrev -- Get the previous element from a queue + * + * Same as SHMQueueNext, just starting at tail and moving towards head. + * All other comments and usage applies. + */ +Pointer +SHMQueuePrev(SHM_QUEUE *queue, SHM_QUEUE *curElem, Size linkOffset) +{ + SHM_QUEUE *elemPtr = curElem->prev; + + Assert(ShmemAddrIsValid(curElem)); + + if (elemPtr == queue) /* back to the queue head? */ + return NULL; + + return (Pointer) (((char *) elemPtr) - linkOffset); +} + +/* + * SHMQueueEmpty -- TRUE if queue head is only element, FALSE otherwise + */ +bool +SHMQueueEmpty(SHM_QUEUE *queue) +{ + Assert(ShmemAddrIsValid(queue)); + + if (queue->prev == queue) + { + Assert(queue->next == queue); + return TRUE; + } + return FALSE; +} diff --git a/pool/shard003/C/0064269_ft_strmap_test.c b/pool/shard003/C/0064269_ft_strmap_test.c new file mode 100644 index 0000000000000000000000000000000000000000..34721330242f8da390fc7a52334a1451a0f84fa9 --- /dev/null +++ b/pool/shard003/C/0064269_ft_strmap_test.c @@ -0,0 +1,41 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_strmap_test.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: jlagneau +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2017/04/01 01:10:32 by jlagneau #+# #+# */ +/* Updated: 2017/04/05 23:09:23 by jlagneau ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include +#include +#include "test.h" + +static int rot13c(int c) +{ + if (ft_isalpha(c)) + { + if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M')) + return (c + 13); + else + return (c - 13); + } + return (c); +} + +int ft_strmap_test(void) +{ + int fails; + char *s; + + fails = g_fails; + s = ft_strdup("Hello, World !"); + ASSERT(0 == ft_strcmp("Uryyb, Jbeyq !", ft_strmap(s, &rot13c))); + ASSERT(0 == ft_strcmp("URYYB, JBEYQ !", ft_strmap(s, &ft_toupper))); + ASSERT(0 == ft_strcmp("uryyb, jbeyq !", ft_strmap(s, &ft_tolower))); + free(s); + return (g_fails - fails); +} diff --git a/pool/shard003/C/0064291_demux_roq.c b/pool/shard003/C/0064291_demux_roq.c new file mode 100644 index 0000000000000000000000000000000000000000..e51fab671763ee70aca3e3fed75eebecf711e3ad --- /dev/null +++ b/pool/shard003/C/0064291_demux_roq.c @@ -0,0 +1,283 @@ +/* + * RoQ file demuxer + * copyright (c) 2002 Mike Melanson + * based on Dr. Tim Ferguson's RoQ document found at: + * http://www.csse.monash.edu.au/~timf/videocodec.html + * + * This file is part of MPlayer. + * + * MPlayer 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. + * + * MPlayer 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 MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include + +#include "config.h" +#include "mp_msg.h" +#include "help_mp.h" + +#include "stream/stream.h" +#include "demuxer.h" +#include "stheader.h" + +#define RoQ_INFO 0x1001 +#define RoQ_QUAD_CODEBOOK 0x1002 +#define RoQ_QUAD_VQ 0x1011 +#define RoQ_SOUND_MONO 0x1020 +#define RoQ_SOUND_STEREO 0x1021 + +#define CHUNK_TYPE_AUDIO 0 +#define CHUNK_TYPE_VIDEO 1 + +typedef struct roq_chunk_t +{ + int chunk_type; + off_t chunk_offset; + int chunk_size; + + float video_chunk_number; // in the case of a video chunk + int running_audio_sample_count; // for an audio chunk +} roq_chunk_t; + +typedef struct roq_data_t +{ + int total_chunks; + int current_chunk; + int total_video_chunks; + int total_audio_sample_count; + roq_chunk_t *chunks; +} roq_data_t; + +// Check if a stream qualifies as a RoQ file based on the magic numbers +// at the start of the file: +// 84 10 FF FF FF FF xx xx +static int roq_check_file(demuxer_t *demuxer) +{ + if ((stream_read_dword(demuxer->stream) == 0x8410FFFF) && + ((stream_read_dword(demuxer->stream) & 0xFFFF0000) == 0xFFFF0000)) + return DEMUXER_TYPE_ROQ; + else + return 0; +} + +// return value: +// 0 = EOF or no stream found +// 1 = successfully read a packet +static int demux_roq_fill_buffer(demuxer_t *demuxer, demux_stream_t *ds) +{ + sh_video_t *sh_video = demuxer->video->sh; + roq_data_t *roq_data = (roq_data_t *)demuxer->priv; + roq_chunk_t roq_chunk; + + if (roq_data->current_chunk >= roq_data->total_chunks) + return 0; + + roq_chunk = roq_data->chunks[roq_data->current_chunk]; + + // make sure we're at the right place in the stream and fetch the chunk + stream_seek(demuxer->stream, roq_chunk.chunk_offset); + + if (roq_chunk.chunk_type == CHUNK_TYPE_AUDIO) + ds_read_packet(demuxer->audio, demuxer->stream, roq_chunk.chunk_size, + 0, + roq_chunk.chunk_offset, 0); + else + ds_read_packet(demuxer->video, demuxer->stream, roq_chunk.chunk_size, + roq_chunk.video_chunk_number / sh_video->fps, + roq_chunk.chunk_offset, 0); + + roq_data->current_chunk++; + return 1; +} + +static demuxer_t* demux_open_roq(demuxer_t* demuxer) +{ + sh_video_t *sh_video = NULL; + sh_audio_t *sh_audio = NULL; + + roq_data_t *roq_data = malloc(sizeof(roq_data_t)); + int chunk_id; + int chunk_size; + int chunk_arg; + int last_chunk_id = 0; + int largest_audio_chunk = 0; + int fps; + + roq_data->total_chunks = 0; + roq_data->current_chunk = 0; + roq_data->total_video_chunks = 0; + roq_data->chunks = NULL; + + // position the stream and start traversing + stream_seek(demuxer->stream, 6); + fps = stream_read_word_le(demuxer->stream); + while (!stream_eof(demuxer->stream)) + { + chunk_id = stream_read_word_le(demuxer->stream); + chunk_size = stream_read_dword_le(demuxer->stream); + chunk_arg = stream_read_word_le(demuxer->stream); + + // this is the only useful header info in the file + if (chunk_id == RoQ_INFO) + { + // there should only be one RoQ_INFO chunk per file + if (sh_video) + { + mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Found more than one RoQ_INFO chunk\n"); + stream_skip(demuxer->stream, 8); + } + else + { + // this is a good opportunity to create a video stream header + sh_video = new_sh_video(demuxer, 0); + // make sure the demuxer knows about the new stream header + demuxer->video->sh = sh_video; + // make sure that the video demuxer stream header knows about its + // parent video demuxer stream + sh_video->ds = demuxer->video; + + sh_video->disp_w = stream_read_word_le(demuxer->stream); + sh_video->disp_h = stream_read_word_le(demuxer->stream); + stream_skip(demuxer->stream, 4); + + // custom fourcc for internal MPlayer use + sh_video->format = mmioFOURCC('R', 'o', 'Q', 'V'); + + // constant frame rate + sh_video->fps = fps; + sh_video->frametime = 1 / sh_video->fps; + } + } + else if ((chunk_id == RoQ_SOUND_MONO) || + (chunk_id == RoQ_SOUND_STEREO)) + { + // create the audio stream header if it hasn't been created it + if (sh_audio == NULL) + { + // make the header first + sh_audio = new_sh_audio(demuxer, 0); + // make sure the demuxer knows about the new stream header + demuxer->audio->id = 0; + demuxer->audio->sh = sh_audio; + // make sure that the audio demuxer stream header knows about its + // parent audio demuxer stream + sh_audio->ds = demuxer->audio; + + // go through the bother of making a WAVEFORMATEX structure + sh_audio->wf = malloc(sizeof(WAVEFORMATEX)); + + // custom fourcc for internal MPlayer use + sh_audio->format = mmioFOURCC('R', 'o', 'Q', 'A'); + if (chunk_id == RoQ_SOUND_STEREO) + sh_audio->wf->nChannels = 2; + else + sh_audio->wf->nChannels = 1; + // always 22KHz, 16-bit + sh_audio->wf->nSamplesPerSec = 22050; + sh_audio->wf->wBitsPerSample = 16; + } + + // index the chunk + roq_data->chunks = realloc(roq_data->chunks, + (roq_data->total_chunks + 1) * sizeof (roq_chunk_t)); + roq_data->chunks[roq_data->total_chunks].chunk_type = CHUNK_TYPE_AUDIO; + roq_data->chunks[roq_data->total_chunks].chunk_offset = + stream_tell(demuxer->stream) - 8; + roq_data->chunks[roq_data->total_chunks].chunk_size = chunk_size + 8; + roq_data->chunks[roq_data->total_chunks].running_audio_sample_count = + roq_data->total_audio_sample_count; + + // audio housekeeping + if (chunk_size > largest_audio_chunk) + largest_audio_chunk = chunk_size; + roq_data->total_audio_sample_count += + (chunk_size / sh_audio->wf->nChannels); + + stream_skip(demuxer->stream, chunk_size); + roq_data->total_chunks++; + } + else if ((chunk_id == RoQ_QUAD_CODEBOOK) || + ((chunk_id == RoQ_QUAD_VQ) && (last_chunk_id != RoQ_QUAD_CODEBOOK))) + { + // index a new chunk if it's a codebook or quad VQ not following a + // codebook + roq_data->chunks = realloc(roq_data->chunks, + (roq_data->total_chunks + 1) * sizeof (roq_chunk_t)); + roq_data->chunks[roq_data->total_chunks].chunk_type = CHUNK_TYPE_VIDEO; + roq_data->chunks[roq_data->total_chunks].chunk_offset = + stream_tell(demuxer->stream) - 8; + roq_data->chunks[roq_data->total_chunks].chunk_size = chunk_size + 8; + roq_data->chunks[roq_data->total_chunks].video_chunk_number = + roq_data->total_video_chunks++; + + stream_skip(demuxer->stream, chunk_size); + roq_data->total_chunks++; + } + else if ((chunk_id == RoQ_QUAD_VQ) && (last_chunk_id == RoQ_QUAD_CODEBOOK)) + { + // if it's a quad VQ chunk following a codebook chunk, extend the last + // chunk + roq_data->chunks[roq_data->total_chunks - 1].chunk_size += (chunk_size + 8); + stream_skip(demuxer->stream, chunk_size); + } + else if (!stream_eof(demuxer->stream)) + { + mp_msg(MSGT_DECVIDEO, MSGL_WARN, "Unknown RoQ chunk ID: %04X\n", chunk_id); + } + + last_chunk_id = chunk_id; + } + + // minimum output buffer size = largest audio chunk * 2, since each byte + // in the DPCM encoding effectively represents 1 16-bit sample + // (store it in wf->nBlockAlign for the time being since init_audio() will + // step on it anyway) + if (sh_audio) + sh_audio->wf->nBlockAlign = largest_audio_chunk * 2; + + roq_data->current_chunk = 0; + + demuxer->priv = roq_data; + + stream_reset(demuxer->stream); + + return demuxer; +} + +static void demux_close_roq(demuxer_t* demuxer) { + roq_data_t *roq_data = demuxer->priv; + + if(!roq_data) + return; + free(roq_data); +} + + +const demuxer_desc_t demuxer_desc_roq = { + "RoQ demuxer", + "roq", + "ROQ", + "Mike Melanson", + "", + DEMUXER_TYPE_ROQ, + 0, // unsafe autodetect + roq_check_file, + demux_roq_fill_buffer, + demux_open_roq, + demux_close_roq, + NULL, + NULL +}; diff --git a/pool/shard003/C/0064292_tbinstal.c b/pool/shard003/C/0064292_tbinstal.c new file mode 100644 index 0000000000000000000000000000000000000000..7b063916da400bcd5dead73e8054657fa31813f7 --- /dev/null +++ b/pool/shard003/C/0064292_tbinstal.c @@ -0,0 +1,547 @@ +/****************************************************************************** + * + * Module Name: tbinstal - ACPI table installation and removal + * $Revision: 45 $ + * + *****************************************************************************/ + +/* + * Copyright (C) 2000, 2001 R. Byron Moore + * + * 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 "acpi.h" +#include "achware.h" +#include "actables.h" + + +#define _COMPONENT ACPI_TABLES + MODULE_NAME ("tbinstal") + + +/******************************************************************************* + * + * FUNCTION: Acpi_tb_install_table + * + * PARAMETERS: Table_ptr - Input buffer pointer, optional + * Table_info - Return value from Acpi_tb_get_table + * + * RETURN: Status + * + * DESCRIPTION: Load and validate all tables other than the RSDT. The RSDT must + * already be loaded and validated. + * Install the table into the global data structs. + * + ******************************************************************************/ + +acpi_status +acpi_tb_install_table ( + acpi_table_header *table_ptr, + acpi_table_desc *table_info) +{ + acpi_status status; + + FUNCTION_TRACE ("Tb_install_table"); + + + /* + * Check the table signature and make sure it is recognized + * Also checks the header checksum + */ + status = acpi_tb_recognize_table (table_ptr, table_info); + if (ACPI_FAILURE (status)) { + return_ACPI_STATUS (status); + } + + /* Lock tables while installing */ + + acpi_ut_acquire_mutex (ACPI_MTX_TABLES); + + /* Install the table into the global data structure */ + + status = acpi_tb_init_table_descriptor (table_info->type, table_info); + + ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "%s located at %p\n", + acpi_gbl_acpi_table_data[table_info->type].name, table_info->pointer)); + + acpi_ut_release_mutex (ACPI_MTX_TABLES); + return_ACPI_STATUS (status); +} + + +/******************************************************************************* + * + * FUNCTION: Acpi_tb_recognize_table + * + * PARAMETERS: Table_ptr - Input buffer pointer, optional + * Table_info - Return value from Acpi_tb_get_table + * + * RETURN: Status + * + * DESCRIPTION: Check a table signature for a match against known table types + * + * NOTE: All table pointers are validated as follows: + * 1) Table pointer must point to valid physical memory + * 2) Signature must be 4 ASCII chars, even if we don't recognize the + * name + * 3) Table must be readable for length specified in the header + * 4) Table checksum must be valid (with the exception of the FACS + * which has no checksum for some odd reason) + * + ******************************************************************************/ + +acpi_status +acpi_tb_recognize_table ( + acpi_table_header *table_ptr, + acpi_table_desc *table_info) +{ + acpi_table_header *table_header; + acpi_status status; + acpi_table_type table_type = 0; + u32 i; + + + FUNCTION_TRACE ("Tb_recognize_table"); + + + /* Ensure that we have a valid table pointer */ + + table_header = (acpi_table_header *) table_info->pointer; + if (!table_header) { + return_ACPI_STATUS (AE_BAD_PARAMETER); + } + + /* + * Search for a signature match among the known table types + * Start at index one -> Skip the RSDP + */ + status = AE_SUPPORT; + for (i = 1; i < NUM_ACPI_TABLES; i++) { + if (!STRNCMP (table_header->signature, + acpi_gbl_acpi_table_data[i].signature, + acpi_gbl_acpi_table_data[i].sig_length)) { + /* + * Found a signature match, get the pertinent info from the + * Table_data structure + */ + table_type = i; + status = acpi_gbl_acpi_table_data[i].status; + + ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Found %4.4s\n", + (char*)acpi_gbl_acpi_table_data[i].signature)); + break; + } + } + + /* Return the table type and length via the info struct */ + + table_info->type = (u8) table_type; + table_info->length = table_header->length; + + + /* + * Validate checksum for _most_ tables, + * even the ones whose signature we don't recognize + */ + if (table_type != ACPI_TABLE_FACS) { + /* But don't abort if the checksum is wrong */ + /* TBD: [Future] make this a configuration option? */ + + acpi_tb_verify_table_checksum (table_header); + } + + /* + * An AE_SUPPORT means that the table was not recognized. + * We basically ignore this; just print a debug message + */ + if (status == AE_SUPPORT) { + ACPI_DEBUG_PRINT ((ACPI_DB_INFO, + "Unsupported table %s (Type %X) was found and discarded\n", + acpi_gbl_acpi_table_data[table_type].name, table_type)); + } + + return_ACPI_STATUS (status); +} + + +/******************************************************************************* + * + * FUNCTION: Acpi_tb_init_table_descriptor + * + * PARAMETERS: Table_type - The type of the table + * Table_info - A table info struct + * + * RETURN: None. + * + * DESCRIPTION: Install a table into the global data structs. + * + ******************************************************************************/ + +acpi_status +acpi_tb_init_table_descriptor ( + acpi_table_type table_type, + acpi_table_desc *table_info) +{ + acpi_table_desc *list_head; + acpi_table_desc *table_desc; + + + FUNCTION_TRACE_U32 ("Tb_init_table_descriptor", table_type); + + /* + * Install the table into the global data structure + */ + list_head = &acpi_gbl_acpi_tables[table_type]; + table_desc = list_head; + + + /* + * Two major types of tables: 1) Only one instance is allowed. This + * includes most ACPI tables such as the DSDT. 2) Multiple instances of + * the table are allowed. This includes SSDT and PSDTs. + */ + if (IS_SINGLE_TABLE (acpi_gbl_acpi_table_data[table_type].flags)) { + /* + * Only one table allowed, and a table has alread been installed + * at this location, so return an error. + */ + if (list_head->pointer) { + return_ACPI_STATUS (AE_EXIST); + } + + table_desc->count = 1; + } + + + else { + /* + * Multiple tables allowed for this table type, we must link + * the new table in to the list of tables of this type. + */ + if (list_head->pointer) { + table_desc = ACPI_MEM_CALLOCATE (sizeof (acpi_table_desc)); + if (!table_desc) { + return_ACPI_STATUS (AE_NO_MEMORY); + } + + list_head->count++; + + /* Update the original previous */ + + list_head->prev->next = table_desc; + + /* Update new entry */ + + table_desc->prev = list_head->prev; + table_desc->next = list_head; + + /* Update list head */ + + list_head->prev = table_desc; + } + + else { + table_desc->count = 1; + } + } + + + /* Common initialization of the table descriptor */ + + table_desc->pointer = table_info->pointer; + table_desc->base_pointer = table_info->base_pointer; + table_desc->length = table_info->length; + table_desc->allocation = table_info->allocation; + table_desc->aml_start = (u8 *) (table_desc->pointer + 1), + table_desc->aml_length = (u32) (table_desc->length - + (u32) sizeof (acpi_table_header)); + table_desc->table_id = acpi_ut_allocate_owner_id (OWNER_TYPE_TABLE); + table_desc->loaded_into_namespace = FALSE; + + /* + * Set the appropriate global pointer (if there is one) to point to the + * newly installed table + */ + if (acpi_gbl_acpi_table_data[table_type].global_ptr) { + *(acpi_gbl_acpi_table_data[table_type].global_ptr) = table_info->pointer; + } + + + /* Return Data */ + + table_info->table_id = table_desc->table_id; + table_info->installed_desc = table_desc; + + return_ACPI_STATUS (AE_OK); +} + + +/******************************************************************************* + * + * FUNCTION: Acpi_tb_delete_acpi_tables + * + * PARAMETERS: None. + * + * RETURN: None. + * + * DESCRIPTION: Delete all internal ACPI tables + * + ******************************************************************************/ + +void +acpi_tb_delete_acpi_tables (void) +{ + acpi_table_type type; + + + /* + * Free memory allocated for ACPI tables + * Memory can either be mapped or allocated + */ + for (type = 0; type < NUM_ACPI_TABLES; type++) { + acpi_tb_delete_acpi_table (type); + } + +} + + +/******************************************************************************* + * + * FUNCTION: Acpi_tb_delete_acpi_table + * + * PARAMETERS: Type - The table type to be deleted + * + * RETURN: None. + * + * DESCRIPTION: Delete an internal ACPI table + * Locks the ACPI table mutex + * + ******************************************************************************/ + +void +acpi_tb_delete_acpi_table ( + acpi_table_type type) +{ + FUNCTION_TRACE_U32 ("Tb_delete_acpi_table", type); + + + if (type > ACPI_TABLE_MAX) { + return_VOID; + } + + + acpi_ut_acquire_mutex (ACPI_MTX_TABLES); + + /* Free the table */ + + acpi_tb_free_acpi_tables_of_type (&acpi_gbl_acpi_tables[type]); + + + /* Clear the appropriate "typed" global table pointer */ + + switch (type) { + case ACPI_TABLE_RSDP: + acpi_gbl_RSDP = NULL; + break; + + case ACPI_TABLE_DSDT: + acpi_gbl_DSDT = NULL; + break; + + case ACPI_TABLE_FADT: + acpi_gbl_FADT = NULL; + break; + + case ACPI_TABLE_FACS: + acpi_gbl_FACS = NULL; + break; + + case ACPI_TABLE_XSDT: + acpi_gbl_XSDT = NULL; + break; + + case ACPI_TABLE_SSDT: + case ACPI_TABLE_PSDT: + default: + break; + } + + acpi_ut_release_mutex (ACPI_MTX_TABLES); + + return_VOID; +} + + +/******************************************************************************* + * + * FUNCTION: Acpi_tb_free_acpi_tables_of_type + * + * PARAMETERS: Table_info - A table info struct + * + * RETURN: None. + * + * DESCRIPTION: Free the memory associated with an internal ACPI table + * Table mutex should be locked. + * + ******************************************************************************/ + +void +acpi_tb_free_acpi_tables_of_type ( + acpi_table_desc *list_head) +{ + acpi_table_desc *table_desc; + u32 count; + u32 i; + + + FUNCTION_TRACE_PTR ("Tb_free_acpi_tables_of_type", list_head); + + + /* Get the head of the list */ + + table_desc = list_head; + count = list_head->count; + + /* + * Walk the entire list, deleting both the allocated tables + * and the table descriptors + */ + for (i = 0; i < count; i++) { + table_desc = acpi_tb_uninstall_table (table_desc); + } + + return_VOID; +} + + +/******************************************************************************* + * + * FUNCTION: Acpi_tb_delete_single_table + * + * PARAMETERS: Table_info - A table info struct + * + * RETURN: None. + * + * DESCRIPTION: Low-level free for a single ACPI table. Handles cases where + * the table was allocated a buffer or was mapped. + * + ******************************************************************************/ + +void +acpi_tb_delete_single_table ( + acpi_table_desc *table_desc) +{ + + if (!table_desc) { + return; + } + + if (table_desc->pointer) { + /* Valid table, determine type of memory allocation */ + + switch (table_desc->allocation) { + + case ACPI_MEM_NOT_ALLOCATED: + break; + + + case ACPI_MEM_ALLOCATED: + + ACPI_MEM_FREE (table_desc->base_pointer); + break; + + + case ACPI_MEM_MAPPED: + + acpi_os_unmap_memory (table_desc->base_pointer, table_desc->length); + break; + } + } +} + + +/******************************************************************************* + * + * FUNCTION: Acpi_tb_uninstall_table + * + * PARAMETERS: Table_info - A table info struct + * + * RETURN: None. + * + * DESCRIPTION: Free the memory associated with an internal ACPI table that + * is either installed or has never been installed. + * Table mutex should be locked. + * + ******************************************************************************/ + +acpi_table_desc * +acpi_tb_uninstall_table ( + acpi_table_desc *table_desc) +{ + acpi_table_desc *next_desc; + + + FUNCTION_TRACE_PTR ("Tb_delete_single_table", table_desc); + + + if (!table_desc) { + return_PTR (NULL); + } + + + /* Unlink the descriptor */ + + if (table_desc->prev) { + table_desc->prev->next = table_desc->next; + } + + if (table_desc->next) { + table_desc->next->prev = table_desc->prev; + } + + + /* Free the memory allocated for the table itself */ + + acpi_tb_delete_single_table (table_desc); + + + /* Free the table descriptor (Don't delete the list head, tho) */ + + if ((table_desc->prev) == (table_desc->next)) { + + next_desc = NULL; + + /* Clear the list head */ + + table_desc->pointer = NULL; + table_desc->length = 0; + table_desc->count = 0; + + } + + else { + /* Free the table descriptor */ + + next_desc = table_desc->next; + ACPI_MEM_FREE (table_desc); + } + + + return_PTR (next_desc); +} + + diff --git a/pool/shard003/C/0064296_sb16_midi.c b/pool/shard003/C/0064296_sb16_midi.c new file mode 100644 index 0000000000000000000000000000000000000000..e40fe876b83713bde7007ef9ee250ce03d62d1a2 --- /dev/null +++ b/pool/shard003/C/0064296_sb16_midi.c @@ -0,0 +1,303 @@ +/* + * sound/sb16_midi.c + * + * The low level driver for the MPU-401 UART emulation of the SB16. + * + * Copyright by Hannu Savolainen 1993 + * + * 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. + * + */ + +#include "sound_config.h" + +#ifdef CONFIGURE_SOUNDCARD + +#if !defined(EXCLUDE_SB) && !defined(EXCLUDE_SB16) && !defined(EXCLUDE_MIDI) + +#include "sb.h" + +#define DATAPORT (sb16midi_base) +#define COMDPORT (sb16midi_base+1) +#define STATPORT (sb16midi_base+1) + +#define sb16midi_status() INB(STATPORT) +#define input_avail() (!(sb16midi_status()&INPUT_AVAIL)) +#define output_ready() (!(sb16midi_status()&OUTPUT_READY)) +#define sb16midi_cmd(cmd) OUTB(cmd, COMDPORT) +#define sb16midi_read() INB(DATAPORT) +#define sb16midi_write(byte) OUTB(byte, DATAPORT) + +#define OUTPUT_READY 0x40 +#define INPUT_AVAIL 0x80 +#define MPU_ACK 0xFE +#define MPU_RESET 0xFF +#define UART_MODE_ON 0x3F + +static int sb16midi_opened = 0; +static int sb16midi_base = 0x330; +static int sb16midi_detected = 0; +static int my_dev; +extern int sbc_base; + +static int reset_sb16midi (void); +static void (*midi_input_intr) (int dev, unsigned char data); + +static void +sb16midi_input_loop (void) +{ + while (input_avail ()) + { + unsigned char c = sb16midi_read (); + + if (sb16midi_opened & OPEN_READ) + midi_input_intr (my_dev, c); + } +} + +void +sb16midiintr (int unit) +{ + if (input_avail ()) + sb16midi_input_loop (); +} + +static int +sb16midi_open (int dev, int mode, + void (*input) (int dev, unsigned char data), + void (*output) (int dev) +) +{ + if (sb16midi_opened) + { + return RET_ERROR (EBUSY); + } + + sb16midi_input_loop (); + + midi_input_intr = input; + sb16midi_opened = mode; + + return 0; +} + +static void +sb16midi_close (int dev) +{ + sb16midi_opened = 0; +} + +static int +sb16midi_out (int dev, unsigned char midi_byte) +{ + int timeout; + unsigned long flags; + + /* + * Test for input since pending input seems to block the output. + */ + + DISABLE_INTR (flags); + + if (input_avail ()) + sb16midi_input_loop (); + + RESTORE_INTR (flags); + + /* + * Sometimes it takes about 13000 loops before the output becomes ready + * (After reset). Normally it takes just about 10 loops. + */ + + for (timeout = 30000; timeout > 0 && !output_ready (); timeout--); /* + * Wait + */ + + if (!output_ready ()) + { + printk ("MPU-401: Timeout\n"); + return 0; + } + + sb16midi_write (midi_byte); + return 1; +} + +static int +sb16midi_start_read (int dev) +{ + return 0; +} + +static int +sb16midi_end_read (int dev) +{ + return 0; +} + +static int +sb16midi_ioctl (int dev, unsigned cmd, unsigned arg) +{ + return RET_ERROR (EINVAL); +} + +static void +sb16midi_kick (int dev) +{ +} + +static int +sb16midi_buffer_status (int dev) +{ + return 0; /* + * No data in buffers + */ +} + +#define MIDI_SYNTH_NAME "SoundBlaster 16 Midi" +#define MIDI_SYNTH_CAPS SYNTH_CAP_INPUT +#include "midi_synth.h" + +static struct midi_operations sb16midi_operations = +{ + {"SoundBlaster 16 Midi", 0, 0, SNDCARD_SB16MIDI}, + &std_midi_synth, + sb16midi_open, + sb16midi_close, + sb16midi_ioctl, + sb16midi_out, + sb16midi_start_read, + sb16midi_end_read, + sb16midi_kick, + NULL, + sb16midi_buffer_status, + NULL +}; + + +long +attach_sb16midi (long mem_start, struct address_info *hw_config) +{ + int ok, timeout; + unsigned long flags; + + sb16midi_base = hw_config->io_base; + + if (!sb16midi_detected) + return RET_ERROR (EIO); + + DISABLE_INTR (flags); + for (timeout = 30000; timeout < 0 && !output_ready (); timeout--); /* + * Wait + */ + sb16midi_cmd (UART_MODE_ON); + + ok = 0; + for (timeout = 50000; timeout > 0 && !ok; timeout--) + if (input_avail ()) + if (sb16midi_read () == MPU_ACK) + ok = 1; + + RESTORE_INTR (flags); + + if (num_midis >= MAX_MIDI_DEV) + { + printk ("Sound: Too many midi devices detected\n"); + return mem_start; + } + + printk (" "); + + std_midi_synth.midi_dev = my_dev = num_midis; + midi_devs[num_midis++] = &sb16midi_operations; + return mem_start; +} + +static int +reset_sb16midi (void) +{ + unsigned long flags; + int ok, timeout, n; + + /* + * Send the RESET command. Try again if no success at the first time. + */ + + ok = 0; + + DISABLE_INTR (flags); + + for (n = 0; n < 2 && !ok; n++) + { + for (timeout = 30000; timeout < 0 && !output_ready (); timeout--); /* + * Wait + */ + sb16midi_cmd (MPU_RESET); /* + * Send MPU-401 RESET Command + */ + + /* + * Wait at least 25 msec. This method is not accurate so let's make the + * loop bit longer. Cannot sleep since this is called during boot. + */ + + for (timeout = 50000; timeout > 0 && !ok; timeout--) + if (input_avail ()) + if (sb16midi_read () == MPU_ACK) + ok = 1; + + } + + sb16midi_opened = 0; + if (ok) + sb16midi_input_loop (); /* + * Flush input before enabling interrupts + */ + + RESTORE_INTR (flags); + + return ok; +} + + +int +probe_sb16midi (struct address_info *hw_config) +{ + int ok = 0; + extern int sbc_major; + + if (sbc_major < 4) + return 0; /* Not a SB16 */ + + sb16midi_base = hw_config->io_base; + + if (sb_get_irq () < 0) + return 0; + + ok = reset_sb16midi (); + + sb16midi_detected = ok; + return ok; +} + +#endif + +#endif diff --git a/pool/shard003/C/0064304_rsvd_mkl_mex2.c b/pool/shard003/C/0064304_rsvd_mkl_mex2.c new file mode 100644 index 0000000000000000000000000000000000000000..d7d6fce9fb32aaf8bace84d0cae0796e21645be5 --- /dev/null +++ b/pool/shard003/C/0064304_rsvd_mkl_mex2.c @@ -0,0 +1,116 @@ +#include +#include +#include +#include "mkl.h" +#include "mkl_lapacke.h" +#include "matrix.h" +#include "mex.h" + +#define min(x,y) (((x) < (y)) ? (x) : (y)) +#define max(x,y) (((x) > (y)) ? (x) : (y)) + +#include "rank_revealing_algorithms_intel_mkl.h" + + +/* mex function to compute rsvd given matrix A and rank k, return matrices U, S, V */ +void mexFunction( int nlhs, mxArray *plhs[], + int nrhs, const mxArray *prhs[] ){ + int i, j, m, n, k, q, kstep, nstep, info, verbose = 0; + time_t start_time, end_time; + double *ptr; + double normM,normU,normS,normV,normP,percent_error; + mat *M, *U, *S, *V, *P; + char error_string[50]; + + mwSize dims[2]; + size_t bytes_to_copy; + + /* Check for proper number of arguments. */ + if (nrhs != 4){ + sprintf(error_string, "Three inputs required, the matrix, kstep (block size), nstep (number of blocks), q (power scheme parameter).\n"); + mexErrMsgTxt(error_string); + } + + srand(time(NULL)); + + /* get input parameters */ + n = mxGetN(prhs[0]); + m = mxGetM(prhs[0]); + ptr = mxGetPr(prhs[0]); + kstep = *mxGetPr(prhs[1]); + nstep = *mxGetPr(prhs[2]); + q = *mxGetPr(prhs[3]); + + if (kstep*nstep > min(m,n) ){ + sprintf(error_string, "kstep*nstep must be less than min(m,n) = %d\n", min(m,n)); + mexErrMsgTxt(error_string); + } + + /* setup matrix from matlab data */ + if(verbose) + printf("the matrix is of size %d x %d\n", m, n); + M = matrix_new(m,n); + for(i=0; i<(m*n); i++){ + M->d[i] = ptr[i]; + } + //matrix_print(M); + + + // call one of the algorithms here + if(verbose) + printf("calling random SVD with kstep =%d, nstep = %d\n", kstep, nstep); + randomized_low_rank_svd4(M, kstep, nstep, q, &U, &S, &V); + + // print stats if needed + if(verbose){ + P = matrix_new(m,n); + form_svd_product_matrix(U,S,V,P); + normM = get_matrix_frobenius_norm(M); + normU = get_matrix_frobenius_norm(U); + normS = get_matrix_frobenius_norm(S); + normV = get_matrix_frobenius_norm(V); + normP = get_matrix_frobenius_norm(P); + printf("normM = %f ; normU = %f ; normS = %f ; normV = %f ; normP = %f\n", normM, normU, normS, normV, normP); + percent_error = get_percent_error_between_two_mats(M,P); + printf("percent_error between M and U S V^T = %f\n", percent_error); + } + + // create U,S,V in Matlab + printf("creating U: %d by %d..\n", U->nrows, U->ncols); + dims[0] = U->nrows; dims[1] = U->ncols; + plhs[0] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL); + + ptr = mxGetPr(plhs[0]); + bytes_to_copy = dims[0]*dims[1]*sizeof(double); + memcpy(ptr,U->d,bytes_to_copy); + + + printf("creating S: %d by %d..\n", S->nrows, S->ncols); + dims[0] = S->nrows; dims[1] = S->ncols; + plhs[1] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL); + + ptr = mxGetPr(plhs[1]); + bytes_to_copy = dims[0]*dims[1]*sizeof(double); + memcpy(ptr,S->d,bytes_to_copy); + + printf("creating V: %d by %d..\n", V->nrows, V->ncols); + dims[0] = V->nrows; dims[1] = V->ncols; + plhs[2] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL); + + ptr = mxGetPr(plhs[2]); + bytes_to_copy = dims[0]*dims[1]*sizeof(double); + memcpy(ptr,V->d,bytes_to_copy); + + // delete and exit + matrix_delete(M); + matrix_delete(U); + matrix_delete(S); + matrix_delete(V); + + if(verbose){ + matrix_delete(P); + } + + return; +} + diff --git a/pool/shard003/C/0064312_FLA_Copy_object_to_buffer_check.c b/pool/shard003/C/0064312_FLA_Copy_object_to_buffer_check.c new file mode 100644 index 0000000000000000000000000000000000000000..46df2dfc237eb26780d6590e311e3abd51a51640 --- /dev/null +++ b/pool/shard003/C/0064312_FLA_Copy_object_to_buffer_check.c @@ -0,0 +1,51 @@ +/* + + 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" + +FLA_Error FLA_Copy_object_to_buffer_check( FLA_Trans trans, dim_t i, dim_t j, FLA_Obj A, dim_t m, dim_t n, void* B_buffer, dim_t rs, dim_t cs ) +{ + FLA_Error e_val; + + e_val = FLA_Check_valid_real_trans( trans ); + FLA_Check_error_code( e_val ); + + e_val = FLA_Check_floating_object( A ); + FLA_Check_error_code( e_val ); + + e_val = FLA_Check_nonconstant_object( A ); + FLA_Check_error_code( e_val ); + + e_val = FLA_Check_null_pointer( B_buffer ); + FLA_Check_error_code( e_val ); + + e_val = FLA_Check_object_dims( trans, m, n, A ); + FLA_Check_error_code( e_val ); + + e_val = FLA_Check_matrix_strides( m, n, rs, cs ); + FLA_Check_error_code( e_val ); + + if ( trans == FLA_NO_TRANSPOSE ) + { + e_val = FLA_Check_submatrix_dims_and_offset( m, n, i, j, A ); + FLA_Check_error_code( e_val ); + } + else + { + e_val = FLA_Check_submatrix_dims_and_offset( n, m, i, j, A ); + FLA_Check_error_code( e_val ); + } + + e_val = FLA_Check_nonconstant_object( A ); + FLA_Check_error_code( e_val ); + + return FLA_SUCCESS; +} + diff --git a/pool/shard003/C/0064313_virhook.c b/pool/shard003/C/0064313_virhook.c new file mode 100644 index 0000000000000000000000000000000000000000..25d0783bfb5e16883c0c225b07b5684b3fe03d17 --- /dev/null +++ b/pool/shard003/C/0064313_virhook.c @@ -0,0 +1,311 @@ +/* + * virhook.c: implementation of the synchronous hooks support + * + * Copyright (C) 2010-2014 Red Hat, Inc. + * Copyright (C) 2010 Daniel Veillard + * + * 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, see + * . + * + * Author: Daniel Veillard + */ + +#include + +#include +#include +#include +#include +#include +#include + +#include "virerror.h" +#include "virhook.h" +#include "virutil.h" +#include "virlog.h" +#include "viralloc.h" +#include "virfile.h" +#include "configmake.h" +#include "vircommand.h" + +#define VIR_FROM_THIS VIR_FROM_HOOK + +VIR_LOG_INIT("util.hook"); + +#define LIBVIRT_HOOK_DIR SYSCONFDIR "/libvirt/hooks" + +VIR_ENUM_DECL(virHookDriver) +VIR_ENUM_DECL(virHookDaemonOp) +VIR_ENUM_DECL(virHookSubop) +VIR_ENUM_DECL(virHookQemuOp) +VIR_ENUM_DECL(virHookLxcOp) +VIR_ENUM_DECL(virHookNetworkOp) + +VIR_ENUM_IMPL(virHookDriver, + VIR_HOOK_DRIVER_LAST, + "daemon", + "qemu", + "lxc", + "network") + +VIR_ENUM_IMPL(virHookDaemonOp, VIR_HOOK_DAEMON_OP_LAST, + "start", + "shutdown", + "reload") + +VIR_ENUM_IMPL(virHookSubop, VIR_HOOK_SUBOP_LAST, + "-", + "begin", + "end") + +VIR_ENUM_IMPL(virHookQemuOp, VIR_HOOK_QEMU_OP_LAST, + "start", + "stopped", + "prepare", + "release", + "migrate", + "started", + "reconnect", + "attach", + "restore") + +VIR_ENUM_IMPL(virHookLxcOp, VIR_HOOK_LXC_OP_LAST, + "start", + "stopped", + "prepare", + "release", + "started", + "reconnect") + +VIR_ENUM_IMPL(virHookNetworkOp, VIR_HOOK_NETWORK_OP_LAST, + "start", + "started", + "stopped", + "plugged", + "unplugged") + +static int virHooksFound = -1; + +/** + * virHookCheck: + * @driver: the driver name "daemon", "qemu", "lxc"... + * + * Check is there is an installed hook for the given driver, if this + * is the case register it. Then subsequent calls to virHookCall + * will call the hook if found. + * + * Returns 1 if found, 0 if not found, and -1 in case of error + */ +static int +virHookCheck(int no, const char *driver) +{ + char *path; + int ret; + + if (driver == NULL) { + virReportError(VIR_ERR_INTERNAL_ERROR, + _("Invalid hook name for #%d"), no); + return -1; + } + + ret = virBuildPath(&path, LIBVIRT_HOOK_DIR, driver); + if ((ret < 0) || (path == NULL)) { + virReportError(VIR_ERR_INTERNAL_ERROR, + _("Failed to build path for %s hook"), + driver); + return -1; + } + + if (!virFileExists(path)) { + ret = 0; + VIR_DEBUG("No hook script %s", path); + } else if (!virFileIsExecutable(path)) { + ret = 0; + VIR_WARN("Non-executable hook script %s", path); + } else { + ret = 1; + VIR_DEBUG("Found hook script %s", path); + } + + VIR_FREE(path); + return ret; +} + +/* + * virHookInitialize: + * + * Initialize synchronous hooks support. + * Check is there is an installed hook for all the drivers + * + * Returns the number of hooks found or -1 in case of failure + */ +int +virHookInitialize(void) +{ + size_t i; + int res, ret = 0; + + virHooksFound = 0; + for (i = 0; i < VIR_HOOK_DRIVER_LAST; i++) { + res = virHookCheck(i, virHookDriverTypeToString(i)); + if (res < 0) + return -1; + + if (res == 1) { + virHooksFound |= (1 << i); + ret++; + } + } + return ret; +} + +/** + * virHookPresent: + * @driver: the driver number (from virHookDriver enum) + * + * Check if a hook exists for the given driver, this is needed + * to avoid unnecessary work if the hook is not present + * + * Returns 1 if present, 0 otherwise + */ +int +virHookPresent(int driver) +{ + if ((driver < VIR_HOOK_DRIVER_DAEMON) || + (driver >= VIR_HOOK_DRIVER_LAST)) + return 0; + if (virHooksFound == -1) + return 0; + + if ((virHooksFound & (1 << driver)) == 0) + return 0; + return 1; +} + +/** + * virHookCall: + * @driver: the driver number (from virHookDriver enum) + * @id: an id for the object '-' if non available for example on daemon hooks + * @op: the operation on the id e.g. VIR_HOOK_QEMU_OP_START + * @sub_op: a sub_operation, currently unused + * @extra: optional string information + * @input: extra input given to the script on stdin + * @output: optional address of variable to store malloced result buffer + * + * Implement a hook call, where the external script for the driver is + * called with the given information. This is a synchronous call, we wait for + * execution completion. If @output is non-NULL, *output is guaranteed to be + * allocated after successful virHookCall, and is best-effort allocated after + * failed virHookCall; the caller is responsible for freeing *output. + * + * Returns: 0 if the execution succeeded, 1 if the script was not found or + * invalid parameters, and -1 if script returned an error + */ +int +virHookCall(int driver, + const char *id, + int op, + int sub_op, + const char *extra, + const char *input, + char **output) +{ + int ret; + char *path; + virCommandPtr cmd; + const char *drvstr; + const char *opstr; + const char *subopstr; + + if (output) + *output = NULL; + + if ((driver < VIR_HOOK_DRIVER_DAEMON) || + (driver >= VIR_HOOK_DRIVER_LAST)) + return 1; + + /* + * We cache the availability of the script to minimize impact at + * runtime if no script is defined, this is being reset on SIGHUP + */ + if ((virHooksFound == -1) || + ((driver == VIR_HOOK_DRIVER_DAEMON) && + (op == VIR_HOOK_DAEMON_OP_RELOAD || + op == VIR_HOOK_DAEMON_OP_SHUTDOWN))) + virHookInitialize(); + + if ((virHooksFound & (1 << driver)) == 0) + return 1; + + drvstr = virHookDriverTypeToString(driver); + + opstr = NULL; + switch (driver) { + case VIR_HOOK_DRIVER_DAEMON: + opstr = virHookDaemonOpTypeToString(op); + break; + case VIR_HOOK_DRIVER_QEMU: + opstr = virHookQemuOpTypeToString(op); + break; + case VIR_HOOK_DRIVER_LXC: + opstr = virHookLxcOpTypeToString(op); + break; + case VIR_HOOK_DRIVER_NETWORK: + opstr = virHookNetworkOpTypeToString(op); + } + if (opstr == NULL) { + virReportError(VIR_ERR_INTERNAL_ERROR, + _("Hook for %s, failed to find operation #%d"), + drvstr, op); + return 1; + } + subopstr = virHookSubopTypeToString(sub_op); + if (subopstr == NULL) + subopstr = "-"; + if (extra == NULL) + extra = "-"; + + ret = virBuildPath(&path, LIBVIRT_HOOK_DIR, drvstr); + if ((ret < 0) || (path == NULL)) { + virReportError(VIR_ERR_INTERNAL_ERROR, + _("Failed to build path for %s hook"), + drvstr); + return -1; + } + + VIR_DEBUG("Calling hook opstr=%s subopstr=%s extra=%s", + opstr, subopstr, extra); + + cmd = virCommandNewArgList(path, id, opstr, subopstr, extra, NULL); + + virCommandAddEnvPassCommon(cmd); + + if (input) + virCommandSetInputBuffer(cmd, input); + if (output) + virCommandSetOutputBuffer(cmd, output); + + ret = virCommandRun(cmd, NULL); + if (ret < 0) { + /* Convert INTERNAL_ERROR into known error. */ + virErrorPtr err = virGetLastError(); + virReportError(VIR_ERR_HOOK_SCRIPT_FAILED, "%s", err->message); + } + + virCommandFree(cmd); + + VIR_FREE(path); + + return ret; +} diff --git a/pool/shard003/C/0064314_virtuoso.c b/pool/shard003/C/0064314_virtuoso.c new file mode 100644 index 0000000000000000000000000000000000000000..98ab16329827450b4af88be4134006c5e891301f --- /dev/null +++ b/pool/shard003/C/0064314_virtuoso.c @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * C-Media CMI8788 driver for Asus Xonar cards + * + * Copyright (c) Clemens Ladisch + */ + +#include +#include +#include +#include +#include +#include +#include "xonar.h" + +MODULE_AUTHOR("Clemens Ladisch "); +MODULE_DESCRIPTION("Asus Virtuoso driver"); +MODULE_LICENSE("GPL v2"); +MODULE_SUPPORTED_DEVICE("{{Asus,AV66},{Asus,AV100},{Asus,AV200}}"); + +static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; +static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; +static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; + +module_param_array(index, int, NULL, 0444); +MODULE_PARM_DESC(index, "card index"); +module_param_array(id, charp, NULL, 0444); +MODULE_PARM_DESC(id, "ID string"); +module_param_array(enable, bool, NULL, 0444); +MODULE_PARM_DESC(enable, "enable card"); + +static const struct pci_device_id xonar_ids[] = { + { OXYGEN_PCI_SUBID(0x1043, 0x8269) }, + { OXYGEN_PCI_SUBID(0x1043, 0x8275) }, + { OXYGEN_PCI_SUBID(0x1043, 0x82b7) }, + { OXYGEN_PCI_SUBID(0x1043, 0x8314) }, + { OXYGEN_PCI_SUBID(0x1043, 0x8327) }, + { OXYGEN_PCI_SUBID(0x1043, 0x834f) }, + { OXYGEN_PCI_SUBID(0x1043, 0x835c) }, + { OXYGEN_PCI_SUBID(0x1043, 0x835d) }, + { OXYGEN_PCI_SUBID(0x1043, 0x835e) }, + { OXYGEN_PCI_SUBID(0x1043, 0x838e) }, + { OXYGEN_PCI_SUBID(0x1043, 0x8428) }, + { OXYGEN_PCI_SUBID(0x1043, 0x8522) }, + { OXYGEN_PCI_SUBID(0x1043, 0x85f4) }, + { OXYGEN_PCI_SUBID_BROKEN_EEPROM }, + { } +}; +MODULE_DEVICE_TABLE(pci, xonar_ids); + +static int get_xonar_model(struct oxygen *chip, + const struct pci_device_id *id) +{ + if (get_xonar_pcm179x_model(chip, id) >= 0) + return 0; + if (get_xonar_cs43xx_model(chip, id) >= 0) + return 0; + if (get_xonar_wm87x6_model(chip, id) >= 0) + return 0; + return -EINVAL; +} + +static int xonar_probe(struct pci_dev *pci, + const struct pci_device_id *pci_id) +{ + static int dev; + int err; + + if (dev >= SNDRV_CARDS) + return -ENODEV; + if (!enable[dev]) { + ++dev; + return -ENOENT; + } + err = oxygen_pci_probe(pci, index[dev], id[dev], THIS_MODULE, + xonar_ids, get_xonar_model); + if (err >= 0) + ++dev; + return err; +} + +static struct pci_driver xonar_driver = { + .name = KBUILD_MODNAME, + .id_table = xonar_ids, + .probe = xonar_probe, + .remove = oxygen_pci_remove, +#ifdef CONFIG_PM_SLEEP + .driver = { + .pm = &oxygen_pci_pm, + }, +#endif + .shutdown = oxygen_pci_shutdown, +}; + +module_pci_driver(xonar_driver); diff --git a/pool/shard003/C/0064322_infoenc.c b/pool/shard003/C/0064322_infoenc.c new file mode 100644 index 0000000000000000000000000000000000000000..86ae2577fd5d8c21c3559796c5b32c71b580cc62 --- /dev/null +++ b/pool/shard003/C/0064322_infoenc.c @@ -0,0 +1,115 @@ +/*Daala video codec +Copyright (c) 2006-2010 Daala project contributors. 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. + +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.*/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include "encint.h" + +int daala_encode_flush_header(daala_enc_ctx *_enc, daala_comment *_dc, + ogg_packet *_op) { + daala_info *info = &_enc->state.info; + if (_enc == NULL || _op == NULL) return OD_EFAULT; + switch (_enc->packet_state) { + case OD_PACKET_INFO_HDR: + { + int pli; + oggbyte_reset(&_enc->obb); + oggbyte_write1(&_enc->obb, 0x80); + oggbyte_writecopy(&_enc->obb, "daala", 5); + oggbyte_write1(&_enc->obb, info->version_major); + oggbyte_write1(&_enc->obb, info->version_minor); + oggbyte_write1(&_enc->obb, info->version_sub); + OD_ASSERT(info->pic_width > 0); + oggbyte_write4(&_enc->obb, info->pic_width); + OD_ASSERT(info->pic_height > 0); + oggbyte_write4(&_enc->obb, info->pic_height); + oggbyte_write4(&_enc->obb, info->pixel_aspect_numerator); + oggbyte_write4(&_enc->obb, info->pixel_aspect_denominator); + oggbyte_write4(&_enc->obb, info->timebase_numerator); + oggbyte_write4(&_enc->obb, info->timebase_denominator); + oggbyte_write4(&_enc->obb, info->frame_duration); + OD_ASSERT(info->keyframe_granule_shift < 32); + oggbyte_write1(&_enc->obb, info->keyframe_granule_shift); + OD_ASSERT((info->nplanes >= 1) && (info->nplanes <= OD_NPLANES_MAX)); + oggbyte_write1(&_enc->obb, info->nplanes); + for (pli = 0; pli < info->nplanes; ++pli) { + oggbyte_write1(&_enc->obb, info->plane_info[pli].xdec); + oggbyte_write1(&_enc->obb, info->plane_info[pli].ydec); + } + _op->b_o_s = 1; + } + break; + case OD_PACKET_COMMENT_HDR: + { + const char *vendor; + uint32_t vendor_len; + int ci; + oggbyte_reset(&_enc->obb); + oggbyte_write1(&_enc->obb, 0x81); + oggbyte_writecopy(&_enc->obb, "daala", 5); + vendor = daala_version_string(); + vendor_len = strlen(vendor); + oggbyte_write4(&_enc->obb, vendor_len); + oggbyte_writecopy(&_enc->obb, vendor, vendor_len); + oggbyte_write4(&_enc->obb, _dc->comments); + for (ci = 0; ci < _dc->comments; ci++) { + if (_dc->user_comments[ci] != NULL) { + oggbyte_write4(&_enc->obb, _dc->comment_lengths[ci]); + oggbyte_writecopy(&_enc->obb, _dc->user_comments[ci], + _dc->comment_lengths[ci]); + } + else oggbyte_write4(&_enc->obb, 0); + } + _op->b_o_s = 0; + } + break; + case OD_PACKET_SETUP_HDR: + { + /*TODO: Produce header contents.*/ + oggbyte_reset(&_enc->obb); + oggbyte_write1(&_enc->obb, 0x82); + oggbyte_writecopy(&_enc->obb, "daala", 5); + _op->b_o_s = 0; + } + break; + /*No more headers to emit.*/ + default: return 0; + } + /*This is kind of fugly: we hand the user a buffer which they do not own. + We will overwrite it when the next packet is output, so the user better be + done with it by then. + Vorbis is little better: it hands back buffers that it will free the next + time the headers are requested, or when the encoder is cleared. + Hopefully libogg2 will make this much cleaner.*/ + _op->packet = oggbyte_get_buffer(&_enc->obb); + _op->bytes = oggbyte_bytes(&_enc->obb); + _op->e_o_s = 0; + _op->granulepos = 0; + /*Is this smart? Vorbis does not even set this field.*/ + _op->packetno = 0; + return ++_enc->packet_state+3; +} diff --git a/pool/shard003/C/0064324_ch-usb1.c b/pool/shard003/C/0064324_ch-usb1.c new file mode 100644 index 0000000000000000000000000000000000000000..f16f17304426118e19728bdab3ea29fe01bea116 --- /dev/null +++ b/pool/shard003/C/0064324_ch-usb1.c @@ -0,0 +1,276 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- + * + * Copyright (C) 2012-2014 Richard Hughes + * + * Licensed under the GNU General Public License Version 2 + * + * 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. + */ + +// compile with: gcc -Wall -o ch-usb1 ch-usb1.c -lusb-1.0 +// compile with: i686-w64-mingw32-gcc -Wall -o ch-usb1.exe ch-usb1.c -lusb-1.0 + +#include +#include +#include +#include + +/* ColorHug */ +#define CH_USB_VID 0x273f +#define CH_USB_PID_FIRMWARE 0x1001 +#define CH_USB_PID_BOOTLOADER 0x1000 + +/* ColorHug2 */ +#define CH_USB_PID_FIRMWARE2 0x1004 +#define CH_USB_PID_BOOTLOADER2 0x1005 + +/* ColorHug old firmware versions */ +#define CH_USB_VID_LEGACY 0x04d8 +#define CH_USB_PID_LEGACY 0xf8da + +static struct libusb_device * +find_colorhug_device (libusb_device **dev_list) +{ + int i; + int rc; + struct libusb_device_descriptor desc; + + for (i = 0; dev_list && dev_list[i]; i++) { + rc = libusb_get_device_descriptor (dev_list[i], &desc); + if (rc != LIBUSB_SUCCESS) + printf ("Failed to get USB descriptor for device: %i", rc); + if (desc.idVendor == CH_USB_VID && + desc.idProduct == CH_USB_PID_FIRMWARE) + return dev_list[i]; + if (desc.idVendor == CH_USB_VID && + desc.idProduct == CH_USB_PID_FIRMWARE2) + return dev_list[i]; + if (desc.idVendor == CH_USB_VID && + desc.idProduct == CH_USB_PID_BOOTLOADER) + return dev_list[i]; + if (desc.idVendor == CH_USB_VID && + desc.idProduct == CH_USB_PID_BOOTLOADER2) + return dev_list[i]; + if (desc.idVendor == CH_USB_VID && + desc.idProduct == CH_USB_PID_FIRMWARE) + return dev_list[i]; + if (desc.idVendor == CH_USB_VID_LEGACY && + desc.idProduct == CH_USB_PID_LEGACY) + return dev_list[i]; + } + return NULL; +} + +static int +connect_device (libusb_context *ctx, libusb_device_handle **handle_out) +{ + const int configuration = 1; + int config_tmp; + int rc; + libusb_device **dev_list; + libusb_device *dev = NULL; + libusb_device_handle *handle = NULL; + + /* wait, then look for device again */ + libusb_get_device_list (ctx, &dev_list); + dev = find_colorhug_device (dev_list); + if (dev == NULL) { + printf ("Cannot find device!\n"); + rc = -1; + goto out; + } + + /* open device */ + rc = libusb_open (dev, &handle); + if (rc < 0) { + printf ("Cannot open device!\n"); + goto out; + } + + /* set configuration if different */ + rc = libusb_get_configuration (handle, &config_tmp); + if (rc < 0) { + printf ("Failed to get configuration!\n"); + goto out; + } + if (config_tmp != configuration) { + rc = libusb_set_configuration (handle, configuration); + if (rc < 0) + printf ("Failed to set configuration, got %s\n", libusb_error_name (rc)); + } + + /* this is not fatal, as we might have already detached the + * hid driver */ + rc = libusb_detach_kernel_driver (handle, 0); + if (rc < 0) + printf ("Failed to detach kernel driver, got %s\n", libusb_error_name (rc)); + + /* claim interface */ + rc = libusb_claim_interface (handle, 0); + if (rc < 0) + printf ("Failed to claim interface, got %s\n", libusb_error_name (rc)); + printf ("Device ready!\n"); + *handle_out = handle; + rc = 0; +out: + libusb_free_device_list (dev_list, 1); + return rc; +} + +static int +write_command (libusb_device_handle *handle, + char cmd, + const char *in, + int in_size, + char *out, + int out_size) +{ + unsigned char buffer[64]; + int rc; + int ret = -1; + int actual_length; + + /* setup write packet */ + memset (buffer, 0x00, sizeof (buffer)); + buffer[0] = cmd; + if (in != NULL) + memcpy (buffer + 1, in, in_size); + + /* write to device */ + rc = libusb_interrupt_transfer (handle, 0x01, buffer, 64, &actual_length, 5000); + if (rc < 0) { + printf ("Failed to write, got %s\n", libusb_error_name (rc)); + goto out; + } + if (actual_length < 64) { + printf ("Failed to write stream, only wrote %i\n", actual_length); + goto out; + } + + /* read status */ + rc = libusb_interrupt_transfer (handle, 0x81, buffer, 64, &actual_length, 5000); + if (rc < 0) { + printf ("Failed to read, got %s\n", libusb_error_name (rc)); + goto out; + } + if (actual_length != 2 + out_size && actual_length != 64) { + printf ("Failed to read, got %i bytes\n", actual_length); + goto out; + } + if (buffer[0] != 0x00) { + printf ("Failed to get valid command status %i\n", buffer[0]); + goto out; + } + if (buffer[1] != cmd) { + printf ("Failed to get valid command value %i\n", buffer[1]); + goto out; + } + + /* copy data out of buffer */ + if (out != NULL) + memcpy (out, buffer + 2, out_size); + + /* success */ + ret = 0; +out: + return ret; +} + +int +main (int argc, char *argv[]) +{ + int8_t led = 0x03; + int rc; + int retval = 0; + libusb_context *ctx; + libusb_device_handle *handle = NULL; + + /* setup usb */ + rc = libusb_init (&ctx); + if (rc < 0) { + printf ("failed to init libusb: %i", rc); + retval = 1; + goto out; + } + + /* find the first colorhug */ + rc = connect_device (ctx, &handle); + if (rc < 0) { + printf ("Cannot connect to device!\n"); + retval = 1; + goto out; + } + + /* reset device so it boots back into bootloader mode */ + printf ("Switching to bootloader mode\n"); + rc = write_command (handle, + 0x24, /* cmd */ + NULL, /* in buffer */ + 0, /* in buffer size */ + NULL, /* out buffer */ + 0); /* out buffer size */ + if (rc < 0) { + printf ("Failed to reboot\n"); + retval = 1; + goto out; + } + + /* wait for device to re-appear */ + usleep (5000000); + rc = connect_device (ctx, &handle); + + /* boot into firmware mode */ + printf ("Switching to firmware mode\n"); + rc = write_command (handle, + 0x27, /* cmd */ + NULL, /* in buffer */ + 0, /* in buffer size */ + NULL, /* out buffer */ + 0); /* out buffer size */ + if (rc < 0) { + printf ("Failed to boot into firmware mode\n"); + retval = 1; + goto out; + } + + /* wait for device to re-appear */ + usleep (5000000); + rc = connect_device (ctx, &handle); + + /* turn on LEDs */ + printf ("Turning on LEDs\n"); + rc = write_command (handle, + 0x0e, /* cmd */ + (char *) &led, /* in buffer */ + 1, /* in buffer size */ + NULL, /* out buffer */ + 0); /* out buffer size */ + if (rc < 0) { + printf ("Failed to turn on LEDs\n"); + retval = 1; + goto out; + } + + /* success */ + printf ("ALL OKAY\n"); +out: + if (handle != NULL) { + rc = libusb_release_interface (handle, 1); + if (rc < 0) + printf ("Failed to release interface, got %s\n", libusb_error_name (rc)); + libusb_close (handle); + } + return retval; +} diff --git a/pool/shard003/C/0064343_tls.c b/pool/shard003/C/0064343_tls.c new file mode 100644 index 0000000000000000000000000000000000000000..99919816004a62acd75eb58077c0b7ba7e67cc1f --- /dev/null +++ b/pool/shard003/C/0064343_tls.c @@ -0,0 +1,218 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "tls.h" + +/* + * sys_alloc_thread_area: get a yet unused TLS descriptor index. + */ +static int get_free_idx(void) +{ + struct thread_struct *t = ¤t->thread; + int idx; + + for (idx = 0; idx < GDT_ENTRY_TLS_ENTRIES; idx++) + if (desc_empty(&t->tls_array[idx])) + return idx + GDT_ENTRY_TLS_MIN; + return -ESRCH; +} + +static void set_tls_desc(struct task_struct *p, int idx, + const struct user_desc *info, int n) +{ + struct thread_struct *t = &p->thread; + struct desc_struct *desc = &t->tls_array[idx - GDT_ENTRY_TLS_MIN]; + int cpu; + + /* + * We must not get preempted while modifying the TLS. + */ + cpu = get_cpu(); + + while (n-- > 0) { + if (LDT_empty(info)) + desc->a = desc->b = 0; + else + fill_ldt(desc, info); + ++info; + ++desc; + } + + if (t == ¤t->thread) + load_TLS(t, cpu); + + put_cpu(); +} + +/* + * Set a given TLS descriptor: + */ +int do_set_thread_area(struct task_struct *p, int idx, + struct user_desc __user *u_info, + int can_allocate) +{ + struct user_desc info; + + if (copy_from_user(&info, u_info, sizeof(info))) + return -EFAULT; + + if (idx == -1) + idx = info.entry_number; + + /* + * index -1 means the kernel should try to find and + * allocate an empty descriptor: + */ + if (idx == -1 && can_allocate) { + idx = get_free_idx(); + if (idx < 0) + return idx; + if (put_user(idx, &u_info->entry_number)) + return -EFAULT; + } + + if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX) + return -EINVAL; + +#ifdef CONFIG_PAX_SEGMEXEC + if ((p->mm->pax_flags & MF_PAX_SEGMEXEC) && (info.contents & MODIFY_LDT_CONTENTS_CODE)) + return -EINVAL; +#endif + + set_tls_desc(p, idx, &info, 1); + + return 0; +} + +SYSCALL_DEFINE1(set_thread_area, struct user_desc __user *, u_info) +{ + return do_set_thread_area(current, -1, u_info, 1); +} + + +/* + * Get the current Thread-Local Storage area: + */ + +static void fill_user_desc(struct user_desc *info, int idx, + const struct desc_struct *desc) + +{ + memset(info, 0, sizeof(*info)); + info->entry_number = idx; + info->base_addr = get_desc_base(desc); + info->limit = get_desc_limit(desc); + info->seg_32bit = desc->d; + info->contents = desc->type >> 2; + info->read_exec_only = !(desc->type & 2); + info->limit_in_pages = desc->g; + info->seg_not_present = !desc->p; + info->useable = desc->avl; +#ifdef CONFIG_X86_64 + info->lm = desc->l; +#endif +} + +int do_get_thread_area(struct task_struct *p, int idx, + struct user_desc __user *u_info) +{ + struct user_desc info; + + if (idx == -1 && get_user(idx, &u_info->entry_number)) + return -EFAULT; + + if (idx < GDT_ENTRY_TLS_MIN || idx > GDT_ENTRY_TLS_MAX) + return -EINVAL; + + fill_user_desc(&info, idx, + &p->thread.tls_array[idx - GDT_ENTRY_TLS_MIN]); + + if (copy_to_user(u_info, &info, sizeof(info))) + return -EFAULT; + return 0; +} + +SYSCALL_DEFINE1(get_thread_area, struct user_desc __user *, u_info) +{ + return do_get_thread_area(current, -1, u_info); +} + +int regset_tls_active(struct task_struct *target, + const struct user_regset *regset) +{ + struct thread_struct *t = &target->thread; + int n = GDT_ENTRY_TLS_ENTRIES; + while (n > 0 && desc_empty(&t->tls_array[n - 1])) + --n; + return n; +} + +int regset_tls_get(struct task_struct *target, const struct user_regset *regset, + unsigned int pos, unsigned int count, + void *kbuf, void __user *ubuf) +{ + const struct desc_struct *tls; + + if (pos >= GDT_ENTRY_TLS_ENTRIES * sizeof(struct user_desc) || + (pos % sizeof(struct user_desc)) != 0 || + (count % sizeof(struct user_desc)) != 0) + return -EINVAL; + + pos /= sizeof(struct user_desc); + count /= sizeof(struct user_desc); + + tls = &target->thread.tls_array[pos]; + + if (kbuf) { + struct user_desc *info = kbuf; + while (count-- > 0) + fill_user_desc(info++, GDT_ENTRY_TLS_MIN + pos++, + tls++); + } else { + struct user_desc __user *u_info = ubuf; + while (count-- > 0) { + struct user_desc info; + fill_user_desc(&info, GDT_ENTRY_TLS_MIN + pos++, tls++); + if (__copy_to_user(u_info++, &info, sizeof(info))) + return -EFAULT; + } + } + + return 0; +} + +int regset_tls_set(struct task_struct *target, const struct user_regset *regset, + unsigned int pos, unsigned int count, + const void *kbuf, const void __user *ubuf) +{ + struct user_desc infobuf[GDT_ENTRY_TLS_ENTRIES]; + const struct user_desc *info; + + if (pos >= GDT_ENTRY_TLS_ENTRIES * sizeof(struct user_desc) || + (pos % sizeof(struct user_desc)) != 0 || + (count % sizeof(struct user_desc)) != 0) + return -EINVAL; + + if (kbuf) + info = kbuf; + else if (count > sizeof infobuf || __copy_from_user(infobuf, ubuf, count)) + return -EFAULT; + else + info = infobuf; + + set_tls_desc(target, + GDT_ENTRY_TLS_MIN + (pos / sizeof(struct user_desc)), + info, count / sizeof(struct user_desc)); + + return 0; +} diff --git a/pool/shard003/C/0064347_st_lsm6ds3_i2c.c b/pool/shard003/C/0064347_st_lsm6ds3_i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..9253dc27b4c4117f5ac640b5f408fa671fc2a6eb --- /dev/null +++ b/pool/shard003/C/0064347_st_lsm6ds3_i2c.c @@ -0,0 +1,188 @@ +/* + * STMicroelectronics lsm6ds3 i2c driver + * + * Copyright 2014 STMicroelectronics Inc. + * + * Denis Ciocca + * + * Licensed under the GPL-2. + */ + +#include +#include +#include +#include +#include + +#include "st_lsm6ds3.h" + +static int st_lsm6ds3_i2c_read(struct st_lsm6ds3_transfer_buffer *tb, + struct device *dev, u8 reg_addr, int len, u8 *data) +{ + int ret = 0; + struct i2c_msg msg[2]; + + struct lsm6ds3_data *cdata = i2c_get_clientdata(to_i2c_client(dev)); + + msg[0].addr = to_i2c_client(dev)->addr; + msg[0].flags = to_i2c_client(dev)->flags; + msg[0].len = 1; + msg[0].buf = ®_addr; + + msg[1].addr = to_i2c_client(dev)->addr; + msg[1].flags = to_i2c_client(dev)->flags | I2C_M_RD; + msg[1].len = len; + msg[1].buf = data; + + if (cdata->err_count <= 3) { + ret = i2c_transfer(to_i2c_client(dev)->adapter, msg, 2); + + if (ret < 0) { + cdata->err_count++; + pr_err("%s - i2c read(0x%x) error %d\n", + __func__, reg_addr, ret); + } + } else { + ret = -1; + } + + return ret; +} + +static int st_lsm6ds3_i2c_write(struct st_lsm6ds3_transfer_buffer *tb, + struct device *dev, u8 reg_addr, int len, u8 *data) +{ + u8 send[len + 1]; + int ret; + struct i2c_msg msg; + + send[0] = reg_addr; + memcpy(&send[1], data, len * sizeof(u8)); + len++; + + msg.addr = to_i2c_client(dev)->addr; + msg.flags = to_i2c_client(dev)->flags; + msg.len = len; + msg.buf = send; + + ret = i2c_transfer(to_i2c_client(dev)->adapter, &msg, 1); + if (ret < 0) + pr_err("%s - i2c read(0x%x) error %d\n", + __func__, reg_addr, ret); + + return ret; +} + +static const struct st_lsm6ds3_transfer_function st_lsm6ds3_tf_i2c = { + .write = st_lsm6ds3_i2c_write, + .read = st_lsm6ds3_i2c_read, +}; + +static int st_lsm6ds3_i2c_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int err; + struct lsm6ds3_data *cdata; + pr_info("%s - i2c Probe Start!\n", __func__); + + if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { + err = -ENOSYS; + pr_err("I2c function error\n"); + goto out_no_free; + } + + cdata = kmalloc(sizeof(*cdata), GFP_KERNEL); + if (!cdata) + return -ENOMEM; + + cdata->dev = &client->dev; + cdata->name = client->name; + cdata->client = client; + i2c_set_clientdata(client, cdata); + + cdata->tf = &st_lsm6ds3_tf_i2c; + + err = st_lsm6ds3_common_probe(cdata, client->irq); + if (err < 0) + goto free_data; + pr_info("%s - i2c Probe Done!\n", __func__); + return 0; + +free_data: + kfree(cdata); +out_no_free: + return err; +} + +static int st_lsm6ds3_i2c_remove(struct i2c_client *client) +{ + struct lsm6ds3_data *cdata = i2c_get_clientdata(client); + + st_lsm6ds3_common_remove(cdata, client->irq); + kfree(cdata); + + return 0; +} + +static void st_lsm6ds3_i2c_shutdown(struct i2c_client *client) +{ + struct lsm6ds3_data *cdata = i2c_get_clientdata(client); + + st_lsm6ds3_common_shutdown(cdata); +} + +#ifdef CONFIG_PM +static int st_lsm6ds3_suspend(struct device *dev) +{ + struct lsm6ds3_data *cdata = i2c_get_clientdata(to_i2c_client(dev)); + + return st_lsm6ds3_common_suspend(cdata); +} + +static int st_lsm6ds3_resume(struct device *dev) +{ + struct lsm6ds3_data *cdata = i2c_get_clientdata(to_i2c_client(dev)); + + return st_lsm6ds3_common_resume(cdata); +} + +static const struct dev_pm_ops st_lsm6ds3_pm_ops = { + SET_SYSTEM_SLEEP_PM_OPS(st_lsm6ds3_suspend, st_lsm6ds3_resume) +}; + +#define ST_LSM6DS3_PM_OPS (&st_lsm6ds3_pm_ops) +#else /* CONFIG_PM */ +#define ST_LSM6DS3_PM_OPS NULL +#endif /* CONFIG_PM */ + +static const struct i2c_device_id st_lsm6ds3_id_table[] = { + { LSM6DS3_DEV_NAME }, + { }, +}; + +#ifdef CONFIG_OF +static struct of_device_id st_lsm6ds3_match_table[] = { + { .compatible = "st,lsm6ds3",}, + {}, +}; +#endif + +MODULE_DEVICE_TABLE(i2c, st_lsm6ds3_id_table); + +static struct i2c_driver st_lsm6ds3_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "st-lsm6ds3-i2c", + .pm = ST_LSM6DS3_PM_OPS, + .of_match_table = st_lsm6ds3_match_table, + }, + .probe = st_lsm6ds3_i2c_probe, + .remove = st_lsm6ds3_i2c_remove, + .shutdown = st_lsm6ds3_i2c_shutdown, + .id_table = st_lsm6ds3_id_table, +}; +module_i2c_driver(st_lsm6ds3_driver); + +MODULE_AUTHOR("Denis Ciocca "); +MODULE_DESCRIPTION("STMicroelectronics lsm6ds3 i2c driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard003/C/0064349_ip-filter.c b/pool/shard003/C/0064349_ip-filter.c new file mode 100644 index 0000000000000000000000000000000000000000..d9eb43668a2cc36070f8dfb99dd929688193ef83 --- /dev/null +++ b/pool/shard003/C/0064349_ip-filter.c @@ -0,0 +1,134 @@ +#include +#include + +#include +#include + +IpFilter IpFilterInstall(IpIface iface, + IpFilterMethod filterMethod, + void* context, + PackosError* error) +{ + IpFilter res; + if (!(iface && filterMethod)) + { + *error=packosErrorInvalidArg; + return 0; + } + + res=(IpFilter)(malloc(sizeof(struct IpFilter))); + if (!res) + { + *error=packosErrorOutOfMemory; + return 0; + } + + res->iface=iface; + res->filterMethod=filterMethod; + res->context=context; + + res->prev=iface->filters.last; + if (res->prev) + res->prev->next=res; + else + iface->filters.first=res; + iface->filters.last=res; + res->next=0; + + return res; +} + +int IpFilterUninstall(IpFilter filter, + PackosError* error) +{ + if (!(filter && (filter->iface))) + { + *error=packosErrorInvalidArg; + return -1; + } + + if (filter->prev) + filter->prev->next=filter->next; + else + filter->iface->filters.first=filter->next; + + + if (filter->next) + filter->next->prev=filter->prev; + else + filter->iface->filters.last=filter->prev; + + free(filter); + return 0; +} + +PackosPacket* IpFilterApply(IpIface iface, + PackosPacket* packet, + PackosError* error) +{ + IpFilterAction action=ipFilterActionPass; + IpFilter cur; + + if (!(iface && packet)) + { + *error=packosErrorInvalidArg; + return ipFilterActionError; + } + + for (cur=iface->filters.first; + cur && (action==ipFilterActionPass); + cur=cur->next + ) + { + *error=packosErrorNone; + action=(cur->filterMethod)(iface,cur->context,packet,error); + if ((action==ipFilterActionError) + && ((*error)!=packosErrorNone) + ) + { + UtilPrintfStream(errStream,error,"IpFilterApply(): method: %s\n", + PackosErrorToString(*error)); + } + } + + switch (action) + { + case ipFilterActionPass: + /*UtilPrintfStream(errStream,error,"IpFilterApply(): action==ipFilterActionPass\n");*/ + return packet; + + case ipFilterActionDrop: + /*UtilPrintfStream(errStream,error,"IpFilterApply(): action==ipFilterActionDrop\n");*/ + *error=packosErrorPacketFilteredOut; + case ipFilterActionError: + /*UtilPrintfStream(errStream,error,"IpFilterApply(): action==ipFilterActionError: %s\n", + PackosErrorToString(*error));*/ + *error=packosErrorNone; + { + PackosError tmp; + PackosPacketFree(packet,&tmp); + } + return 0; + + case ipFilterActionErrorICMPed: + /*UtilPrintfStream(errStream,error,"IpFilterApply(): action==ipFilterActionErrorICMPed\n");*/ + *error=packosErrorNone; + return 0; + + case ipFilterActionForwarded: + /*UtilPrintfStream(errStream,error,"IpFilterApply(): action==ipFilterActionForwarded\n");*/ + *error=packosErrorNone; + return 0; + + case ipFilterActionReplied: + /*UtilPrintfStream(errStream,error,"IpFilterApply(): action==ipFilterActionReplied\n");*/ + *error=packosErrorNone; + return 0; + + default: + UtilPrintfStream(errStream,error,"IpFilterApply(): action==?\n"); + *error=packosErrorInvalidArg; + PackosPacketFree(packet,error); + return 0; + } +} diff --git a/pool/shard003/C/0064364_hg_addrdescr.c b/pool/shard003/C/0064364_hg_addrdescr.c new file mode 100644 index 0000000000000000000000000000000000000000..abf5aa5c4c5d63249723eb05ce55feb0d97bc50d --- /dev/null +++ b/pool/shard003/C/0064364_hg_addrdescr.c @@ -0,0 +1,121 @@ + +/*--------------------------------------------------------------------*/ +/*--- Address Description. ---*/ +/*--- hg_addrdescr.c ---*/ +/*--------------------------------------------------------------------*/ + +/* + This file is part of Helgrind, a Valgrind tool for detecting errors + in threaded programs. + + Copyright (C) 2007-2012 OpenWorks Ltd + info@open-works.co.uk + + 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. + + The GNU General Public License is contained in the file COPYING. +*/ +#include "pub_tool_basics.h" +#include "pub_tool_libcbase.h" +#include "pub_tool_libcprint.h" +#include "pub_tool_libcassert.h" +#include "pub_tool_wordfm.h" +#include "pub_tool_xarray.h" +#include "pub_tool_execontext.h" +#include "pub_tool_debuginfo.h" +#include "pub_tool_threadstate.h" +#include "pub_tool_aspacemgr.h" +#include "pub_tool_addrinfo.h" + +#include "hg_basics.h" +#include "hg_wordset.h" +#include "hg_lock_n_thread.h" +#include "hg_addrdescr.h" /* self */ + +void HG_(describe_addr) ( Addr a, /*OUT*/AddrInfo* ai ) +{ + tl_assert(ai->tag == Addr_Undescribed); + + /* hctxt/tnr/haddr/hszB describe the addr if it is a heap block. */ + ExeContext* hctxt; + UInt tnr; + Addr haddr; + SizeT hszB; + + /* First, see if it's in any heap block. Unfortunately this + means a linear search through all allocated heap blocks. The + assertion says that if it's detected as a heap block, then we + must have an allocation context for it, since all heap blocks + should have an allocation context. */ + Bool is_heapblock + = HG_(mm_find_containing_block)( + &hctxt, + &tnr, + &haddr, + &hszB, + a + ); + if (is_heapblock) { + tl_assert(is_heapblock == (hctxt != NULL)); + ai->tag = Addr_Block; + ai->Addr.Block.block_kind = Block_Mallocd; + ai->Addr.Block.block_desc = "block"; + ai->Addr.Block.block_szB = hszB; + ai->Addr.Block.rwoffset = (Word)(a) - (Word)(haddr); + ai->Addr.Block.allocated_at = hctxt; + VG_(initThreadInfo) (&ai->Addr.Block.alloc_tinfo); + ai->Addr.Block.alloc_tinfo.tnr = tnr; + ai->Addr.Block.freed_at = VG_(null_ExeContext)();; + } else { + /* No block found. Search a non-heap block description. */ + VG_(describe_addr) (a, ai); + + /* In case ai contains a tid, set tnr to the corresponding helgrind + thread number. */ + if (ai->tag == Addr_Stack) { + Thread* thr = get_admin_threads(); + + tl_assert(ai->Addr.Stack.tinfo.tid); + while (thr) { + if (thr->coretid == ai->Addr.Stack.tinfo.tid) { + ai->Addr.Stack.tinfo.tnr = thr->errmsg_index; + break; + } + thr = thr->admin; + } + } + } +} + +Bool HG_(get_and_pp_addrdescr) (Addr addr) +{ + + Bool ret; + AddrInfo glai; + + glai.tag = Addr_Undescribed; + HG_(describe_addr) (addr, &glai); + VG_(pp_addrinfo) (addr, &glai); + ret = glai.tag != Addr_Unknown; + + VG_(clear_addrinfo) (&glai); + + return ret; +} + +/*--------------------------------------------------------------------*/ +/*--- end hg_addrdescr.c ---*/ +/*--------------------------------------------------------------------*/ diff --git a/pool/shard003/C/0064365_stack.c b/pool/shard003/C/0064365_stack.c new file mode 100644 index 0000000000000000000000000000000000000000..7956e3949e31f07b7400700079be87cd3504a96e --- /dev/null +++ b/pool/shard003/C/0064365_stack.c @@ -0,0 +1,160 @@ +/*************************************************************************** + stack.c - This is a generic stack implementation used for + both the rtf state stack, and the html tag stack + ------------------- + begin : Mon Mar 8 2004 + copyright : (C) 2004 by Coy D. Barnes + email : coy.barnes@gmail.com + ***************************************************************************/ + +/*************************************************************************** + * * + * 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 +#include +#include +#include + +#ifdef MSVC +#pragma warning(disable:4700) +#endif + +#ifndef NULL +#define NULL 0 +#endif + +#define sn_alloc() (stack_node*)malloc(sizeof(struct stack_node)) +#define stack_alloc() (stack*)malloc(sizeof(struct stack)) + +static stack_node* create_node(int size) +{ + stack_node* ret; + ret = sn_alloc(); + if (ret == NULL) + { + return NULL; + } + ret->next=NULL; + ret->item = malloc(size); + return ret; +} + +static void delete_node(stack_node* p) +{ + if (p == NULL) + { + return; + } + free(p->item); + free(p); +} + +stack *stack_create(int size) +{ + stack* ret; + ret = stack_alloc(); + if (ret == NULL) + { + return NULL; + } + ret->top = NULL; + ret->size = size; + return ret; +} + +static void destroy_r(stack_node* p,int size) +{ + if (p==NULL) + { + return; + } + if (p->next != NULL) + { + destroy_r(p->next,size); + } + delete_node(p); +} + +void stack_destroy(stack* p) +{ + if (p==NULL) + { + return; + } + destroy_r(p->top,p->size); +} + +int stack_push(stack* p, const void *item) +{ + stack_node *tmp; + if (p==NULL) + { + return 0; + } + if (p->top==NULL) + { + tmp = create_node(p->size); + if(tmp==NULL) + { + return 0; + } + p->top=tmp; + memcpy(p->top->item,item,p->size); + p->top->next = NULL; + return 1; + } + tmp = create_node(p->size); + tmp->next=p->top; + memcpy(tmp->item,item,p->size); + p->top=tmp; + return 1; +} + +int stack_pop(stack* p,void *item) +{ + stack_node* tmp; + if (p == NULL) + { + return 0; + } + if (p->top==NULL) + { + return 0; + } + memcpy(item, p->top->item,p->size); + tmp = p->top; + p->top = p->top->next; + delete_node(tmp); + return 1; +} + +int stack_peek(stack* p,void *item) +{ + if (p == NULL) + { + return 0; + } + if (p->top==NULL) + { + return 0; + } + memcpy(item, p->top->item,p->size); + return 1; +} + +int stack_size(stack* p) +{ + stack_node *tmp; + int ret = 0; + for(tmp=p->top;tmp;tmp=tmp->next) + { + ret++; + } + return ret; +} diff --git a/pool/shard003/C/0064379_elf_begin.c b/pool/shard003/C/0064379_elf_begin.c new file mode 100644 index 0000000000000000000000000000000000000000..bb695c21d5fab30466f796c9d607fbbb9df4a75e --- /dev/null +++ b/pool/shard003/C/0064379_elf_begin.c @@ -0,0 +1,159 @@ +/*- + * Copyright (c) 2006 Joseph Koshy + * 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. + */ + +#include +__FBSDID("$FreeBSD: soc2013/dpl/head/lib/libelf/elf_begin.c 210394 2010-07-21 13:18:57Z kaiw $"); + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "_libelf.h" + +static Elf * +_libelf_open_object(int fd, Elf_Cmd c) +{ + Elf *e; + void *m; + struct stat sb; + + /* + * 'Raw' files are always mapped with 'PROT_READ'. At + * elf_update(3) time for files opened with ELF_C_RDWR the + * mapping is unmapped, file data is written to using write(2) + * and then the raw data is immediately mapped back in. + */ + if (fstat(fd, &sb) < 0) { + LIBELF_SET_ERROR(IO, errno); + return (NULL); + } + + m = NULL; + if ((m = mmap(NULL, (size_t) sb.st_size, PROT_READ, MAP_PRIVATE, fd, + (off_t) 0)) == MAP_FAILED) { + LIBELF_SET_ERROR(IO, errno); + return (NULL); + } + + if ((e = elf_memory(m, (size_t) sb.st_size)) == NULL) { + (void) munmap(m, (size_t) sb.st_size); + return (NULL); + } + + e->e_flags |= LIBELF_F_MMAP; + e->e_fd = fd; + e->e_cmd = c; + + if (c == ELF_C_RDWR && e->e_kind == ELF_K_AR) { + (void) elf_end(e); + LIBELF_SET_ERROR(ARGUMENT, 0); + return (NULL); + } + + return (e); +} + +Elf * +elf_begin(int fd, Elf_Cmd c, Elf *a) +{ + Elf *e; + + e = NULL; + + if (LIBELF_PRIVATE(version) == EV_NONE) { + LIBELF_SET_ERROR(SEQUENCE, 0); + return (NULL); + } + + switch (c) { + case ELF_C_NULL: + return (NULL); + + case ELF_C_WRITE: + + if (a != NULL) { /* not allowed for ar(1) archives. */ + LIBELF_SET_ERROR(ARGUMENT, 0); + return (NULL); + } + + /* + * Check writeability of `fd' immediately and fail if + * not writeable. + */ + if (ftruncate(fd, (off_t) 0) < 0) { + LIBELF_SET_ERROR(IO, errno); + return (NULL); + } + + if ((e = _libelf_allocate_elf()) != NULL) { + _libelf_init_elf(e, ELF_K_ELF); + e->e_byteorder = LIBELF_PRIVATE(byteorder); + e->e_fd = fd; + e->e_cmd = c; + } + return (e); + + case ELF_C_RDWR: + if (a != NULL) { /* not allowed for ar(1) archives. */ + LIBELF_SET_ERROR(ARGUMENT, 0); + return (NULL); + } + /*FALLTHROUGH*/ + case ELF_C_READ: + /* + * Descriptor `a' could be for a regular ELF file, or + * for an ar(1) archive. If descriptor `a' was opened + * using a valid file descriptor, we need to check if + * the passed in `fd' value matches the original one. + */ + if (a && + ((a->e_fd != -1 && a->e_fd != fd) || c != a->e_cmd)) { + LIBELF_SET_ERROR(ARGUMENT, 0); + return (NULL); + } + break; + + default: + LIBELF_SET_ERROR(ARGUMENT, 0); + return (NULL); + + } + + if (a == NULL) + e = _libelf_open_object(fd, c); + else if (a->e_kind == ELF_K_AR) + e = _libelf_ar_open_member(a->e_fd, c, a); + else + (e = a)->e_activations++; + + return (e); +} diff --git a/pool/shard003/C/0064394_led.c b/pool/shard003/C/0064394_led.c new file mode 100644 index 0000000000000000000000000000000000000000..1476a2544cd37e062e1f85af7d6949ccb89f0c7b --- /dev/null +++ b/pool/shard003/C/0064394_led.c @@ -0,0 +1,144 @@ +/* + * File: led.c + * + * Copyright (C) 2014 pic32mcu@gmail.com + * + * 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 "led.h" + +static LED _led[3]; + +static int getLedIndex(BYTE id) { + int i; + for(i=0; i +#include +#include +#include "jsre.h" + +typedef struct +{ + unsigned int tv; + unsigned int pad0[3]; + unsigned int tz; + unsigned int pad1[3]; +} syscall_gettimeofday_t; + +int +gettimeofday (struct timeval *tv, void *tz) +{ + syscall_gettimeofday_t sys; + + sys.tv = (unsigned int)tv; + sys.tz = (unsigned int)tz; + return __send_to_ppe(JSRE_POSIX1_SIGNALCODE, JSRE_GETTIMEOFDAY, &sys); +} diff --git a/pool/shard003/C/0064399_nic7018_wdt.c b/pool/shard003/C/0064399_nic7018_wdt.c new file mode 100644 index 0000000000000000000000000000000000000000..82843abe38f8b8c598bf07b17d686fa6a74fe9c8 --- /dev/null +++ b/pool/shard003/C/0064399_nic7018_wdt.c @@ -0,0 +1,262 @@ +/* + * Copyright (C) 2016 National Instruments Corp. + * + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define LOCK 0xA5 +#define UNLOCK 0x5A + +#define WDT_CTRL_RESET_EN BIT(7) +#define WDT_RELOAD_PORT_EN BIT(7) + +#define WDT_CTRL 1 +#define WDT_RELOAD_CTRL 2 +#define WDT_PRESET_PRESCALE 4 +#define WDT_REG_LOCK 5 +#define WDT_COUNT 6 +#define WDT_RELOAD_PORT 7 + +#define WDT_MIN_TIMEOUT 1 +#define WDT_MAX_TIMEOUT 464 +#define WDT_DEFAULT_TIMEOUT 80 + +#define WDT_MAX_COUNTER 15 + +static unsigned int timeout; +module_param(timeout, uint, 0); +MODULE_PARM_DESC(timeout, + "Watchdog timeout in seconds. (default=" + __MODULE_STRING(WDT_DEFAULT_TIMEOUT) ")"); + +static bool nowayout = WATCHDOG_NOWAYOUT; +module_param(nowayout, bool, 0); +MODULE_PARM_DESC(nowayout, + "Watchdog cannot be stopped once started. (default=" + __MODULE_STRING(WATCHDOG_NOWAYOUT) ")"); + +struct nic7018_wdt { + u16 io_base; + u32 period; + struct watchdog_device wdd; +}; + +struct nic7018_config { + u32 period; + u8 divider; +}; + +static const struct nic7018_config nic7018_configs[] = { + { 2, 4 }, + { 32, 5 }, +}; + +static inline u32 nic7018_timeout(u32 period, u8 counter) +{ + return period * counter - period / 2; +} + +static const struct nic7018_config *nic7018_get_config(u32 timeout, + u8 *counter) +{ + const struct nic7018_config *config; + u8 count; + + if (timeout < 30 && timeout != 16) { + config = &nic7018_configs[0]; + count = timeout / 2 + 1; + } else { + config = &nic7018_configs[1]; + count = DIV_ROUND_UP(timeout + 16, 32); + + if (count > WDT_MAX_COUNTER) + count = WDT_MAX_COUNTER; + } + *counter = count; + return config; +} + +static int nic7018_set_timeout(struct watchdog_device *wdd, + unsigned int timeout) +{ + struct nic7018_wdt *wdt = watchdog_get_drvdata(wdd); + const struct nic7018_config *config; + u8 counter; + + config = nic7018_get_config(timeout, &counter); + + outb(counter << 4 | config->divider, + wdt->io_base + WDT_PRESET_PRESCALE); + + wdd->timeout = nic7018_timeout(config->period, counter); + wdt->period = config->period; + + return 0; +} + +static int nic7018_start(struct watchdog_device *wdd) +{ + struct nic7018_wdt *wdt = watchdog_get_drvdata(wdd); + u8 control; + + nic7018_set_timeout(wdd, wdd->timeout); + + control = inb(wdt->io_base + WDT_RELOAD_CTRL); + outb(control | WDT_RELOAD_PORT_EN, wdt->io_base + WDT_RELOAD_CTRL); + + outb(1, wdt->io_base + WDT_RELOAD_PORT); + + control = inb(wdt->io_base + WDT_CTRL); + outb(control | WDT_CTRL_RESET_EN, wdt->io_base + WDT_CTRL); + + return 0; +} + +static int nic7018_stop(struct watchdog_device *wdd) +{ + struct nic7018_wdt *wdt = watchdog_get_drvdata(wdd); + + outb(0, wdt->io_base + WDT_CTRL); + outb(0, wdt->io_base + WDT_RELOAD_CTRL); + outb(0xF0, wdt->io_base + WDT_PRESET_PRESCALE); + + return 0; +} + +static int nic7018_ping(struct watchdog_device *wdd) +{ + struct nic7018_wdt *wdt = watchdog_get_drvdata(wdd); + + outb(1, wdt->io_base + WDT_RELOAD_PORT); + + return 0; +} + +static unsigned int nic7018_get_timeleft(struct watchdog_device *wdd) +{ + struct nic7018_wdt *wdt = watchdog_get_drvdata(wdd); + u8 count; + + count = inb(wdt->io_base + WDT_COUNT) & 0xF; + if (!count) + return 0; + + return nic7018_timeout(wdt->period, count); +} + +static const struct watchdog_info nic7018_wdd_info = { + .options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE, + .identity = "NIC7018 Watchdog", +}; + +static const struct watchdog_ops nic7018_wdd_ops = { + .owner = THIS_MODULE, + .start = nic7018_start, + .stop = nic7018_stop, + .ping = nic7018_ping, + .set_timeout = nic7018_set_timeout, + .get_timeleft = nic7018_get_timeleft, +}; + +static int nic7018_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct watchdog_device *wdd; + struct nic7018_wdt *wdt; + struct resource *io_rc; + int ret; + + wdt = devm_kzalloc(dev, sizeof(*wdt), GFP_KERNEL); + if (!wdt) + return -ENOMEM; + + platform_set_drvdata(pdev, wdt); + + io_rc = platform_get_resource(pdev, IORESOURCE_IO, 0); + if (!io_rc) { + dev_err(dev, "missing IO resources\n"); + return -EINVAL; + } + + if (!devm_request_region(dev, io_rc->start, resource_size(io_rc), + KBUILD_MODNAME)) { + dev_err(dev, "failed to get IO region\n"); + return -EBUSY; + } + + wdt->io_base = io_rc->start; + wdd = &wdt->wdd; + wdd->info = &nic7018_wdd_info; + wdd->ops = &nic7018_wdd_ops; + wdd->min_timeout = WDT_MIN_TIMEOUT; + wdd->max_timeout = WDT_MAX_TIMEOUT; + wdd->timeout = WDT_DEFAULT_TIMEOUT; + wdd->parent = dev; + + watchdog_set_drvdata(wdd, wdt); + watchdog_set_nowayout(wdd, nowayout); + watchdog_init_timeout(wdd, timeout, dev); + + /* Unlock WDT register */ + outb(UNLOCK, wdt->io_base + WDT_REG_LOCK); + + ret = watchdog_register_device(wdd); + if (ret) { + outb(LOCK, wdt->io_base + WDT_REG_LOCK); + dev_err(dev, "failed to register watchdog\n"); + return ret; + } + + dev_dbg(dev, "io_base=0x%04X, timeout=%d, nowayout=%d\n", + wdt->io_base, timeout, nowayout); + return 0; +} + +static int nic7018_remove(struct platform_device *pdev) +{ + struct nic7018_wdt *wdt = platform_get_drvdata(pdev); + + watchdog_unregister_device(&wdt->wdd); + + /* Lock WDT register */ + outb(LOCK, wdt->io_base + WDT_REG_LOCK); + + return 0; +} + +static const struct acpi_device_id nic7018_device_ids[] = { + {"NIC7018", 0}, + {"", 0}, +}; +MODULE_DEVICE_TABLE(acpi, nic7018_device_ids); + +static struct platform_driver watchdog_driver = { + .probe = nic7018_probe, + .remove = nic7018_remove, + .driver = { + .name = KBUILD_MODNAME, + .acpi_match_table = ACPI_PTR(nic7018_device_ids), + }, +}; + +module_platform_driver(watchdog_driver); + +MODULE_DESCRIPTION("National Instruments NIC7018 Watchdog driver"); +MODULE_AUTHOR("Hui Chun Ong "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard003/C/0064400_no_op.c b/pool/shard003/C/0064400_no_op.c new file mode 100644 index 0000000000000000000000000000000000000000..8b29c219dcfa6a452aaa83144190599e77c4d4b0 --- /dev/null +++ b/pool/shard003/C/0064400_no_op.c @@ -0,0 +1,106 @@ +/* + * + * Copyright 2015, Google 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 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 "test/core/end2end/end2end_tests.h" + +#include +#include + +#include +#include +#include +#include +#include +#include "test/core/end2end/cq_verifier.h" + +static void *tag(intptr_t t) { return (void *)t; } + +static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, + const char *test_name, + grpc_channel_args *client_args, + grpc_channel_args *server_args) { + grpc_end2end_test_fixture f; + gpr_log(GPR_INFO, "%s/%s", test_name, config.name); + f = config.create_fixture(client_args, server_args); + config.init_server(&f, server_args); + config.init_client(&f, client_args); + return f; +} + +static gpr_timespec n_seconds_time(int n) { + return GRPC_TIMEOUT_SECONDS_TO_DEADLINE(n); +} + +static gpr_timespec five_seconds_time(void) { return n_seconds_time(5); } + +static void drain_cq(grpc_completion_queue *cq) { + grpc_event ev; + do { + ev = grpc_completion_queue_next(cq, five_seconds_time(), NULL); + } while (ev.type != GRPC_QUEUE_SHUTDOWN); +} + +static void shutdown_server(grpc_end2end_test_fixture *f) { + if (!f->server) return; + grpc_server_shutdown_and_notify(f->server, f->cq, tag(1000)); + GPR_ASSERT(grpc_completion_queue_pluck( + f->cq, tag(1000), GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5), NULL) + .type == GRPC_OP_COMPLETE); + grpc_server_destroy(f->server); + f->server = NULL; +} + +static void shutdown_client(grpc_end2end_test_fixture *f) { + if (!f->client) return; + grpc_channel_destroy(f->client); + f->client = NULL; +} + +static void end_test(grpc_end2end_test_fixture *f) { + shutdown_server(f); + shutdown_client(f); + + grpc_completion_queue_shutdown(f->cq); + drain_cq(f->cq); + grpc_completion_queue_destroy(f->cq); +} + +static void test_no_op(grpc_end2end_test_config config) { + grpc_end2end_test_fixture f = begin_test(config, "no-op", NULL, NULL); + end_test(&f); + config.tear_down_data(&f); +} + +void no_op(grpc_end2end_test_config config) { test_no_op(config); } + +void no_op_pre_init(void) {} diff --git a/pool/shard003/C/0064432_cs_ldemo.c b/pool/shard003/C/0064432_cs_ldemo.c new file mode 100644 index 0000000000000000000000000000000000000000..9fbfec5eb175c055c23079f5883a6f6d47711121 --- /dev/null +++ b/pool/shard003/C/0064432_cs_ldemo.c @@ -0,0 +1,57 @@ +#include "cs.h" +/* test real/complex conversion routines (cs_long_t version) */ +int main (void) +{ + cs_cl *T, *A, *A1, *A2, *B ; + cs_dl *C1, *C2, *Treal, *Timag ; + + printf ("\n--- cs_ldemo, size of CS_INT: %d\n", (int) sizeof (CS_INT)) ; + + T = cs_cl_load (stdin) ; /* load a complex triplet matrix, T */ + printf ("\nT:\n") ; + cs_cl_print (T, 0) ; + + Treal = cs_l_real (T, 1) ; /* Treal = real part of T */ + printf ("\nTreal:\n") ; + cs_dl_print (Treal, 0) ; + + Timag = cs_l_real (T, 0) ; /* Treal = imaginary part of T */ + printf ("\nTimag:\n") ; + cs_dl_print (Timag, 0) ; + + A = cs_cl_compress (T) ; /* A = compressed-column form of T */ + printf ("\nA:\n") ; + cs_cl_print (A, 0) ; + + C1 = cs_l_real (A, 1) ; /* C1 = real (A) */ + printf ("\nC1 = real(A):\n") ; + cs_dl_print (C1, 0) ; + + C2 = cs_l_real (A, 0) ; /* C2 = imag (A) */ + printf ("\nC2 = imag(A):\n") ; + cs_dl_print (C2, 0) ; + + A1 = cs_l_complex (C1, 1) ; /* A1 = complex version of C1 */ + printf ("\nA1:\n") ; + cs_cl_print (A1, 0) ; + + A2 = cs_l_complex (C2, 0) ; /* A2 = complex version of C2 (imag.) */ + printf ("\nA2:\n") ; + cs_cl_print (A2, 0) ; + + B = cs_cl_add (A1, A2, 1., -1.) ; /* B = A1 - A2 */ + printf ("\nB = conj(A):\n") ; + cs_cl_print (B, 0) ; + + cs_cl_spfree (T) ; + cs_cl_spfree (A) ; + cs_cl_spfree (A1) ; + cs_cl_spfree (A2) ; + cs_cl_spfree (B) ; + cs_dl_spfree (C1) ; + cs_dl_spfree (C2) ; + cs_dl_spfree (Treal) ; + cs_dl_spfree (Timag) ; + + return (0) ; +} diff --git a/pool/shard003/C/0064433_arithmetic_decoding.c b/pool/shard003/C/0064433_arithmetic_decoding.c new file mode 100644 index 0000000000000000000000000000000000000000..e7da8bff05c780eb2e17b71114034c1ad3912a4a --- /dev/null +++ b/pool/shard003/C/0064433_arithmetic_decoding.c @@ -0,0 +1,192 @@ +/* + * Arithmetic decoding + * + * Copyright (C) 2012 Vincenzo Maffione + * + * 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 "bitbuffer.h" +#include "cumulative_sums_tree.h" + +#include +#include +#include + + +#define min(a,b) ((a) < (b)) ? (a) : (b) + +#define NUM_CODEPOINTS 257 // compatible with ASCII encoding +uint64_t total_count; // current total symbols counter +uint64_t LOW, HIGH; + + +static int bs(struct CST* CST_p, uint64_t x) +{ + int l, m, h; + uint64_t ncs_0, ncs_1, ratio; + l = 0; + h = NUM_CODEPOINTS; + ratio = (HIGH - LOW) / total_count; + for (;;) + { + m = (l + h) / 2; + ncs_0 = cumulative_sums_lookup(CST_p, m) * ratio + LOW; + ncs_1 = cumulative_sums_lookup(CST_p, m + 1) * ratio + LOW; + if (m == NUM_CODEPOINTS-1) + { + if (ncs_0 <= x) + break; + } + else if (ncs_0 <= x && x < ncs_1) + break; + if (x < ncs_0) + h = m; + else + l = m + 1; + if (l >= h) + break; + } + if (l >= h) + return -1; + return m; +} + + +int arithmetic_decoding(const char* encoded_file, const char* decoded_file) +{ + FILE* fout; + uint8_t byte; + int i; + int i_ss; + int i_d; + int n; + int bitc = 0; + uint64_t tmp, mask, stream_slice; + int bits_to_read; + struct CST* cumulative_sums_tree_pointer; + + struct BitBuffer* bbp = bit_open(encoded_file, BIT_BUFFER_READ); + if (bbp == NULL) + { + printf("%s: No such file\n", encoded_file); + return -1; + } + + cumulative_sums_tree_pointer = CST_create(NUM_CODEPOINTS); + if (cumulative_sums_tree_pointer == NULL) + { + printf("Error: CST creation failed\n"); + bit_close(bbp); + return -1; + } + + fout = fopen(decoded_file, "wb"); + if (fout == NULL) + { + printf("Error: cannot create output file %s\n", decoded_file); + return -1; + } + + // we deal with the zero-frequency problem initializing all counters to 1 and consequently NUM_CODEPOINTS to total_count + total_count = NUM_CODEPOINTS; + for (i=1; i>= 1; + } + LOW &= ~mask; + HIGH |= mask; + HIGH <<= i_d; + LOW <<= i_d; + } + else + i_d = 0; + + // stream scaling + tmp = LOW ^ HIGH; + i_ss = 0; + mask = 0x8000000000000000; + while (mask && (tmp & mask) == 0) + { + i_ss++; + mask >>= 1; + } + bits_to_read = i_ss + i_d; // for the next cycle + LOW <<= i_ss; + HIGH <<= i_ss; + + // adaptive update + counter_increment(cumulative_sums_tree_pointer, byte + 1); + total_count++; + } + + bit_close(bbp); + CST_destroy(cumulative_sums_tree_pointer); + fclose(fout); + + return 0; +} diff --git a/pool/shard003/C/0064448_gui-gtk-color.c b/pool/shard003/C/0064448_gui-gtk-color.c new file mode 100644 index 0000000000000000000000000000000000000000..b25e7baedbb4b4063f206b8c91e67f2d9320496c --- /dev/null +++ b/pool/shard003/C/0064448_gui-gtk-color.c @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2003-2009 by FlashCode + * See README for License detail, AUTHORS for developers list. + * + * 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 . + */ + +/* gui-gtk-color.c: color functions for Gtk GUI */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include + +#include "../../core/weechat.h" +#include "../../core/wee-config.h" +#include "../../core/wee-string.h" +#include "../gui-color.h" +#include "gui-gtk.h" + + +struct t_gui_color gui_weechat_colors[] = +{ { -1, 0, 0, "default" }, + { WEECHAT_COLOR_BLACK, 0, 0, "black" }, + { WEECHAT_COLOR_RED, 0, 0, "red" }, + { WEECHAT_COLOR_RED, 0, A_BOLD, "lightred" }, + { WEECHAT_COLOR_GREEN, 0, 0, "green" }, + { WEECHAT_COLOR_GREEN, 0, A_BOLD, "lightgreen" }, + { WEECHAT_COLOR_YELLOW, 0, 0, "brown" }, + { WEECHAT_COLOR_YELLOW, 0, A_BOLD, "yellow" }, + { WEECHAT_COLOR_BLUE, 0, 0, "blue" }, + { WEECHAT_COLOR_BLUE, 0, A_BOLD, "lightblue" }, + { WEECHAT_COLOR_MAGENTA, 0, 0, "magenta" }, + { WEECHAT_COLOR_MAGENTA, 0, A_BOLD, "lightmagenta" }, + { WEECHAT_COLOR_CYAN, 0, 0, "cyan" }, + { WEECHAT_COLOR_CYAN, 0, A_BOLD, "lightcyan" }, + { WEECHAT_COLOR_WHITE, 0, A_BOLD, "white" }, + { 0, 0, 0, NULL } +}; + + +/* + * gui_color_search: search a color by name + * Return: number of color in WeeChat colors table + */ + +int +gui_color_search (const char *color_name) +{ + int i; + + for (i = 0; gui_weechat_colors[i].string; i++) + { + if (string_strcasecmp (gui_weechat_colors[i].string, color_name) == 0) + return i; + } + + /* color not found */ + return -1; +} + +/* + * gui_color_assign: assign a WeeChat color (read from config) + */ + +int +gui_color_assign (int *color, const char *color_name) +{ + int i; + + /* look for curses colors in table */ + i = 0; + while (gui_weechat_colors[i].string) + { + if (string_strcasecmp (gui_weechat_colors[i].string, color_name) == 0) + { + *color = i; + return 1; + } + i++; + } + + /* color not found */ + return 0; +} + +/* + * gui_color_get_number: get number of available colors + */ + +int +gui_color_get_number () +{ + return 0; +} + +/* + * gui_color_get_name: get color name + */ + +const char * +gui_color_get_name (int num_color) +{ + return gui_weechat_colors[num_color].string; +} + +/* + * gui_color_get_pair: get color pair with a WeeChat color number + */ + +int +gui_color_get_pair (int num_color) +{ + int fg, bg; + + if ((num_color < 0) || (num_color > GUI_COLOR_NUM_COLORS - 1)) + return WEECHAT_COLOR_WHITE; + + fg = gui_color[num_color]->foreground; + bg = gui_color[num_color]->background; + + if (((fg == -1) || (fg == 99)) + && ((bg == -1) || (bg == 99))) + return 63; + if ((fg == -1) || (fg == 99)) + fg = WEECHAT_COLOR_WHITE; + if ((bg == -1) || (bg == 99)) + bg = 0; + + return (bg * 8) + fg; +} + +/* + * gui_color_init_pairs: init color pairs + */ + +void +gui_color_init_pairs () +{ + /* This function does nothing in Gtk GUI */ +} + +/* + * gui_color_init_weechat: init WeeChat colors + */ + +void +gui_color_init_weechat () +{ + /* TODO: write this function for Gtk */ +} + +/* + * gui_color_rebuild_weechat: rebuild WeeChat colors + */ + +void +gui_color_rebuild_weechat () +{ + int i; + + for (i = 0; i < GUI_COLOR_NUM_COLORS; i++) + { + if (gui_color[i]) + { + if (gui_color[i]->string) + free (gui_color[i]->string); + free (gui_color[i]); + gui_color[i] = NULL; + } + } + gui_color_init_weechat (); +} + +/* + * gui_color_pre_init: pre-init colors + */ + +void +gui_color_pre_init () +{ + int i; + + for (i = 0; i < GUI_COLOR_NUM_COLORS; i++) + { + gui_color[i] = NULL; + } +} + +/* + * gui_color_init: init GUI colors + */ + +void +gui_color_init () +{ + gui_color_init_pairs (); + gui_color_init_weechat (); +} + +/* + * gui_color_end: end GUI colors + */ + +void +gui_color_end () +{ + int i; + + for (i = 0; i < GUI_COLOR_NUM_COLORS; i++) + { + gui_color_free (gui_color[i]); + } +} diff --git a/pool/shard003/C/0064455_avx512vl-vpcmpneqd-1.c b/pool/shard003/C/0064455_avx512vl-vpcmpneqd-1.c new file mode 100644 index 0000000000000000000000000000000000000000..f063f1dabe15466c4cd3cdeb8549fcc8056eab8e --- /dev/null +++ b/pool/shard003/C/0064455_avx512vl-vpcmpneqd-1.c @@ -0,0 +1,21 @@ +/* { dg-do compile } */ +/* { dg-options "-mavx512vl -O2" } */ +/* { dg-final { scan-assembler-times "vpcmpd\[ \\t\]+\[^\{\n\]*%ymm\[0-9\]+\[^\n\]*%k\[1-7\]\{%k\[1-7\]\}(?:\n|\[ \\t\]+#)" 1 } } */ +/* { dg-final { scan-assembler-times "vpcmpd\[ \\t\]+\[^\{\n\]*%xmm\[0-9\]+\[^\n\]*%k\[1-7\]\{%k\[1-7\]\}(?:\n|\[ \\t\]+#)" 1 } } */ +/* { dg-final { scan-assembler-times "vpcmpd\[ \\t\]+\[^\{\n\]*%ymm\[0-9\]+\[^\n\]*%k\[1-7\](?:\n|\[ \\t\]+#)" 1 } } */ +/* { dg-final { scan-assembler-times "vpcmpd\[ \\t\]+\[^\{\n\]*%xmm\[0-9\]+\[^\n\]*%k\[1-7\](?:\n|\[ \\t\]+#)" 1 } } */ + +#include + +volatile __m256i x256; +volatile __m128i x128; +volatile __mmask8 m; + +void extern +avx512vl_test (void) +{ + m = _mm_cmpneq_epi32_mask (x128, x128); + m = _mm256_cmpneq_epi32_mask (x256, x256); + m = _mm_mask_cmpneq_epi32_mask (3, x128, x128); + m = _mm256_mask_cmpneq_epi32_mask (3, x256, x256); +} diff --git a/pool/shard003/C/0064474_smtc-proc.c b/pool/shard003/C/0064474_smtc-proc.c new file mode 100644 index 0000000000000000000000000000000000000000..38635a996cbfd6a2f883cacb68e8950e9a792b25 --- /dev/null +++ b/pool/shard003/C/0064474_smtc-proc.c @@ -0,0 +1,102 @@ +/* + * /proc hooks for SMTC kernel + * Copyright (C) 2005 Mips Technologies, Inc + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +/* + * /proc diagnostic and statistics hooks + */ + +/* + * Statistics gathered + */ +unsigned long selfipis[NR_CPUS]; + +struct smtc_cpu_proc smtc_cpu_stats[NR_CPUS]; + +atomic_t smtc_fpu_recoveries; + +static int smtc_proc_show(struct seq_file *m, void *v) +{ + int i; + extern unsigned long ebase; + + seq_printf(m, "SMTC Status Word: 0x%08x\n", smtc_status); + seq_printf(m, "Config7: 0x%08x\n", read_c0_config7()); + seq_printf(m, "EBASE: 0x%08lx\n", ebase); + seq_printf(m, "Counter Interrupts taken per CPU (TC)\n"); + for (i=0; i < NR_CPUS; i++) + seq_printf(m, "%d: %ld\n", i, smtc_cpu_stats[i].timerints); + seq_printf(m, "Self-IPIs by CPU:\n"); + for(i = 0; i < NR_CPUS; i++) + seq_printf(m, "%d: %ld\n", i, smtc_cpu_stats[i].selfipis); + seq_printf(m, "%d Recoveries of \"stolen\" FPU\n", + atomic_read(&smtc_fpu_recoveries)); + return 0; +} + +static int smtc_proc_open(struct inode *inode, struct file *file) +{ + return single_open(file, smtc_proc_show, NULL); +} + +static const struct file_operations smtc_proc_fops = { + .open = smtc_proc_open, + .read = seq_read, + .llseek = seq_lseek, + .release = single_release, +}; + +void init_smtc_stats(void) +{ + int i; + + for (i=0; im; + unsigned long n = pcn->n; + + if (!cpu_has_mipsmt) + return NOTIFY_OK; + + seq_printf(m, "VPE\t\t\t: %d\n", cpu_data[n].vpe_id); + seq_printf(m, "TC\t\t\t: %d\n", cpu_data[n].tc_id); + + return NOTIFY_OK; +} + +static int __init proc_cpuinfo_notifier_init(void) +{ + return proc_cpuinfo_notifier(proc_cpuinfo_chain_call, 0); +} + +subsys_initcall(proc_cpuinfo_notifier_init); diff --git a/pool/shard003/C/0064477_main.c b/pool/shard003/C/0064477_main.c new file mode 100644 index 0000000000000000000000000000000000000000..91c966a3eb486468433b71983c7f22894b4c1d8d --- /dev/null +++ b/pool/shard003/C/0064477_main.c @@ -0,0 +1,167 @@ +// +// WacomWebPlugin - An implementation of the Wacom Web API on Linux. +// Copyright (C) 2013 Zane Ashby +// +// 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 . +// + +// +// Entrypoint for plugin. +// + +#include "common.h" +#include "BaseObject.h" +#include "PenAPIObject.h" +#include "XInput.h" + +// Hold a pointer to browser functions. +NPNetscapeFuncs *g_netscapeFuncs = NULL; + +// Hold global instances of BaseObject and PenAPIObject in here. +// This can work because the plugin has no instance state. +api_t g_api; + + +// +// Plugin functions. +// + +// Plugin version. +const char* NP_GetPluginVersion(void) +{ + return PLUGIN_VERSION; +} + +// Plugin MIME + description. +const char* NP_GetMIMEDescription(void) +{ + return PLUGIN_MIME_DESCRIPTION; +} + +// Called when plugin is loaded. +NPError NP_Initialize(NPNetscapeFuncs *netscapeFuncs, NPPluginFuncs *pluginFuncs) +{ + pluginFuncs->version = PLUGIN_VERSIONL; + pluginFuncs->size = sizeof(*pluginFuncs); + + // Link up function pointers for instances. + pluginFuncs->newp = NPP_New; + pluginFuncs->destroy = NPP_Destroy; + pluginFuncs->getvalue = NPP_GetValue; + + // FIXME This should probably be copied in case it goes away. + g_netscapeFuncs = netscapeFuncs; + + return NPERR_NO_ERROR; +} + +// Called when plugin is unloaded. +void NP_Shutdown(void) +{ +} + +// Called to fetch a value from the plugin. +NPError NP_GetValue(NPP instance, NPNVariable variable, void *value) +{ + NPError err = NPERR_NO_ERROR; + + switch (variable) { + // If browser is asking for name or description, + // then return PLUGIN_NAME. + case NPPVpluginNameString: + case NPPVpluginDescriptionString: + *((char**)value) = PLUGIN_NAME; + break; + + // Tell the browser that we don't want a window. + // Chrome seems to ignore this and give us one anyway. + case NPPVpluginWindowBool: + *((bool*)value) = false; + break; + + default: + return NPERR_INVALID_PARAM; + } + + return err; +} + + +// +// Plugin *instance* functions. +// + +// Called when a plugin *instance* is created. +NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16_t mode, int16_t argc, char *argn[], char *argv[], NPSavedData *saved) +{ + // Create Base object if needed. + if (g_api.base == NULL) { + g_api.base = g_netscapeFuncs->createobject(instance, &BaseClass); + } + + // Create PenAPI object if needed. + if (g_api.penAPI == NULL) { + g_api.penAPI = g_netscapeFuncs->createobject(instance, &PenAPIClass); + } + + // Retain both. + g_netscapeFuncs->retainobject(g_api.base); + g_netscapeFuncs->retainobject(g_api.penAPI); + + // Start XInput thread. + xinput_start(); + + return NPERR_NO_ERROR; +} + +// Called when a plugin *instance* is destroyed. +NPError NPP_Destroy(NPP instance, NPSavedData **save) +{ + // Stop XInput thread. + xinput_stop(); + + // Release objects. + g_netscapeFuncs->releaseobject(g_api.penAPI); + g_netscapeFuncs->releaseobject(g_api.base); + + return NPERR_NO_ERROR; +} + +NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) +{ + NPError err = NPERR_NO_ERROR; + + switch (variable) { + // Return our scriptable "Base" object here. + // This is the root of our plugins scriptable interface. + case NPPVpluginScriptableNPObject: + { + void **v = value; + NPObject *obj = g_api.base; + g_netscapeFuncs->retainobject(obj); + *v = obj; + } + break; + + // Work around Chrome bug. + case NPPVpluginNeedsXEmbed: + *((NPBool*)value) = true; + break; + + default: + return NPERR_INVALID_PARAM; + } + + return err; +} diff --git a/pool/shard003/C/0064485_help-unknown-cmd.c b/pool/shard003/C/0064485_help-unknown-cmd.c new file mode 100644 index 0000000000000000000000000000000000000000..15b95300d7f37e24775c7e40edf0a61422b249e7 --- /dev/null +++ b/pool/shard003/C/0064485_help-unknown-cmd.c @@ -0,0 +1,115 @@ +#include "cache.h" +#include "config.h" +#include +#include +#include +#include "../builtin.h" +#include "levenshtein.h" + +static int autocorrect; + +static int perf_unknown_cmd_config(const char *var, const char *value, + void *cb __maybe_unused) +{ + if (!strcmp(var, "help.autocorrect")) + return perf_config_int(&autocorrect, var,value); + + return 0; +} + +static int levenshtein_compare(const void *p1, const void *p2) +{ + const struct cmdname *const *c1 = p1, *const *c2 = p2; + const char *s1 = (*c1)->name, *s2 = (*c2)->name; + int l1 = (*c1)->len; + int l2 = (*c2)->len; + return l1 != l2 ? l1 - l2 : strcmp(s1, s2); +} + +static int add_cmd_list(struct cmdnames *cmds, struct cmdnames *old) +{ + unsigned int i, nr = cmds->cnt + old->cnt; + void *tmp; + + if (nr > cmds->alloc) { + /* Choose bigger one to alloc */ + if (alloc_nr(cmds->alloc) < nr) + cmds->alloc = nr; + else + cmds->alloc = alloc_nr(cmds->alloc); + tmp = realloc(cmds->names, cmds->alloc * sizeof(*cmds->names)); + if (!tmp) + return -1; + cmds->names = tmp; + } + for (i = 0; i < old->cnt; i++) + cmds->names[cmds->cnt++] = old->names[i]; + zfree(&old->names); + old->cnt = 0; + return 0; +} + +const char *help_unknown_cmd(const char *cmd) +{ + unsigned int i, n = 0, best_similarity = 0; + struct cmdnames main_cmds, other_cmds; + + memset(&main_cmds, 0, sizeof(main_cmds)); + memset(&other_cmds, 0, sizeof(main_cmds)); + + perf_config(perf_unknown_cmd_config, NULL); + + load_command_list("perf-", &main_cmds, &other_cmds); + + if (add_cmd_list(&main_cmds, &other_cmds) < 0) { + fprintf(stderr, "ERROR: Failed to allocate command list for unknown command.\n"); + goto end; + } + qsort(main_cmds.names, main_cmds.cnt, + sizeof(main_cmds.names), cmdname_compare); + uniq(&main_cmds); + + if (main_cmds.cnt) { + /* This reuses cmdname->len for similarity index */ + for (i = 0; i < main_cmds.cnt; ++i) + main_cmds.names[i]->len = + levenshtein(cmd, main_cmds.names[i]->name, 0, 2, 1, 4); + + qsort(main_cmds.names, main_cmds.cnt, + sizeof(*main_cmds.names), levenshtein_compare); + + best_similarity = main_cmds.names[0]->len; + n = 1; + while (n < main_cmds.cnt && best_similarity == main_cmds.names[n]->len) + ++n; + } + + if (autocorrect && n == 1) { + const char *assumed = main_cmds.names[0]->name; + + main_cmds.names[0] = NULL; + clean_cmdnames(&main_cmds); + fprintf(stderr, "WARNING: You called a perf program named '%s', " + "which does not exist.\n" + "Continuing under the assumption that you meant '%s'\n", + cmd, assumed); + if (autocorrect > 0) { + fprintf(stderr, "in %0.1f seconds automatically...\n", + (float)autocorrect/10.0); + poll(NULL, 0, autocorrect * 100); + } + return assumed; + } + + fprintf(stderr, "perf: '%s' is not a perf-command. See 'perf --help'.\n", cmd); + + if (main_cmds.cnt && best_similarity < 6) { + fprintf(stderr, "\nDid you mean %s?\n", + n < 2 ? "this": "one of these"); + + for (i = 0; i < n; i++) + fprintf(stderr, "\t%s\n", main_cmds.names[i]->name); + } +end: + exit(1); +} diff --git a/pool/shard003/C/0064494_main.c b/pool/shard003/C/0064494_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5f580b73567b8c9b3d77582c5aa30f6a5a00db5a --- /dev/null +++ b/pool/shard003/C/0064494_main.c @@ -0,0 +1,52 @@ +#include "memoria.h" +#include "bancos.h" +#include "fetch.h" + +#include + +//cargar a partir de 0x0 las instrucciones contenidas en rom +static void load_rom(){ + /* + mov r2, r2 + 2 + mov r5, 5 + sw r5, r0+inmd(C0) + add r6,r2,r5 + beq @0, 0 0 + */ + set_contenido_mem(0x00, 0x04420002); + set_contenido_mem(0x04, 0x04050005); + set_contenido_mem(0x08, 0x0c0500C0); + set_contenido_mem(0x0c, 0x28453000); + set_contenido_mem(0x10, 0x10000000); + set_pc(0x0); +} + +int main(){ + mem_init(); + + load_rom(); + /*printf("Instrucciones: \n"); + print_contenido_mem_detalle(0x00, 0x02c, get_pc());*/ + char entrada = ' '; + while(entrada != 'e'){ + printf("Instrucciones: \n"); + print_contenido_mem_detalle(0x00, 0x2c, get_pc()); + //printf("%c\n", &entrada); + etapa_fetch_run();//ejecutar un ciclo + printf("Datos: \n"); + print_contenido_mem_detalle(0x00C0, 0x00CC); + printf("Banco: \n"); + print_contenido_BR_detalle(0,7); + scanf("%c", &entrada); + //siguiente ciclo + //copiar bancos de entrada en bacnos de salida + if(F_D_F.carga == 1) F_D_D = F_D_F; + D_E_E = D_E_D; + E_M_M = E_M_E; + M_W_W = M_W_M; + } + + //set_contenido_mem(0xfffc, 0x12f18404); + + //print_contenido_mem(); +} diff --git a/pool/shard003/C/0064498_avx512f-vcvttsd2usi64-2.c b/pool/shard003/C/0064498_avx512f-vcvttsd2usi64-2.c new file mode 100644 index 0000000000000000000000000000000000000000..4aa45ef8264503568e4fab92a1f8ef69a9049d67 --- /dev/null +++ b/pool/shard003/C/0064498_avx512f-vcvttsd2usi64-2.c @@ -0,0 +1,27 @@ +/* { dg-do run { target { ! { ia32 } } } } */ +/* { dg-options "-O2 -mavx512f" } */ +/* { dg-require-effective-target avx512f } */ + +#include "avx512f-check.h" + +static unsigned long long +__attribute__((noinline, unused)) +test (union128d s1) +{ + return _mm_cvttsd_u64 (s1.x); +} + +void static +avx512f_test (void) +{ + union128d s1; + unsigned long long d; + unsigned long long e; + + s1.x = _mm_set_pd (24.43, 68.346); + d = test (s1); + e = (unsigned long long)s1.a[0]; + + if (e != d) + abort (); +} diff --git a/pool/shard003/C/0064505_gtkiimagetool.c b/pool/shard003/C/0064505_gtkiimagetool.c new file mode 100644 index 0000000000000000000000000000000000000000..6439ce62afa55dc8fe133981c3dc9d596077f53b --- /dev/null +++ b/pool/shard003/C/0064505_gtkiimagetool.c @@ -0,0 +1,199 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; coding: utf-8 -*- + * + * Copyright © 2007-2010 Björn Lindqvist + * + * 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, 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., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + */ + +/** + * SECTION:gtkiimagetool + * @see_also: Non-instantiable + * classed types: Interfaces + * @short_description: Interface for objects capable of being used as + * tools by #GtkImageView + * + * + * GtkIImageTool is an interface that defines how GtkImageView + * interacts with objects that acts as tools. GtkImageView delegates + * many of its most important tasks (such as drawing) to its tool which + * carries out all the hard work. The GtkImageView package comes with + * two tools; #GtkImageToolDragger and #GtkImageToolSelector, but by + * implementing your own tool it is possible to extend GtkImageView to + * do stuff its author (thats me) didn't imagine. + * + * + * GtkImageView uses #GtkImageToolDragger by default, as that tool is + * he most generally useful one. However, it is trivial to make it use + * another tool. + * + * + * GtkImageView *view = GTK_IMAGE_VIEW (gtk_image_view_new ()); + * GtkIImageTool *tool = gtk_image_tool_selector_new (view); + * gtk_image_view_set_tool (view, tool); + * + * + * Using the above code makes the view use the selector tool instead of + * the default dragger tool. + * + **/ +#include "gtkiimagetool.h" + +/*************************************************************/ +/***** Stuff that deals with the type ************************/ +/*************************************************************/ +GType +gtk_iimage_tool_get_type (void) +{ + static GType type = 0; + if (type) + return type; + static const GTypeInfo info = { + sizeof (GtkIImageToolClass), + NULL, + NULL, + NULL, + NULL, + NULL, + 0, + 0, + NULL + }; + type = g_type_register_static (G_TYPE_INTERFACE, + "GtkIImageTool", + &info, + 0); + g_type_interface_add_prerequisite (type, G_TYPE_OBJECT); + return type; +} + +/*************************************************************/ +/***** Pseudo signal handlers ********************************/ +/*************************************************************/ +gboolean +gtk_iimage_tool_button_press (GtkIImageTool *tool, + GdkEventButton *ev) +{ + return GTK_IIMAGE_TOOL_GET_CLASS (tool)->button_press (tool, ev); +} + +/** + * gtk_iimage_tool_button_release: + * @tool: the tool + * @ev: a %GdkEventButton event + * @returns: %TRUE if the event was handled, %FALSE otherwise + * + * Handles a %GdkEventButton event of a button release. The + * implementing function should return %TRUE if it handled the event, + * for examply by releasing the grab, and %FALSE otherwise. + **/ +gboolean +gtk_iimage_tool_button_release (GtkIImageTool *tool, + GdkEventButton *ev) +{ + return GTK_IIMAGE_TOOL_GET_CLASS (tool)->button_release (tool, ev); +} + +/** + * gtk_iimage_tool_motion_notify: + * @tool: the tool + * @ev: a %GdkEventMotion event + * @returns: %TRUE if the event was handled, %FALSE otherwise + * + * Handles a %GdkEventMotion event. The implementing function should + * return %TRUE if it handled the event and %FALSE otherwise. + **/ +gboolean +gtk_iimage_tool_motion_notify (GtkIImageTool *tool, + GdkEventMotion *ev) +{ + return GTK_IIMAGE_TOOL_GET_CLASS (tool)->motion_notify (tool, ev); +} + +/** + * gtk_iimage_tool_pixbuf_changed: + * @tool: the tool + * @reset_fit: whether the view is resetting its fit mode or not + * @rect: rectangle containing the changed area or %NULL + * + * Indiate to the tool that either a part of, or the whole pixbuf that + * the image view shows has changed. This method is called by the view + * whenever its pixbuf or its tool changes. That is, when any of the + * following methods are used: + * + * + * gtk_image_view_set_pixbuf() + * gtk_image_view_set_tool() + * gtk_image_view_damage_pixels() + * + * + * If the @reset_fit parameter is %TRUE, it means that a new pixbuf + * has been loaded into the view. @rect is a rectangle in image space + * coordinates that indicates which rectangular region of the pixbufs + * pixels that is modified. If @rect is %NULL, then all of the pixbuf + * has changed. See also GtkImageView::pixbuf-changed. + **/ +void +gtk_iimage_tool_pixbuf_changed (GtkIImageTool *tool, + gboolean reset_fit, + GdkRectangle *rect) +{ + GtkIImageToolClass *klass = GTK_IIMAGE_TOOL_GET_CLASS (tool); + klass->pixbuf_changed (tool, reset_fit, rect); +} + +/** + * gtk_iimage_tool_paint_image: + * @tool: the tool + * @opts: the #GdkPixbufDrawOpts to use in this draw + * @drawable: a #GdkDrawable to draw on + * + * Called whenever the image view decides that any part of the image + * it shows needs to be redrawn. + **/ +void +gtk_iimage_tool_paint_image (GtkIImageTool *tool, + GdkPixbufDrawOpts *opts, + GdkDrawable *drawable) +{ + GtkIImageToolClass *klass = GTK_IIMAGE_TOOL_GET_CLASS (tool); + klass->paint_image (tool, opts, drawable); +} + +/*************************************************************/ +/***** Read-only properties **********************************/ +/*************************************************************/ +/** + * gtk_iimage_tool_cursor_at_point: + * @tool: the tool + * @x: the mouse pointers X-coordinate + * @y: the mouse pointers Y-coordinate + * @returns: The appropriate cursor or %NULL if the widgets default + * cursor should be used. + * + * Ask the tool what cursor it wants displayed. E.g. if the tool keeps + * track of image maps in the image, then this method can be + * implemented to return an appropriate cursor when the mouse pointer + * hovers at the specified point in the widget. + **/ +GdkCursor* +gtk_iimage_tool_cursor_at_point (GtkIImageTool *tool, + int x, + int y) +{ + return GTK_IIMAGE_TOOL_GET_CLASS (tool)->cursor_at_point (tool, x, y); +} + diff --git a/pool/shard003/C/0064510_logging.c b/pool/shard003/C/0064510_logging.c new file mode 100644 index 0000000000000000000000000000000000000000..dce5b866853adf103304f3e52bfcc71bb467176a --- /dev/null +++ b/pool/shard003/C/0064510_logging.c @@ -0,0 +1,132 @@ +/* + $Id: logging.c,v 1.1 2003/10/13 11:47:12 f1rmb Exp $ + + Copyright (C) 2000 Herbert Valerio Riedel + + 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 +*/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include + +/* Public headers */ +#include + +/* Private headers */ +#include "assert.h" + +static const char _rcsid[] = "$Id: logging.c,v 1.1 2003/10/13 11:47:12 f1rmb Exp $"; + +static void +default_vcd_log_handler (vcd_log_level_t level, const char message[]) +{ + switch (level) + { + case VCD_LOG_ERROR: + fprintf (stderr, "**ERROR: %s\n", message); + fflush (stderr); + exit (EXIT_FAILURE); + break; + case VCD_LOG_DEBUG: + fprintf (stdout, "--DEBUG: %s\n", message); + break; + case VCD_LOG_WARN: + fprintf (stdout, "++ WARN: %s\n", message); + break; + case VCD_LOG_INFO: + fprintf (stdout, " INFO: %s\n", message); + break; + case VCD_LOG_ASSERT: + fprintf (stderr, "!ASSERT: %s\n", message); + fflush (stderr); + abort (); + break; + default: + vcd_assert_not_reached (); + break; + } + + fflush (stdout); +} + +static vcd_log_handler_t _handler = default_vcd_log_handler; + +vcd_log_handler_t +vcd_log_set_handler (vcd_log_handler_t new_handler) +{ + vcd_log_handler_t old_handler = _handler; + + _handler = new_handler; + + return old_handler; +} + +static void +vcd_logv (vcd_log_level_t level, const char format[], va_list args) +{ + char buf[1024] = { 0, }; + static int in_recursion = 0; + + if (in_recursion) + vcd_assert_not_reached (); + + in_recursion = 1; + + vsnprintf(buf, sizeof(buf)-1, format, args); + + _handler(level, buf); + + in_recursion = 0; +} + +void +vcd_log (vcd_log_level_t level, const char format[], ...) +{ + va_list args; + va_start (args, format); + vcd_logv (level, format, args); + va_end (args); +} + +#define VCD_LOG_TEMPLATE(level, LEVEL) \ +void \ +vcd_ ## level (const char format[], ...) \ +{ \ + va_list args; \ + va_start (args, format); \ + vcd_logv (VCD_LOG_ ## LEVEL, format, args); \ + va_end (args); \ +} + +VCD_LOG_TEMPLATE(debug, DEBUG) +VCD_LOG_TEMPLATE(info, INFO) +VCD_LOG_TEMPLATE(warn, WARN) +VCD_LOG_TEMPLATE(error, ERROR) + +#undef VCD_LOG_TEMPLATE + + +/* + * Local variables: + * c-file-style: "gnu" + * tab-width: 8 + * indent-tabs-mode: nil + * End: + */ diff --git a/pool/shard003/C/0064517_boot_descriptor_block.c b/pool/shard003/C/0064517_boot_descriptor_block.c new file mode 100644 index 0000000000000000000000000000000000000000..86fd312fe324cd533d73f14cf7ae04c56efffe45 --- /dev/null +++ b/pool/shard003/C/0064517_boot_descriptor_block.c @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2015 Martin Glueck + * Copyright (c) 2020 Stefan Haller + * + * 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. + */ + +#include "boot_descriptor_block.h" +#include "crc.h" + + +/* This is the sanity check as described in 26.3.3 of the UM10398 user guide +* However, this shouldn't matter since we boot into the BL anyways and just it's vector table +* needs to be correct. +* This test get's important if we like to bypass the KNX bootloader. +* Note that the LPC device as a build in BL ROM for UART ISP which is always started first. +* This ROM BL checks if the vector table is correct to determine if the KNX BL can be started. +*/ +#if 0 +unsigned int checkVectorTable(unsigned int start) +{ + unsigned int i; + unsigned int * address; + unsigned int cs = 0; + address = (unsigned int *) start; // Vector table start always at base address, each entry is 4 byte + + for (i = 0; i < 7; i++) // Checksum is 2's complement of entries 0 through 6 + cs += address[i]; + //if (address[7]) + + return (~cs+1); + return (address[0]); +} +#else +#define checkVectorTable(s) 1 +#endif + +unsigned int checkApplication(AppDescriptionBlock * block) +{ + if (block->startAddress < FIRST_SECTOR) + return 0; + if (block->endAddress > 0x10000) // we have just 64k of Flash + return 0; + if (block->startAddress == block->endAddress) + return 0; + + unsigned int crc = crc32(0xFFFFFFFF, (unsigned char *) block->startAddress, + block->endAddress - block->startAddress); + if (crc == block->crc) + { + return checkVectorTable(block->startAddress); + } + return 0; +} + +inline unsigned char * getAppVersion(AppDescriptionBlock * block) +{ + return (unsigned char *) (block->appVersionAddress); +} + +// Return start address of application in case of valid descriptor block +// otherwise, base address of firmware area, directly behind bootloader +unsigned char * getFWstartAddress(AppDescriptionBlock * block) +{ + if (checkApplication(block)) + return (unsigned char *) (block->startAddress); + else + return (unsigned char *) FIRST_SECTOR; +} diff --git a/pool/shard003/C/0064522_bcm4329_rfkill.c b/pool/shard003/C/0064522_bcm4329_rfkill.c new file mode 100644 index 0000000000000000000000000000000000000000..4259b69c9d1bfa71d80ffc8d3e43415f90745b42 --- /dev/null +++ b/pool/shard003/C/0064522_bcm4329_rfkill.c @@ -0,0 +1,235 @@ +/* + * drivers/misc/bcm4329_rfkill.c + * + * Copyright (c) 2010, NVIDIA Corporation. + * + * 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 +#include +#include +#include +#include + +#ifdef CONFIG_MACH_SMBA1002 +#include "../../arch/arm/mach-tegra/board-smba1002.h" +#endif + +struct bcm4329_rfkill_data { + int gpio_reset; + int gpio_shutdown; + int delay; + bool state; + struct clk *bt_32k_clk; +}; + +static struct bcm4329_rfkill_data *bcm4329_rfkill; + +static int bcm4329_bt_rfkill_set_power(void *data, bool blocked) +{ + if (blocked) { + if (!bcm4329_rfkill->state) + return 0; +#ifdef CONFIG_MACH_SMBA1002 + smba1002_bt_wifi_gpio_set(0); +#else + if (bcm4329_rfkill->gpio_shutdown) + gpio_direction_output(bcm4329_rfkill->gpio_shutdown, 0); + if (bcm4329_rfkill->bt_32k_clk) + clk_disable(bcm4329_rfkill->bt_32k_clk); +#endif + if (bcm4329_rfkill->gpio_reset) + gpio_direction_output(bcm4329_rfkill->gpio_reset, 0); + bcm4329_rfkill->state = 0; + + } else { + if (bcm4329_rfkill->state) + return 0; +#ifdef CONFIG_MACH_SMBA1002 + smba1002_bt_wifi_gpio_set(1); +#else + if (bcm4329_rfkill->bt_32k_clk) + clk_enable(bcm4329_rfkill->bt_32k_clk); + if (bcm4329_rfkill->gpio_shutdown) + { + gpio_direction_output(bcm4329_rfkill->gpio_shutdown, 0); + msleep(100); + gpio_direction_output(bcm4329_rfkill->gpio_shutdown, 1); + msleep(100); + } +#endif + if (bcm4329_rfkill->gpio_reset) + { + gpio_direction_output(bcm4329_rfkill->gpio_reset, 0); + msleep(100); + gpio_direction_output(bcm4329_rfkill->gpio_reset, 1); + msleep(100); + } + bcm4329_rfkill->state = 1; + + } + + return 0; +} + +static const struct rfkill_ops bcm4329_bt_rfkill_ops = { + .set_block = bcm4329_bt_rfkill_set_power, +}; + +static int bcm4329_rfkill_probe(struct platform_device *pdev) +{ + struct rfkill *bt_rfkill; + struct resource *res; + int ret; + bool enable = false; /* off */ + bool default_sw_block_state; + + bcm4329_rfkill = kzalloc(sizeof(*bcm4329_rfkill), GFP_KERNEL); + if (!bcm4329_rfkill) + return -ENOMEM; + + bcm4329_rfkill->state = 0; + +#ifdef CONFIG_MACH_SMBA1002 + // Init the gpio manager if it isn't already. + smba1002_bt_wifi_gpio_init(); +#else + bcm4329_rfkill->bt_32k_clk = clk_get(&pdev->dev, "bcm4329_32k_clk"); + if (IS_ERR(bcm4329_rfkill->bt_32k_clk)) { + pr_warn("%s: can't find bcm4329_32k_clk.\ + assuming 32k clock to chip\n", __func__); + bcm4329_rfkill->bt_32k_clk = NULL; + } +#endif + + res = platform_get_resource_byname(pdev, IORESOURCE_IO, + "bcm4329_nreset_gpio"); + if (res) { + bcm4329_rfkill->gpio_reset = res->start; + tegra_gpio_enable(bcm4329_rfkill->gpio_reset); + ret = gpio_request(bcm4329_rfkill->gpio_reset, + "bcm4329_nreset_gpio"); + } else { + pr_warn("%s : can't find reset gpio.\n", __func__); + bcm4329_rfkill->gpio_reset = 0; + } + + res = platform_get_resource_byname(pdev, IORESOURCE_IO, + "bcm4329_nshutdown_gpio"); + if (res) { + bcm4329_rfkill->gpio_shutdown = res->start; + tegra_gpio_enable(bcm4329_rfkill->gpio_shutdown); + ret = gpio_request(bcm4329_rfkill->gpio_shutdown, + "bcm4329_nshutdown_gpio"); + } else { + pr_warn("%s : can't find shutdown gpio.\n", __func__); + bcm4329_rfkill->gpio_shutdown = 0; + } + + /* make sure at-least one of the GPIO is defined */ + if (!bcm4329_rfkill->gpio_reset && !bcm4329_rfkill->gpio_shutdown) + goto free_bcm_res; + + if (bcm4329_rfkill->bt_32k_clk && enable) + clk_enable(bcm4329_rfkill->bt_32k_clk); + if (bcm4329_rfkill->gpio_shutdown) + gpio_direction_output(bcm4329_rfkill->gpio_shutdown, enable); + if (bcm4329_rfkill->gpio_reset) + gpio_direction_output(bcm4329_rfkill->gpio_reset, enable); + + bt_rfkill = rfkill_alloc("bcm4329 Bluetooth", &pdev->dev, + RFKILL_TYPE_BLUETOOTH, &bcm4329_bt_rfkill_ops, + NULL); + + if (unlikely(!bt_rfkill)) + goto free_bcm_res; + + default_sw_block_state = !enable; + rfkill_set_states(bt_rfkill, default_sw_block_state, false); + + ret = rfkill_register(bt_rfkill); + + if (unlikely(ret)) { + rfkill_destroy(bt_rfkill); + goto free_bcm_res; + } + + return 0; + +free_bcm_res: + if (bcm4329_rfkill->gpio_shutdown) + gpio_free(bcm4329_rfkill->gpio_shutdown); + if (bcm4329_rfkill->gpio_reset) + gpio_free(bcm4329_rfkill->gpio_reset); + if (bcm4329_rfkill->bt_32k_clk && enable) + clk_disable(bcm4329_rfkill->bt_32k_clk); + if (bcm4329_rfkill->bt_32k_clk) + clk_put(bcm4329_rfkill->bt_32k_clk); + kfree(bcm4329_rfkill); + return -ENODEV; +} + +static int bcm4329_rfkill_remove(struct platform_device *pdev) +{ + struct rfkill *bt_rfkill = platform_get_drvdata(pdev); + + if (bcm4329_rfkill->bt_32k_clk) + clk_put(bcm4329_rfkill->bt_32k_clk); + rfkill_unregister(bt_rfkill); + rfkill_destroy(bt_rfkill); + if (bcm4329_rfkill->gpio_shutdown) + gpio_free(bcm4329_rfkill->gpio_shutdown); + if (bcm4329_rfkill->gpio_reset) + gpio_free(bcm4329_rfkill->gpio_reset); + kfree(bcm4329_rfkill); + + return 0; +} + +static struct platform_driver bcm4329_rfkill_driver = { + .probe = bcm4329_rfkill_probe, + .remove = bcm4329_rfkill_remove, + .driver = { + .name = "bcm4329_rfkill", + .owner = THIS_MODULE, + }, +}; + +static int __init bcm4329_rfkill_init(void) +{ + return platform_driver_register(&bcm4329_rfkill_driver); +} + +static void __exit bcm4329_rfkill_exit(void) +{ + platform_driver_unregister(&bcm4329_rfkill_driver); +} + +module_init(bcm4329_rfkill_init); +module_exit(bcm4329_rfkill_exit); + +MODULE_DESCRIPTION("BCM4329 rfkill"); +MODULE_AUTHOR("NVIDIA"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard003/C/0064523_chsys.c b/pool/shard003/C/0064523_chsys.c new file mode 100644 index 0000000000000000000000000000000000000000..82a9e78d6aa8c12989bf0ba3aae421fb5897dc59 --- /dev/null +++ b/pool/shard003/C/0064523_chsys.c @@ -0,0 +1,441 @@ +/* + ChibiOS - Copyright (C) 2006..2016 Giovanni Di Sirio. + + This file is part of ChibiOS. + + ChibiOS 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. + + ChibiOS 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 chsys.c + * @brief System related code. + * + * @addtogroup system + * @details System related APIs and services: + * - Initialization. + * - Locks. + * - Interrupt Handling. + * - Power Management. + * - Abnormal Termination. + * - Realtime counter. + * . + * @{ + */ + +#include "ch.h" + +/*===========================================================================*/ +/* Module exported variables. */ +/*===========================================================================*/ + +#if (CH_CFG_NO_IDLE_THREAD == FALSE) || defined(__DOXYGEN__) +/** + * @brief Idle thread working area. + */ +THD_WORKING_AREA(ch_idle_thread_wa, PORT_IDLE_THREAD_STACK_SIZE); +#endif + +/*===========================================================================*/ +/* Module local types. */ +/*===========================================================================*/ + +/*===========================================================================*/ +/* Module local variables. */ +/*===========================================================================*/ + +/*===========================================================================*/ +/* Module local functions. */ +/*===========================================================================*/ + +#if (CH_CFG_NO_IDLE_THREAD == FALSE) || defined(__DOXYGEN__) +/** + * @brief This function implements the idle thread infinite loop. + * @details The function puts the processor in the lowest power mode capable + * to serve interrupts.
    + * The priority is internally set to the minimum system value so + * that this thread is executed only if there are no other ready + * threads in the system. + * + * @param[in] p the thread parameter, unused in this scenario + */ +static void _idle_thread(void *p) { + + (void)p; + + while (true) { + /*lint -save -e522 [2.2] Apparently no side effects because it contains + an asm instruction.*/ + port_wait_for_interrupt(); + /*lint -restore*/ + CH_CFG_IDLE_LOOP_HOOK(); + } +} +#endif /* CH_CFG_NO_IDLE_THREAD == FALSE */ + +/*===========================================================================*/ +/* Module exported functions. */ +/*===========================================================================*/ + +/** + * @brief ChibiOS/RT initialization. + * @details After executing this function the current instructions stream + * becomes the main thread. + * @pre Interrupts must disabled before invoking this function. + * @post The main thread is created with priority @p NORMALPRIO and + * interrupts are enabled. + * + * @special + */ +void chSysInit(void) { + extern stkalign_t __main_thread_stack_base__; + + _scheduler_init(); + _vt_init(); + +#if CH_DBG_SYSTEM_STATE_CHECK == TRUE + ch.dbg.isr_cnt = (cnt_t)0; + ch.dbg.lock_cnt = (cnt_t)0; +#endif +#if CH_CFG_USE_TM == TRUE + _tm_init(); +#endif +#if CH_CFG_USE_MEMCORE == TRUE + _core_init(); +#endif +#if CH_CFG_USE_HEAP == TRUE + _heap_init(); +#endif +#if CH_DBG_STATISTICS == TRUE + _stats_init(); +#endif +#if CH_DBG_TRACE_MASK != CH_DBG_TRACE_MASK_NONE + _dbg_trace_init(); +#endif + +#if CH_CFG_NO_IDLE_THREAD == FALSE + /* Now this instructions flow becomes the main thread.*/ +#if CH_CFG_USE_REGISTRY == TRUE + currp = _thread_init(&ch.mainthread, (const char *)&ch_debug, NORMALPRIO); +#else + currp = _thread_init(&ch.mainthread, "main", NORMALPRIO); +#endif +#else + /* Now this instructions flow becomes the idle thread.*/ + currp = _thread_init(&ch.mainthread, "idle", IDLEPRIO); +#endif + + /* Setting up the base address of the static main thread stack.*/ + currp->stklimit = &__main_thread_stack_base__; + + /* Setting up the caller as current thread.*/ + currp->state = CH_STATE_CURRENT; + + /* Port layer initialization last because it depend on some of the + initializations performed before.*/ + port_init(); + +#if CH_DBG_STATISTICS == TRUE + /* Starting measurement for this thread.*/ + chTMStartMeasurementX(&currp->stats); +#endif + + /* It is alive now.*/ + chSysEnable(); + +#if CH_CFG_NO_IDLE_THREAD == FALSE + { + static const thread_descriptor_t idle_descriptor = { + "idle", + THD_WORKING_AREA_BASE(ch_idle_thread_wa), + THD_WORKING_AREA_END(ch_idle_thread_wa), + IDLEPRIO, + _idle_thread, + NULL + }; + + /* This thread has the lowest priority in the system, its role is just to + serve interrupts in its context while keeping the lowest energy saving + mode compatible with the system status.*/ + (void) chThdCreate(&idle_descriptor); + } +#endif +} + +/** + * @brief Halts the system. + * @details This function is invoked by the operating system when an + * unrecoverable error is detected, for example because a programming + * error in the application code that triggers an assertion while + * in debug mode. + * @note Can be invoked from any system state. + * + * @param[in] reason pointer to an error string + * + * @special + */ +void chSysHalt(const char *reason) { + + port_disable(); + + /* Halt hook code, usually empty.*/ + CH_CFG_SYSTEM_HALT_HOOK(reason); + + /* Logging the event.*/ + _dbg_trace_halt(reason); + + /* Pointing to the passed message.*/ + ch.dbg.panic_msg = reason; + + /* Harmless infinite loop.*/ + while (true) { + } +} + +/** + * @brief System integrity check. + * @details Performs an integrity check of the important ChibiOS/RT data + * structures. + * @note The appropriate action in case of failure is to halt the system + * before releasing the critical zone. + * @note If the system is corrupted then one possible outcome of this + * function is an exception caused by @p NULL or corrupted pointers + * in list elements. Exception vectors must be monitored as well. + * @note This function is not used internally, it is up to the + * application to define if and where to perform system + * checking. + * @note Performing all tests at once can be a slow operation and can + * degrade the system response time. It is suggested to execute + * one test at time and release the critical zone in between tests. + * + * @param[in] testmask Each bit in this mask is associated to a test to be + * performed. + * @return The test result. + * @retval false The test succeeded. + * @retval true Test failed. + * + * @iclass + */ +bool chSysIntegrityCheckI(unsigned testmask) { + cnt_t n; + + chDbgCheckClassI(); + + /* Ready List integrity check.*/ + if ((testmask & CH_INTEGRITY_RLIST) != 0U) { + thread_t *tp; + + /* Scanning the ready list forward.*/ + n = (cnt_t)0; + tp = ch.rlist.queue.next; + while (tp != (thread_t *)&ch.rlist.queue) { + n++; + tp = tp->next; + } + + /* Scanning the ready list backward.*/ + tp = ch.rlist.queue.prev; + while (tp != (thread_t *)&ch.rlist.queue) { + n--; + tp = tp->prev; + } + + /* The number of elements must match.*/ + if (n != (cnt_t)0) { + return true; + } + } + + /* Timers list integrity check.*/ + if ((testmask & CH_INTEGRITY_VTLIST) != 0U) { + virtual_timer_t * vtp; + + /* Scanning the timers list forward.*/ + n = (cnt_t)0; + vtp = ch.vtlist.next; + while (vtp != (virtual_timer_t *)&ch.vtlist) { + n++; + vtp = vtp->next; + } + + /* Scanning the timers list backward.*/ + vtp = ch.vtlist.prev; + while (vtp != (virtual_timer_t *)&ch.vtlist) { + n--; + vtp = vtp->prev; + } + + /* The number of elements must match.*/ + if (n != (cnt_t)0) { + return true; + } + } + +#if CH_CFG_USE_REGISTRY == TRUE + if ((testmask & CH_INTEGRITY_REGISTRY) != 0U) { + thread_t *tp; + + /* Scanning the ready list forward.*/ + n = (cnt_t)0; + tp = ch.rlist.newer; + while (tp != (thread_t *)&ch.rlist) { + n++; + tp = tp->newer; + } + + /* Scanning the ready list backward.*/ + tp = ch.rlist.older; + while (tp != (thread_t *)&ch.rlist) { + n--; + tp = tp->older; + } + + /* The number of elements must match.*/ + if (n != (cnt_t)0) { + return true; + } + } +#endif /* CH_CFG_USE_REGISTRY == TRUE */ + +#if defined(PORT_INTEGRITY_CHECK) + if ((testmask & CH_INTEGRITY_PORT) != 0U) { + PORT_INTEGRITY_CHECK(); + } +#endif + + return false; +} + +/** + * @brief Handles time ticks for round robin preemption and timer increments. + * @details Decrements the remaining time quantum of the running thread + * and preempts it when the quantum is used up. Increments system + * time and manages the timers. + * @note The frequency of the timer determines the system tick granularity + * and, together with the @p CH_CFG_TIME_QUANTUM macro, the round robin + * interval. + * + * @iclass + */ +void chSysTimerHandlerI(void) { + + chDbgCheckClassI(); + +#if CH_CFG_TIME_QUANTUM > 0 + /* Running thread has not used up quantum yet? */ + if (currp->preempt > (tslices_t)0) { + /* Decrement remaining quantum.*/ + currp->preempt--; + } +#endif +#if CH_DBG_THREADS_PROFILING == TRUE + currp->time++; +#endif + chVTDoTickI(); + CH_CFG_SYSTEM_TICK_HOOK(); +} + +/** + * @brief Returns the execution status and enters a critical zone. + * @details This functions enters into a critical zone and can be called + * from any context. Because its flexibility it is less efficient + * than @p chSysLock() which is preferable when the calling context + * is known. + * @post The system is in a critical zone. + * + * @return The previous system status, the encoding of this + * status word is architecture-dependent and opaque. + * + * @xclass + */ +syssts_t chSysGetStatusAndLockX(void) { + + syssts_t sts = port_get_irq_status(); + if (port_irq_enabled(sts)) { + if (port_is_isr_context()) { + chSysLockFromISR(); + } + else { + chSysLock(); + } + } + return sts; +} + +/** + * @brief Restores the specified execution status and leaves a critical zone. + * @note A call to @p chSchRescheduleS() is automatically performed + * if exiting the critical zone and if not in ISR context. + * + * @param[in] sts the system status to be restored. + * + * @xclass + */ +void chSysRestoreStatusX(syssts_t sts) { + + if (port_irq_enabled(sts)) { + if (port_is_isr_context()) { + chSysUnlockFromISR(); + } + else { + chSchRescheduleS(); + chSysUnlock(); + } + } +} + +#if (PORT_SUPPORTS_RT == TRUE) || defined(__DOXYGEN__) +/** + * @brief Realtime window test. + * @details This function verifies if the current realtime counter value + * lies within the specified range or not. The test takes care + * of the realtime counter wrapping to zero on overflow. + * @note When start==end then the function returns always true because the + * whole time range is specified. + * @note This function is only available if the port layer supports the + * option @p PORT_SUPPORTS_RT. + * + * @param[in] cnt the counter value to be tested + * @param[in] start the start of the time window (inclusive) + * @param[in] end the end of the time window (non inclusive) + * @retval true current time within the specified time window. + * @retval false current time not within the specified time window. + * + * @xclass + */ +bool chSysIsCounterWithinX(rtcnt_t cnt, rtcnt_t start, rtcnt_t end) { + + return (bool)((cnt - start) < (end - start)); +} + +/** + * @brief Polled delay. + * @note The real delay is always few cycles in excess of the specified + * value. + * @note This function is only available if the port layer supports the + * option @p PORT_SUPPORTS_RT. + * + * @param[in] cycles number of cycles + * + * @xclass + */ +void chSysPolledDelayX(rtcnt_t cycles) { + rtcnt_t start = chSysGetRealtimeCounterX(); + rtcnt_t end = start + cycles; + + while (chSysIsCounterWithinX(chSysGetRealtimeCounterX(), start, end)) { + } +} +#endif /* PORT_SUPPORTS_RT == TRUE */ + +/** @} */ diff --git a/pool/shard003/C/0064530_guest.c b/pool/shard003/C/0064530_guest.c new file mode 100644 index 0000000000000000000000000000000000000000..38436150643b4bcfe158ad203db8114cd8690c74 --- /dev/null +++ b/pool/shard003/C/0064530_guest.c @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include "bee.h" +static int conn_status = 0; +int status_cb(void *ctx, int status) +{ + if(status == BEE_CONNECTED){ + printf("connect/subscribe to server\n"); + conn_status = 1; + } + return 0; +} +int connector_callback(void *ctx, char *remote, int cid, int status){ + printf("%d connect success\n", cid); + char *tmp = malloc(64000); + memset(tmp, 'a', 64000); + tmp[63999] = 0; + if(tmp){ + bee_send_data("f835dd1af5f3", -1 , tmp, 64000, SM_MSG_TYPE_RT); + } + return 0; +} + +int main() +{ + bee_user_init(NULL); + bee_set_service("HA-45058956", "0744424235"); + bee_reg_status_cb(status_cb); + bee_guest_mode("kaija.chang@gmail.com", "12345678"); + //bee_guest_mode("kaija.chang@gmail.com", BEE_GUEST_UID); + bee_offline(); + bee_discover_nbr(); + bee_reg_status_cb(status_cb); + bee_reg_sender_cb(connector_callback); + sleep(2); + printf("Connect to 600000751......\n"); + bee_connect("f835dd1af5f3"); + while(1){ + sleep(2); + } + return 0; +} diff --git a/pool/shard003/C/0064546_msp_shared.c b/pool/shard003/C/0064546_msp_shared.c new file mode 100644 index 0000000000000000000000000000000000000000..3177d38f8059794363e4b0ce767a29f7a4f9d47d --- /dev/null +++ b/pool/shard003/C/0064546_msp_shared.c @@ -0,0 +1,243 @@ +/* + * This file is part of Cleanflight and Betaflight. + * + * Cleanflight and Betaflight are free software. You can redistribute + * this software and/or modify this software 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. + * + * Cleanflight and Betaflight are distributed in the hope that they + * 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. + * + * If not, see . + */ + +#include +#include +#include + +#include "platform.h" + +#if defined(USE_MSP_OVER_TELEMETRY) + +#include "build/build_config.h" + +#include "common/utils.h" + +#include "interface/msp.h" + +#include "telemetry/crsf.h" +#include "telemetry/msp_shared.h" +#include "telemetry/smartport.h" + +#define TELEMETRY_MSP_VERSION 1 +#define TELEMETRY_MSP_VER_SHIFT 5 +#define TELEMETRY_MSP_VER_MASK (0x7 << TELEMETRY_MSP_VER_SHIFT) +#define TELEMETRY_MSP_ERROR_FLAG (1 << 5) +#define TELEMETRY_MSP_START_FLAG (1 << 4) +#define TELEMETRY_MSP_SEQ_MASK 0x0F +#define TELEMETRY_MSP_RES_ERROR (-10) + +enum { + TELEMETRY_MSP_VER_MISMATCH=0, + TELEMETRY_MSP_CRC_ERROR=1, + TELEMETRY_MSP_ERROR=2 +}; + +STATIC_UNIT_TESTED uint8_t checksum = 0; +STATIC_UNIT_TESTED mspPackage_t mspPackage; +static mspRxBuffer_t mspRxBuffer; +static mspTxBuffer_t mspTxBuffer; +static mspPacket_t mspRxPacket; +static mspPacket_t mspTxPacket; + +void initSharedMsp(void) +{ + mspPackage.requestBuffer = (uint8_t *)&mspRxBuffer; + mspPackage.requestPacket = &mspRxPacket; + mspPackage.requestPacket->buf.ptr = mspPackage.requestBuffer; + mspPackage.requestPacket->buf.end = mspPackage.requestBuffer; + + mspPackage.responseBuffer = (uint8_t *)&mspTxBuffer; + mspPackage.responsePacket = &mspTxPacket; + mspPackage.responsePacket->buf.ptr = mspPackage.responseBuffer; + mspPackage.responsePacket->buf.end = mspPackage.responseBuffer; +} + +static void processMspPacket(void) +{ + mspPackage.responsePacket->cmd = 0; + mspPackage.responsePacket->result = 0; + mspPackage.responsePacket->buf.end = mspPackage.responseBuffer; + + mspPostProcessFnPtr mspPostProcessFn = NULL; + if (mspFcProcessCommand(mspPackage.requestPacket, mspPackage.responsePacket, &mspPostProcessFn) == MSP_RESULT_ERROR) { + sbufWriteU8(&mspPackage.responsePacket->buf, TELEMETRY_MSP_ERROR); + } + if (mspPostProcessFn) { + mspPostProcessFn(NULL); + } + + sbufSwitchToReader(&mspPackage.responsePacket->buf, mspPackage.responseBuffer); +} + +void sendMspErrorResponse(uint8_t error, int16_t cmd) +{ + mspPackage.responsePacket->cmd = cmd; + mspPackage.responsePacket->result = 0; + mspPackage.responsePacket->buf.end = mspPackage.responseBuffer; + + sbufWriteU8(&mspPackage.responsePacket->buf, error); + mspPackage.responsePacket->result = TELEMETRY_MSP_RES_ERROR; + sbufSwitchToReader(&mspPackage.responsePacket->buf, mspPackage.responseBuffer); +} + +bool handleMspFrame(uint8_t *frameStart, int frameLength) +{ + static uint8_t mspStarted = 0; + static uint8_t lastSeq = 0; + + if (sbufBytesRemaining(&mspPackage.responsePacket->buf) > 0) { + mspStarted = 0; + } + + if (mspStarted == 0) { + initSharedMsp(); + } + + mspPacket_t *packet = mspPackage.requestPacket; + sbuf_t *frameBuf = sbufInit(&mspPackage.requestFrame, frameStart, frameStart + (uint8_t)frameLength); + sbuf_t *rxBuf = &mspPackage.requestPacket->buf; + const uint8_t header = sbufReadU8(frameBuf); + const uint8_t seqNumber = header & TELEMETRY_MSP_SEQ_MASK; + const uint8_t version = (header & TELEMETRY_MSP_VER_MASK) >> TELEMETRY_MSP_VER_SHIFT; + + if (version != TELEMETRY_MSP_VERSION) { + sendMspErrorResponse(TELEMETRY_MSP_VER_MISMATCH, 0); + return true; + } + + if (header & TELEMETRY_MSP_START_FLAG) { + // first packet in sequence + uint8_t mspPayloadSize = sbufReadU8(frameBuf); + + packet->cmd = sbufReadU8(frameBuf); + packet->result = 0; + packet->buf.ptr = mspPackage.requestBuffer; + packet->buf.end = mspPackage.requestBuffer + mspPayloadSize; + + checksum = mspPayloadSize ^ packet->cmd; + mspStarted = 1; + } else if (!mspStarted) { + // no start packet yet, throw this one away + return false; + } else if (((lastSeq + 1) & TELEMETRY_MSP_SEQ_MASK) != seqNumber) { + // packet loss detected! + mspStarted = 0; + return false; + } + + const uint8_t bufferBytesRemaining = sbufBytesRemaining(rxBuf); + const uint8_t frameBytesRemaining = sbufBytesRemaining(frameBuf); + uint8_t payload[frameBytesRemaining]; + + if (bufferBytesRemaining >= frameBytesRemaining) { + sbufReadData(frameBuf, payload, frameBytesRemaining); + sbufAdvance(frameBuf, frameBytesRemaining); + sbufWriteData(rxBuf, payload, frameBytesRemaining); + lastSeq = seqNumber; + + return false; + } else { + sbufReadData(frameBuf, payload, bufferBytesRemaining); + sbufAdvance(frameBuf, bufferBytesRemaining); + sbufWriteData(rxBuf, payload, bufferBytesRemaining); + sbufSwitchToReader(rxBuf, mspPackage.requestBuffer); + while (sbufBytesRemaining(rxBuf)) { + checksum ^= sbufReadU8(rxBuf); + } + + if (checksum != *frameBuf->ptr) { + mspStarted = 0; + sendMspErrorResponse(TELEMETRY_MSP_CRC_ERROR, packet->cmd); + return true; + } + } + + mspStarted = 0; + sbufSwitchToReader(rxBuf, mspPackage.requestBuffer); + processMspPacket(); + return true; +} + +bool sendMspReply(uint8_t payloadSize, mspResponseFnPtr responseFn) +{ + static uint8_t checksum = 0; + static uint8_t seq = 0; + + uint8_t payloadOut[payloadSize]; + sbuf_t payload; + sbuf_t *payloadBuf = sbufInit(&payload, payloadOut, payloadOut + payloadSize); + sbuf_t *txBuf = &mspPackage.responsePacket->buf; + + // detect first reply packet + if (txBuf->ptr == mspPackage.responseBuffer) { + + // header + uint8_t head = TELEMETRY_MSP_START_FLAG | (seq++ & TELEMETRY_MSP_SEQ_MASK); + if (mspPackage.responsePacket->result < 0) { + head |= TELEMETRY_MSP_ERROR_FLAG; + } + sbufWriteU8(payloadBuf, head); + + uint8_t size = sbufBytesRemaining(txBuf); + sbufWriteU8(payloadBuf, size); + } else { + // header + sbufWriteU8(payloadBuf, (seq++ & TELEMETRY_MSP_SEQ_MASK)); + } + + const uint8_t bufferBytesRemaining = sbufBytesRemaining(txBuf); + const uint8_t payloadBytesRemaining = sbufBytesRemaining(payloadBuf); + uint8_t frame[payloadBytesRemaining]; + + if (bufferBytesRemaining >= payloadBytesRemaining) { + + sbufReadData(txBuf, frame, payloadBytesRemaining); + sbufAdvance(txBuf, payloadBytesRemaining); + sbufWriteData(payloadBuf, frame, payloadBytesRemaining); + responseFn(payloadOut); + + return true; + + } else { + + sbufReadData(txBuf, frame, bufferBytesRemaining); + sbufAdvance(txBuf, bufferBytesRemaining); + sbufWriteData(payloadBuf, frame, bufferBytesRemaining); + sbufSwitchToReader(txBuf, mspPackage.responseBuffer); + + checksum = sbufBytesRemaining(txBuf) ^ mspPackage.responsePacket->cmd; + + while (sbufBytesRemaining(txBuf)) { + checksum ^= sbufReadU8(txBuf); + } + sbufWriteU8(payloadBuf, checksum); + + while (sbufBytesRemaining(payloadBuf)>1) { + sbufWriteU8(payloadBuf, 0); + } + + } + + responseFn(payloadOut); + return false; +} + +#endif diff --git a/pool/shard003/C/0064557_main.c b/pool/shard003/C/0064557_main.c new file mode 100644 index 0000000000000000000000000000000000000000..d4b57769f6e9903171d748226db332e80fc9d12b --- /dev/null +++ b/pool/shard003/C/0064557_main.c @@ -0,0 +1,70 @@ +// +// main.c +// Audio Librarian +// +// Created by Cedric Spindler on 29.08.14. +// Copyright (c) 2014 Zedcat. All rights reserved. +// + +#include "main.h" + +int main(int argc, const char * argv[]) +{ + struct gengetopt_args_info args; + struct cmdline_parser_params *params; + params = cmdline_parser_params_create(); + params->initialize = 1; + params->override = 0; + params->check_required = 0; + + if (cmdline_parser_ext(argc, argv, &args, params) != 0) { + exit(EXIT_SUCCESS); + } + + /* initialize setup structure */ + t_alib *setup = (t_alib *)malloc(sizeof(t_alib)); + + /* arg: input file */ + if (args.input_file_given) { + setup->file_name = args.input_file_arg; + } else { + printf("need input file!\n"); + exit(1); + } + + /* arg: target file name */ + if (args.target_given) { + setup->target_file_name = args.target_arg; + } else { + // TODO: use input filename as base to create output filenames + } + + /* arg: ouput directory name */ + setup->output_path = args.output_path_arg; + + /* arg: dry run flag */ + if (args.dry_run_given) setup->dryrun=true; + else setup->dryrun=false; + + /* arg: max/msp progress compatibility flag */ + if (args.max_progress_given) setup->max_progress=true; + else setup->max_progress=false; + + /* arg: tags */ + if (args.tags_given) setup->tags = args.tags_arg; + else setup->tags = NULL; + + init(setup); + + loop(setup); + + alib_free(setup); + + return 0; +} + +void alib_free(t_alib * setup) +{ + free(setup->hop_memory); // here starts the global memory, no need to free other pointers to this part of mem. +} + diff --git a/pool/shard003/C/0064558_CWE400_Resource_Exhaustion__listen_socket_fwrite_53a.c b/pool/shard003/C/0064558_CWE400_Resource_Exhaustion__listen_socket_fwrite_53a.c new file mode 100644 index 0000000000000000000000000000000000000000..a9d5a9da00dad8c4347813fa1cabd54599a5a4c1 --- /dev/null +++ b/pool/shard003/C/0064558_CWE400_Resource_Exhaustion__listen_socket_fwrite_53a.c @@ -0,0 +1,255 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE400_Resource_Exhaustion__listen_socket_fwrite_53a.c +Label Definition File: CWE400_Resource_Exhaustion.label.xml +Template File: sources-sinks-53a.tmpl.c +*/ +/* + * @description + * CWE: 400 Resource Exhaustion + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Assign count to be a relatively small number + * Sinks: fwrite + * GoodSink: Write to a file count number of times, but first validate count + * BadSink : Write to a file count number of times + * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files + * + * */ + +#include "std_testcase.h" + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else +#include +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define LISTEN_BACKLOG 5 +#define CHAR_ARRAY_SIZE (3 * sizeof(count) + 2) + +#define SENTENCE "This is the sentence we are printing to the file. " + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE400_Resource_Exhaustion__listen_socket_fwrite_53b_badSink(int count); + +void CWE400_Resource_Exhaustion__listen_socket_fwrite_53_bad() +{ + int count; + /* Initialize count */ + count = -1; + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + char inputBuffer[CHAR_ARRAY_SIZE]; + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read count using a listen socket */ + listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listenSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = INADDR_ANY; + service.sin_port = htons(TCP_PORT); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed */ + recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* NUL-terminate the string */ + inputBuffer[recvResult] = '\0'; + /* Convert to int */ + count = atoi(inputBuffer); + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + CWE400_Resource_Exhaustion__listen_socket_fwrite_53b_badSink(count); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE400_Resource_Exhaustion__listen_socket_fwrite_53b_goodG2BSink(int count); + +static void goodG2B() +{ + int count; + /* Initialize count */ + count = -1; + /* FIX: Use a relatively small number */ + count = 20; + CWE400_Resource_Exhaustion__listen_socket_fwrite_53b_goodG2BSink(count); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void CWE400_Resource_Exhaustion__listen_socket_fwrite_53b_goodB2GSink(int count); + +static void goodB2G() +{ + int count; + /* Initialize count */ + count = -1; + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + char inputBuffer[CHAR_ARRAY_SIZE]; + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read count using a listen socket */ + listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listenSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = INADDR_ANY; + service.sin_port = htons(TCP_PORT); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed */ + recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* NUL-terminate the string */ + inputBuffer[recvResult] = '\0'; + /* Convert to int */ + count = atoi(inputBuffer); + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + CWE400_Resource_Exhaustion__listen_socket_fwrite_53b_goodB2GSink(count); +} + +void CWE400_Resource_Exhaustion__listen_socket_fwrite_53_good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE400_Resource_Exhaustion__listen_socket_fwrite_53_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE400_Resource_Exhaustion__listen_socket_fwrite_53_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard003/C/0064563_packet.c b/pool/shard003/C/0064563_packet.c new file mode 100644 index 0000000000000000000000000000000000000000..f46288d87ef10f70618c32162a9d5b65184d125d --- /dev/null +++ b/pool/shard003/C/0064563_packet.c @@ -0,0 +1,93 @@ +#include "packet.h" +#include +#include +#include +#include "TWI_slave.h" + +static uint8_t sendBuff[sizeof(struct Packet)]; +static uint8_t recvBuff[sizeof(struct Packet)]; + +static inline uint16_t checksum(struct Packet* packet) { + uint16_t crc = 0xFFFF; + + crc = _crc16_update(crc, packet->type); + crc = _crc16_update(crc, packet->length); + + for(int i = 0; i < packet->length; i++) { + crc = _crc16_update(crc, packet->data[i]); + } + return crc; +} + +void Packet_init(uint8_t id) { + TWI_Slave_Initialise((id << TWI_ADR_BITS) | (TRUE << TWI_GEN_BIT)); + TWI_Start_Transceiver(); +} + +struct Packet ackPack = { + .type = PT_ACK, + .length = 0 +}; + +//packet param is in an undefined state when return value is != 0 +uint8_t Packet_get(struct Packet* packet) { + if(!TWI_Transceiver_Busy()) { + if(TWI_statusReg.lastTransOK) { + if(TWI_statusReg.RxDataInBuf){ + packet->broadcast = TWI_statusReg.genAddressCall ? true : false; + TWI_Get_Data_From_Transceiver(recvBuff, sizeof(uint8_t) * 2); //READ HEADER + packet->type = recvBuff[0]; + packet->length = recvBuff[1]; + + TWI_Get_Data_From_Transceiver(recvBuff, sizeof(uint8_t) * (packet->length + 4)); //READ DATA AND FOOTER + + memcpy(packet->data, recvBuff + 2, packet->length); + + packet->checksum = (recvBuff[packet->length + 2] << 8) | recvBuff[packet->length + 3]; + + if(checksum(packet) != packet->checksum) { + packet->type = PT_NACK; + packet->length = 0; + + Packet_put(packet); + return 10; + } + if(packet->type == PT_NACK){ + TWI_Start_Transceiver_With_Data(sendBuff, 4 + sendBuff[1]); + } + return 0; + } else { + return 1; + } + } else { + if(TWI_statusReg.RxDataInBuf) { + packet->type = PT_NACK; + packet->length = 0; + + Packet_put(packet); + return 10; + } + } + } + return 1; +} + +void Packet_noput() { + TWI_Start_Transceiver(); +} + +void Packet_put(struct Packet* packet) { + packet->checksum = checksum(packet); + + + sendBuff[0] = packet->type; + sendBuff[1] = packet->length; + + memcpy(sendBuff + 2, packet->data, packet->length); + + sendBuff[2 + packet->length] = (packet->checksum >> 8) & 0x00FF; + sendBuff[3 + packet->length] = packet->checksum; + + TWI_Start_Transceiver_With_Data(sendBuff, 4 + packet->length); +} + diff --git a/pool/shard003/C/0064583_color_manager.c b/pool/shard003/C/0064583_color_manager.c new file mode 100644 index 0000000000000000000000000000000000000000..4e6f6223024d5f43326dca260af6249489b8c6e5 --- /dev/null +++ b/pool/shard003/C/0064583_color_manager.c @@ -0,0 +1,145 @@ +/* vifm + * Copyright (C) 2013 xaizek. + * + * 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 "color_manager.h" + +#include + +#include /* assert() */ +#include /* CHAR_BIT */ +#include /* NULL size_t */ +#include /* calloc() */ +#include /* memset() */ + +#include "utils/macros.h" +#include "colors.h" + +static int find_pair(int fg, int bg); +static int color_pair_matches(int pair, int fg, int bg); +static int allocate_pair(int fg, int bg); + +static int get_bit(const char bit_array[], size_t i); +static void set_bit(char bit_array[], size_t i); + +/* Number of color pairs available. */ +static int avail_pairs; +/* Map of allocated color pairs. If element has non-zero value, it means it's + * allocated. */ +static char *color_pair_map; +/* Size of the color_pair_map in chars. */ +static size_t color_pair_map_size; + +void +colmgr_init(int max_color_pairs) +{ + avail_pairs = max_color_pairs - FCOLOR_BASE; + assert(avail_pairs >= 0 && "Too few color pairs available."); + + color_pair_map_size = DIV_ROUND_UP(avail_pairs, CHAR_BIT); + color_pair_map = calloc(color_pair_map_size, 1); + assert((color_pair_map != NULL || avail_pairs == 0) && "Not enough memory."); +} + +void +colmgr_reset(void) +{ + memset(color_pair_map, '\0', color_pair_map_size); +} + +int +colmgr_alloc_pair(int fg, int bg) +{ + const int pair_index = find_pair(fg, bg); + return (pair_index != -1) ? pair_index : allocate_pair(fg, bg); +} + +/* Tries to find pair with specified colors among already allocated pairs. + * Returns -1 when search fails. */ +static int +find_pair(int fg, int bg) +{ + int i; + + for(i = 0; i < DCOLOR_BASE + MAXNUM_COLOR; i++) + { + if(color_pair_matches(i, fg, bg)) + { + return i; + } + } + + for(i = 0; i < avail_pairs; i++) + { + if(get_bit(color_pair_map, i)) + { + if(color_pair_matches(FCOLOR_BASE + i, fg, bg)) + { + break; + } + } + } + return (i < avail_pairs) ? (FCOLOR_BASE + i) : -1; +} + +/* Checks whether color pair number pair has specified foreground (fg) and + * background (bg) colors. */ +static int +color_pair_matches(int pair, int fg, int bg) +{ + short pair_fg, pair_bg; + pair_content(pair, &pair_fg, &pair_bg); + return (pair_fg == fg && pair_bg == bg); +} + +/* Allocates new color pair. Returns new pair index, or -1 on failure. */ +static int +allocate_pair(int fg, int bg) +{ + int i; + for(i = 0; i < avail_pairs; i++) + { + if(!get_bit(color_pair_map, i)) + { + init_pair(FCOLOR_BASE + i, fg, bg); + set_bit(color_pair_map, i); + break; + } + } + return (i < avail_pairs) ? (FCOLOR_BASE + i) : -1; +} + +/* Returns value of the i-th bit in the bit_array. */ +static int +get_bit(const char bit_array[], size_t i) +{ + const size_t index = i/CHAR_BIT; + const size_t offset = i%CHAR_BIT; + return (bit_array[index] >> offset) & 1; +} + +/* Sets value of the i-th bit in the bit_array. */ +static void +set_bit(char bit_array[], size_t i) +{ + const size_t index = i/CHAR_BIT; + const size_t offset = i%CHAR_BIT; + bit_array[index] |= 1 << offset; +} + +/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 noexpandtab cinoptions-=(0 : */ +/* vim: set cinoptions+=t0 : */ diff --git a/pool/shard003/C/0064587_mystack.c b/pool/shard003/C/0064587_mystack.c new file mode 100644 index 0000000000000000000000000000000000000000..f72dbe00edce8baf9b25c1a01f2c00c3830f906a --- /dev/null +++ b/pool/shard003/C/0064587_mystack.c @@ -0,0 +1,129 @@ +#include +#include +#include + +typedef struct _MyStack +{ + void **data; + size_t cap; + size_t size; +} MyStack; + +// Create a new stack +MyStack *stack_new(size_t cap) +{ + if (cap <= 0) return NULL; + MyStack *s = (MyStack *)malloc(sizeof(MyStack)); + s->cap = cap; + s->size = 0; + s->data = (void **)malloc(s->cap * sizeof(void *)); + return s; +} + +// Push x into the stack +void stack_push(MyStack *s, void *x) +{ + if (s->size == s->cap) + { + s->cap *= 2; + s->data = (void **)realloc(s->data, s->cap * sizeof(void *)); + } + s->data[s->size] = x; + ++s->size; +} + +// Get the pointer of the value indexed i from the stack +void **stack_get(MyStack *s, size_t i) +{ + return s->data + i; +} + +// Remove the top element +void stack_pop(MyStack *s) +{ + --s->size; +} + +// Remove the top element and free it +void stack_pop_and_free(MyStack *s) +{ + --s->size; + free(s->data[s->size]); +} + +// Get the pointer of the value in the stack top +void **stack_top(MyStack *s) +{ + return s->data + s->size - 1; +} + +// Get the size of the stack +size_t stack_size(MyStack *s) +{ + return s->size; +} + +// Get the capacity of the stack +size_t stack_capacity(MyStack *s) +{ + return s->cap; +} + +void **stack_begin(MyStack *s) +{ + return s->data; +} + +void **stack_end(MyStack *s) +{ + return s->data + s->size; +} + +// Delete the stack preserving the values +void stack_free(MyStack *s) +{ + free(s->data); + s->data = NULL; + free(s); + s = NULL; +} + +// Delete the stack and its values +void stack_deepfree(MyStack *s) +{ + for (size_t i = 0; i < s->size; ++i) + { + free(s->data[i]); + s->data[i] = NULL; + } + free(s->data); + s->data = NULL; + free(s); + s = NULL; +} + +int main() +{ + for (;;) + { + MyStack *a = stack_new(8); + int n = 10000; + for (int i = 0; i < n; ++i) + { + int *x = (int *)malloc(sizeof(int)); + *x = i; + stack_push(a, (void *)x); + } + while (stack_size(a) > 0) + { + int *x = (int *)(*(stack_top(a))); + stack_pop_and_free(a); + //printf("%d ", *x); + } + //printf(".\n"); + + stack_deepfree(a); + a = NULL; + } + return 0; +} \ No newline at end of file diff --git a/pool/shard003/C/0064590_uartecho.c b/pool/shard003/C/0064590_uartecho.c new file mode 100644 index 0000000000000000000000000000000000000000..bf12feced22895522193f124aef38410d556856e --- /dev/null +++ b/pool/shard003/C/0064590_uartecho.c @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2015, Texas Instruments Incorporated + * 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 Texas Instruments Incorporated 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. + */ + +/* + * ======== uartecho.c ======== + */ + +/* XDCtools Header files */ +#include +#include + +/* BIOS Header files */ +#include +#include + +/* TI-RTOS Header files */ +#include +#include + +/* Example/Board Header files */ +#include "Board.h" + +#include + +#define TASKSTACKSIZE 768 + +Task_Struct task0Struct; +Char task0Stack[TASKSTACKSIZE]; + + UART_Handle uartPC; + UART_Handle uartGSM; + UART_Handle uartXBEE; + + void pcReadUARTCallback(UART_Handle handle, void *buf, size_t count) { + if (count != UART_ERROR) { + // Write the data to the GSM + UART_write(uartGSM, buf, count); + // Write the data to the PC too + UART_write(uartPC, buf, count); + // Write the data to the PC too + UART_write(uartXBEE, buf, count); + } + } + + void pcWriteUARTCallback(UART_Handle handle, void *buf, size_t count) { + // Empty! + } + + void gsmReadUARTCallback(UART_Handle handle, void *buf, size_t count) { + if (count != UART_ERROR) { + // Write the data to the GSM + UART_write(uartPC, buf, count); + } + } + + void gsmWriteUARTCallback(UART_Handle handle, void *buf, size_t count) { + // Empty! + } + + void xbeeReadUARTCallback(UART_Handle handle, void *buf, size_t count) { + if (count != UART_ERROR) { + // Write the data to the GSM + UART_write(uartPC, buf, count); + } + } + + void xbeeWriteUARTCallback(UART_Handle handle, void *buf, size_t count) { + // Empty! + } + + /* + * ======== echoFxn ======== + * Task for this function is created statically. See the project's .cfg file. + */ + Void echoFxn(UArg arg0, UArg arg1) + { + char input; + UART_Params uartPCParams; + UART_Params uartGSMParams; + UART_Params uartXBEEParams; + + const char echoPrompt[] = "\fEchoing characters:\r\n"; + + // Create a UART for PC + UART_Params_init(&uartPCParams); + uartPCParams.readMode = UART_MODE_CALLBACK; + uartPCParams.writeMode = UART_MODE_CALLBACK; + uartPCParams.readCallback = &pcReadUARTCallback; + uartPCParams.writeCallback = &pcWriteUARTCallback; + uartPCParams.writeDataMode = UART_DATA_BINARY; + uartPCParams.readDataMode = UART_DATA_BINARY; + uartPCParams.readReturnMode = UART_RETURN_NEWLINE; + uartPCParams.readEcho = UART_ECHO_OFF; + uartPCParams.baudRate = 115200; + uartPC = UART_open(Board_UART0, &uartPCParams); + + if (uartPC == NULL) { + System_abort("Error opening the UART"); + } + + + // Create a UART for GSM + UART_Params_init(&uartGSMParams); + uartGSMParams.readMode = UART_MODE_CALLBACK; + uartGSMParams.writeMode = UART_MODE_CALLBACK; + uartGSMParams.readCallback = &gsmReadUARTCallback; + uartGSMParams.writeCallback = &gsmWriteUARTCallback; + uartGSMParams.writeDataMode = UART_DATA_BINARY; + uartGSMParams.readDataMode = UART_DATA_BINARY; + uartGSMParams.readReturnMode = UART_RETURN_NEWLINE; + uartGSMParams.baudRate = 115200; + uartGSM = UART_open(Board_UART1, &uartGSMParams); + + if (uartGSM == NULL) { + System_abort("Error opening the GSM UART"); + } + + // Create a UART for GSM + UART_Params_init(&uartXBEEParams); + + uartXBEEParams.readMode = UART_MODE_CALLBACK; + uartXBEEParams.writeMode = UART_MODE_CALLBACK; + uartXBEEParams.readCallback = &xbeeReadUARTCallback; + uartXBEEParams.writeCallback = &xbeeWriteUARTCallback; + uartXBEEParams.writeDataMode = UART_DATA_BINARY; + uartXBEEParams.readDataMode = UART_DATA_BINARY; + uartXBEEParams.readReturnMode = UART_RETURN_NEWLINE; + uartXBEEParams.baudRate = 115200; + uartXBEE = UART_open(Board_UART3, &uartXBEEParams); + + if (uartXBEE == NULL) { + System_abort("Error opening the GSM UART"); + } + + UART_write(uartPC, echoPrompt, sizeof(echoPrompt)); + + + while (1) { + + // Read from all the UARTS + UART_read(uartPC, &input, 1); + UART_read(uartGSM, &input, 1); + UART_read(uartXBEE, &input, 1); + + + } + } + +/* + * ======== main ======== + */ +int main(void) +{ + /* Call board init functions */ + Board_initGeneral(); + Board_initGPIO(); + Board_initUART(); + + /* Construct BIOS objects */ + Task_Params taskParams; + + Task_Params_init(&taskParams); + taskParams.stackSize = TASKSTACKSIZE; + taskParams.stack = &task0Stack; + taskParams.instance->name = "echo"; + Task_construct(&task0Struct, (Task_FuncPtr)echoFxn, &taskParams, NULL); + + /* Turn on user LED */ + GPIO_write(Board_LED0, Board_LED_ON); + + + /* Start BIOS */ + BIOS_start(); + + return (0); +} diff --git a/pool/shard003/C/0064597_packet-turnchannel.c b/pool/shard003/C/0064597_packet-turnchannel.c new file mode 100644 index 0000000000000000000000000000000000000000..e15a2895fc5394a06e021c1fe55ace889e8af610 --- /dev/null +++ b/pool/shard003/C/0064597_packet-turnchannel.c @@ -0,0 +1,226 @@ +/* packet-turnchannel.c + * Routines for TURN channel dissection (TURN negociation is handled + * in the STUN2 dissector + * Copyright 2008, 8x8 Inc. + * + * $Id$ + * + * 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. + * + * Please refer to the following specs for protocol detail: + * - draft-ietf-behave-rfc3489bis-15 + * - draft-ietf-mmusic-ice-19 + * - draft-ietf-behave-nat-behavior-discovery-03 + * - draft-ietf-behave-turn-07 + * - draft-ietf-behave-turn-ipv6-03 + */ + +#include "config.h" + +#include + +#include +#include + +/* heuristic subdissectors */ +static heur_dissector_list_t heur_subdissector_list; + +/* data dissector handle */ +static dissector_handle_t data_handle; + +/* Initialize the protocol and registered fields */ +static int proto_turnchannel = -1; + +static int hf_turnchannel_id = -1; +static int hf_turnchannel_len = -1; + +#define TURNCHANNEL_HDR_LEN ((guint)4) + + +/* Initialize the subtree pointers */ +static gint ett_turnchannel = -1; + +static int +dissect_turnchannel_message(tvbuff_t *tvb, packet_info *pinfo, + proto_tree *tree, void *data _U_) +{ + guint len; + guint16 channel_id; + guint16 data_len; + proto_item *ti; + proto_tree *turnchannel_tree; + + len = tvb_length(tvb); + /* First, make sure we have enough data to do the check. */ + if (len < TURNCHANNEL_HDR_LEN) { + return 0; + } + + channel_id = tvb_get_ntohs(tvb, 0); + data_len = tvb_get_ntohs(tvb, 2); + + if ((channel_id < 0x4000) || (channel_id > 0xFFFE)) { + return 0; + } + + if (len != TURNCHANNEL_HDR_LEN + data_len) { + return 0; + } + + /* Seems to be a decent TURN channel message */ + col_set_str(pinfo->cinfo, COL_PROTOCOL, "TURN CHANNEL"); + + if (check_col(pinfo->cinfo, COL_INFO)) + col_add_fstr(pinfo->cinfo, COL_INFO, "Channel Id 0x%x", channel_id); + + ti = proto_tree_add_item(tree, proto_turnchannel, tvb, 0, -1, ENC_NA); + + turnchannel_tree = proto_item_add_subtree(ti, ett_turnchannel); + + proto_tree_add_uint(turnchannel_tree, hf_turnchannel_id, tvb, 0, 2, channel_id); + proto_tree_add_uint(turnchannel_tree, hf_turnchannel_len, tvb, 2, 2, data_len); + + + if (len > TURNCHANNEL_HDR_LEN) { + tvbuff_t *next_tvb; + guint reported_len, new_len; + + new_len = tvb_length_remaining(tvb, TURNCHANNEL_HDR_LEN); + reported_len = tvb_reported_length_remaining(tvb, + TURNCHANNEL_HDR_LEN); + if (data_len < reported_len) { + reported_len = data_len; + } + next_tvb = tvb_new_subset(tvb, TURNCHANNEL_HDR_LEN, new_len, + reported_len); + + + if (!dissector_try_heuristic(heur_subdissector_list, + next_tvb, pinfo, tree, NULL)) { + call_dissector(data_handle,next_tvb, pinfo, tree); + } + } + + return tvb_length(tvb); +} + + +static void +dissect_turnchannel_message_no_return(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) +{ + dissect_turnchannel_message(tvb, pinfo, tree, NULL); +} + + +static guint +get_turnchannel_message_len(packet_info *pinfo _U_, tvbuff_t *tvb, int offset) +{ + return (guint)tvb_get_ntohs(tvb, offset+2) + TURNCHANNEL_HDR_LEN; +} + +static void +dissect_turnchannel_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) +{ + tcp_dissect_pdus(tvb, pinfo, tree, TRUE, TURNCHANNEL_HDR_LEN, + get_turnchannel_message_len, dissect_turnchannel_message_no_return); +} + + +static gboolean +dissect_turnchannel_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) +{ + guint len; + guint16 channel_id; + guint16 data_len; + + len = tvb_length(tvb); + /* First, make sure we have enough data to do the check. */ + if (len < TURNCHANNEL_HDR_LEN) { + return FALSE; + } + + channel_id = tvb_get_ntohs(tvb, 0); + data_len = tvb_get_ntohs(tvb, 2); + + if ((channel_id < 0x4000) || (channel_id > 0xFFFE)) { + return FALSE; + } + + if (len != TURNCHANNEL_HDR_LEN + data_len) { + return FALSE; + } + + return dissect_turnchannel_message(tvb, pinfo, tree, NULL); +} + +void +proto_register_turnchannel(void) +{ + static hf_register_info hf[] = { + { &hf_turnchannel_id, + { "TURN Channel ID", "turnchannel.id", FT_UINT16, + BASE_HEX, NULL, 0x0, NULL, HFILL } + }, + { &hf_turnchannel_len, + { "Data Length", "turnchannel.length", FT_UINT16, + BASE_DEC, NULL, 0x0, NULL, HFILL } + }, + }; + +/* Setup protocol subtree array */ + static gint *ett[] = { + &ett_turnchannel, + }; + +/* Register the protocol name and description */ + proto_turnchannel = proto_register_protocol("TURN Channel", + "TURNCHANNEL", "turnchannel"); + + new_register_dissector("turnchannel", dissect_turnchannel_message, + proto_turnchannel); + +/* subdissectors */ + register_heur_dissector_list("turnchannel", &heur_subdissector_list); + +/* Required function calls to register the header fields and subtrees used */ + proto_register_field_array(proto_turnchannel, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); + +} + + +void +proto_reg_handoff_turnchannel(void) +{ + dissector_handle_t turnchannel_tcp_handle; + dissector_handle_t turnchannel_udp_handle; + + turnchannel_tcp_handle = create_dissector_handle(dissect_turnchannel_tcp, proto_turnchannel); + turnchannel_udp_handle = find_dissector("turnchannel"); + + /* Used for "Decode As" in case STUN negotiation isn't captured */ + dissector_add_handle("tcp.port", turnchannel_tcp_handle); + dissector_add_handle("udp.port", turnchannel_udp_handle); + + /* TURN negoiation is handled through STUN2 dissector (packet-stun.c), + so only it should be able to determine if a packet is a TURN packet */ + heur_dissector_add("stun", dissect_turnchannel_heur, proto_turnchannel); + + data_handle = find_dissector("data"); +} diff --git a/pool/shard003/C/0064614_arvgcconverternode.c b/pool/shard003/C/0064614_arvgcconverternode.c new file mode 100644 index 0000000000000000000000000000000000000000..cd35e14273f38912f8778eaa32886c167ef4a7ce --- /dev/null +++ b/pool/shard003/C/0064614_arvgcconverternode.c @@ -0,0 +1,182 @@ +/* Aravis - Digital camera library + * + * Copyright © 2009-2019 Emmanuel Pacaud + * + * 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, write to the + * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + * Author: Emmanuel Pacaud + */ + +/** + * SECTION: arvgcconverternode + * @short_description: Converter node class + */ + +#include +#include +#include +#include +#include + +struct _ArvGcConverterNode { + ArvGcConverter converter; +}; + +struct _ArvGcConverterNodeClass { + ArvGcConverterClass parent_class; +}; + +static const char * +arv_gc_converter_node_get_node_name (ArvDomNode *node) +{ + return "Converter"; +} + +ArvGcNode * +arv_gc_converter_node_new (void) +{ + return g_object_new (ARV_TYPE_GC_CONVERTER_NODE, NULL); +} + +static void +arv_gc_converter_node_init (ArvGcConverterNode *gc_converter_node) +{ +} + +static void +arv_gc_converter_node_class_init (ArvGcConverterNodeClass *this_class) +{ + ArvDomNodeClass *dom_node_class = ARV_DOM_NODE_CLASS (this_class); + + dom_node_class->get_node_name = arv_gc_converter_node_get_node_name; +} + +static double +arv_gc_converter_get_float_value (ArvGcFloat *gc_float, GError **error) +{ + return arv_gc_converter_convert_to_double (ARV_GC_CONVERTER (gc_float), ARV_GC_CONVERTER_NODE_TYPE_VALUE, error); +} + +static double +arv_gc_converter_get_float_min (ArvGcFloat *gc_float, GError **error) +{ + GError *local_error = NULL; + double a, b; + + /* TODO: we should use the Slope node here, instead of using MIN (min, max) */ + + a = arv_gc_converter_convert_to_double (ARV_GC_CONVERTER (gc_float), ARV_GC_CONVERTER_NODE_TYPE_MIN, &local_error); + if (local_error != NULL) { + g_propagate_error (error, local_error); + return -G_MAXDOUBLE; + } + + b = arv_gc_converter_convert_to_double (ARV_GC_CONVERTER (gc_float), ARV_GC_CONVERTER_NODE_TYPE_MAX, &local_error); + if (local_error != NULL) { + g_propagate_error (error, local_error); + return -G_MAXDOUBLE; + } + + return MIN (a, b); +} + +static double +arv_gc_converter_get_float_max (ArvGcFloat *gc_float, GError **error) +{ + GError *local_error = NULL; + double a, b; + + /* TODO: we should use the Slope node here, instead of using MAX (min, max) */ + + a = arv_gc_converter_convert_to_double (ARV_GC_CONVERTER (gc_float), ARV_GC_CONVERTER_NODE_TYPE_MIN, &local_error); + if (local_error != NULL) { + g_propagate_error (error, local_error); + return G_MAXDOUBLE; + } + + b = arv_gc_converter_convert_to_double (ARV_GC_CONVERTER (gc_float), ARV_GC_CONVERTER_NODE_TYPE_MAX, &local_error); + if (local_error != NULL) { + g_propagate_error (error, local_error); + return G_MAXDOUBLE; + } + + return MAX (a, b); +} + +static double +_get_inc (ArvGcFloat *gc_float, GError **error) +{ + GError *local_error = NULL; + ArvGcIsLinear is_linear; + + is_linear = arv_gc_converter_get_is_linear (ARV_GC_CONVERTER (gc_float), &local_error); + if (local_error != NULL) { + g_propagate_error (error, local_error); + return G_MINDOUBLE; + } + + if (is_linear == ARV_GC_IS_LINEAR_NO) + return G_MINDOUBLE; + + return arv_gc_converter_convert_to_double (ARV_GC_CONVERTER (gc_float), ARV_GC_CONVERTER_NODE_TYPE_INC, &local_error); +} + +static ArvGcRepresentation +arv_gc_converter_get_float_representation (ArvGcFloat *gc_float) +{ + return arv_gc_converter_get_representation (ARV_GC_CONVERTER (gc_float)); +} + +static const char * +arv_gc_converter_get_float_unit (ArvGcFloat *gc_float) +{ + return arv_gc_converter_get_unit (ARV_GC_CONVERTER (gc_float)); +} + +static ArvGcDisplayNotation +arv_gc_converter_get_float_display_notation (ArvGcFloat *gc_float) +{ + return arv_gc_converter_get_display_notation (ARV_GC_CONVERTER (gc_float)); +} + +static gint64 +arv_gc_converter_get_float_display_precision (ArvGcFloat *gc_float) +{ + return arv_gc_converter_get_display_precision (ARV_GC_CONVERTER (gc_float)); +} + +static void +arv_gc_converter_set_float_value (ArvGcFloat *gc_float, double value, GError **error) +{ + arv_gc_converter_convert_from_double (ARV_GC_CONVERTER (gc_float), value, error); +} + +static void +arv_gc_converter_node_float_interface_init (ArvGcFloatInterface *interface) +{ + interface->get_value = arv_gc_converter_get_float_value; + interface->get_min = arv_gc_converter_get_float_min; + interface->get_max = arv_gc_converter_get_float_max; + interface->get_inc = _get_inc; + interface->set_value = arv_gc_converter_set_float_value; + interface->get_representation = arv_gc_converter_get_float_representation; + interface->get_unit = arv_gc_converter_get_float_unit; + interface->get_display_notation = arv_gc_converter_get_float_display_notation; + interface->get_display_precision = arv_gc_converter_get_float_display_precision; +} + +G_DEFINE_TYPE_WITH_CODE (ArvGcConverterNode, arv_gc_converter_node, ARV_TYPE_GC_CONVERTER, + G_IMPLEMENT_INTERFACE (ARV_TYPE_GC_FLOAT, arv_gc_converter_node_float_interface_init)) diff --git a/pool/shard003/C/0064628_simpleStackBuffer.c b/pool/shard003/C/0064628_simpleStackBuffer.c new file mode 100644 index 0000000000000000000000000000000000000000..6d06dc8fafeab92ac8b02607b3dc03413d2beaa9 --- /dev/null +++ b/pool/shard003/C/0064628_simpleStackBuffer.c @@ -0,0 +1,51 @@ +#define BUFFER_SIZE 1024 + +typedef struct buffer { + char data[BUFFER_SIZE]; + int len; + int start; +} BUF; + +void printBuffer(BUF *buffer) { + int i; + for(i = 0; i < 20; i++) { + printf("%d: 0x%x | ", i, buffer->data[i]); + } + printf("\n"); + printf("Buffer len: %d\n", buffer->len); + printf("Buffer start: %d\n", buffer->start); +} + +BUF *newBuffer() { + BUF *buffer; + buffer = malloc(sizeof(BUF)); + buffer->len = 0; + buffer->start = 0; + buffer->checksum = 0; + return buffer; +} + +void pushBufferByte(BUF *buffer, char c) { + //printf("Pushing byte: 0x%x\n", c); + buffer->data[buffer->len] = c; + buffer->len++; +} + +void bufferIndex(BUF *buffer, int index, char c) { + buffer->data[index] = c; +} + +void pushBuffer(BUF *buffer, char *c, int length) { + sprintf(&(buffer->data[buffer->len]), "%s", c); + buffer->len += length; +} + +int popBuffer(BUF *buffer, char *c) { + if(buffer->start == buffer->len) { + printf("Nothing left to pop\n"); + return -1; + } + *c = buffer->data[buffer->start]; + buffer->start++; + return 1; +} diff --git a/pool/shard003/C/0064630_bug-iconv5.c b/pool/shard003/C/0064630_bug-iconv5.c new file mode 100644 index 0000000000000000000000000000000000000000..1b9f50f58af0ec207e73341344a9be00d27032a1 --- /dev/null +++ b/pool/shard003/C/0064630_bug-iconv5.c @@ -0,0 +1,53 @@ +#include +#include +#include + + +static int +do_test (void) +{ + iconv_t cd = iconv_open ("utf-8", "unicode"); + if (cd == (iconv_t) -1) + { + puts ("cannot open iconv module"); + return 1; + } + + static const uint16_t us[] = { 0xfeff, 0x0041, 0x0042, 0x0043 }; + char buf[100]; + + char *inbuf; + size_t inlen; + char *outbuf; + size_t outlen; + size_t n; + + inbuf = (char *) us; + inlen = sizeof (us); + outbuf = buf; + outlen = sizeof (buf); + n = iconv (cd, &inbuf, &inlen, &outbuf, &outlen); + if (n == (size_t) -1 || inlen != 0 || outlen != sizeof (buf) - 3) + { + puts ("first conversion failed"); + return 1; + } + + iconv (cd, NULL, NULL, NULL, NULL); + + inbuf = (char *) us; + inlen = sizeof (us); + outbuf = buf; + outlen = sizeof (buf); + n = iconv (cd, &inbuf, &inlen, &outbuf, &outlen); + if (n == (size_t) -1 || inlen != 0 || outlen != sizeof (buf) - 3) + { + puts ("second conversion failed"); + return 1; + } + + return 0; +} + +#define TEST_FUNCTION do_test () +#include "../test-skeleton.c" diff --git a/pool/shard003/C/0064641_145.c b/pool/shard003/C/0064641_145.c new file mode 100644 index 0000000000000000000000000000000000000000..ea8c09bbeaf5adbbb5c388393a26eea8ed1ba440 --- /dev/null +++ b/pool/shard003/C/0064641_145.c @@ -0,0 +1,39 @@ +#include +#include + +int reverse( int n ) { + int i; + i = 0; + while ( n ) { + i *= 10; + i += n % 10; + n /= 10; + } + return i; +} + +char hasOdd( int n ) { + while ( n ) { + if ( ( n % 10 ) % 2 == 0 ) { + return 0; + } + n /= 10; + } + return 1; +} + +int main() { + const int N = 1000000000; + int i, ri, ans; + + ans = 0; + for ( i = 1; i < N; ++i ) { + ri = reverse( i ); + if ( hasOdd( i + ri ) && ( int )log10( i ) == ( int )log10( ri ) ) { + ++ans; + } + } + printf( "%d\n", ans ); + + return 0; +} diff --git a/pool/shard003/C/0064648_regmap-i2c.c b/pool/shard003/C/0064648_regmap-i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..ef436236c7cb0f47697294915a9b00c63e92de64 --- /dev/null +++ b/pool/shard003/C/0064648_regmap-i2c.c @@ -0,0 +1,109 @@ +/* + * Register map access API - I2C support + * + * Copyright 2011 Wolfson Microelectronics plc + * + * Author: Mark Brown + * + * 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 + +static int regmap_i2c_write(struct device *dev, const void *data, size_t count) +{ + struct i2c_client *i2c = to_i2c_client(dev); + int ret; + + ret = i2c_master_send(i2c, data, count); + if (ret == count) + return 0; + else if (ret < 0) + return ret; + else + return -EIO; +} + +static int regmap_i2c_gather_write(struct device *dev, + const void *reg, size_t reg_size, + const void *val, size_t val_size) +{ + struct i2c_client *i2c = to_i2c_client(dev); + struct i2c_msg xfer[2]; + int ret; + + if (!i2c_check_functionality(i2c->adapter, I2C_FUNC_PROTOCOL_MANGLING)) + return -ENOTSUPP; + + xfer[0].addr = i2c->addr; + xfer[0].flags = 0; + xfer[0].len = reg_size; + xfer[0].buf = (void *)reg; + + xfer[1].addr = i2c->addr; + xfer[1].flags = I2C_M_NOSTART; + xfer[1].len = val_size; + xfer[1].buf = (void *)val; + + ret = i2c_transfer(i2c->adapter, xfer, 2); + if (ret == 2) + return 0; + if (ret < 0) + return ret; + else + return -EIO; +} + +static int regmap_i2c_read(struct device *dev, + const void *reg, size_t reg_size, + void *val, size_t val_size) +{ + struct i2c_client *i2c = to_i2c_client(dev); + struct i2c_msg xfer[2]; + int ret; + + xfer[0].addr = i2c->addr; + xfer[0].flags = 0; + xfer[0].len = reg_size; + xfer[0].buf = (void *)reg; + + xfer[1].addr = i2c->addr; + xfer[1].flags = I2C_M_RD; + xfer[1].len = val_size; + xfer[1].buf = val; + + ret = i2c_transfer(i2c->adapter, xfer, 2); + if (ret == 2) + return 0; + else if (ret < 0) + return ret; + else + return -EIO; +} + +static struct regmap_bus regmap_i2c = { + .write = regmap_i2c_write, + .gather_write = regmap_i2c_gather_write, + .read = regmap_i2c_read, +}; + +struct regmap *regmap_init_i2c(struct i2c_client *i2c, + const struct regmap_config *config) +{ + return regmap_init(&i2c->dev, ®map_i2c, config); +} +EXPORT_SYMBOL_GPL(regmap_init_i2c); + +struct regmap *devm_regmap_init_i2c(struct i2c_client *i2c, + const struct regmap_config *config) +{ + return devm_regmap_init(&i2c->dev, ®map_i2c, config); +} +EXPORT_SYMBOL_GPL(devm_regmap_init_i2c); + +MODULE_LICENSE("GPL"); diff --git a/pool/shard003/C/0064654_mkdtemp.c b/pool/shard003/C/0064654_mkdtemp.c new file mode 100644 index 0000000000000000000000000000000000000000..715d56d1dda7e96d6358db65bbe537af47835e30 --- /dev/null +++ b/pool/shard003/C/0064654_mkdtemp.c @@ -0,0 +1,55 @@ +/* Copyright (c) 2018, 2021, 2022 Dennis Wölfing + * + * 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. + */ + +/* libc/src/stdlib/mkdtemp.c + * Create a temporary directory. (POSIX2008) + */ + +#define arc4random_buf __arc4random_buf +#include +#include +#include +#include +#include + +static const char* letters = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + +char* mkdtemp(char* template) { + size_t length = strlen(template); + if (length < 6) { + errno = EINVAL; + return NULL; + } + + char* xtemplate = template + length - 6; + if (strcmp(xtemplate, "XXXXXX") != 0) { + errno = EINVAL; + return NULL; + } + + do { + uint64_t value; + arc4random_buf(&value, sizeof(value)); + for (size_t i = 0; i < 6; i++) { + xtemplate[i] = letters[value % 64]; + value /= 64; + } + + if (mkdir(template, 0700) == 0) return template; + } while (errno == EEXIST); + + return NULL; +} diff --git a/pool/shard003/C/0064658_element_80211_directsequencecontrol.c b/pool/shard003/C/0064658_element_80211_directsequencecontrol.c new file mode 100644 index 0000000000000000000000000000000000000000..bf53db47134b7e99136c7ba81f5c97f1fb6f2f97 --- /dev/null +++ b/pool/shard003/C/0064658_element_80211_directsequencecontrol.c @@ -0,0 +1,88 @@ +#include "capwap.h" +#include "element.h" + +/******************************************************************** + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Radio ID | Reserved | Current Chan | Current CCA | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Energy Detect Threshold | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +Type: 1028 for IEEE 802.11 Direct Sequence Control + +Length: 8 + +********************************************************************/ + +/* */ +static void capwap_80211_directsequencecontrol_element_create(void* data, capwap_message_elements_handle handle, struct capwap_write_message_elements_ops* func) { + struct capwap_80211_directsequencecontrol_element* element = (struct capwap_80211_directsequencecontrol_element*)data; + + ASSERT(data != NULL); + ASSERT(IS_VALID_RADIOID(element->radioid)); + + /* */ + func->write_u8(handle, element->radioid); + func->write_u8(handle, 0); + func->write_u8(handle, element->currentchannel); + func->write_u8(handle, element->currentcca); + func->write_u32(handle, element->enerydetectthreshold); +} + +/* */ +static void* capwap_80211_directsequencecontrol_element_clone(void* data) { + ASSERT(data != NULL); + + return capwap_clone(data, sizeof(struct capwap_80211_directsequencecontrol_element)); +} + +/* */ +static void capwap_80211_directsequencecontrol_element_free(void* data) { + ASSERT(data != NULL); + + capwap_free(data); +} + +/* */ +static void* capwap_80211_directsequencecontrol_element_parsing(capwap_message_elements_handle handle, struct capwap_read_message_elements_ops* func) { + struct capwap_80211_directsequencecontrol_element* data; + + ASSERT(handle != NULL); + ASSERT(func != NULL); + + if (func->read_ready(handle) != 8) { + log_printf(LOG_DEBUG, "Invalid IEEE 802.11 Direct Sequence Control element"); + return NULL; + } + + /* */ + data = (struct capwap_80211_directsequencecontrol_element*)capwap_alloc(sizeof(struct capwap_80211_directsequencecontrol_element)); + memset(data, 0, sizeof(struct capwap_80211_directsequencecontrol_element)); + + /* Retrieve data */ + func->read_u8(handle, &data->radioid); + if (!IS_VALID_RADIOID(data->radioid)) { + capwap_80211_directsequencecontrol_element_free((void*)data); + log_printf(LOG_DEBUG, "Invalid IEEE 802.11 Direct Sequence Control element: invalid radio"); + return NULL; + } + + func->read_u8(handle, NULL); + func->read_u8(handle, &data->currentchannel); + func->read_u8(handle, &data->currentcca); + func->read_u32(handle, &data->enerydetectthreshold); + + return data; +} + +/* */ +const struct capwap_message_elements_ops capwap_element_80211_directsequencecontrol_ops = { + .category = CAPWAP_MESSAGE_ELEMENT_ARRAY, + .create = capwap_80211_directsequencecontrol_element_create, + .parse = capwap_80211_directsequencecontrol_element_parsing, + .clone = capwap_80211_directsequencecontrol_element_clone, + .free = capwap_80211_directsequencecontrol_element_free +}; diff --git a/pool/shard003/C/0064668_bond.c b/pool/shard003/C/0064668_bond.c new file mode 100644 index 0000000000000000000000000000000000000000..00ed1e3daeaf161457cd7a8cfc3d9b541e68074b --- /dev/null +++ b/pool/shard003/C/0064668_bond.c @@ -0,0 +1,99 @@ +/***************************************************************************** + +* File Name: Bond.c + +* Author: Ludvig Sundström + +* Description: Defines a bond, which is a relation between two vertices. + +* Creation Date: 28-07-2015 + +*****************************************************************************/ + +#include +#include +#include + +#include "util.h" +#include "constants.h" +#include "bond.h" + +double g_watr; + +Bond Bond_initialize( + const VertexPointer fst, + const VertexPointer snd, + const double dist0 + ) +{ + Bond rtn; + rtn.fst = fst; + rtn.snd = snd; + rtn.dist0 = dist0; + rtn.stiffness = g_watr; + + return rtn; +} + +BondPointer Bond_create( + const VertexPointer fst, + const VertexPointer snd, + const double dist0 + ) +{ + + BondPointer rtn = malloc(sizeof(Bond)); + *rtn = Bond_initialize(fst, snd, dist0); + + return rtn; +} + +static double Bond_attraction_weight(const BondPointer bp) +{ + return bp->stiffness; +} + +double Bond_attraction_energy(const BondPointer bp) +{ + double d0, d; + if (CUSTOM_LENGTHS) { + d0 = bp->dist0 * SPRING_LENGTH; + } else { + d0 = SPRING_LENGTH; + } + d = Vector_norm(Vector_sub(bp->snd->pos, bp->fst->pos)); + + double w; + w = Bond_attraction_weight(bp); + return w * pow(d - d0, 2); +} + +Vector Bond_attraction_gradient(const BondPointer bp) +{ + double d0; + if (CUSTOM_LENGTHS) { + d0 = bp->dist0 * SPRING_LENGTH; + } else { + d0 = SPRING_LENGTH; + } + + Vector vecb; + vecb = Vector_sub(bp->snd->pos, bp->fst->pos); + + double d; + d = Vector_norm(vecb); + if (fabs(d) < MIN_DIST) { + d = MIN_DIST; + } + + double w; + w = Bond_attraction_weight(bp); + + return Vector_scalar_mult(vecb, 2 * w * (1 - (d0 / d))); +} + +void Bond_free(BondPointer bp) +{ + free(bp); +} + diff --git a/pool/shard003/C/0064688_wrapper.c b/pool/shard003/C/0064688_wrapper.c new file mode 100644 index 0000000000000000000000000000000000000000..4ac88ff79aa6671ef37b66fdbb96d7e6ff5609f7 --- /dev/null +++ b/pool/shard003/C/0064688_wrapper.c @@ -0,0 +1,240 @@ +/* + * linux/fs/hfsplus/wrapper.c + * + * Copyright (C) 2001 + * Brad Boyer (flar@allandria.com) + * (C) 2003 Ardis Technologies + * + * Handling of HFS wrappers around HFS+ volumes + */ + +#include +#include +#include +#include +#include + +#include "hfsplus_fs.h" +#include "hfsplus_raw.h" + +struct hfsplus_wd { + u32 ablk_size; + u16 ablk_start; + u16 embed_start; + u16 embed_count; +}; + +static void hfsplus_end_io_sync(struct bio *bio, int err) +{ + if (err) + clear_bit(BIO_UPTODATE, &bio->bi_flags); + complete(bio->bi_private); +} + +int hfsplus_submit_bio(struct block_device *bdev, sector_t sector, + void *data, int rw) +{ + DECLARE_COMPLETION_ONSTACK(wait); + struct bio *bio; + int ret = 0; + + bio = bio_alloc(GFP_NOIO, 1); + bio->bi_sector = sector; + bio->bi_bdev = bdev; + bio->bi_end_io = hfsplus_end_io_sync; + bio->bi_private = &wait; + + /* + * We always submit one sector at a time, so bio_add_page must not fail. + */ + if (bio_add_page(bio, virt_to_page(data), HFSPLUS_SECTOR_SIZE, + offset_in_page(data)) != HFSPLUS_SECTOR_SIZE) + BUG(); + + submit_bio(rw, bio); + wait_for_completion(&wait); + + if (!bio_flagged(bio, BIO_UPTODATE)) + ret = -EIO; + + bio_put(bio); + return ret; +} + +static int hfsplus_read_mdb(void *bufptr, struct hfsplus_wd *wd) +{ + u32 extent; + u16 attrib; + __be16 sig; + + sig = *(__be16 *)(bufptr + HFSP_WRAPOFF_EMBEDSIG); + if (sig != cpu_to_be16(HFSPLUS_VOLHEAD_SIG) && + sig != cpu_to_be16(HFSPLUS_VOLHEAD_SIGX)) + return 0; + + attrib = be16_to_cpu(*(__be16 *)(bufptr + HFSP_WRAPOFF_ATTRIB)); + if (!(attrib & HFSP_WRAP_ATTRIB_SLOCK) || + !(attrib & HFSP_WRAP_ATTRIB_SPARED)) + return 0; + + wd->ablk_size = + be32_to_cpu(*(__be32 *)(bufptr + HFSP_WRAPOFF_ABLKSIZE)); + if (wd->ablk_size < HFSPLUS_SECTOR_SIZE) + return 0; + if (wd->ablk_size % HFSPLUS_SECTOR_SIZE) + return 0; + wd->ablk_start = + be16_to_cpu(*(__be16 *)(bufptr + HFSP_WRAPOFF_ABLKSTART)); + + extent = get_unaligned_be32(bufptr + HFSP_WRAPOFF_EMBEDEXT); + wd->embed_start = (extent >> 16) & 0xFFFF; + wd->embed_count = extent & 0xFFFF; + + return 1; +} + +static int hfsplus_get_last_session(struct super_block *sb, + sector_t *start, sector_t *size) +{ + struct cdrom_multisession ms_info; + struct cdrom_tocentry te; + int res; + + /* default values */ + *start = 0; + *size = sb->s_bdev->bd_inode->i_size >> 9; + + if (HFSPLUS_SB(sb)->session >= 0) { + te.cdte_track = HFSPLUS_SB(sb)->session; + te.cdte_format = CDROM_LBA; + res = ioctl_by_bdev(sb->s_bdev, + CDROMREADTOCENTRY, (unsigned long)&te); + if (!res && (te.cdte_ctrl & CDROM_DATA_TRACK) == 4) { + *start = (sector_t)te.cdte_addr.lba << 2; + return 0; + } + printk(KERN_ERR "hfs: invalid session number or type of track\n"); + return -EINVAL; + } + ms_info.addr_format = CDROM_LBA; + res = ioctl_by_bdev(sb->s_bdev, CDROMMULTISESSION, + (unsigned long)&ms_info); + if (!res && ms_info.xa_flag) + *start = (sector_t)ms_info.addr.lba << 2; + return 0; +} + +/* Find the volume header and fill in some minimum bits in superblock */ +/* Takes in super block, returns true if good data read */ +int hfsplus_read_wrapper(struct super_block *sb) +{ + struct hfsplus_sb_info *sbi = HFSPLUS_SB(sb); + struct hfsplus_wd wd; + sector_t part_start, part_size; + u32 blocksize; + int error = 0; + + error = -EINVAL; + blocksize = sb_min_blocksize(sb, HFSPLUS_SECTOR_SIZE); + if (!blocksize) + goto out; + + if (hfsplus_get_last_session(sb, &part_start, &part_size)) + goto out; + if ((u64)part_start + part_size > 0x100000000ULL) { + pr_err("hfs: volumes larger than 2TB are not supported yet\n"); + goto out; + } + + error = -ENOMEM; + sbi->s_vhdr = kmalloc(HFSPLUS_SECTOR_SIZE, GFP_KERNEL); + if (!sbi->s_vhdr) + goto out; + sbi->s_backup_vhdr = kmalloc(HFSPLUS_SECTOR_SIZE, GFP_KERNEL); + if (!sbi->s_backup_vhdr) + goto out_free_vhdr; + +reread: + error = hfsplus_submit_bio(sb->s_bdev, + part_start + HFSPLUS_VOLHEAD_SECTOR, + sbi->s_vhdr, READ); + if (error) + goto out_free_backup_vhdr; + + error = -EINVAL; + switch (sbi->s_vhdr->signature) { + case cpu_to_be16(HFSPLUS_VOLHEAD_SIGX): + set_bit(HFSPLUS_SB_HFSX, &sbi->flags); + /*FALLTHRU*/ + case cpu_to_be16(HFSPLUS_VOLHEAD_SIG): + break; + case cpu_to_be16(HFSP_WRAP_MAGIC): + if (!hfsplus_read_mdb(sbi->s_vhdr, &wd)) + goto out_free_backup_vhdr; + wd.ablk_size >>= HFSPLUS_SECTOR_SHIFT; + part_start += wd.ablk_start + wd.embed_start * wd.ablk_size; + part_size = wd.embed_count * wd.ablk_size; + goto reread; + default: + /* + * Check for a partition block. + * + * (should do this only for cdrom/loop though) + */ + if (hfs_part_find(sb, &part_start, &part_size)) + goto out_free_backup_vhdr; + goto reread; + } + + error = hfsplus_submit_bio(sb->s_bdev, + part_start + part_size - 2, + sbi->s_backup_vhdr, READ); + if (error) + goto out_free_backup_vhdr; + + error = -EINVAL; + if (sbi->s_backup_vhdr->signature != sbi->s_vhdr->signature) { + printk(KERN_WARNING + "hfs: invalid secondary volume header\n"); + goto out_free_backup_vhdr; + } + + blocksize = be32_to_cpu(sbi->s_vhdr->blocksize); + + /* + * Block size must be at least as large as a sector and a multiple of 2. + */ + if (blocksize < HFSPLUS_SECTOR_SIZE || ((blocksize - 1) & blocksize)) + goto out_free_backup_vhdr; + sbi->alloc_blksz = blocksize; + sbi->alloc_blksz_shift = 0; + while ((blocksize >>= 1) != 0) + sbi->alloc_blksz_shift++; + blocksize = min(sbi->alloc_blksz, (u32)PAGE_SIZE); + + /* + * Align block size to block offset. + */ + while (part_start & ((blocksize >> HFSPLUS_SECTOR_SHIFT) - 1)) + blocksize >>= 1; + + if (sb_set_blocksize(sb, blocksize) != blocksize) { + printk(KERN_ERR "hfs: unable to set blocksize to %u!\n", + blocksize); + goto out_free_backup_vhdr; + } + + sbi->blockoffset = + part_start >> (sb->s_blocksize_bits - HFSPLUS_SECTOR_SHIFT); + sbi->part_start = part_start; + sbi->sect_count = part_size; + sbi->fs_shift = sbi->alloc_blksz_shift - sb->s_blocksize_bits; + return 0; + +out_free_backup_vhdr: + kfree(sbi->s_backup_vhdr); +out_free_vhdr: + kfree(sbi->s_vhdr); +out: + return error; +} diff --git a/pool/shard003/C/0064689_emer-gzip.c b/pool/shard003/C/0064689_emer-gzip.c new file mode 100644 index 0000000000000000000000000000000000000000..40d2f9706342770ef5197195fcc9aa2848f4185c --- /dev/null +++ b/pool/shard003/C/0064689_emer-gzip.c @@ -0,0 +1,133 @@ +/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ + +/* Copyright 2015 Endless Mobile, Inc. */ + +/* + * This file is part of eos-event-recorder-daemon. + * + * eos-event-recorder-daemon 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. + * + * eos-event-recorder-daemon 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 eos-event-recorder-daemon. If not, see + * . + */ + +#include "config.h" +#include "emer-gzip.h" + +#include +#include + +/* 9 is the highest compression level, meaning it typically achieves the best + * compression ratio but takes the longest time to run. + */ +#define COMPRESSION_LEVEL 9 + +/* + * SECTION:emer-gzip + * @title: gzip + * @short_description: Compresses data using the gzip algorithm. + * + * Provides a simplified interface to GZlibCompressor that only supports + * compression level 9, the gzip algorithm, and non-streaming compression. + */ + +/* + * emer_gzip_compress: + * @input_data: the data to compress. + * @input_length: the length of the data to compress in bytes. + * @compressed_length: (out): the length of the compressed data. + * @error: (out) (optional): if compression failed, error will be set to a GError + * describing the failure; otherwise it won't be modified. Pass NULL to ignore + * this value. + * + * Compresses input_data with the gzip algorithm at compression level 9. Returns + * NULL and sets error if compression fails. Sets compressed_length to the + * length of the compressed data in bytes. + * + * Returns: the compressed data or NULL if compression fails. Free with g_free. + */ +gpointer +emer_gzip_compress (gconstpointer input_data, + gsize input_length, + gsize *compressed_length, + GError **error) +{ + GZlibCompressor *zlib_compressor = + g_zlib_compressor_new (G_ZLIB_COMPRESSOR_FORMAT_GZIP, COMPRESSION_LEVEL); + GConverter *converter = G_CONVERTER (zlib_compressor); + + gsize allocated_space = input_length + 1; + GByteArray *byte_array = g_byte_array_sized_new (allocated_space); + gsize total_bytes_read = 0; + gsize total_bytes_written = 0; + while (TRUE) + { + gsize bytes_left_in_buffer = allocated_space - total_bytes_written; + if (bytes_left_in_buffer == 0) + { + allocated_space *= 2; + g_byte_array_set_size (byte_array, allocated_space); + continue; + } + + gsize bytes_left_in_input = input_length - total_bytes_read; + GConverterFlags conversion_flags = bytes_left_in_input > 0 ? + G_CONVERTER_NO_FLAGS : G_CONVERTER_INPUT_AT_END; + + guint8 *curr_output = byte_array->data + total_bytes_written; + const guint8 *curr_input = + ((const guint8 *) input_data) + total_bytes_read; + + gsize curr_bytes_written, curr_bytes_read; + GError *local_error = NULL; + GConverterResult conversion_result = + g_converter_convert (converter, + curr_input, bytes_left_in_input, + curr_output, bytes_left_in_buffer, + conversion_flags, + &curr_bytes_read, &curr_bytes_written, + &local_error); + + if (conversion_result == G_CONVERTER_ERROR) + { + if (g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NO_SPACE)) + { + g_error_free (local_error); + + allocated_space *= 2; + g_byte_array_set_size (byte_array, allocated_space); + continue; + } + + g_object_unref (zlib_compressor); + g_byte_array_free (byte_array, TRUE); + g_propagate_error (error, local_error); + return NULL; + } + + total_bytes_read += curr_bytes_read; + total_bytes_written += curr_bytes_written; + + if (conversion_result == G_CONVERTER_FINISHED) + break; + + /* Expand the byte array. */ + allocated_space *= 2; + g_byte_array_set_size (byte_array, allocated_space); + } + + g_object_unref (zlib_compressor); + gpointer compressed_data = g_memdup (byte_array->data, total_bytes_written); + g_byte_array_free (byte_array, TRUE); + *compressed_length = total_bytes_written; + return compressed_data; +} diff --git a/pool/shard003/C/0064695_progress.c b/pool/shard003/C/0064695_progress.c new file mode 100644 index 0000000000000000000000000000000000000000..99da1ebed40a1ef711b3561b3bbf4f8ef8a327c5 --- /dev/null +++ b/pool/shard003/C/0064695_progress.c @@ -0,0 +1,60 @@ +#include +#include +#include "../cache.h" +#include "progress.h" + +struct ui_progress { + newtComponent form, scale; +}; + +struct ui_progress *ui_progress__new(const char *title, u64 total) +{ + struct ui_progress *self = malloc(sizeof(*self)); + + if (self != NULL) { + int cols; + + if (use_browser <= 0) + return self; + newtGetScreenSize(&cols, NULL); + cols -= 4; + newtCenteredWindow(cols, 1, title); + self->form = newtForm(NULL, NULL, 0); + if (self->form == NULL) + goto out_free_self; + self->scale = newtScale(0, 0, cols, total); + if (self->scale == NULL) + goto out_free_form; + newtFormAddComponent(self->form, self->scale); + newtRefresh(); + } + + return self; + +out_free_form: + newtFormDestroy(self->form); +out_free_self: + free(self); + return NULL; +} + +void ui_progress__update(struct ui_progress *self, u64 curr) +{ + /* + * FIXME: We should have a per UI backend way of showing progress, + * stdio will just show a percentage as NN%, etc. + */ + if (use_browser <= 0) + return; + newtScaleSet(self->scale, curr); + newtRefresh(); +} + +void ui_progress__delete(struct ui_progress *self) +{ + if (use_browser > 0) { + newtFormDestroy(self->form); + newtPopWindow(); + } + free(self); +} diff --git a/pool/shard003/C/0064715_pgtable.c b/pool/shard003/C/0064715_pgtable.c new file mode 100644 index 0000000000000000000000000000000000000000..ad90429bbd8b4b25883738bd867719588ac32b92 --- /dev/null +++ b/pool/shard003/C/0064715_pgtable.c @@ -0,0 +1,237 @@ +/* + * This file contains common routines for dealing with free of page tables + * Along with common page table handling code + * + * Derived from arch/powerpc/mm/tlb_64.c: + * Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org) + * + * Modifications by Paul Mackerras (PowerMac) (paulus@cs.anu.edu.au) + * and Cort Dougan (PReP) (cort@cs.nmt.edu) + * Copyright (C) 1996 Paul Mackerras + * + * Derived from "arch/i386/mm/init.c" + * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds + * + * Dave Engebretsen + * Rework for PPC64 port. + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static inline int is_exec_fault(void) +{ + return current->thread.regs && TRAP(current->thread.regs) == 0x400; +} + +/* We only try to do i/d cache coherency on stuff that looks like + * reasonably "normal" PTEs. We currently require a PTE to be present + * and we avoid _PAGE_SPECIAL and _PAGE_NO_CACHE. We also only do that + * on userspace PTEs + */ +static inline int pte_looks_normal(pte_t pte) +{ + return (pte_val(pte) & + (_PAGE_PRESENT | _PAGE_SPECIAL | _PAGE_NO_CACHE | _PAGE_USER)) == + (_PAGE_PRESENT | _PAGE_USER); +} + +struct page * maybe_pte_to_page(pte_t pte) +{ + unsigned long pfn = pte_pfn(pte); + struct page *page; + + if (unlikely(!pfn_valid(pfn))) + return NULL; + page = pfn_to_page(pfn); + if (PageReserved(page)) + return NULL; + return page; +} + +#if defined(CONFIG_PPC_STD_MMU) || _PAGE_EXEC == 0 + +/* Server-style MMU handles coherency when hashing if HW exec permission + * is supposed per page (currently 64-bit only). If not, then, we always + * flush the cache for valid PTEs in set_pte. Embedded CPU without HW exec + * support falls into the same category. + */ + +static pte_t set_pte_filter(pte_t pte) +{ + pte = __pte(pte_val(pte) & ~_PAGE_HPTEFLAGS); + if (pte_looks_normal(pte) && !(cpu_has_feature(CPU_FTR_COHERENT_ICACHE) || + cpu_has_feature(CPU_FTR_NOEXECUTE))) { + struct page *pg = maybe_pte_to_page(pte); + if (!pg) + return pte; + if (!test_bit(PG_arch_1, &pg->flags)) { + flush_dcache_icache_page(pg); + set_bit(PG_arch_1, &pg->flags); + } + } + return pte; +} + +static pte_t set_access_flags_filter(pte_t pte, struct vm_area_struct *vma, + int dirty) +{ + return pte; +} + +#else /* defined(CONFIG_PPC_STD_MMU) || _PAGE_EXEC == 0 */ + +/* Embedded type MMU with HW exec support. This is a bit more complicated + * as we don't have two bits to spare for _PAGE_EXEC and _PAGE_HWEXEC so + * instead we "filter out" the exec permission for non clean pages. + */ +static pte_t set_pte_filter(pte_t pte) +{ + struct page *pg; + + /* No exec permission in the first place, move on */ + if (!(pte_val(pte) & _PAGE_EXEC) || !pte_looks_normal(pte)) + return pte; + + /* If you set _PAGE_EXEC on weird pages you're on your own */ + pg = maybe_pte_to_page(pte); + if (unlikely(!pg)) + return pte; + + /* If the page clean, we move on */ + if (test_bit(PG_arch_1, &pg->flags)) + return pte; + + /* If it's an exec fault, we flush the cache and make it clean */ + if (is_exec_fault()) { + flush_dcache_icache_page(pg); + set_bit(PG_arch_1, &pg->flags); + return pte; + } + + /* Else, we filter out _PAGE_EXEC */ + return __pte(pte_val(pte) & ~_PAGE_EXEC); +} + +static pte_t set_access_flags_filter(pte_t pte, struct vm_area_struct *vma, + int dirty) +{ + struct page *pg; + + /* So here, we only care about exec faults, as we use them + * to recover lost _PAGE_EXEC and perform I$/D$ coherency + * if necessary. Also if _PAGE_EXEC is already set, same deal, + * we just bail out + */ + if (dirty || (pte_val(pte) & _PAGE_EXEC) || !is_exec_fault()) + return pte; + +#ifdef CONFIG_DEBUG_VM + /* So this is an exec fault, _PAGE_EXEC is not set. If it was + * an error we would have bailed out earlier in do_page_fault() + * but let's make sure of it + */ + if (WARN_ON(!(vma->vm_flags & VM_EXEC))) + return pte; +#endif /* CONFIG_DEBUG_VM */ + + /* If you set _PAGE_EXEC on weird pages you're on your own */ + pg = maybe_pte_to_page(pte); + if (unlikely(!pg)) + goto bail; + + /* If the page is already clean, we move on */ + if (test_bit(PG_arch_1, &pg->flags)) + goto bail; + + /* Clean the page and set PG_arch_1 */ + flush_dcache_icache_page(pg); + set_bit(PG_arch_1, &pg->flags); + + bail: + return __pte(pte_val(pte) | _PAGE_EXEC); +} + +#endif /* !(defined(CONFIG_PPC_STD_MMU) || _PAGE_EXEC == 0) */ + +/* + * set_pte stores a linux PTE into the linux page table. + */ +void set_pte_at(struct mm_struct *mm, unsigned long addr, pte_t *ptep, + pte_t pte) +{ +#ifdef CONFIG_DEBUG_VM + WARN_ON(pte_val(*ptep) & _PAGE_PRESENT); +#endif + /* Note: mm->context.id might not yet have been assigned as + * this context might not have been activated yet when this + * is called. + */ + pte = set_pte_filter(pte); + + /* Perform the setting of the PTE */ + __set_pte_at(mm, addr, ptep, pte, 0); +} + +/* + * This is called when relaxing access to a PTE. It's also called in the page + * fault path when we don't hit any of the major fault cases, ie, a minor + * update of _PAGE_ACCESSED, _PAGE_DIRTY, etc... The generic code will have + * handled those two for us, we additionally deal with missing execute + * permission here on some processors + */ +int ptep_set_access_flags(struct vm_area_struct *vma, unsigned long address, + pte_t *ptep, pte_t entry, int dirty) +{ + int changed; + entry = set_access_flags_filter(entry, vma, dirty); + changed = !pte_same(*(ptep), entry); + if (changed) { + if (!is_vm_hugetlb_page(vma)) + assert_pte_locked(vma->vm_mm, address); + __ptep_set_access_flags(ptep, entry); + flush_tlb_page_nohash(vma, address); + } + return changed; +} + +#ifdef CONFIG_DEBUG_VM +void assert_pte_locked(struct mm_struct *mm, unsigned long addr) +{ + pgd_t *pgd; + pud_t *pud; + pmd_t *pmd; + + if (mm == &init_mm) + return; + pgd = mm->pgd + pgd_index(addr); + BUG_ON(pgd_none(*pgd)); + pud = pud_offset(pgd, addr); + BUG_ON(pud_none(*pud)); + pmd = pmd_offset(pud, addr); + /* + * khugepaged to collapse normal pages to hugepage, first set + * pmd to none to force page fault/gup to take mmap_sem. After + * pmd is set to none, we do a pte_clear which does this assertion + * so if we find pmd none, return. + */ + if (pmd_none(*pmd)) + return; + BUG_ON(!pmd_present(*pmd)); + assert_spin_locked(pte_lockptr(mm, pmd)); +} +#endif /* CONFIG_DEBUG_VM */ + diff --git a/pool/shard003/C/0064719_af_packet.c b/pool/shard003/C/0064719_af_packet.c new file mode 100644 index 0000000000000000000000000000000000000000..5f9c5243e53391bea9af61ccea06c2f9b6251cb8 --- /dev/null +++ b/pool/shard003/C/0064719_af_packet.c @@ -0,0 +1,237 @@ +/** + * @file + * @brief PF_PACKET protocol family socket handler + * + * @date 30.01.12 + * @author Anton Bondarev + */ + +#include +#include +#include +#include + +#include + + +#include "net_sock.h" +#include "family.h" + +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include +#include + +#define MODOPS_AMOUNT_SOCKETS OPTION_GET(NUMBER, amount_sockets) + +static const struct sock_family_ops packet_raw_ops; +static const struct net_family_type packet_types[] = { + { SOCK_STREAM, NULL }, + { SOCK_DGRAM, NULL}, + { SOCK_RAW, &packet_raw_ops } +}; +static const struct net_pack_out_ops packet_out_ops_struct; +static const struct net_pack_out_ops *const packet_out_ops = &packet_out_ops_struct; +EMBOX_NET_FAMILY(AF_PACKET, packet_types, packet_out_ops); + +static DLIST_DEFINE(packet_sock_list); +static const struct sock_proto_ops packet_sock_ops_struct = { + .sock_list = &packet_sock_list +}; +EMBOX_NET_SOCK(AF_PACKET, SOCK_RAW, 0x300 /*htons(ETH_P_ALL)*/, 0, packet_sock_ops_struct); + +struct packet_sock { + struct sock sk; + struct dlist_head lnk; + struct sockaddr_ll sll; + struct sk_buff_head rx_q; +}; + +POOL_DEF(packet_sock_pool, struct packet_sock, 2); + +static DLIST_DEFINE(packet_g_sock_list); + +static inline struct packet_sock *sk2packet(struct sock *sk) { + return member_cast_out(sk, struct packet_sock, sk); +} + +static inline void af_packet_rcv_lock(void) { + sched_lock(); +} + +static inline void af_packet_rcv_unlock(void) { + sched_unlock(); +} + +static int packet_sock_init(struct sock *sk) { + struct packet_sock *psk = sk2packet(sk); + + dlist_head_init(&psk->lnk); + memset(&psk->sll, 0, sizeof(psk->sll)); + skb_queue_init(&psk->rx_q); + + af_packet_rcv_lock(); + { + dlist_add_prev(&psk->lnk, &packet_g_sock_list); + } + af_packet_rcv_unlock(); + + return 0; +} + +static int packet_sock_close(struct sock *sk) { + struct packet_sock *psk = sk2packet(sk); + + af_packet_rcv_lock(); + { + dlist_del(&psk->lnk); + } + af_packet_rcv_unlock(); + + skb_queue_purge(&psk->rx_q); + sock_release(sk); + return 0; +} + +static int packet_sock_bind(struct sock *sk, const struct sockaddr *addr, + socklen_t addrlen) { + struct packet_sock *psk = sk2packet(sk); + struct sockaddr_ll *newsll = (struct sockaddr_ll *) addr; + + assert(sk); + assert(addr); + + if (addrlen != sizeof(struct sockaddr_ll)) { + return -EINVAL; + } + + if (newsll->sll_family != AF_PACKET) { + return -EINVAL; + } + + af_packet_rcv_lock(); + { + memcpy(&psk->sll, addr, sizeof(psk->sll)); + skb_queue_purge(&psk->rx_q); + } + af_packet_rcv_unlock(); + + return 0; +} + +static void packet_sll_fill(struct sockaddr_ll *sll, struct sk_buff *skb) { + sll->sll_family = AF_PACKET; + sll->sll_protocol = htons(ETH_P_ALL); /* XXX */ + sll->sll_ifindex = skb->dev->index; + sll->sll_hatype = 0; + sll->sll_pkttype = pkt_type(skb); + sll->sll_halen = 0; + memset(&sll->sll_addr, 0, sizeof(sll->sll_addr)); +} + +static int packet_recvmsg(struct sock *sk, struct msghdr *msg, + int flags) { + struct packet_sock *psk = sk2packet(sk); + struct sk_buff *skb; + int n_byte, skb_err; + + af_packet_rcv_lock(); + { + + do { + skb = skb_queue_pop(&psk->rx_q); + if (skb) { + break; + } + skb_err = sock_wait(sk, POLLIN | POLLERR, 0); + } while (0 == skb_err); + } + af_packet_rcv_unlock(); + + if (!skb) { + return skb_err; + } + + if (msg->msg_namelen >= sizeof(struct sockaddr_ll)) { + packet_sll_fill(msg->msg_name, skb); + } + + sock_update_tstamp(sk, skb); + + assert(sk->opt.so_type == SOCK_DGRAM || sk->opt.so_type == SOCK_RAW); + + if (sk->opt.so_type == SOCK_DGRAM) { + n_byte = skb_iovec_buf(msg->msg_iov, msg->msg_iovlen, + skb->nh.raw, skb->len - (skb->nh.raw - skb->mac.raw)); + } else if (sk->opt.so_type == SOCK_RAW) { + /* + * See https://www.kernel.org/doc/Documentation/networking/tuntap.txt + * section 3.2 Frame format. + * XXX Suppose flag IFF_NO_PI is always set. It is used for raw sockets, + * when Embox's kernel passes the whole packet starting from IP header to an user program. + * + * TODO: The code below is workaround to emulate behaviour of TUN described by link above. + * The problem is that Embox's TUN (src/drivers/tun.c) fill MAC, but it should'nt. + */ + if (!strncmp(skb->dev->name, "tun", 3)) { + n_byte = skb_iovec_buf(msg->msg_iov, msg->msg_iovlen, + skb->nh.raw, skb->len - (skb->nh.raw - skb->mac.raw)); + } else { + n_byte = skb_iovec_buf(msg->msg_iov, msg->msg_iovlen, skb->mac.raw, skb->len); + } + } + + skb_free(skb); + return n_byte; +} + +static int packet_sendmsg(struct sock *sk, struct msghdr *msg, int flags) { + return 0; +} + +static int packet_sock_setsockopt(struct sock *sk, int level, + int optname, const void *optval, socklen_t optlen) { + + if (optname == SO_ATTACH_FILTER) { + return 0; + } + + return -ENOTSUP; +} + +static const struct sock_family_ops packet_raw_ops = { + .init = packet_sock_init, + .close = packet_sock_close, + .bind = packet_sock_bind, + .sendmsg = packet_sendmsg, + .recvmsg = packet_recvmsg, + .setsockopt = packet_sock_setsockopt, + .sock_pool = &packet_sock_pool +}; + +void sock_packet_add(struct sk_buff *skb, unsigned short protocol) { + struct packet_sock *psk; + int proto_check, iface_check; + + dlist_foreach_entry(psk, &packet_g_sock_list, lnk) { + proto_check = (psk->sll.sll_protocol == htons(ETH_P_ALL) + || psk->sll.sll_protocol == protocol); + + iface_check = (psk->sll.sll_ifindex == 0 + || psk->sll.sll_ifindex == skb->dev->index); + + if (proto_check && iface_check) { + skb_queue_push(&psk->rx_q, skb_clone(skb)); + sock_notify(&psk->sk, POLLIN | POLLERR); + } + } +} diff --git a/pool/shard003/C/0064728_ppc-ravenscar-thread.c b/pool/shard003/C/0064728_ppc-ravenscar-thread.c new file mode 100644 index 0000000000000000000000000000000000000000..d65cc4d7c089a0db79bd30df8ac851e7db4230e8 --- /dev/null +++ b/pool/shard003/C/0064728_ppc-ravenscar-thread.c @@ -0,0 +1,274 @@ +/* Ravenscar PowerPC target support. + + Copyright (C) 2011-2020 Free Software Foundation, Inc. + + This file is part of GDB. + + 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 "defs.h" +#include "gdbcore.h" +#include "regcache.h" +#include "ppc-tdep.h" +#include "inferior.h" +#include "ravenscar-thread.h" +#include "ppc-ravenscar-thread.h" + +#define NO_OFFSET -1 + +/* See ppc-tdep.h for register numbers. */ + +static const int powerpc_context_offsets[] = +{ + /* R0 - R32 */ + NO_OFFSET, 0, 4, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, 8, 12, 16, + 20, 24, 28, 32, + 36, 40, 44, 48, + 52, 56, 60, 64, + 68, 72, 76, 80, + + /* F0 - F31 */ + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, 96, 104, + 112, 120, 128, 136, + 144, 152, 160, 168, + 176, 184, 192, 200, + 208, 216, 224, 232, + + /* PC, MSR, CR, LR */ + 88, NO_OFFSET, 84, NO_OFFSET, + + /* CTR, XER, FPSCR */ + NO_OFFSET, NO_OFFSET, 240 +}; + +static const int e500_context_offsets[] = +{ + /* R0 - R32 */ + NO_OFFSET, 4, 12, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, 20, 28, 36, + 44, 52, 60, 68, + 76, 84, 92, 100, + 108, 116, 124, 132, + 140, 148, 156, 164, + + /* F0 - F31 */ + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + + /* PC, MSR, CR, LR */ + 172, NO_OFFSET, 168, NO_OFFSET, + + /* CTR, XER, FPSCR, MQ */ + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + + /* Upper R0-R32. */ + NO_OFFSET, 0, 8, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, NO_OFFSET, NO_OFFSET, NO_OFFSET, + NO_OFFSET, 16, 24, 32, + 40, 48, 56, 64, + 72, 80, 88, 96, + 104, 112, 120, 128, + 136, 144, 152, 160, + + /* ACC, FSCR */ + NO_OFFSET, 176 +}; + +/* The register layout info. */ + +struct ravenscar_reg_info +{ + /* A table providing the offset relative to the context structure + where each register is saved. */ + const int *context_offsets; + + /* The number of elements in the context_offsets table above. */ + int context_offsets_size; +}; + +/* supply register REGNUM, which has been saved on REGISTER_ADDR, to the + regcache. */ + +static void +supply_register_at_address (struct regcache *regcache, int regnum, + CORE_ADDR register_addr) +{ + struct gdbarch *gdbarch = regcache->arch (); + int buf_size = register_size (gdbarch, regnum); + gdb_byte *buf; + + buf = (gdb_byte *) alloca (buf_size); + read_memory (register_addr, buf, buf_size); + regcache->raw_supply (regnum, buf); +} + +/* Return true if, for a non-running thread, REGNUM has been saved on the + Thread_Descriptor. */ + +static int +register_in_thread_descriptor_p (const struct ravenscar_reg_info *reg_info, + int regnum) +{ + return (regnum < reg_info->context_offsets_size + && reg_info->context_offsets[regnum] != NO_OFFSET); +} + +/* to_fetch_registers when inferior_ptid is different from the running + thread. */ + +static void +ppc_ravenscar_generic_fetch_registers + (const struct ravenscar_reg_info *reg_info, + struct regcache *regcache, int regnum) +{ + struct gdbarch *gdbarch = regcache->arch (); + const int num_regs = gdbarch_num_regs (gdbarch); + int current_regnum; + CORE_ADDR current_address; + CORE_ADDR thread_descriptor_address; + + /* The tid is the thread_id field, which is a pointer to the thread. */ + thread_descriptor_address = (CORE_ADDR) inferior_ptid.tid (); + + /* Read registers. */ + for (current_regnum = 0; current_regnum < num_regs; current_regnum++) + { + if (register_in_thread_descriptor_p (reg_info, current_regnum)) + { + current_address = thread_descriptor_address + + reg_info->context_offsets[current_regnum]; + supply_register_at_address (regcache, current_regnum, + current_address); + } + } +} + +/* to_store_registers when inferior_ptid is different from the running + thread. */ + +static void +ppc_ravenscar_generic_store_registers + (const struct ravenscar_reg_info *reg_info, + struct regcache *regcache, int regnum) +{ + struct gdbarch *gdbarch = regcache->arch (); + int buf_size = register_size (gdbarch, regnum); + gdb_byte buf[buf_size]; + ULONGEST register_address; + + if (register_in_thread_descriptor_p (reg_info, regnum)) + register_address + = inferior_ptid.tid () + reg_info->context_offsets [regnum]; + else + return; + + regcache->raw_collect (regnum, buf); + write_memory (register_address, + buf, + buf_size); +} + +/* The ravenscar_reg_info for most PowerPC targets. */ + +static const struct ravenscar_reg_info ppc_reg_info = +{ + powerpc_context_offsets, + ARRAY_SIZE (powerpc_context_offsets), +}; + +struct ppc_ravenscar_powerpc_ops : public ravenscar_arch_ops +{ + void fetch_registers (struct regcache *, int) override; + void store_registers (struct regcache *, int) override; +}; + +void +ppc_ravenscar_powerpc_ops::fetch_registers (struct regcache *regcache, int regnum) +{ + ppc_ravenscar_generic_fetch_registers (&ppc_reg_info, regcache, regnum); +} + +void +ppc_ravenscar_powerpc_ops::store_registers (struct regcache *regcache, int regnum) +{ + ppc_ravenscar_generic_store_registers (&ppc_reg_info, regcache, regnum); +} + +/* The ravenscar_arch_ops vector for most PowerPC targets. */ + +static struct ppc_ravenscar_powerpc_ops ppc_ravenscar_powerpc_ops; + +/* Register ppc_ravenscar_powerpc_ops in GDBARCH. */ + +void +register_ppc_ravenscar_ops (struct gdbarch *gdbarch) +{ + set_gdbarch_ravenscar_ops (gdbarch, &ppc_ravenscar_powerpc_ops); +} + +/* The ravenscar_reg_info for E500 targets. */ + +static const struct ravenscar_reg_info e500_reg_info = +{ + e500_context_offsets, + ARRAY_SIZE (e500_context_offsets), +}; + +struct ppc_ravenscar_e500_ops : public ravenscar_arch_ops +{ + void fetch_registers (struct regcache *, int) override; + void store_registers (struct regcache *, int) override; +}; + +void +ppc_ravenscar_e500_ops::fetch_registers (struct regcache *regcache, int regnum) +{ + ppc_ravenscar_generic_fetch_registers (&e500_reg_info, regcache, regnum); +} + +/* Implement the to_store_registers ravenscar_arch_ops method + for E500 targets. */ + +void +ppc_ravenscar_e500_ops::store_registers (struct regcache *regcache, int regnum) +{ + ppc_ravenscar_generic_store_registers (&e500_reg_info, regcache, regnum); +} + +/* The ravenscar_arch_ops vector for E500 targets. */ + +static struct ppc_ravenscar_e500_ops ppc_ravenscar_e500_ops; + +/* Register ppc_ravenscar_e500_ops in GDBARCH. */ + +void +register_e500_ravenscar_ops (struct gdbarch *gdbarch) +{ + set_gdbarch_ravenscar_ops (gdbarch, &ppc_ravenscar_e500_ops); +} diff --git a/pool/shard003/C/0064730_CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53a.c b/pool/shard003/C/0064730_CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53a.c new file mode 100644 index 0000000000000000000000000000000000000000..ddf08921968a973aad288d4a1ce587020c830175 --- /dev/null +++ b/pool/shard003/C/0064730_CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53a.c @@ -0,0 +1,88 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53a.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_dest.label.xml +Template File: sources-sink-53a.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sink: cpy + * BadSink : Copy string to data using strcpy + * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53b_badSink(char * data); + +void CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53_bad() +{ + char * data; + data = NULL; + /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ + data = (char *)malloc(50*sizeof(char)); + if (data == NULL) {exit(-1);} + data[0] = '\0'; /* null terminate */ + CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53b_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declaration */ +void CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53b_goodG2BSink(char * data); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + char * data; + data = NULL; + /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ + data = (char *)malloc(100*sizeof(char)); + if (data == NULL) {exit(-1);} + data[0] = '\0'; /* null terminate */ + CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53b_goodG2BSink(data); +} + +void CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cpy_53_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard003/C/0064736_CWE401_Memory_Leak__malloc_realloc_char_12.c b/pool/shard003/C/0064736_CWE401_Memory_Leak__malloc_realloc_char_12.c new file mode 100644 index 0000000000000000000000000000000000000000..7430fbff3841b89363a0bd2cbc27fd64e068483f --- /dev/null +++ b/pool/shard003/C/0064736_CWE401_Memory_Leak__malloc_realloc_char_12.c @@ -0,0 +1,149 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE401_Memory_Leak__malloc_realloc_char_12.c +Label Definition File: CWE401_Memory_Leak__malloc_realloc.label.xml +Template File: point-flaw-12.tmpl.c +*/ +/* + * @description + * CWE: 401 Memory Leak + * Sinks: + * GoodSink: Ensure the memory block pointed to by data is always freed + * BadSink : malloc() and use then realloc() and use data before free() + * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse()) + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#ifndef OMITBAD + +void CWE401_Memory_Leak__malloc_realloc_char_12_bad() +{ + if(globalReturnsTrueOrFalse()) + { + { + char * data = (char *)malloc(100*sizeof(char)); + /* Initialize and make use of data */ + strcpy(data, "A String"); + printLine(data); + /* FLAW: If realloc() fails, the initial memory block will not be freed() */ + data = (char *)realloc(data, (130000)*sizeof(char)); + if (data != NULL) + { + /* Reinitialize and make use of data */ + strcpy(data, "New String"); + printLine(data); + free(data); + } + } + } + else + { + { + char * data = (char *)malloc(100*sizeof(char)); + char * tmpData; + /* Initialize and make use of data */ + strcpy(data, "A String"); + printLine(data); + tmpData = (char *)realloc(data, (130000)*sizeof(char)); + /* FIX: Ensure realloc() was successful before assigning data to the memory block + * allocated with realloc() */ + if (tmpData != NULL) + { + data = tmpData; + /* Reinitialize and make use of data */ + strcpy(data, "New String"); + printLine(data); + } + free(data); + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good1() uses the GoodSink on both sides of the "if" statement */ +static void good1() +{ + if(globalReturnsTrueOrFalse()) + { + { + char * data = (char *)malloc(100*sizeof(char)); + char * tmpData; + /* Initialize and make use of data */ + strcpy(data, "A String"); + printLine(data); + tmpData = (char *)realloc(data, (130000)*sizeof(char)); + /* FIX: Ensure realloc() was successful before assigning data to the memory block + * allocated with realloc() */ + if (tmpData != NULL) + { + data = tmpData; + /* Reinitialize and make use of data */ + strcpy(data, "New String"); + printLine(data); + } + free(data); + } + } + else + { + { + char * data = (char *)malloc(100*sizeof(char)); + char * tmpData; + /* Initialize and make use of data */ + strcpy(data, "A String"); + printLine(data); + tmpData = (char *)realloc(data, (130000)*sizeof(char)); + /* FIX: Ensure realloc() was successful before assigning data to the memory block + * allocated with realloc() */ + if (tmpData != NULL) + { + data = tmpData; + /* Reinitialize and make use of data */ + strcpy(data, "New String"); + printLine(data); + } + free(data); + } + } +} + +void CWE401_Memory_Leak__malloc_realloc_char_12_good() +{ + good1(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE401_Memory_Leak__malloc_realloc_char_12_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE401_Memory_Leak__malloc_realloc_char_12_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard003/C/0064738_create.c b/pool/shard003/C/0064738_create.c new file mode 100644 index 0000000000000000000000000000000000000000..b1ae50de6ee9f49c27443ce84cabfbb5eeff5778 --- /dev/null +++ b/pool/shard003/C/0064738_create.c @@ -0,0 +1,163 @@ +#include +#include "create.h" + +nodeBac *createNode(cVec pos, cInt isProducer, simBac *sim, errorCode *err) +{ + nodeBac *newNode = stackPop(&sim->graph.dead_stack); + // Get an unused node + + if (newNode) // If there actually was a free slot... + { + // Assign new properties + + newNode->used = 1; // set used to true + for (cInt i=0; ipos[i] = pos[i]; // assign each coordinate + } + updateNeiVol(newNode,sim); // update volume of neighborhood sphere + newNode->num_r_n = 0; // reset producer neighbor counter + newNode->c = sim->c_b; // initialize concentration for this node + newNode->dProd = sim->param.r_d; + // default nearest neighbor as very far away + nnAdd(&sim->buckets,newNode,err); + // Add newNode to NN data struct + if (*err != SUCCESS) + { + return NULL; + } + newNode->enz = isProducer; // assign enzyme production + ++sim->num_bac; // stores number of bacteria + if (isProducer) + { + ++sim->num_pro; // if bacteria is producer, advances that counter + // Set conditions that are now invariant: + newNode->p_hgt = 0; // probability of acquiring plasmid is now invariant at 0 + newNode->c = abConc(sim->param.r_c, sim); // set concentration at cell surface + updatePABDie(newNode,sim); // update probability of AB-induced death + + } + + if (tableIsInit(&newNode->neighbors)) // if table has been initialized, + { + tableReset(&newNode->neighbors); // just reset it + } + else // if not, + { + mapInitBacTable(&newNode->neighbors,1,err); // init neighbor table + if (*err != SUCCESS) // if there's an error + { + return NULL; // run away, run away + } + } + + // Add neighbors and add self to neighbors + + setBac *potNei; // potential neighbors + nnState state; + nnInitMagic(&state, &sim->buckets,newNode,err); // init iterator + if (*err != SUCCESS) + { + return NULL; + } + for (cInt i=0; iparam.r_d && n != newNode) + // if within neighborhood limits and neighbor is not self + { + cInt num_nei_prev = tableCard(&newNode->neighbors); + // Used to check if adding same bacterium + mapAddBacterium(&newNode->neighbors,n,d,err); + // add this potential neighbor to newNode's + // neighborhood + if (*err != SUCCESS) // if there's an error + { + return NULL; // run away, run away + } + if (n->enz && \ + num_nei_prev + 1 == tableCard(&newNode->neighbors)) + // if new node is producer + // and was not already a neighbor + { + ++newNode->num_r_n; + // increase num producer neighbors + if (!newNode->enz) // if new node is not a producer + { + if (newNode->dProd > d) + // if this producer is closer than + // nearest neighbor, + { + newNode->dProd = d; + // set as new distance + } + } + } + + num_nei_prev = tableCard(&n->neighbors); + // Used to check if adding same bacterium + mapAddBacterium(&n->neighbors,newNode,d,err); + // add newNode to this potential neighbor's + // neighborhood + if (*err != SUCCESS) // if there's an error + { + return NULL; // run away, run away + } + if (newNode->enz && \ + num_nei_prev + 1 == tableCard(&n->neighbors)) + // if new node is producer + // and was not already a neighbor + { + ++n->num_r_n; // increase neighbor's producer + //neighbors + setAdd(&sim->graph.update_set,n,err); + // neighbor added to update set + if (*err != SUCCESS) + { + return NULL; + } + + cFloat possibleNewD = \ + distance(newNode,n,sim); + // [ab] due to new node + if ( possibleNewD < n->dProd ) + // if this concentration is higher, + { + n->dProd = possibleNewD; // update [ab] + } + } + } + + mapMagical(&state, &n, NULL); // move node iterator forward + } + } + } + + // update this node + setAdd(&sim->graph.update_set,newNode,err); // new node must be updated + if (*err != SUCCESS) + { + return NULL; + } + + *err = SUCCESS; // no errors here! + } + else // if there were no free nodes + { + *err = OUT_OF_BACT; // we're in trouble + } + + return newNode; +} diff --git a/pool/shard003/C/0064739_netio.c b/pool/shard003/C/0064739_netio.c new file mode 100644 index 0000000000000000000000000000000000000000..2a25d7f8aa08ab00d29bb68aed44d54d82359fd1 --- /dev/null +++ b/pool/shard003/C/0064739_netio.c @@ -0,0 +1,84 @@ +/* $OpenBSD: netio.c,v 1.1 2012/03/19 17:38:31 miod Exp $ */ + +/* + * Copyright (c) 2012 Miodrag Vallat. + * + * 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 +#include +#include + +#include + +int +netstrategy(void *devdata, int rw, daddr32_t bn, size_t reqcnt, void *addr, + size_t *cnt) +{ + long fd = (long)devdata; + long result; + int rc; + + rc = Bios_Read(fd, addr, reqcnt, &result); + if (rc != 0) + return (EIO); + + *cnt = result; + return 0; +} + +int +netopen(struct open_file *f, ...) +{ + char *path; + long fd; + int rc; + va_list ap; + + va_start(ap, f); + path = va_arg(ap, char *); + va_end(ap); + + /* to match netfs.c filename buffers... */ + if (strlen(path) > 128 - 1) + return ENAMETOOLONG; + + rc = Bios_Open(path, 0, &fd); + if (rc != 0) { + switch (rc) { + case arc_EACCES: + return EACCES; + case arc_EISDIR: + return EISDIR; + case arc_ENOENT: + return ENOENT; + default: + return ENXIO; + } + } + + f->f_devdata = (void *)fd; + + return 0; +} + +int +netclose(struct open_file *f) +{ + long fd = (long)f->f_devdata; + + (void)Bios_Close(fd); + return 0; +} diff --git a/pool/shard003/C/0064742_ditto.c b/pool/shard003/C/0064742_ditto.c new file mode 100644 index 0000000000000000000000000000000000000000..a6a294d11df228f7b3769b5589e0d7465aa97bbb --- /dev/null +++ b/pool/shard003/C/0064742_ditto.c @@ -0,0 +1,116 @@ +/* This file is an image processing operation for GEGL + * + * GEGL 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. + * + * GEGL 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 GEGL; if not, see . + * + * Copyright 2011 Michael Muré + * Copyright 2011 Robert Sasu + * Copyright 2011 Hans Lo + * Copyright 1997 Brian Degenhardt + */ + +#include "config.h" +#include + +#ifdef GEGL_CHANT_PROPERTIES + +gegl_chant_enum (sampler_type, _("Sampler"), GeglSamplerType, gegl_sampler_type, + GEGL_SAMPLER_CUBIC, _("Sampler used internally")) + +#else + +#define GEGL_CHANT_TYPE_AREA_FILTER +#define GEGL_CHANT_C_FILE "ditto.c" + +#include "gegl-chant.h" +#include +#include + +static void prepare (GeglOperation *operation) +{ + gegl_operation_set_format (operation, "input", + babl_format ("RGBA float")); + gegl_operation_set_format (operation, "output", + babl_format ("RGBA float")); +} + +static gboolean +process (GeglOperation *operation, + GeglBuffer *input, + GeglBuffer *output, + const GeglRectangle *result, + gint level) +{ + GeglChantO *o = GEGL_CHANT_PROPERTIES (operation); + + gint x = result->x; /* initial x */ + gint y = result->y; /* and y coordinates */ + + gfloat *dst_buf = g_slice_alloc (result->width * result->height * 4 * sizeof (float)); + gfloat *out_pixel = dst_buf; + + GeglSampler *sampler = gegl_buffer_sampler_new (input, + babl_format ("RGBA float"), + o->sampler_type); + + gint n_pixels = result->width * result->height; + + while (n_pixels--) + { + gegl_sampler_get (sampler, + x, + y, + NULL, + out_pixel, + GEGL_ABYSS_NONE); + + out_pixel += 4; + + /* update x and y coordinates */ + x++; + if (x>=result->x + result->width) + { + x=result->x; + y++; + } + } + + gegl_buffer_set (output, result, 0, babl_format ("RGBA float"), dst_buf, GEGL_AUTO_ROWSTRIDE); + g_slice_free1 (result->width * result->height * 4 * sizeof(gfloat), dst_buf); + + g_object_unref (sampler); + + return TRUE; +} + + +static void +gegl_chant_class_init (GeglChantClass *klass) +{ + GeglOperationClass *operation_class; + GeglOperationFilterClass *filter_class; + + operation_class = GEGL_OPERATION_CLASS (klass); + filter_class = GEGL_OPERATION_FILTER_CLASS (klass); + + filter_class->process = process; + operation_class->prepare = prepare; + + gegl_operation_class_set_keys (operation_class, + "categories" , "distort", + "name" , "gegl:ditto", + "description" , _("Test op to do a 1:1 map of input to output, while sampling"), + NULL); +} + +#endif diff --git a/pool/shard003/C/0064747_nvm.c b/pool/shard003/C/0064747_nvm.c new file mode 100644 index 0000000000000000000000000000000000000000..99a1fbfb15039870096bb015490ed9a3d64a7a58 --- /dev/null +++ b/pool/shard003/C/0064747_nvm.c @@ -0,0 +1,136 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2014 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 +#include +#include +#include "nvm.h" +#include "spi_flash.h" + +/* This module assumes the flash is memory mapped just below 4GiB in the + * address space for reading. Also this module assumes an area it erased + * when all bytes read as all 0xff's. */ + +static struct spi_flash *flash; + +static int nvm_init(void) +{ + if (flash != NULL) + return 0; + + spi_init(); + flash = spi_flash_probe(0, 0); + if (!flash) { + printk(BIOS_DEBUG, "Could not find SPI device\n"); + return -1; + } + + return 0; +} + +/* + * Convert memory mapped pointer to flash offset. + * + * This is weak because not every platforms memory-maps the NVM media in the + * same manner. This is a stop-gap solution. + * + * The root of the problem is that users of this API work in memory space for + * both reads and writes, but erase and write must be done in flash space. This + * also only works when the media is memory-mapped, which is no longer + * universally true. The long-term approach should be to rewrite this and its + * users to work in flash space, while using rdev_read() instead of rdev_mmap(). + */ +__attribute__((weak)) +uint32_t nvm_mmio_to_flash_offset(void *p) +{ + return CONFIG_ROM_SIZE + (uintptr_t)p; +} + +int nvm_is_erased(const void *start, size_t size) +{ + const uint8_t *cur = start; + const uint8_t erased_value = 0xff; + + while (size > 0) { + if (*cur != erased_value) + return 0; + cur++; + size--; + } + return 1; +} + +int nvm_erase(void *start, size_t size) +{ + if (nvm_init() < 0) + return -1; + return spi_flash_erase(flash, nvm_mmio_to_flash_offset(start), size); +} + +/* Write data to NVM. Returns 0 on success < 0 on error. */ +int nvm_write(void *start, const void *data, size_t size) +{ + if (nvm_init() < 0) + return -1; + return spi_flash_write(flash, nvm_mmio_to_flash_offset(start), size, + data); +} + +/* Read flash status register to determine if write protect is active */ +int nvm_is_write_protected(void) +{ + if (nvm_init() < 0) + return -1; + + if (IS_ENABLED(CONFIG_CHROMEOS)) { + u8 sr1; + u8 wp_gpio; + u8 wp_spi; + + /* Read Write Protect GPIO if available */ + wp_gpio = get_write_protect_state(); + + /* Read Status Register 1 */ + if (spi_flash_status(flash, &sr1) < 0) { + printk(BIOS_ERR, + "Failed to read SPI status register 1\n"); + return -1; + } + wp_spi = !!(sr1 & 0x80); + + printk(BIOS_DEBUG, "SPI flash protection: WPSW=%d SRP0=%d\n", + wp_gpio, wp_spi); + + return wp_gpio && wp_spi; + } + return 0; +} + +/* Apply protection to a range of flash */ +int nvm_protect(void *start, size_t size) +{ +#if IS_ENABLED(CONFIG_MRC_SETTINGS_PROTECT) + if (nvm_init() < 0) + return -1; + return spi_flash_protect(nvm_mmio_to_flash_offset(start), size); +#else + return -1; +#endif +} diff --git a/pool/shard003/C/0064758_perf.c b/pool/shard003/C/0064758_perf.c new file mode 100644 index 0000000000000000000000000000000000000000..5bf73d9425468da61b2ab333d139e8d245d9f9df --- /dev/null +++ b/pool/shard003/C/0064758_perf.c @@ -0,0 +1,110 @@ +/* Copyright (C) 2002-2013 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 2002. + + The GNU C 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. + + The GNU C 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 the GNU C Library; if not, see + . */ + +/* + * perf.c - get_clockfreq() function implementation + */ + +#ident "$Id$" + +#include "config.h" + +#include +#include "tsc_timer.h" + +/* + * get_clockfreq() - get the CPU clock rate + * return: the CPU or Mainboard clock rate (KHz) + */ +TSC_UINT64 +get_clockfreq (void) +{ +#if defined (WINDOWS) + /* + * Note: It has been implemented for Windows. + */ + LARGE_INTEGER fr; + QueryPerformanceFrequency (&fr); + return (TSC_UINT64) fr.QuadPart; + +#elif defined (LINUX) + /* + * Note: The implementation is derived from glibc-2.18. + */ + + /* We read the information from the /proc filesystem. It contains at least one line like cpu MHz : 497.840237 or + * also cpu MHz : 497.841 We search for this line and convert the number in an integer. */ + TSC_UINT64 result = 0; + int fd; + + fd = open ("/proc/cpuinfo", O_RDONLY); + if (fd != -1) + { + /* XXX AFAIK the /proc filesystem can generate "files" only up to a size of 4096 bytes. */ + char buf[4096]; + ssize_t n; + + n = read (fd, buf, sizeof buf); + if (n > 0) + { + char *mhz = strstr (buf, "cpu MHz"); + + if (mhz != NULL) + { + char *endp = buf + n; + int seen_decpoint = 0; + int ndigits = 0; + + /* Search for the beginning of the string. */ + while (mhz < endp && (*mhz < '0' || *mhz > '9') && *mhz != '\n') + ++mhz; + + while (mhz < endp && *mhz != '\n') + { + if (*mhz >= '0' && *mhz <= '9') + { + result *= 10; + result += *mhz - '0'; + if (seen_decpoint) + ++ndigits; + } + else if (*mhz == '.') + seen_decpoint = 1; + + ++mhz; + } + + /* Compensate for missing digits at the end. */ + while (ndigits++ < 6) + result *= 10; + } + } + + close (fd); + } + + return result; + +#else + /* + * Note: Unknown OS. the return value will not be used. + */ + return 1; + +#endif +} diff --git a/pool/shard003/C/0064761_Chapter_eleven_exercise_3.c b/pool/shard003/C/0064761_Chapter_eleven_exercise_3.c new file mode 100644 index 0000000000000000000000000000000000000000..1f6d60f0a3a587ba36e1f06c66c77494b7bc0e00 --- /dev/null +++ b/pool/shard003/C/0064761_Chapter_eleven_exercise_3.c @@ -0,0 +1,42 @@ +/******************************************************************************* + + Code Writer :The . L; + + Chapter eleven programe exercise 3 + + If this somewhere in this code could change into better condition,please touch me. + + E-mail:liuzijianlinux@gmail.com + + Blog: http://blog.csdn.net/cinmyheart +********************************************************************************/ + +#include +#include +char* ReadString(void); + +int main () +{ + char * temp; + + temp = (char*)ReadString(); + + puts(temp); + + free(temp); + + return 0; +} + +char* ReadString(void) +{ + char* String = (char*) malloc(sizeof(char)); + char* OP = String;//Original pointer + int num = 1; + while((String[num-1] = getchar())!= '\n') + { + String = (char*)realloc(String,(++num)*sizeof(char)); + } + + return OP; +} diff --git a/pool/shard003/C/0064764_usb2.c b/pool/shard003/C/0064764_usb2.c new file mode 100644 index 0000000000000000000000000000000000000000..590dedf04aef8d025d9c220ce521a25d554cb35e --- /dev/null +++ b/pool/shard003/C/0064764_usb2.c @@ -0,0 +1,49 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2004 Tyan Computer + * Written by Yinghai Lu for Tyan Computer. + * Copyright (C) 2006,2007 AMD + * Written by Yinghai Lu for AMD. + * + * 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. + */ + +#include +#include +#include +#include +#include "mcp55.h" +#include + +static void usb2_init(struct device *dev) +{ + u32 dword; + dword = pci_read_config32(dev, 0xf8); + dword |= 40; + pci_write_config32(dev, 0xf8, dword); +} + +static struct device_operations usb2_ops = { + .read_resources = pci_ehci_read_resources, + .set_resources = pci_dev_set_resources, + .enable_resources = pci_dev_enable_resources, + .init = usb2_init, +// .enable = mcp55_enable, + .scan_bus = 0, + .ops_pci = &mcp55_pci_ops, +}; + +static const struct pci_driver usb2_driver __pci_driver = { + .ops = &usb2_ops, + .vendor = PCI_VENDOR_ID_NVIDIA, + .device = PCI_DEVICE_ID_NVIDIA_MCP55_USB2, +}; diff --git a/pool/shard003/C/0064767_main.c b/pool/shard003/C/0064767_main.c new file mode 100644 index 0000000000000000000000000000000000000000..1c9d0c4ab27a66a77465a85b4fc828fe99f78523 --- /dev/null +++ b/pool/shard003/C/0064767_main.c @@ -0,0 +1,66 @@ +/* + * File: main.c + * Author: vaschalr + * + * Created on 5 décembre 2011, 10:58 + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "fonctionClient.h" + +/* + * + */ +int main(int argc, char** argv) { + int sock; + struct sockaddr_in sin; + + //on demande l'addresse et le port du serveur + afficherEnTete(); + char addr_serveur[15]; + int port_serveur; + + //on regarde si on a des param sinon on les demandes + if(argc > 2) { + sprintf(addr_serveur, "%s", argv[1]); + port_serveur = atoi(argv[2]); + } else { + printf("Adresse IP du serveur : "); + gets(addr_serveur); + printf("Port du serveur : "); + scanf("%d", & port_serveur); + } + + + //creation de la socket + sock = socket(AF_INET, SOCK_STREAM, 0); + + //configuration de la socket + sin.sin_addr.s_addr = inet_addr(addr_serveur); + sin.sin_family = AF_INET; + sin.sin_port = htons(port_serveur); + + //le client ce connect au serveur + if(connect(sock, (struct sockaddr*)&sin, sizeof(sin)) != -1) { + printf("Connexion à %s sur le port %d\n", inet_ntoa(sin.sin_addr), htons(sin.sin_port)); + menu(sock); + } + else + perror("Impossible de se connecter\n"); + + /* TEST ENVOI MSG CLIENT -> SERVER OK + write(sock,"test",4); + */ + + //A la fin on ferme la socket + close(sock); + + return (EXIT_SUCCESS); +} \ No newline at end of file diff --git a/pool/shard003/C/0064778_main.c b/pool/shard003/C/0064778_main.c new file mode 100644 index 0000000000000000000000000000000000000000..a02de7b0fb84a94ab157e20144c3c5dd360a230d --- /dev/null +++ b/pool/shard003/C/0064778_main.c @@ -0,0 +1,177 @@ +#include +#include +#include +#include +#include +#include +#include "clbpt.h" + +#define MAT_SIZE 15 + +extern void +_clbptPrintTree( + clbpt_property *property, + size_t record_size + ); + +void err_check( int err, char *err_code ) { + if ( err != CL_SUCCESS ) { + printf("Error: %d\n",err); + exit(-1); + } +} + +int main() +{ + cl_platform_id platform_id = NULL; + cl_device_id device_id = NULL; + cl_context context = NULL; + cl_program program = NULL; + cl_kernel kernel = NULL; + cl_uint ret_num_devices; + cl_uint ret_num_platforms; + cl_int err; + clbpt_platform p; + clbpt_tree t; + + + cl_device_id arr[5]; + printf("size of device id: %lu\n",sizeof(cl_device_id)); + printf("size of cl_int: %lu\n",sizeof(cl_int)); + + float mat_a[ MAT_SIZE ]; + for ( cl_int i = 0; i < MAT_SIZE; i++ ) { + mat_a[i] = i; + } + + err = clGetPlatformIDs( 1, &platform_id, &ret_num_platforms ); + err_check( err, "clGetPlatformIDs" ); + + err = clGetDeviceIDs( platform_id, CL_DEVICE_TYPE_GPU, 1, &device_id, &ret_num_devices ); + err_check(err, "clGetDeviceIDs"); + { + cl_device_svm_capabilities caps; + + cl_int err = clGetDeviceInfo( + device_id, + CL_DEVICE_SVM_CAPABILITIES, + sizeof(cl_device_svm_capabilities), + &caps, + 0 + ); + + if (err != CL_SUCCESS) + fprintf(stderr, "No info!\n"); + if (!(caps & CL_DEVICE_SVM_COARSE_GRAIN_BUFFER)) + fprintf(stderr, "No support for svm!\n"); + } + + + context = clCreateContext( NULL, 1, &device_id, NULL, NULL, &err ); + err_check( err, "clCreateContext" ); + + //printf("data information about devices are: %d\n", (int)arr[0]); + + p = malloc(sizeof(struct _clbpt_platform)); + clbptCreatePlatform(&p, context); + fprintf(stderr, "CreatePlatform SUCCESS\n"); + clbptCreateTree(&t, p, 32, sizeof(int)); + fprintf(stderr, "CreateTree SUCCESS\n"); + + // read test data +#define CLBPT_STOP_TYPE 0 +#define CLBPT_INSERT_TYPE 1 +#define CLBPT_SEARCH_TYPE 2 +#define CLBPT_DELETE_TYPE 3 +#define CLBPT_RANGE_TYPE 4 + FILE *input_data ; + input_data=fopen("input","r"); + assert(input_data != NULL); + int bfsize = 128; + int *data_buffer = calloc(128, sizeof(int)); + int *rec_buffer = calloc(128, sizeof(int)); + clbpt_pair_group_list pg_list; + struct timeval start_time, end_time; + //time_t start_time; + //time_t end_time; + while(1){ + int i; + int err = CL_SUCCESS; + int data_info[2] = {0,0}; + fscanf(input_data, "%d%d", &data_info[0], &data_info[1]); + //fread(data_info, 2, sizeof(int), input_data); + printf("Info %d %d\n",data_info[0],data_info[1]); + getchar(); + if(!data_info[0] ) break; + if (data_info[1] > bfsize){ + bfsize = data_info[1]; + data_buffer = realloc(data_buffer, bfsize*sizeof(int)); + rec_buffer = realloc(rec_buffer, bfsize*sizeof(int)); + } + switch (data_info[0]){ + case CLBPT_SEARCH_TYPE: + //fread(data_buffer, data_info[1], sizeof(int), input_data); + for (i = 0; i < data_info[1]; i++){ + fscanf(input_data, "%d", &data_buffer[i]); + //printf("%d key : %d.\n", i, data_buffer[i]); + } + gettimeofday(&start_time, NULL); + //time(&start_time); + clbptEnqueueSearches(t, data_info[1], data_buffer, (void **)rec_buffer); + break; + case CLBPT_INSERT_TYPE: + //fread(data_buffer, data_info[1], sizeof(int), input_data); + //fread(rec_buffer, data_info[1], sizeof(int), input_data); + for (i = 0; i < data_info[1]; i++){ + fscanf(input_data, "%d", &data_buffer[i]); + fscanf(input_data, "%d", &rec_buffer[i]); + //printf("%d key : %d.\n", i, data_buffer[i]); + } + gettimeofday(&start_time, NULL); + //time(&start_time); + clbptEnqueueInsertions(t, data_info[1], data_buffer, (void **)rec_buffer); + break; + case CLBPT_DELETE_TYPE: + //fread(data_buffer, data_info[1], sizeof(int), input_data); + for (i = 0; i < data_info[1]; i++){ + fscanf(input_data, "%d", &data_buffer[i]); + //printf("%d key : %d.\n", i, data_buffer[i]); + } + gettimeofday(&start_time, NULL); + //time(&start_time); + clbptEnqueueDeletions(t, data_info[1], data_buffer); + break; + case CLBPT_RANGE_TYPE: + //clbptCreatePairGroupList(&pg_list, data_info[1], l_keys, u_keys); + //clbptEnqueueRangeSearches(t, data_info[1], l_keys, u_keys, pg_list); + //clbptReleasePairGroupList(&pg_list, data_info[1]); + break; + default: exit(-1); + } + if (err != CL_SUCCESS) + { + fprintf(stderr, "EnqueInsertions ERROR\n"); + exit(err); + } + clbptFinish(t); + fflush(0); + //if (data_info[0] == CLBPT_SEARCH_TYPE) + // for (i = 0; i < data_info[1]; i++) + // printf("key(%d) : %d\n", data_buffer[i], rec_buffer[i]); + gettimeofday(&end_time, NULL); + int msec = (end_time.tv_sec-start_time.tv_sec)*1000; + msec += (end_time.tv_usec-start_time.tv_usec)/1000; + int delay = msec; + //time(&end_time); + //int delay = difftime(end_time, start_time); + //_clbptPrintTree(t->property, t->record_size); + printf("CLBPT Cost time : %d ms\n", delay); + } + + clbptReleaseTree(t); + clbptReleasePlatform(p); + assert(clReleaseContext(context) == CL_SUCCESS); + + return 0; + +} diff --git a/pool/shard003/C/0064786_hid-gaff.c b/pool/shard003/C/0064786_hid-gaff.c new file mode 100644 index 0000000000000000000000000000000000000000..71211f6a4f027161e88b2a85a0a39ec4315b62ee --- /dev/null +++ b/pool/shard003/C/0064786_hid-gaff.c @@ -0,0 +1,185 @@ +/* + * Force feedback support for GreenAsia (Product ID 0x12) based devices + * + * The devices are distributed under various names and the same USB device ID + * can be used in many game controllers. + * + * + * 0e8f:0012 "GreenAsia Inc. USB Joystick " + * - tested with MANTA Warior MM816 and SpeedLink Strike2 SL-6635. + * + * Copyright (c) 2008 Lukasz Lubojanski + */ + +/* + * 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 "hid-ids.h" +#include "usbhid/usbhid.h" + +struct gaff_device { + struct hid_report *report; +}; + +static int hid_gaff_play(struct input_dev *dev, void *data, + struct ff_effect *effect) +{ + struct hid_device *hid = input_get_drvdata(dev); + struct gaff_device *gaff = data; + int left, right; + + left = effect->u.rumble.strong_magnitude; + right = effect->u.rumble.weak_magnitude; + + dbg_hid("called with 0x%04x 0x%04x", left, right); + + left = left * 0xfe / 0xffff; + right = right * 0xfe / 0xffff; + + gaff->report->field[0]->value[0] = 0x51; + gaff->report->field[0]->value[1] = 0x0; + gaff->report->field[0]->value[2] = right; + gaff->report->field[0]->value[3] = 0; + gaff->report->field[0]->value[4] = left; + gaff->report->field[0]->value[5] = 0; + dbg_hid("running with 0x%02x 0x%02x", left, right); + usbhid_submit_report(hid, gaff->report, USB_DIR_OUT); + + gaff->report->field[0]->value[0] = 0xfa; + gaff->report->field[0]->value[1] = 0xfe; + gaff->report->field[0]->value[2] = 0x0; + gaff->report->field[0]->value[4] = 0x0; + + usbhid_submit_report(hid, gaff->report, USB_DIR_OUT); + + return 0; +} + +static int gaff_init(struct hid_device *hid) +{ + struct gaff_device *gaff; + struct hid_report *report; + struct hid_input *hidinput = list_entry(hid->inputs.next, + struct hid_input, list); + struct list_head *report_list = + &hid->report_enum[HID_OUTPUT_REPORT].report_list; + struct list_head *report_ptr = report_list; + struct input_dev *dev = hidinput->input; + int error; + + if (list_empty(report_list)) { + dev_err(&hid->dev, "no output reports found\n"); + return -ENODEV; + } + + report_ptr = report_ptr->next; + + report = list_entry(report_ptr, struct hid_report, list); + if (report->maxfield < 1) { + dev_err(&hid->dev, "no fields in the report\n"); + return -ENODEV; + } + + if (report->field[0]->report_count < 6) { + dev_err(&hid->dev, "not enough values in the field\n"); + return -ENODEV; + } + + gaff = kzalloc(sizeof(struct gaff_device), GFP_KERNEL); + if (!gaff) + return -ENOMEM; + + set_bit(FF_RUMBLE, dev->ffbit); + + error = input_ff_create_memless(dev, gaff, hid_gaff_play); + if (error) { + kfree(gaff); + return error; + } + + gaff->report = report; + gaff->report->field[0]->value[0] = 0x51; + gaff->report->field[0]->value[1] = 0x00; + gaff->report->field[0]->value[2] = 0x00; + gaff->report->field[0]->value[3] = 0x00; + usbhid_submit_report(hid, gaff->report, USB_DIR_OUT); + + gaff->report->field[0]->value[0] = 0xfa; + gaff->report->field[0]->value[1] = 0xfe; + + usbhid_submit_report(hid, gaff->report, USB_DIR_OUT); + + dev_info(&hid->dev, "Force Feedback for GreenAsia 0x12" + " devices by Lukasz Lubojanski \n"); + + return 0; +} + +static int ga_probe(struct hid_device *hdev, const struct hid_device_id *id) +{ + int ret; + + dev_dbg(&hdev->dev, "Greenasia HID hardware probe..."); + + ret = hid_parse(hdev); + if (ret) { + dev_err(&hdev->dev, "parse failed\n"); + goto err; + } + + ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT & ~HID_CONNECT_FF); + if (ret) { + dev_err(&hdev->dev, "hw start failed\n"); + goto err; + } + + gaff_init(hdev); + + return 0; +err: + return ret; +} + +static const struct hid_device_id ga_devices[] = { + { HID_USB_DEVICE(USB_VENDOR_ID_GREENASIA, 0x0012), }, + { } +}; +MODULE_DEVICE_TABLE(hid, ga_devices); + +static struct hid_driver ga_driver = { + .name = "greenasia", + .id_table = ga_devices, + .probe = ga_probe, +}; + +static int __init ga_init(void) +{ + return hid_register_driver(&ga_driver); +} + +static void __exit ga_exit(void) +{ + hid_unregister_driver(&ga_driver); +} + +module_init(ga_init); +module_exit(ga_exit); +MODULE_LICENSE("GPL"); + +HID_COMPAT_LOAD_DRIVER(greenasia); diff --git a/pool/shard003/C/0064793_system.c b/pool/shard003/C/0064793_system.c new file mode 100644 index 0000000000000000000000000000000000000000..8119ed835cfd040b0c7817e6f05b9f43f8903ce5 --- /dev/null +++ b/pool/shard003/C/0064793_system.c @@ -0,0 +1,192 @@ +/* +** ZABBIX +** Copyright (C) 2000-2005 SIA Zabbix +** +** 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., 675 Mass Ave, Cambridge, MA 02139, USA. +**/ + +#include "common.h" +#include "sysinfo.h" + +#include "system.h" + +int SYSTEM_LOCALTIME(const char *cmd, const char *param, unsigned flags, AGENT_RESULT *result) +{ + assert(result); + + init_result(result); + + SET_UI64_RESULT(result, time(NULL)); + + return SYSINFO_RET_OK; +} + +int SYSTEM_UNUM(const char *cmd, const char *param, unsigned flags, AGENT_RESULT *result) +{ +#if defined(_WINDOWS) +# ifdef TODO +# error Realize function SYSTEM_UNUM!!! +# endif /* todo */ + return SYSINFO_RET_FAIL; +#else + assert(result); + + init_result(result); + + return EXECUTE_INT(cmd, "who|wc -l", flags, result); +#endif /* _WINDOWS */ +} + +int SYSTEM_UNAME(const char *cmd, const char *param, unsigned flags, AGENT_RESULT *result) +{ +#if defined(_WINDOWS) + DWORD dwSize; + char *cpuType, + + /* NOTE: The buffer size should be large enough to contain MAX_COMPUTERNAME_LENGTH + 1 characters.*/ + computerName[MAX_COMPUTERNAME_LENGTH + 1], + + osVersion[256], + buffer[MAX_STRING_LEN]; + SYSTEM_INFO + sysInfo; + OSVERSIONINFO + versionInfo; + + dwSize = sizeof(computerName); + + if( 0 == GetComputerName(computerName,&dwSize)) + computerName[0] = '\0'; + + versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&versionInfo); + switch(versionInfo.dwPlatformId) + { + case VER_PLATFORM_WIN32_WINDOWS: + zbx_snprintf( + osVersion, + sizeof(osVersion), + "Windows %s-%s", + versionInfo.dwMinorVersion==0 ? "95" : + (versionInfo.dwMinorVersion==10 ? "98" : + (versionInfo.dwMinorVersion==90 ? "Me" : "Unknown")), + versionInfo.szCSDVersion); + break; + case VER_PLATFORM_WIN32_NT: + if (versionInfo.dwMajorVersion!=5) + { + zbx_snprintf( + osVersion, + sizeof(osVersion), + "Windows NT %d.%d %s", + versionInfo.dwMajorVersion, + versionInfo.dwMinorVersion, + versionInfo.szCSDVersion + ); + } + else /* Windows 2000, Windows XP or Windows Server 2003 */ + { + zbx_snprintf( + osVersion, + sizeof(osVersion), + "Windows %s%s%s", + (versionInfo.dwMinorVersion == 0) ? "2000" : + ((versionInfo.dwMinorVersion == 1) ? "XP" : "Server 2003"), + versionInfo.szCSDVersion[0]==0 ? "" : " ", + versionInfo.szCSDVersion); + } + break; + default: + zbx_snprintf(osVersion, sizeof(osVersion), "Windows [Unknown Version]"); + break; + } + + GetSystemInfo(&sysInfo); + switch(sysInfo.wProcessorArchitecture) + { + case PROCESSOR_ARCHITECTURE_INTEL: + cpuType="Intel IA-32"; + break; + case PROCESSOR_ARCHITECTURE_MIPS: + cpuType="MIPS"; + break; + case PROCESSOR_ARCHITECTURE_ALPHA: + cpuType="Alpha"; + break; + case PROCESSOR_ARCHITECTURE_PPC: + cpuType="PowerPC"; + break; + case PROCESSOR_ARCHITECTURE_IA64: + cpuType="Intel IA-64"; + break; + case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: + cpuType="IA-32 on IA-64"; + break; + case PROCESSOR_ARCHITECTURE_AMD64: + cpuType="AMD-64"; + break; + default: + cpuType="unknown"; + break; + } + + zbx_snprintf( + buffer, + sizeof(buffer), + "Windows %s %d.%d.%d %s %s", + computerName, + versionInfo.dwMajorVersion, + versionInfo.dwMinorVersion, + versionInfo.dwBuildNumber, + osVersion, + cpuType + ); + + SET_STR_RESULT(result, strdup(buffer)); + + return SYSINFO_RET_OK; +#else + assert(result); + + init_result(result); + + return EXECUTE_STR(cmd, "uname -a", flags, result); +#endif /* _WINDOWS */ +} + +int SYSTEM_HOSTNAME(const char *cmd, const char *param, unsigned flags, AGENT_RESULT *result) +{ +#if defined(_WINDOWS) + DWORD dwSize; + + /* NOTE: The buffer size should be large enough to contain MAX_COMPUTERNAME_LENGTH + 1 characters.*/ + char buffer[MAX_COMPUTERNAME_LENGTH + 1]; + + + dwSize = sizeof(buffer); + if( 0 == GetComputerName(buffer, &dwSize) ) + buffer[0] = '\0'; + + SET_STR_RESULT(result, strdup(buffer)); + + return SYSINFO_RET_OK; +#else + assert(result); + + init_result(result); + + return EXECUTE_STR(cmd, "hostname", flags, result); +#endif /* _WINDOWS */ +} diff --git a/pool/shard003/C/0064808_mfreerdp.c b/pool/shard003/C/0064808_mfreerdp.c new file mode 100644 index 0000000000000000000000000000000000000000..661653def505a4048e26fdb14f343a55dbd28a4f --- /dev/null +++ b/pool/shard003/C/0064808_mfreerdp.c @@ -0,0 +1,102 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Mac OS X Server + * + * Copyright 2012 Marc-Andre Moreau + * Copyright 2012 Corey Clayton + * + * 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. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include "mfreerdp.h" +#include "mf_peer.h" + +static void mf_server_main_loop(freerdp_listener* instance) +{ + WINPR_ASSERT(instance); + WINPR_ASSERT(instance->GetEventHandles); + WINPR_ASSERT(instance->CheckFileDescriptor); + + while (1) + { + DWORD status; + HANDLE handles[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD count = instance->GetEventHandles(instance, handles, ARRAYSIZE(handles)); + + if (count == 0) + { + WLog_ERR(TAG, "Failed to get FreeRDP file descriptor"); + break; + } + + status = WaitForMultipleObjects(handles, count, FALSE, INFINITE); + if (status == WAIT_FAILED) + { + WLog_ERR(TAG, "WaitForMultipleObjects failed"); + break; + } + + if (instance->CheckFileDescriptor(instance) != TRUE) + { + break; + } + } + + instance->Close(instance); +} + +int main(int argc, char* argv[]) +{ + freerdp_listener* instance; + + signal(SIGPIPE, SIG_IGN); + + WTSRegisterWtsApiFunctionTable(FreeRDP_InitWtsApi()); + + if (!(instance = freerdp_listener_new())) + return 1; + + instance->PeerAccepted = mf_peer_accepted; + + if (instance->Open(instance, NULL, 3389)) + { + mf_server_main_loop(instance); + } + + freerdp_listener_free(instance); + + return 0; +} diff --git a/pool/shard003/C/0064809_fsu-video-sink.c b/pool/shard003/C/0064809_fsu-video-sink.c new file mode 100644 index 0000000000000000000000000000000000000000..fabacc9895d7f781202cd652e7b77bd91de46efa --- /dev/null +++ b/pool/shard003/C/0064809_fsu-video-sink.c @@ -0,0 +1,241 @@ +/* + * fsu-video-sink.c - Sink for FsuVideoSink + * + * Copyright (C) 2010 Collabora Ltd. + * @author: Youness Alaoui + * + * 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 + */ + +/** + * SECTION:element-fsuvideosink + * @short_description: Farsight-Utils Magic Video Sink + * + * This element is a video sink for Farsight-utils. + * + * See also #FsuSink + */ + + +#ifdef HAVE_CONFIG_H + #include "config.h" +#endif + +#include "fsu-video-sink.h" +#include "fsu.h" +#include +#include + + +GST_DEBUG_CATEGORY_STATIC (fsu_video_sink_debug); +#define GST_CAT_DEFAULT fsu_video_sink_debug +#define DEBUG(args...) GST_DEBUG_OBJECT (self, ## args) +#define WARNING(args...) GST_WARNING_OBJECT (self, ## args) + + +static const GstElementDetails fsu_video_sink_details = +GST_ELEMENT_DETAILS( + "Farsight-Utils Magic Video Sink", + "Video Sink", + "FsuVideoSink class", + "Youness Alaoui "); + +static void +_do_init (GType type) +{ + GST_DEBUG_CATEGORY_INIT + (fsu_video_sink_debug, "fsuvideosink", 0, "fsuvideosink element"); +} + +GST_BOILERPLATE_FULL (FsuVideoSink, fsu_video_sink, + FsuSink, FSU_TYPE_SINK, _do_init) + +/* properties */ +enum +{ + PROP_XID = 1, +}; + +struct _FsuVideoSinkPrivate +{ + /* Properties */ + gint xid; +}; + + +static void fsu_video_sink_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec); +static void fsu_video_sink_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec); +static void fsu_video_sink_handle_message (GstBin *bin, + GstMessage *message); + +static void +sink_element_added (GstBin *bin, + GstElement *sink, + gpointer user_data) +{ + FsuSink *self = user_data; + + fsu_sink_element_added (self, bin, sink); +} + +static GstElement * +create_auto_sink (FsuSink *self) +{ +#ifdef __APPLE__ + return gst_element_factory_make ("osxvideosink", NULL); +#else + GstElement *sink = gst_element_factory_make ("autovideosink", NULL); + g_signal_connect_object (sink, "element-added", + G_CALLBACK (sink_element_added), self, 0); + return sink; +#endif +} + +static gchar * +need_mixer (FsuSink *self, + GstElement *sink) +{ + return "fsfunnel"; +} + +static void +add_filters (FsuSink *self, + FsuFilterManager *manager) +{ + FsuVideoconverterFilter *filter = fsu_videoconverter_filter_new (); + + fsu_filter_manager_append_filter (manager, FSU_FILTER (filter)); + g_object_unref (filter); +} + +static void +fsu_video_sink_base_init (gpointer g_class) +{ + GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class); + + gst_element_class_set_details (gstelement_class, &fsu_video_sink_details); +} + +static void +fsu_video_sink_class_init (FsuVideoSinkClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + FsuSinkClass *fsu_sink_class = FSU_SINK_CLASS (klass); + GstBinClass *gstbin_class = GST_BIN_CLASS (klass); + + g_type_class_add_private (klass, sizeof (FsuVideoSinkPrivate)); + + gobject_class->get_property = fsu_video_sink_get_property; + gobject_class->set_property = fsu_video_sink_set_property; + + fsu_sink_class->auto_sink_name = "autovideosink"; + fsu_sink_class->create_auto_sink = create_auto_sink; + fsu_sink_class->need_mixer = need_mixer; + fsu_sink_class->add_filters = add_filters; + + gstbin_class->handle_message = + GST_DEBUG_FUNCPTR (fsu_video_sink_handle_message); + + g_object_class_install_property (gobject_class, PROP_XID, + g_param_spec_int ("xid", "Sink window xid", + "The xid of the window in which to embed the video sink.", + G_MININT, G_MAXINT, 0, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +fsu_video_sink_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec) +{ + FsuVideoSink *self = FSU_VIDEO_SINK (object); + FsuVideoSinkPrivate *priv = self->priv; + + switch (property_id) + { + case PROP_XID: + g_value_set_int (value, priv->xid); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +fsu_video_sink_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + FsuVideoSink *self = FSU_VIDEO_SINK (object); + FsuVideoSinkPrivate *priv = self->priv; + + switch (property_id) + { + case PROP_XID: + priv->xid = g_value_get_int (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + + +static void +fsu_video_sink_init (FsuVideoSink *self, + FsuVideoSinkClass *klass) +{ + FsuVideoSinkPrivate *priv = + G_TYPE_INSTANCE_GET_PRIVATE (self, FSU_TYPE_VIDEO_SINK, + FsuVideoSinkPrivate); + + self->priv = priv; + priv->xid = 0; +} + +static void +fsu_video_sink_handle_message (GstBin *bin, + GstMessage *message) +{ + FsuVideoSink *self = FSU_VIDEO_SINK (bin); + const GstStructure *s = gst_message_get_structure (message); + gint xid = 0; + + GST_OBJECT_LOCK (GST_OBJECT (self)); + xid = self->priv->xid; + GST_OBJECT_UNLOCK (GST_OBJECT (self)); + + if (GST_MESSAGE_TYPE (message) == GST_MESSAGE_ELEMENT && + gst_structure_has_name (s, "prepare-xwindow-id")) + gst_x_overlay_set_xwindow_id (GST_X_OVERLAY (GST_MESSAGE_SRC (message)), + xid); + +#ifdef __APPLE__ + else if (GST_MESSAGE_TYPE (message) == GST_MESSAGE_ELEMENT && + gst_structure_has_name (s, "have-ns-view")) + (void); /* TODO: do what? */ +#endif + + GST_BIN_CLASS (parent_class)->handle_message (bin, message); +} diff --git a/pool/shard003/C/0064811_m_prefs_num_prefs_ful_ret.c b/pool/shard003/C/0064811_m_prefs_num_prefs_ful_ret.c new file mode 100644 index 0000000000000000000000000000000000000000..f55f1a90b5720aaf806df86219dbc9b8b5a1f002 --- /dev/null +++ b/pool/shard003/C/0064811_m_prefs_num_prefs_ful_ret.c @@ -0,0 +1,51 @@ +/* + Copyright (c) 2008 - Chris Buckley. + + Permission is granted for use and modification of this file for + research, non-commercial purposes. +*/ + +#include "common.h" +#include "sysfunc.h" +#include "trec_eval.h" +#include "functions.h" +#include "trec_format.h" + +static int +te_calc_prefs_num_prefs_ful_ret (const EPI *epi, const REL_INFO *rel_info, + const RESULTS *results, const TREC_MEAS *tm, + TREC_EVAL *eval); + +/* See trec_eval.h for definition of TREC_MEAS */ +TREC_MEAS te_meas_prefs_num_prefs_ful_ret = + {"prefs_num_prefs_ful_ret", + " Number of prefs fulfilled among retrieved docs\n\ + For doc pref A>B, both A nd B must be retrieved to be counted.\n\ + Summary figure is sum of individual topics, not average.\n", + te_init_meas_s_long, + te_calc_prefs_num_prefs_ful_ret, + te_acc_meas_s, + te_calc_avg_meas_empty, + te_print_single_meas_s_long, + te_print_final_meas_s_long, + NULL, -1}; + +static int +te_calc_prefs_num_prefs_ful_ret (const EPI *epi, const REL_INFO *rel_info, + const RESULTS *results, const TREC_MEAS *tm, + TREC_EVAL *eval) +{ + RESULTS_PREFS results_prefs; + long i; + long ful; + + if (UNDEF == form_prefs_counts (epi, rel_info, results, &results_prefs)) + return (UNDEF); + + ful = 0; + for (i = 0; i < results_prefs.num_jgs; i++) { + ful += results_prefs.jgs[i].num_prefs_fulfilled_ret; + } + eval->values[tm->eval_index].value = (double) ful; + return (1); +} diff --git a/pool/shard003/C/0064818_packet-ypbind.c b/pool/shard003/C/0064818_packet-ypbind.c new file mode 100644 index 0000000000000000000000000000000000000000..54e66282dae7db054ce2c1101510f02b438a5736 --- /dev/null +++ b/pool/shard003/C/0064818_packet-ypbind.c @@ -0,0 +1,225 @@ +/* packet-ypbind.c + * Routines for ypbind dissection + * + * $Id: packet-ypbind.c 47390 2013-01-31 18:31:28Z wmeier $ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * Copied from packet-smb.c + * + * 2001 Ronnie Sahlberg, added dissectors for the commands + * + * 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" + +#if defined(LEAN_YP) +# error LEAN_YP: Should not be build +#endif + +#include "packet-rpc.h" +#include "packet-ypbind.h" + +static int proto_ypbind = -1; +static int hf_ypbind_procedure_v1 = -1; +static int hf_ypbind_procedure_v2 = -1; +static int hf_ypbind_domain = -1; +static int hf_ypbind_resp_type = -1; +/* static int hf_ypbind_error = -1; */ +static int hf_ypbind_addr = -1; +static int hf_ypbind_port = -1; +static int hf_ypbind_setdom_version = -1; + +static gint ett_ypbind = -1; + + +static int +dissect_ypbind_domain_v2_request(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree) +{ + /* domain */ + offset = dissect_rpc_string(tvb, tree, + hf_ypbind_domain, offset, NULL); + + return offset; +} + +#define YPBIND_RESP_TYPE_SUCC_VAL 1 +#define YPBIND_RESP_TYPE_FAIL_VAL 2 +static const value_string resp_type_vals[] = { + {YPBIND_RESP_TYPE_SUCC_VAL, "SUCC_VAL"}, + {YPBIND_RESP_TYPE_FAIL_VAL, "FAIL_VAL"}, + {0, NULL} +}; + +#if 0 +#define YPBIND_ERROR_ERR 1 +#define YPBIND_ERROR_NOSERV 2 +#define YPBIND_ERROR_RESC 3 +static const value_string error_vals[] = { + {YPBIND_ERROR_ERR, "Internal error"}, + {YPBIND_ERROR_NOSERV, "No bound server for passed domain"}, + {YPBIND_ERROR_RESC, "System resource allocation failure"}, + {0, NULL} +}; +#endif + +static int +dissect_ypbind_domain_v2_reply(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree) +{ + guint32 type; + + /* response type */ + type=tvb_get_ntohl(tvb, offset); + offset = dissect_rpc_uint32(tvb, tree, hf_ypbind_resp_type, offset); + + switch(type){ + case YPBIND_RESP_TYPE_SUCC_VAL: + /* ip address */ + proto_tree_add_item(tree, hf_ypbind_addr, + tvb, offset, 4, ENC_BIG_ENDIAN); + offset += 4; + + /* port */ + offset = dissect_rpc_uint32(tvb, tree, + hf_ypbind_port, offset); + + break; + case YPBIND_RESP_TYPE_FAIL_VAL: + /* error */ + offset = dissect_rpc_uint32(tvb, tree, + hf_ypbind_resp_type, offset); + break; + } + + return offset; +} + +static int +dissect_ypbind_setdomain_v2_request(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree) +{ + /* domain */ + offset = dissect_rpc_string(tvb, tree, + hf_ypbind_domain, offset, NULL); + + /* ip address */ + proto_tree_add_item(tree, hf_ypbind_addr, + tvb, offset, 4, ENC_BIG_ENDIAN); + offset += 4; + + /* port */ + offset = dissect_rpc_uint32(tvb, tree, + hf_ypbind_port, offset); + + /* version */ + offset = dissect_rpc_uint32(tvb, tree, + hf_ypbind_setdom_version, offset); + + return offset; +} + + + +/* proc number, "proc name", dissect_request, dissect_reply */ +/* NULL as function pointer means: type of arguments is "void". */ +static const vsff ypbind1_proc[] = { + { YPBINDPROC_NULL, "NULL", NULL, NULL }, + { YPBINDPROC_DOMAIN, "DOMAIN", NULL, NULL }, + { YPBINDPROC_SETDOM, "SETDOMAIN", NULL, NULL }, + { 0, NULL, NULL, NULL } +}; +static const value_string ypbind1_proc_vals[] = { + { YPBINDPROC_NULL, "NULL" }, + { YPBINDPROC_DOMAIN, "DOMAIN" }, + { YPBINDPROC_SETDOM, "SETDOMAIN" }, + { 0, NULL } +}; +/* end of YPBind version 1 */ + +static const vsff ypbind2_proc[] = { + { YPBINDPROC_NULL, "NULL", NULL, NULL }, + { YPBINDPROC_DOMAIN, "DOMAIN", + dissect_ypbind_domain_v2_request, dissect_ypbind_domain_v2_reply}, + { YPBINDPROC_SETDOM, "SETDOMAIN", + dissect_ypbind_setdomain_v2_request, NULL}, + { 0, NULL, NULL, NULL } +}; +static const value_string ypbind2_proc_vals[] = { + { YPBINDPROC_NULL, "NULL" }, + { YPBINDPROC_DOMAIN, "DOMAIN" }, + { YPBINDPROC_SETDOM, "SETDOMAIN" }, + { 0, NULL } +}; +/* end of YPBind version 2 */ + + +void +proto_register_ypbind(void) +{ + static hf_register_info hf[] = { + { &hf_ypbind_procedure_v1, { + "V1 Procedure", "ypbind.procedure_v1", FT_UINT32, BASE_DEC, + VALS(ypbind1_proc_vals), 0, NULL, HFILL }}, + { &hf_ypbind_procedure_v2, { + "V2 Procedure", "ypbind.procedure_v2", FT_UINT32, BASE_DEC, + VALS(ypbind2_proc_vals), 0, NULL, HFILL }}, + { &hf_ypbind_domain, { + "Domain", "ypbind.domain", FT_STRING, BASE_NONE, + NULL, 0, "Name of the NIS/YP Domain", HFILL }}, + + { &hf_ypbind_resp_type, { + "Response Type", "ypbind.resp_type", FT_UINT32, BASE_DEC, + VALS(resp_type_vals), 0, NULL, HFILL }}, + +#if 0 + { &hf_ypbind_error, { + "Error", "ypbind.error", FT_UINT32, BASE_DEC, + VALS(error_vals), 0, "YPBIND Error code", HFILL }}, +#endif + { &hf_ypbind_addr, { + "IP Addr", "ypbind.addr", FT_IPv4, BASE_NONE, + NULL, 0, "IP Address of server", HFILL }}, + + { &hf_ypbind_port, { + "Port", "ypbind.port", FT_UINT32, BASE_DEC, + NULL, 0, "Port to use", HFILL }}, + + { &hf_ypbind_setdom_version, { + "Version", "ypbind.setdom.version", FT_UINT32, BASE_DEC, + NULL, 0, "Version of setdom", HFILL }}, + + }; + + static gint *ett[] = { + &ett_ypbind, + }; + + proto_ypbind = proto_register_protocol("Yellow Pages Bind", + "YPBIND", "ypbind"); + proto_register_field_array(proto_ypbind, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); +} + +void +proto_reg_handoff_ypbind(void) +{ + /* Register the protocol as RPC */ + rpc_init_prog(proto_ypbind, YPBIND_PROGRAM, ett_ypbind); + /* Register the procedure tables */ + rpc_init_proc_table(YPBIND_PROGRAM, 1, ypbind1_proc, hf_ypbind_procedure_v1); + rpc_init_proc_table(YPBIND_PROGRAM, 2, ypbind2_proc, hf_ypbind_procedure_v2); +} diff --git a/pool/shard003/C/0064847_tempnam.c b/pool/shard003/C/0064847_tempnam.c new file mode 100644 index 0000000000000000000000000000000000000000..2a55a5c2bf8aacc7bcbc5e98abb30e4406007cbe --- /dev/null +++ b/pool/shard003/C/0064847_tempnam.c @@ -0,0 +1,102 @@ +/* $NetBSD: tempnam.c,v 1.22 2012/03/15 18:22:30 christos Exp $ */ + +/* + * Copyright (c) 1988, 1993 + * The 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: + * 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 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. + */ + +#include +#if defined(LIBC_SCCS) && !defined(lint) +#if 0 +static char sccsid[] = "@(#)tempnam.c 8.1 (Berkeley) 6/4/93"; +#else +__RCSID("$NetBSD: tempnam.c,v 1.22 2012/03/15 18:22:30 christos Exp $"); +#endif +#endif /* LIBC_SCCS and not lint */ + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include +#include "reentrant.h" +#include "local.h" + +__warn_references(tempnam, + "warning: tempnam() possibly used unsafely, use mkstemp() or mkdtemp()") + +static const char * +trailsl(const char *f) +{ + const char *s = f; + while (*s) + s++; + return (f != s && s[-1] == '/') ? "" : "/"; +} + +static char * +gentemp(char *name, size_t len, const char *tmp, const char *pfx) +{ + (void)snprintf(name, len, "%s%s%sXXXXXXXXXX", tmp, trailsl(tmp), pfx); + return _mktemp(name); +} + +char * +tempnam(const char *dir, const char *pfx) +{ + int sverrno; + char *name, *f; + const char *tmp; + + if (!(name = malloc((size_t)MAXPATHLEN))) + return NULL; + + if (!pfx) + pfx = "tmp."; + + if ((tmp = getenv("TMPDIR")) != NULL && + (f = gentemp(name, (size_t)MAXPATHLEN, tmp, pfx)) != NULL) + return f; + + if (dir != NULL && + (f = gentemp(name, (size_t)MAXPATHLEN, dir, pfx)) != NULL) + return f; + + if ((f = gentemp(name, (size_t)MAXPATHLEN, P_tmpdir, pfx)) != NULL) + return f; + + if ((f = gentemp(name, (size_t)MAXPATHLEN, _PATH_TMP, pfx)) != NULL) + return f; + + sverrno = errno; + free(name); + errno = sverrno; + return NULL; +} diff --git a/pool/shard003/C/0064856_packet-rmt-alc.c b/pool/shard003/C/0064856_packet-rmt-alc.c new file mode 100644 index 0000000000000000000000000000000000000000..593235b27bddef3a0f7ac5a8d04dbb1eab80b184 --- /dev/null +++ b/pool/shard003/C/0064856_packet-rmt-alc.c @@ -0,0 +1,268 @@ +/* packet-rmt-alc.c + * Reliable Multicast Transport (RMT) + * ALC Protocol Instantiation dissector + * Copyright 2005, Stefano Pettini + * + * Asynchronous Layered Coding (ALC): + * ---------------------------------- + * + * A massively scalable reliable content delivery protocol. + * Asynchronous Layered Coding combines the Layered Coding Transport + * (LCT) building block, a multiple rate congestion control building + * block and the Forward Error Correction (FEC) building block to + * provide congestion controlled reliable asynchronous delivery of + * content to an unlimited number of concurrent receivers from a single + * sender. + * + * References: + * RFC 3450, Asynchronous Layered Coding protocol instantiation + * + * 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 "packet-rmt-common.h" + +/* Initialize the protocol and registered fields */ +/* ============================================= */ + +void proto_register_alc(void); +void proto_reg_handoff_alc(void); + +static int proto_rmt_alc = -1; + +static int hf_version = -1; +static int hf_payload = -1; + +static int ett_main = -1; + +static expert_field ei_version1_only = EI_INIT; + +static dissector_handle_t xml_handle; +static dissector_handle_t rmt_lct_handle; +static dissector_handle_t rmt_fec_handle; + +static guint g_default_udp_port = 0; /* 4001 */ +static gboolean g_codepoint_as_fec_encoding = TRUE; +static gint g_ext_192 = LCT_PREFS_EXT_192_FLUTE; +static gint g_ext_193 = LCT_PREFS_EXT_193_FLUTE; + +/* Code to actually dissect the packets */ +/* ==================================== */ +static int +dissect_alc(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) +{ + guint8 version; + lct_data_exchange_t lct; + fec_data_exchange_t fec; + int len; + + /* Offset for subpacket dissection */ + guint offset = 0; + + /* Set up structures needed to add the protocol subtree and manage it */ + proto_item *ti; + proto_tree *alc_tree; + + tvbuff_t *new_tvb; + + /* Make entries in Protocol column and Info column on summary display */ + col_set_str(pinfo->cinfo, COL_PROTOCOL, "ALC"); + col_clear(pinfo->cinfo, COL_INFO); + + /* ALC header dissection */ + /* --------------------- */ + + version = hi_nibble(tvb_get_guint8(tvb, offset)); + + /* Create subtree for the ALC protocol */ + ti = proto_tree_add_item(tree, proto_rmt_alc, tvb, offset, -1, ENC_NA); + alc_tree = proto_item_add_subtree(ti, ett_main); + + /* Fill the ALC subtree */ + ti = proto_tree_add_uint(alc_tree, hf_version, tvb, offset, 1, version); + + /* This dissector supports only ALCv1 packets. + * If version > 1 print only version field and quit. + */ + if (version != 1) { + expert_add_info(pinfo, ti, &ei_version1_only); + + /* Complete entry in Info column on summary display */ + col_add_fstr(pinfo->cinfo, COL_INFO, "Version: %u (not supported)", version); + return 0; + } + + /* LCT header dissection */ + /* --------------------- */ + new_tvb = tvb_new_subset_remaining(tvb,offset); + + lct.ext_192 = g_ext_192; + lct.ext_193 = g_ext_193; + lct.codepoint = 0; + lct.is_flute = FALSE; + len = call_dissector_with_data(rmt_lct_handle, new_tvb, pinfo, alc_tree, &lct); + if (len < 0) + return offset; + + offset += len; + + /* FEC header dissection */ + /* --------------------- */ + + /* Only if LCT dissector has determined FEC Encoding ID */ + /* FEC dissector needs to be called with encoding_id filled */ + if (g_codepoint_as_fec_encoding && tvb_reported_length(tvb) > offset) + { + fec.encoding_id = lct.codepoint; + + new_tvb = tvb_new_subset_remaining(tvb,offset); + len = call_dissector_with_data(rmt_fec_handle, new_tvb, pinfo, alc_tree, &fec); + if (len < 0) + return offset; + + offset += len; + } + + /* Add the Payload item */ + if (tvb_reported_length(tvb) > offset){ + if(lct.is_flute){ + new_tvb = tvb_new_subset_remaining(tvb,offset); + call_dissector(xml_handle, new_tvb, pinfo, alc_tree); + }else{ + proto_tree_add_item(alc_tree, hf_payload, tvb, offset, -1, ENC_NA); + } + } + + return tvb_reported_length(tvb); +} + +void proto_register_alc(void) +{ + /* Setup ALC header fields */ + static hf_register_info hf_ptr[] = { + + { &hf_version, + { "Version", "alc.version", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }}, + + { &hf_payload, + { "Payload", "alc.payload", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }} + }; + + /* Setup protocol subtree array */ + static gint *ett_ptr[] = { + &ett_main, + }; + + static ei_register_info ei[] = { + { &ei_version1_only, { "alc.version1_only", PI_PROTOCOL, PI_WARN, "Sorry, this dissector supports ALC version 1 only", EXPFILL }}, + }; + + module_t *module; + expert_module_t* expert_rmt_alc; + + /* Register the protocol name and description */ + proto_rmt_alc = proto_register_protocol("Asynchronous Layered Coding", "ALC", "alc"); + new_register_dissector("alc", dissect_alc, proto_rmt_alc); + + /* Register the header fields and subtrees used */ + proto_register_field_array(proto_rmt_alc, hf_ptr, array_length(hf_ptr)); + proto_register_subtree_array(ett_ptr, array_length(ett_ptr)); + expert_rmt_alc = expert_register_protocol(proto_rmt_alc); + expert_register_field_array(expert_rmt_alc, ei, array_length(ei)); + + /* Register preferences */ + module = prefs_register_protocol(proto_rmt_alc, proto_reg_handoff_alc); + + prefs_register_obsolete_preference(module, "default.udp_port.enabled"); + + prefs_register_uint_preference(module, + "default.udp_port", + "UDP destination port", + "Specifies the UDP destination port for automatic dissection of ALC packets", + 10, &g_default_udp_port); + + prefs_register_bool_preference(module, + "lct.codepoint_as_fec_id", + "LCT Codepoint as FEC Encoding ID", + "Whether the LCT header Codepoint field should be considered the FEC Encoding ID of carried object", + &g_codepoint_as_fec_encoding); + + prefs_register_enum_preference(module, + "lct.ext.192", + "LCT header extension 192", + "How to decode LCT header extension 192", + &g_ext_192, + enum_lct_ext_192, + FALSE); + + prefs_register_enum_preference(module, + "lct.ext.193", + "LCT header extension 193", + "How to decode LCT header extension 193", + &g_ext_193, + enum_lct_ext_193, + FALSE); +} + +void proto_reg_handoff_alc(void) +{ + static dissector_handle_t handle; + static gboolean preferences_initialized = FALSE; + static guint old_udp_port = 0; + + if (!preferences_initialized) + { + preferences_initialized = TRUE; + handle = new_create_dissector_handle(dissect_alc, proto_rmt_alc); + dissector_add_for_decode_as("udp.port", handle); + xml_handle = find_dissector("xml"); + rmt_lct_handle = find_dissector("rmt-lct"); + rmt_fec_handle = find_dissector("rmt-fec"); + } + + /* Register UDP port for dissection */ + if(old_udp_port != 0 && old_udp_port != g_default_udp_port){ + dissector_delete_uint("udp.port", old_udp_port, handle); + } + + if(g_default_udp_port != 0 && old_udp_port != g_default_udp_port) { + dissector_add_uint("udp.port", g_default_udp_port, handle); + } + + old_udp_port = g_default_udp_port; +} + +/* + * Editor modelines - http://www.wireshark.org/tools/modelines.html + * + * Local variables: + * c-basic-offset: 4 + * tab-width: 8 + * indent-tabs-mode: nil + * End: + * + * ex: set shiftwidth=4 tabstop=8 expandtab: + * :indentSize=4:tabSize=8:noTabs=true: + */ diff --git a/pool/shard003/C/0064863_nem_transport1.c b/pool/shard003/C/0064863_nem_transport1.c new file mode 100644 index 0000000000000000000000000000000000000000..1ae03fb125e397e68f36429418a4c863ffecc9b1 --- /dev/null +++ b/pool/shard003/C/0064863_nem_transport1.c @@ -0,0 +1,48 @@ +/* This file is part of the Neper software package. */ +/* Copyright (C) 2003-2022, Romain Quey. */ +/* See the COPYING file in the top-level directory. */ + +#include"nem_transport_.h" + +void +nem_transport (struct IN_M In, struct TESS Tess, struct NODES RNodes, + struct MESH *RMesh, struct NODES Nodes, struct MESH *Mesh) +{ + int i, transportqty, valqty; + char **transport = NULL, **val = NULL; + int *oldelt = NULL; + int dim = Tess.Dim; + + ut_print_message (0, 2, "Transporting data...\n"); + ut_list_break (In.transportstring, NEUT_SEP_NODEP, &transport, + &transportqty); + + for (i = 0; i < transportqty; i++) + { + ut_list_break (transport[i], NEUT_SEP_DEP, &val, &valqty); + + if (valqty != 3) + ut_print_message (2, 3, "Bad format for transport expression `%s'.\n", + transport[i]); + + ut_print_message (0, 3, "Transporting `%s'...\n", val[2]); + + if (!strcmp (val[0], "elt")) + nem_transport_elt (val[1], val[2], In.transporteltmethodstring, RNodes, + RMesh[dim], Nodes, Mesh[dim], &oldelt); + else if (!strcmp (val[0], "node")) + nem_transport_node (val[1], val[2], RNodes, RMesh[dim], Nodes); + else + ut_print_message (2, 3, + "Unknown type of data in `%s' (must be `elt')\n", + transport[i]); + + ut_free_2d_char (&val, valqty); + val = NULL; + } + + ut_free_1d_int (&oldelt); + ut_free_2d_char (&transport, transportqty); + + return; +} diff --git a/pool/shard003/C/0064869_ulock_wake.c b/pool/shard003/C/0064869_ulock_wake.c new file mode 100644 index 0000000000000000000000000000000000000000..cf40959c11a31e351644a7c25e277ccebf382471 --- /dev/null +++ b/pool/shard003/C/0064869_ulock_wake.c @@ -0,0 +1,42 @@ +#include "ulock_wait.h" +#include "ulock_wake.h" +#include "../base.h" +#include "../errno.h" +#include +#include "../../../../../platform-include/sys/errno.h" +#include +#include + +long sys_ulock_wake(uint32_t operation, void* addr, uint64_t wake_value) +{ + int ret, op; + bool no_errno = operation & ULF_NO_ERRNO; + + op = operation & UL_OPCODE_MASK; + if (op == UL_COMPARE_AND_WAIT || op == UL_UNFAIR_LOCK) + { + int value; + + if (operation & ULF_WAKE_ALL) + value = INT_MAX; + else if (operation & ULF_WAKE_THREAD) + value = INT_MAX; // incorrect + else + value = 1; + + ret = LINUX_SYSCALL(__NR_futex, addr, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, + value); + } + else + return no_errno ? -(EINVAL | 0x800) : -EINVAL; + + if (ret < 0) + { + ret = errno_linux_to_bsd(ret); + if (no_errno) + ret &= ~0x800; + } + + return ret; +} + diff --git a/pool/shard003/C/0064870_CWE78_OS_Command_Injection__char_console_w32spawnl_17.c b/pool/shard003/C/0064870_CWE78_OS_Command_Injection__char_console_w32spawnl_17.c new file mode 100644 index 0000000000000000000000000000000000000000..97e81568df9243bec31df3ffc9885e611d2da9ac --- /dev/null +++ b/pool/shard003/C/0064870_CWE78_OS_Command_Injection__char_console_w32spawnl_17.c @@ -0,0 +1,132 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_console_w32spawnl_17.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-17.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: console Read input from the console + * GoodSource: Fixed string + * Sink: w32spawnl + * BadSink : execute command with spawnl + * Flow Variant: 17 Control flow: for loops + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT "cmd.exe" +#define COMMAND_ARG1 "/c" +#define COMMAND_ARG2 "dir " +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH "/bin/sh" +#define COMMAND_INT "sh" +#define COMMAND_ARG1 "-c" +#define COMMAND_ARG2 "ls " +#define COMMAND_ARG3 data +#endif + +#include + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__char_console_w32spawnl_17_bad() +{ + int i; + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + for(i = 0; i < 1; i++) + { + { + /* Read input from the console */ + size_t dataLen = strlen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgets() */ + dataLen = strlen(data); + if (dataLen > 0 && data[dataLen-1] == '\n') + { + data[dataLen-1] = '\0'; + } + } + else + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + } + } + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by changing the conditions on the for statements */ +static void goodG2B() +{ + int h; + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + for(h = 0; h < 1; h++) + { + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__char_console_w32spawnl_17_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__char_console_w32spawnl_17_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_console_w32spawnl_17_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard003/C/0064873_adreno_debugfs.c b/pool/shard003/C/0064873_adreno_debugfs.c new file mode 100644 index 0000000000000000000000000000000000000000..ad8224cee9bf2eecba56d560e180fc8864614656 --- /dev/null +++ b/pool/shard003/C/0064873_adreno_debugfs.c @@ -0,0 +1,84 @@ +/* Copyright (c) 2002,2008-2012, The Linux Foundation. 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 version 2 and + * only 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. + * + */ + +#include +#include +#include +#include +#include + +#include "kgsl.h" +#include "adreno.h" + +#include "a2xx_reg.h" + +unsigned int kgsl_cff_dump_enable; + +static int kgsl_cff_dump_enable_set(void *data, u64 val) +{ +#ifdef CONFIG_MSM_KGSL_CFF_DUMP + kgsl_cff_dump_enable = (val != 0); + return 0; +#else + return -EINVAL; +#endif +} + +static int kgsl_cff_dump_enable_get(void *data, u64 *val) +{ + *val = kgsl_cff_dump_enable; + return 0; +} + +DEFINE_SIMPLE_ATTRIBUTE(kgsl_cff_dump_enable_fops, kgsl_cff_dump_enable_get, + kgsl_cff_dump_enable_set, "%llu\n"); + +typedef void (*reg_read_init_t)(struct kgsl_device *device); +typedef void (*reg_read_fill_t)(struct kgsl_device *device, int i, + unsigned int *vals, int linec); + +void adreno_debugfs_init(struct kgsl_device *device) +{ + struct adreno_device *adreno_dev = ADRENO_DEVICE(device); + + if (!device->d_debugfs || IS_ERR(device->d_debugfs)) + return; + + debugfs_create_file("cff_dump", 0644, device->d_debugfs, device, + &kgsl_cff_dump_enable_fops); + debugfs_create_u32("wait_timeout", 0644, device->d_debugfs, + &adreno_dev->wait_timeout); + debugfs_create_u32("ib_check", 0644, device->d_debugfs, + &adreno_dev->ib_check_level); + + adreno_dev->fast_hang_detect = 1; + debugfs_create_u32("fast_hang_detect", 0644, device->d_debugfs, + &adreno_dev->fast_hang_detect); + + + adreno_dev->ft_user_control = 0; + debugfs_create_u32("ft_user_control", 0644, device->d_debugfs, + &adreno_dev->ft_user_control); + adreno_dev->ft_policy = KGSL_FT_DEFAULT_POLICY; + debugfs_create_u32("ft_policy", 0644, device->d_debugfs, + &adreno_dev->ft_policy); + + + adreno_dev->long_ib_detect = 1; + debugfs_create_u32("long_ib_detect", 0644, device->d_debugfs, + &adreno_dev->long_ib_detect); + + adreno_dev->ft_pf_policy = KGSL_FT_PAGEFAULT_DEFAULT_POLICY; + debugfs_create_u32("ft_pagefault_policy", 0644, device->d_debugfs, + &adreno_dev->ft_pf_policy); +} diff --git a/pool/shard003/C/0064881_PolicyDuplicationSelect.c b/pool/shard003/C/0064881_PolicyDuplicationSelect.c new file mode 100644 index 0000000000000000000000000000000000000000..6eec4a77336ca7c4055919e5a5a23220314af2eb --- /dev/null +++ b/pool/shard003/C/0064881_PolicyDuplicationSelect.c @@ -0,0 +1,113 @@ +/* Microsoft Reference Implementation for TPM 2.0 + * + * The copyright in this software is being made available under the BSD License, + * included below. This software may be subject to other third party and + * contributor rights, including patent rights, and no such rights are granted + * under this license. + * + * Copyright (c) Microsoft Corporation + * + * All rights reserved. + * + * BSD License + * + * 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. + * + * 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. + */ +#include "Tpm.h" +#include "PolicyDuplicationSelect_fp.h" + +#if CC_PolicyDuplicationSelect // Conditional expansion of this file + +/*(See part 3 specification) +// allows qualification of duplication so that it a specific new parent may be +// selected or a new parent selected for a specific object. +*/ +// Return Type: TPM_RC +// TPM_RC_COMMAND_CODE 'commandCode' of 'policySession; is not empty +// TPM_RC_CPHASH 'cpHash' of 'policySession' is not empty +TPM_RC +TPM2_PolicyDuplicationSelect( + PolicyDuplicationSelect_In *in // IN: input parameter list + ) +{ + SESSION *session; + HASH_STATE hashState; + TPM_CC commandCode = TPM_CC_PolicyDuplicationSelect; + +// Input Validation + + // Get pointer to the session structure + session = SessionGet(in->policySession); + + // cpHash in session context must be empty + if(session->u1.cpHash.t.size != 0) + return TPM_RC_CPHASH; + + // commandCode in session context must be empty + if(session->commandCode != 0) + return TPM_RC_COMMAND_CODE; + +// Internal Data Update + + // Update name hash + session->u1.cpHash.t.size = CryptHashStart(&hashState, session->authHashAlg); + + // add objectName + CryptDigestUpdate2B(&hashState, &in->objectName.b); + + // add new parent name + CryptDigestUpdate2B(&hashState, &in->newParentName.b); + + // complete hash + CryptHashEnd2B(&hashState, &session->u1.cpHash.b); + + // update policy hash + // Old policyDigest size should be the same as the new policyDigest size since + // they are using the same hash algorithm + session->u2.policyDigest.t.size + = CryptHashStart(&hashState, session->authHashAlg); +// add old policy + CryptDigestUpdate2B(&hashState, &session->u2.policyDigest.b); + + // add command code + CryptDigestUpdateInt(&hashState, sizeof(TPM_CC), commandCode); + + // add objectName + if(in->includeObject == YES) + CryptDigestUpdate2B(&hashState, &in->objectName.b); + + // add new parent name + CryptDigestUpdate2B(&hashState, &in->newParentName.b); + + // add includeObject + CryptDigestUpdateInt(&hashState, sizeof(TPMI_YES_NO), in->includeObject); + + // complete digest + CryptHashEnd2B(&hashState, &session->u2.policyDigest.b); + + // set commandCode in session context + session->commandCode = TPM_CC_Duplicate; + + return TPM_RC_SUCCESS; +} + +#endif // CC_PolicyDuplicationSelect \ No newline at end of file diff --git a/pool/shard003/C/0064885_mutex_deadlock_check.c b/pool/shard003/C/0064885_mutex_deadlock_check.c new file mode 100644 index 0000000000000000000000000000000000000000..3ea7c10f0ce59f8d42c52295388fa90531affac0 --- /dev/null +++ b/pool/shard003/C/0064885_mutex_deadlock_check.c @@ -0,0 +1,162 @@ +/**************************************************************** + * * + * Copyright 2001, 2003 Sanchez Computer Associates, Inc. * + * * + * This source code contains the intellectual property * + * of its copyright holder(s), and is made available * + * under a license. If you do not know the terms of * + * the license, please stop and do not read further. * + * * + ****************************************************************/ + +/* mutex_deadlock_check -- mutex deadlock detection check + + There are 2 possible cases at this point: + + 1) This is not a TP transaction + 2) This is a TP transaction + + For case 1, when we come in here we should not have crit in any other region (except as noted below) + so instruct have_crit to complain about and release any such regions it finds. + For case 2, we should not have crit in regions that are not part of this transaction and regions + with an "ftok" that is higher than the region for which we are presently grabbing crit. + Since tp_reg_list is sorted by ftok, we can just run this list in order and mark the regions that are allowed + to have crit with our current cycle number. +*/ + +#include "mdef.h" + +#include /* Required for gtmsource.h */ +#include + +#ifdef VMS +#include /* Required for gtmsource.h */ +#endif + +#include "gdsroot.h" +#include "gdsblk.h" +#include "gdskill.h" +#include "gtm_facility.h" +#include "fileinfo.h" +#include "gdsbt.h" +#include "gdsfhead.h" +#include "gdscc.h" +#include "filestruct.h" +#include "hashtab.h" +#include "buddy_list.h" +#include "jnl.h" +#include "tp.h" +#include "gtmimagename.h" +#include "repl_msg.h" /* needed for gtmsource.h */ +#include "gtmsource.h" /* for jnlpool_addrs structure definition */ + +#include "have_crit.h" +#include "mutex_deadlock_check.h" + +GBLREF short dollar_tlevel; +GBLREF unsigned int t_tries; +GBLREF tp_region *tp_reg_list; /* Chained list of regions used in this transaction */ +GBLREF uint4 crit_deadlock_check_cycle; +GBLREF boolean_t is_replicator; +GBLREF boolean_t mu_reorg_process; +GBLREF jnlpool_addrs jnlpool; +GBLREF gd_region *gv_cur_region; +GBLREF sgmnt_addrs *cs_addrs; +GBLREF boolean_t in_mutex_deadlock_check; +GBLREF volatile int4 crit_count; + +void mutex_deadlock_check(mutex_struct_ptr_t criticalPtr) +{ + tp_region *tr; + sgmnt_addrs *csa; + int4 save_crit_count; + + if (in_mutex_deadlock_check) + return; + in_mutex_deadlock_check = TRUE; + /* A zero value of "crit_count" implies asynchronous activities can occur (e.g. db flush timer, periodic epoch timers etc.). + * At this point, although we are here through grab_crit()/grab_lock() (which would have incremented "crit_count"), we are + * in a safe and consistent state as far as the mutex structures go so it is ok to set "crit_count" to 0 implying we + * are now in an interruptible state (of course, we need to restore "crit_count" to what it was before returning). + * The other alternative of not changing "crit_count" presents us with complex situations wherein recursion + * of grab_crit/rel_crit might occur (through direct or indirect calls from mutex_deadlock_check()) + * causing crit_count to be > 1 and in turn causing the crit_count-reset-logic in grab_crit/rel_crit to + * do a "crit_count--" (instead of "crit_count = 0"). This suffers from the problem that in case of an error code path + * crit_count might not get decremented appropriately and hence become out-of-sync (i.e. a positive value instead + * of zero) and a non-zero value might cause indefinite deferrals of asynchronous events. + */ + assert(1 == crit_count); + save_crit_count = crit_count; + crit_count = 0; + + /* Need to determine who should and should not go through the deadlock checker. + * + * List of who needs to be considered + * ------------------------------------ + * -> GT.M, Update process, MUPIP LOAD and GT.CM GNP/OMI server : since they go through t_end() to update the database. + * Note that all of the above (and only those) have the "is_replicator" flag set to TRUE. + * -> MUPIP REORG, since it does non-TP transactions and goes through t_end() (has "mu_reorg_process" flag set). + * + * List of who does not need to be considered (with reasons) + * ----------------------------------------------------------- + * -> MUPIP RECOVER can hold crit on several regions (through TP or non-TP transactions). + * But it has standalone access and hence no possibility of a deadlock. + * -> MUPIP RESTORE too holds standalone access so does not need to be considered. + * -> Source Server, Receiver Server etc. can hold only one CRIT resource at any point of time. + * -> DSE, MUPIP BACKUP, MUPIP SET JOURNAL etc. can legitimately hold crit on several regions though in non-TP. + */ + if (is_replicator || mu_reorg_process) + { + if (0 == dollar_tlevel) + { + if ((NULL != jnlpool.jnlpool_dummy_reg) && jnlpool.jnlpool_dummy_reg->open) + { + ++crit_deadlock_check_cycle; + if (FILE_INFO(jnlpool.jnlpool_dummy_reg)->s_addrs.critical == criticalPtr) + { /* grab_lock going for crit on the jnlpool region. gv_cur_region points to the + * current region of interest, which better have replication enabled, and be now crit + */ + assert(cs_addrs == &FILE_INFO(gv_cur_region)->s_addrs); + csa = &FILE_INFO(gv_cur_region)->s_addrs; + if (FALSE == csa->now_crit || !REPL_ENABLED(csa->hdr)) + GTMASSERT; /* should have crit on gv_cur_region before asking for jnlpool */ + csa->crit_check_cycle = crit_deadlock_check_cycle; /* allow for crit in gv_cur_region */ + } + } + } else + { /* Need to mark the regions allowed to have crit as follows: + * Place the current cycle into the csa's of regions allowed to have crit so have_crit() can easily test. + * Note that should the system be up long enough for the 2**32 cycle value to + * wrap and a region be unused for most of that time, such a region might not be entitled to crit + * but have an old csa->crit_cycle_check matching the current crit_deadlock_cycle_check - + * that case would not trigger have_crit() to release crit on that region; + * however, the next call to this routine increments crit_deadlock_check_cycle and so + * crit on that region gets released after two calls instead of (the usual) one. + */ + ++crit_deadlock_check_cycle; + for (tr = tp_reg_list; NULL != tr; tr = tr->fPtr) + { + if (!tr->reg->open) + continue; + csa = &FILE_INFO(tr->reg)->s_addrs; + if (csa->now_crit) + csa->crit_check_cycle = crit_deadlock_check_cycle; + else + { /* Seen first non-crit region. Make sure either of the following is true. + * (i) this is the region we are currently grabbing crit on + * (ii) we do not hold crit on any region in the tp_reg_list. + * If neither of the above, we have an out of design condition that can only + * warrant blowing the process up.. + */ + if ((csa->critical != criticalPtr) && (tr != tp_reg_list)) + GTMASSERT; + break; + } + } + } + /* Release crit in regions not legitimately part of this TP/non-TP transaction */ + have_crit(CRIT_RELEASE | CRIT_NOT_TRANS_REG); + } + crit_count = save_crit_count; + in_mutex_deadlock_check = FALSE; +} diff --git a/pool/shard003/C/0064904_msm_ringbuffer.c b/pool/shard003/C/0064904_msm_ringbuffer.c new file mode 100644 index 0000000000000000000000000000000000000000..bf065a54013086b774dfbffb4175a8f407bfa51d --- /dev/null +++ b/pool/shard003/C/0064904_msm_ringbuffer.c @@ -0,0 +1,66 @@ +/* + * Copyright (C) 2013 Red Hat + * Author: Rob Clark + * + * 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, see . + */ + +#include "msm_ringbuffer.h" +#include "msm_gpu.h" + +struct msm_ringbuffer *msm_ringbuffer_new(struct msm_gpu *gpu, int size) +{ + struct msm_ringbuffer *ring; + int ret; + + if (WARN_ON(!is_power_of_2(size))) + return ERR_PTR(-EINVAL); + + ring = kzalloc(sizeof(*ring), GFP_KERNEL); + if (!ring) { + ret = -ENOMEM; + goto fail; + } + + ring->gpu = gpu; + + /* Pass NULL for the iova pointer - we will map it later */ + ring->start = msm_gem_kernel_new(gpu->dev, size, MSM_BO_WC, + gpu->aspace, &ring->bo, NULL); + + if (IS_ERR(ring->start)) { + ret = PTR_ERR(ring->start); + ring->start = 0; + goto fail; + } + ring->end = ring->start + (size / 4); + ring->cur = ring->start; + + ring->size = size; + + return ring; + +fail: + if (ring) + msm_ringbuffer_destroy(ring); + return ERR_PTR(ret); +} + +void msm_ringbuffer_destroy(struct msm_ringbuffer *ring) +{ + if (ring->bo) { + msm_gem_put_vaddr(ring->bo); + drm_gem_object_unreference_unlocked(ring->bo); + } + kfree(ring); +} diff --git a/pool/shard003/C/0064905_tizidletoloaded.c b/pool/shard003/C/0064905_tizidletoloaded.c new file mode 100644 index 0000000000000000000000000000000000000000..f695fd9d9325625cc7e761ff0751d844cf92ebb5 --- /dev/null +++ b/pool/shard003/C/0064905_tizidletoloaded.c @@ -0,0 +1,177 @@ +/** + * Copyright (C) 2011-2020 Aratelia Limited - Juan A. Rubio and contributors and contributors + * + * This file is part of Tizonia + * + * Tizonia 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. + * + * Tizonia 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 Tizonia. If not, see . + */ + +/** + * @file tizidletoloaded.c + * @author Juan A. Rubio + * + * @brief Tizonia OpenMAX IL - IdleToLoaded OMX IL substate implementation + * + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "tizidletoloaded.h" +#include "tizstate.h" +#include "tizstate_decls.h" +#include "tizutils.h" +#include "tizplatform.h" + +#include + +#ifdef TIZ_LOG_CATEGORY_NAME +#undef TIZ_LOG_CATEGORY_NAME +#define TIZ_LOG_CATEGORY_NAME "tiz.tizonia.fsm.idletoloaded" +#endif + +static void * +idletoloaded_ctor (void * ap_obj, va_list * app) +{ + tiz_idletoloaded_t * p_obj + = super_ctor (typeOf (ap_obj, "tizidletoloaded"), ap_obj, app); + return p_obj; +} + +static void * +idletoloaded_dtor (void * ap_obj) +{ + return super_dtor (typeOf (ap_obj, "tizidletoloaded"), ap_obj); +} + +/* + * from tiz_api class + */ + +static OMX_ERRORTYPE +idletoloaded_SetParameter (const void * ap_obj, OMX_HANDLETYPE ap_hdl, + OMX_INDEXTYPE a_index, OMX_PTR ap_struct) +{ + return OMX_ErrorNotImplemented; +} + +static OMX_ERRORTYPE +idletoloaded_GetState (const void * ap_obj, OMX_HANDLETYPE ap_hdl, + OMX_STATETYPE * ap_state) +{ + *ap_state = OMX_StateIdle; + return OMX_ErrorNone; +} + +static OMX_ERRORTYPE +idletoloaded_UseBuffer (const void * ap_obj, OMX_HANDLETYPE ap_hdl, + OMX_BUFFERHEADERTYPE ** app_buf_hdr, + OMX_U32 a_port_index, OMX_PTR ap_app_private, + OMX_U32 a_size_bytes, OMX_U8 * ap_buf) +{ + return OMX_ErrorNotImplemented; +} + +static OMX_ERRORTYPE +idletoloaded_AllocateBuffer (const void * ap_obj, OMX_HANDLETYPE ap_hdl, + OMX_BUFFERHEADERTYPE ** pap_buf, + OMX_U32 a_port_index, OMX_PTR ap_app_private, + OMX_U32 a_size_bytes) +{ + return OMX_ErrorNotImplemented; +} + +static OMX_ERRORTYPE +idletoloaded_FreeBuffer (const void * ap_obj, OMX_HANDLETYPE ap_hdl, + OMX_U32 a_port_index, OMX_BUFFERHEADERTYPE * ap_buf) +{ + return OMX_ErrorNotImplemented; +} + +static OMX_ERRORTYPE +idletoloaded_EmptyThisBuffer (const void * ap_obj, OMX_HANDLETYPE ap_hdl, + OMX_BUFFERHEADERTYPE * ap_buf) +{ + return OMX_ErrorNotImplemented; +} + +static OMX_ERRORTYPE +idletoloaded_FillThisBuffer (const void * ap_obj, OMX_HANDLETYPE ap_hdl, + OMX_BUFFERHEADERTYPE * ap_buf) +{ + return OMX_ErrorNotImplemented; +} + +/* + * from tiz_state class + */ + +static OMX_ERRORTYPE +idletoloaded_trans_complete (const void * ap_obj, OMX_PTR ap_servant, + OMX_STATETYPE a_new_state) +{ + TIZ_TRACE (handleOf (ap_servant), "Trans complete to state [%s]...", + tiz_fsm_state_to_str ((tiz_fsm_state_id_t) a_new_state)); + assert (OMX_StateLoaded == a_new_state); + return tiz_state_super_trans_complete (typeOf (ap_obj, "tizidletoloaded"), + ap_obj, ap_servant, a_new_state); +} + +/* + * idletoloaded_class + */ + +static void * +idletoloaded_class_ctor (void * ap_obj, va_list * app) +{ + /* NOTE: Class methods might be added in the future. None for now. */ + return super_ctor (typeOf (ap_obj, "tizidletoloaded_class"), ap_obj, app); +} + +/* + * initialization + */ + +void * +tiz_idletoloaded_class_init (void * ap_tos, void * ap_hdl) +{ + void * tizidle = tiz_get_type (ap_hdl, "tizidle"); + void * tizidletoloaded_class + = factory_new (classOf (tizidle), "tizidletoloaded_class", + classOf (tizidle), sizeof (tiz_idletoloaded_class_t), ap_tos, + ap_hdl, ctor, idletoloaded_class_ctor, 0); + return tizidletoloaded_class; +} + +void * +tiz_idletoloaded_init (void * ap_tos, void * ap_hdl) +{ + void * tizidle = tiz_get_type (ap_hdl, "tizidle"); + void * tizidletoloaded_class = tiz_get_type (ap_hdl, "tizidletoloaded_class"); + TIZ_LOG_CLASS (tizidletoloaded_class); + void * tizidletoloaded = factory_new ( + tizidletoloaded_class, "tizidletoloaded", tizidle, + sizeof (tiz_idletoloaded_t), ap_tos, ap_hdl, ctor, idletoloaded_ctor, dtor, + idletoloaded_dtor, tiz_api_SetParameter, idletoloaded_SetParameter, + tiz_api_GetState, idletoloaded_GetState, tiz_api_UseBuffer, + idletoloaded_UseBuffer, tiz_api_AllocateBuffer, idletoloaded_AllocateBuffer, + tiz_api_FreeBuffer, idletoloaded_FreeBuffer, tiz_api_EmptyThisBuffer, + idletoloaded_EmptyThisBuffer, tiz_api_FillThisBuffer, + idletoloaded_FillThisBuffer, tiz_state_trans_complete, + idletoloaded_trans_complete, 0); + + return tizidletoloaded; +} diff --git a/pool/shard003/C/0064928_main.c b/pool/shard003/C/0064928_main.c new file mode 100644 index 0000000000000000000000000000000000000000..52c503110d8388038f176789b93a0bc024941350 --- /dev/null +++ b/pool/shard003/C/0064928_main.c @@ -0,0 +1,45 @@ + +#include "../generic/main.c" + +void movie_record_task() +{ +} + +long get_vbatt_min() +{ + return 3550; +} + +long get_vbatt_max() +{ + return 4110; +} + +static const int fl_tbl[] = {5800, 7109, 8462, 10093, 12120, 14421, 17400}; +#define NUM_FL (sizeof(fl_tbl)/sizeof(fl_tbl[0])) +#define CF_EFL 60345 + +const int zoom_points = NUM_FL; + +int get_effective_focal_length(int zp) { + return (CF_EFL*get_focal_length(zp))/10000; +} + +int get_focal_length(int zp) { + if (zp<0) return fl_tbl[0]; + else if (zp>NUM_FL-1) return fl_tbl[NUM_FL-1]; + else return fl_tbl[zp]; +} + +int get_zoom_x(int zp) { + if (zp<1) return 10; + else if (zp>NUM_FL-1) return fl_tbl[NUM_FL-1]*10/fl_tbl[0]; + else return fl_tbl[zp]*10/fl_tbl[0]; +} + +#if 0 +int rec_switch_state(void) { +// mode = (physw_status[2] & 0x00002000)?MODE_REC:MODE_PLAY; + return (physw_status[2] & 0x00002000); +} +#endif diff --git a/pool/shard003/C/0064939_test14.c b/pool/shard003/C/0064939_test14.c new file mode 100644 index 0000000000000000000000000000000000000000..4ce6992bc37a2a21b25d566fd91efa7232e1ee29 --- /dev/null +++ b/pool/shard003/C/0064939_test14.c @@ -0,0 +1,51 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +/*===================================================================== +** +** Source: test14.c +** +** Purpose: Test #14 for the vsprintf function. +** +** +**===================================================================*/ + +#include +#include "../vsprintf.h" + +/* + * Notes: memcmp is used, as is strlen. + */ + + +int __cdecl main(int argc, char *argv[]) +{ + double val = 256.0; + double neg = -256.0; + + if (PAL_Initialize(argc, argv) != 0) + { + return(FAIL); + } + + DoDoubleTest("foo %e", val, "foo 2.560000e+002", "foo 2.560000e+02"); + DoDoubleTest("foo %le", val, "foo 2.560000e+002", "foo 2.560000e+02"); + DoDoubleTest("foo %he", val, "foo 2.560000e+002", "foo 2.560000e+02"); + DoDoubleTest("foo %Le", val, "foo 2.560000e+002", "foo 2.560000e+02"); + DoDoubleTest("foo %I64e", val, "foo 2.560000e+002", "foo 2.560000e+02"); + DoDoubleTest("foo %14e", val, "foo 2.560000e+002", "foo 2.560000e+02"); + DoDoubleTest("foo %-14e", val, "foo 2.560000e+002 ", "foo 2.560000e+02 "); + DoDoubleTest("foo %.1e", val, "foo 2.6e+002", "foo 2.6e+02"); + DoDoubleTest("foo %.8e", val, "foo 2.56000000e+002", "foo 2.56000000e+02"); + DoDoubleTest("foo %014e", val, "foo 02.560000e+002", "foo 002.560000e+02"); + DoDoubleTest("foo %#e", val, "foo 2.560000e+002", "foo 2.560000e+02"); + DoDoubleTest("foo %+e", val, "foo +2.560000e+002", "foo +2.560000e+02"); + DoDoubleTest("foo % e", val, "foo 2.560000e+002", "foo 2.560000e+02"); + DoDoubleTest("foo %+e", neg, "foo -2.560000e+002", "foo -2.560000e+02"); + DoDoubleTest("foo % e", neg, "foo -2.560000e+002", "foo -2.560000e+02"); + + PAL_Terminate(); + return PASS; +} diff --git a/pool/shard003/C/0064952_lib590.c b/pool/shard003/C/0064952_lib590.c new file mode 100644 index 0000000000000000000000000000000000000000..ca54e3070a5981232179f37c4172dcacb5c6df39 --- /dev/null +++ b/pool/shard003/C/0064952_lib590.c @@ -0,0 +1,71 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +#include "test.h" + +/* + Based on a bug report recipe by Rene Bernhardt in + https://curl.haxx.se/mail/lib-2011-10/0323.html + + It is reproducible by the following steps: + + - Use a proxy that offers NTLM and Negotiate ( CURLOPT_PROXY and + CURLOPT_PROXYPORT) + - Tell libcurl NOT to use Negotiate CURL_EASY_SETOPT(CURLOPT_PROXYAUTH, + CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_NTLM) + - Start the request +*/ + +#include "memdebug.h" + +int test(char *URL) +{ + CURLcode res; + CURL *curl; + + if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { + fprintf(stderr, "curl_global_init() failed\n"); + return TEST_ERR_MAJOR_BAD; + } + + curl = curl_easy_init(); + if(!curl) { + fprintf(stderr, "curl_easy_init() failed\n"); + curl_global_cleanup(); + return TEST_ERR_MAJOR_BAD; + } + + test_setopt(curl, CURLOPT_URL, URL); + test_setopt(curl, CURLOPT_HEADER, 1L); + test_setopt(curl, CURLOPT_PROXYAUTH, + (long) (CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_NTLM)); + test_setopt(curl, CURLOPT_PROXY, libtest_arg2); /* set in first.c */ + test_setopt(curl, CURLOPT_PROXYUSERPWD, "me:password"); + + res = curl_easy_perform(curl); + + test_cleanup: + + curl_easy_cleanup(curl); + curl_global_cleanup(); + + return (int)res; +} diff --git a/pool/shard003/C/0064957_slang_compile_function.c b/pool/shard003/C/0064957_slang_compile_function.c new file mode 100644 index 0000000000000000000000000000000000000000..4dd885176d445d920ecfd02e18a83752c02f48c3 --- /dev/null +++ b/pool/shard003/C/0064957_slang_compile_function.c @@ -0,0 +1,262 @@ +/* + * Mesa 3-D graphics library + * Version: 6.5 + * + * Copyright (C) 2005-2006 Brian Paul 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 + * BRIAN PAUL 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. + */ + +/** + * \file slang_compile_function.c + * slang front-end compiler + * \author Michal Krol + */ + +#include "main/imports.h" +#include "slang_compile.h" +#include "slang_mem.h" + + +int +slang_function_construct(slang_function * func) +{ + func->kind = SLANG_FUNC_ORDINARY; + if (!slang_variable_construct(&func->header)) + return 0; + + func->parameters = (slang_variable_scope *) + _slang_alloc(sizeof(slang_variable_scope)); + if (func->parameters == NULL) { + slang_variable_destruct(&func->header); + return 0; + } + + _slang_variable_scope_ctr(func->parameters); + func->param_count = 0; + func->body = NULL; + return 1; +} + +void +slang_function_destruct(slang_function * func) +{ + slang_variable_destruct(&func->header); + slang_variable_scope_destruct(func->parameters); + _slang_free(func->parameters); + if (func->body != NULL) { + slang_operation_destruct(func->body); + _slang_free(func->body); + } +} + + +slang_function * +slang_function_new(slang_function_kind kind) +{ + slang_function *fun = (slang_function *) + _slang_alloc(sizeof(slang_function)); + if (fun) { + slang_function_construct(fun); + fun->kind = kind; + } + return fun; +} + + +/* + * slang_function_scope + */ + +GLvoid +_slang_function_scope_ctr(slang_function_scope * self) +{ + self->functions = NULL; + self->num_functions = 0; + self->outer_scope = NULL; +} + +void +slang_function_scope_destruct(slang_function_scope * scope) +{ + unsigned int i; + + for (i = 0; i < scope->num_functions; i++) + slang_function_destruct(scope->functions + i); + _slang_free(scope->functions); +} + + +/** + * Does this function have a non-void return value? + */ +GLboolean +_slang_function_has_return_value(const slang_function *fun) +{ + return fun->header.type.specifier.type != SLANG_SPEC_VOID; +} + + +/** + * Search a list of functions for a particular function by name. + * \param funcs the list of functions to search + * \param a_name the name to search for + * \param all_scopes if non-zero, search containing scopes too. + * \return pointer to found function, or NULL. + */ +int +slang_function_scope_find_by_name(slang_function_scope * funcs, + slang_atom a_name, int all_scopes) +{ + unsigned int i; + + for (i = 0; i < funcs->num_functions; i++) + if (a_name == funcs->functions[i].header.a_name) + return 1; + if (all_scopes && funcs->outer_scope != NULL) + return slang_function_scope_find_by_name(funcs->outer_scope, a_name, 1); + return 0; +} + + +/** + * Search a list of functions for a particular function (for implementing + * function calls. Matching is done by first comparing the function's name, + * then the function's parameter list. + * + * \param funcs the list of functions to search + * \param fun the function to search for + * \param all_scopes if non-zero, search containing scopes too. + * \return pointer to found function, or NULL. + */ +slang_function * +slang_function_scope_find(slang_function_scope * funcs, slang_function * fun, + int all_scopes) +{ + unsigned int i; + + for (i = 0; i < funcs->num_functions; i++) { + slang_function *f = &funcs->functions[i]; + const GLuint haveRetValue = 0; +#if 0 + = (f->header.type.specifier.type != SLANG_SPEC_VOID); +#endif + unsigned int j; + + /* + printf("Compare name %s to %s (ret %u, %d, %d)\n", + (char *) fun->header.a_name, (char *) f->header.a_name, + haveRetValue, + fun->param_count, f->param_count); + */ + + if (fun->header.a_name != f->header.a_name) + continue; + if (fun->param_count != f->param_count) + continue; + for (j = haveRetValue; j < fun->param_count; j++) { + if (!slang_type_specifier_equal + (&fun->parameters->variables[j]->type.specifier, + &f->parameters->variables[j]->type.specifier)) + break; + } + if (j == fun->param_count) { + /* + printf("Found match\n"); + */ + return f; + } + } + /* + printf("Not found\n"); + */ + if (all_scopes && funcs->outer_scope != NULL) + return slang_function_scope_find(funcs->outer_scope, fun, 1); + return NULL; +} + + +/** + * Lookup a function according to name and parameter count/types. + */ +slang_function * +_slang_function_locate(const slang_function_scope * funcs, slang_atom a_name, + slang_operation * args, GLuint num_args, + const slang_name_space * space, slang_atom_pool * atoms, + slang_info_log *log, GLboolean *error) +{ + slang_typeinfo arg_ti[100]; + GLuint i; + + *error = GL_FALSE; + + /* determine type of each argument */ + assert(num_args < 100); + for (i = 0; i < num_args; i++) { + if (!slang_typeinfo_construct(&arg_ti[i])) + return NULL; + if (!_slang_typeof_operation(&args[i], space, &arg_ti[i], atoms, log)) { + return NULL; + } + } + + /* loop over function scopes */ + while (funcs) { + + /* look for function with matching name and argument/param types */ + for (i = 0; i < funcs->num_functions; i++) { + slang_function *f = &funcs->functions[i]; + const GLuint haveRetValue = _slang_function_has_return_value(f); + GLuint j; + + if (a_name != f->header.a_name) + continue; + if (f->param_count - haveRetValue != num_args) + continue; + + /* compare parameter / argument types */ + for (j = 0; j < num_args; j++) { + if (!slang_type_specifier_compatible(&arg_ti[j].spec, + &f->parameters->variables[j]->type.specifier)) { + /* param/arg types don't match */ + break; + } + + /* "out" and "inout" formal parameter requires the actual + * argument to be an l-value. + */ + if (!arg_ti[j].can_be_referenced && + (f->parameters->variables[j]->type.qualifier == SLANG_QUAL_OUT || + f->parameters->variables[j]->type.qualifier == SLANG_QUAL_INOUT)) { + /* param is not an lvalue! */ + *error = GL_TRUE; + return NULL; + } + } + + if (j == num_args) { + /* name and args match! */ + return f; + } + } + + funcs = funcs->outer_scope; + } + + return NULL; +} diff --git a/pool/shard003/C/0064966_url_parse.c b/pool/shard003/C/0064966_url_parse.c new file mode 100644 index 0000000000000000000000000000000000000000..a884073ed8e5fb1f0ea88bf6e8d36aac0b40f54f --- /dev/null +++ b/pool/shard003/C/0064966_url_parse.c @@ -0,0 +1,89 @@ +#include "url.h" + +#include +#include + +static int has_port(const char *s); +static const char *parse_protocol(struct url_t *self, const char *p); +static const char *parse_host(struct url_t *self, const char *p); +static const char *parse_port(struct url_t *self, const char *p); + +struct url_t *url_parse(const char *url) { + struct url_t *self = url_new(); + const char *p = url; + + if (!(p = parse_protocol(self, p))) { + url_free(self); + return NULL; + } + + self->has_port = has_port(p); + if (!(p = parse_host(self, p))) { + url_free(self); + return NULL; + } + + if (!(p = parse_port(self, p))) { + url_free(self); + return NULL; + } + + self->path = strdup(p); + return self; +} + +/*** private functions ***/ + +static int has_port(const char *s) { + const char *slash = strchr(s, '/'); + const char *colon = strchr(s, ':'); + if (!colon) { + return 0; + } + return colon < slash; +} + +static const char *parse_protocol(struct url_t *self, const char *p) { + const char *q; + + if (q = strstr(p, "://")) { + int len = q - p; + self->protocol = strndup(p, len); + return q + 3; + } else { + return NULL; + } +} + +static const char *parse_host(struct url_t *self, const char *p) { + const char *q; + + if (q = strchr(p, self->has_port ? ':' : '/')) { + int len = q - p; + self->host = strndup(p, len); + return q + 1; + } else { + return NULL; + } +} + +static const char *parse_port(struct url_t *self, const char *p) { + const char *q; + + if (self->has_port) { + if (q = strchr(p, '/')) { + int len = q - p; + self->port = strndup(p, len); + return q + 1; + } else { + return NULL; + } + } else { + if (!strcmp(self->protocol, "http")) { + self->port = strdup("80"); + } else if (!strcmp(self->protocol, "https")) { + self->port = strdup("443"); + } + return p; + } +} diff --git a/pool/shard003/C/0064974_numa.c b/pool/shard003/C/0064974_numa.c new file mode 100644 index 0000000000000000000000000000000000000000..cbc63a80aaf83b4863677ca8d417d1570828cba2 --- /dev/null +++ b/pool/shard003/C/0064974_numa.c @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "stats.h" +#include "collect.h" +#include "trace.h" + +// # cat /sys/devices/system/node/node0/numastat +// numa_hit 24972369 +// numa_miss 41182663 +// numa_foreign 12112910 +// interleave_hit 49948 +// local_node 24910136 +// other_node 41244896 + +#define KEYS \ + X(numa_hit, "E", ""), \ + X(numa_miss, "E", ""), \ + X(numa_foreign, "E", ""), \ + X(interleave_hit, "E", ""), \ + X(local_node, "E", ""), \ + X(other_node, "E", "") + +static void numa_collect(struct stats_type *type) +{ + const char *dir_path = "/sys/devices/system/node"; + DIR *dir = NULL; + + dir = opendir(dir_path); + if (dir == NULL) { + ERROR("cannot open `%s': %m\n", dir_path); + goto out; + } + + struct dirent *ent; + while ((ent = readdir(dir)) != NULL) { + struct stats *stats = NULL; + const char *node; + char path[80]; + + if (strncmp(ent->d_name, "node", 4) != 0) + continue; + + node = ent->d_name + 4; + stats = get_current_stats(type, node); + if (stats == NULL) + continue; + + snprintf(path, sizeof(path), "%s/node%s/numastat", dir_path, node); + path_collect_key_value(path, stats); + } + + out: + if (dir != NULL) + closedir(dir); +} + +struct stats_type numa_stats_type = { + .st_name = "numa", + .st_collect = &numa_collect, +#define X SCHEMA_DEF + .st_schema_def = JOIN(KEYS), +#undef X +}; diff --git a/pool/shard003/C/0064983_archive_text.c b/pool/shard003/C/0064983_archive_text.c new file mode 100644 index 0000000000000000000000000000000000000000..fc2a8e7d225dd33ffd015de969024c71de04a37d --- /dev/null +++ b/pool/shard003/C/0064983_archive_text.c @@ -0,0 +1,214 @@ +/* + * GEM-Mapper v3 (GEM3) + * Copyright (c) 2011-2017 by Santiago Marco-Sola + * + * This file is part of GEM-Mapper v3 (GEM3). + * + * 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 . + * + * PROJECT: GEM-Mapper v3 (GEM3) + * AUTHOR(S): Santiago Marco-Sola + * DESCRIPTION: + * Archive text module provides data structures and functions to + * manipulate and query a genomic-text (ACGTN) + */ + +#include "archive/archive_text.h" +#include "archive/archive_text_rl.h" + +/* + * Archive-Text Model & Version + */ +#define ARCHIVE_TEXT_MODEL_NO 1006ull + +/* + * Builder + */ +void archive_text_write( + fm_t* const file_manager, + dna_text_t* const enc_text, + const bool explicit_complement, + const uint64_t forward_text_length, + sampled_rl_t* const sampled_rl, + const bool verbose) { + // Write Header (Meta-data) + fm_write_uint64(file_manager,ARCHIVE_TEXT_MODEL_NO); + fm_write_uint64(file_manager,(sampled_rl!=NULL) ? 1ul : 0ul); // RL-Text + fm_write_uint64(file_manager,(explicit_complement) ? 1ul : 0ul); // Explicit RC-text + fm_write_uint64(file_manager,forward_text_length); // Total length of the forward text + // Text + if (explicit_complement) { + // Save all (except extra separator) + dna_text_write_chunk(file_manager,enc_text,dna_text_get_length(enc_text)-1); + } else { + // Save just forward text + dna_text_write_chunk(file_manager,enc_text,forward_text_length); + } + // Sampled RL-Index Positions + if (sampled_rl!=NULL) sampled_rl_write(file_manager,sampled_rl); +} +/* + * Loader + */ +archive_text_t* archive_text_read_mem(mm_t* const memory_manager) { + // Allocate + archive_text_t* const archive_text = mm_alloc(archive_text_t); + // Read Header + const uint64_t archive_text_model_no = mm_read_uint64(memory_manager); + gem_cond_error(archive_text_model_no!=ARCHIVE_TEXT_MODEL_NO, + ARCHIVE_TEXT_WRONG_MODEL_NO,archive_text_model_no,(uint64_t)ARCHIVE_TEXT_MODEL_NO); + archive_text->run_length = (mm_read_uint64(memory_manager)==1); // RL-Text + archive_text->explicit_complement = (mm_read_uint64(memory_manager)==1); // Explicit RC-text + archive_text->forward_text_length = mm_read_uint64(memory_manager); // Total length of the forward text + // Text + archive_text->enc_text = dna_text_read_mem(memory_manager); + // Load Sampled RL-Index Positions + if (archive_text->run_length) archive_text->sampled_rl = sampled_rl_read_mem(memory_manager); + // Return + return archive_text; +} +void archive_text_delete(archive_text_t* const archive_text) { + // Delete Text + dna_text_delete(archive_text->enc_text); + // Delete Sampled RL-Index Positions + if (archive_text->run_length) sampled_rl_delete(archive_text->sampled_rl); + mm_free(archive_text); +} +/* + * Accessors + */ +uint64_t archive_text_get_size(archive_text_t* const archive_text) { + const uint64_t graph_size = 0; + const uint64_t text_size = dna_text_get_size(archive_text->enc_text); + const uint64_t sampled_rl_size = 0; // TODO + return graph_size+text_size+sampled_rl_size; +} +strand_t archive_text_get_position_strand( + archive_text_t* const archive_text, + const uint64_t index_position) { + return index_position < archive_text->forward_text_length ? Forward : Reverse; +} +uint64_t archive_text_get_unitary_projection( + archive_text_t* const archive_text, + const uint64_t index_position) { + return 2*archive_text->forward_text_length - index_position - 2; +} +uint64_t archive_text_get_projection( + archive_text_t* const archive_text, + const uint64_t index_position, + const uint64_t length) { + return 2*archive_text->forward_text_length - index_position - length - 1; +} +/* + * Archive Text Retriever + */ +void archive_text_retrieve( + archive_text_t* const archive_text, + const uint64_t text_position, + const uint64_t text_length, + const bool reverse_complement_text, + const bool run_length_text, + text_trace_t* const text_trace, + mm_allocator_t* const mm_allocator) { + // Retrieve text + text_trace->text_allocated = false; + text_trace->text_padded_allocated = false; + text_trace->text_length = text_length; + text_trace->strand = archive_text_get_position_strand(archive_text,text_position); + text_trace->position = text_position; + if (text_position < archive_text->forward_text_length || archive_text->explicit_complement) { + if (reverse_complement_text) { + if (archive_text->explicit_complement) { + const uint64_t position_fprojection = archive_text_get_projection(archive_text,text_position,text_length); + text_trace->text = dna_text_retrieve_sequence(archive_text->enc_text,position_fprojection); + } else { + // Reverse-Complement the text + uint8_t* const text = dna_text_retrieve_sequence(archive_text->enc_text,text_position); + text_trace->text = mm_allocator_calloc(mm_allocator,text_length,uint8_t,false); + text_trace->text_allocated = true; + uint64_t i_forward, i_backward; + for (i_forward=0,i_backward=text_length-1;i_forwardtext[i_forward] = dna_encoded_complement(text[i_backward]); + } + } + } else { + text_trace->text = dna_text_retrieve_sequence(archive_text->enc_text,text_position); + } + } else { + // Forward projection + const uint64_t position_fprojection = archive_text_get_projection(archive_text,text_position,text_length); + uint8_t* const text = dna_text_retrieve_sequence(archive_text->enc_text,position_fprojection); + if (reverse_complement_text) { + text_trace->text = text; + } else { + // Reverse-Complement the text + text_trace->text = mm_allocator_calloc(mm_allocator,text_length,uint8_t,false); + text_trace->text_allocated = true; + uint64_t i_forward, i_backward; + for (i_forward=0,i_backward=text_length-1;i_forwardtext[i_forward] = dna_encoded_complement(text[i_backward]); + } + } + } + // Compute RL-text + if (run_length_text) { + // Allocate RL-Encoded Text + text_trace->rl_text = mm_allocator_calloc(mm_allocator,text_length,uint8_t,false); + text_trace->rl_runs_acc = mm_allocator_calloc(mm_allocator,text_length,uint32_t,false); + // RL encode + archive_text_rl_encode( + text_trace->text,text_length,text_trace->rl_text, + &text_trace->rl_text_length,text_trace->rl_runs_acc); + } else { + text_trace->rl_text = NULL; + text_trace->rl_runs_acc = NULL; + } + // Init Padded Text + text_trace->text_padded = text_trace->text; + text_trace->text_padded_length = text_trace->text_length; + text_trace->text_padded_left = 0; + text_trace->text_padded_right = 0; +} +/* + * Display + */ +void archive_text_print( + FILE* const stream, + const archive_text_t* const archive_text) { + const uint64_t text_size = dna_text_get_size(archive_text->enc_text); + const uint64_t sampled_rl_size = 0; // TODO + const uint64_t archive_text_size = text_size + sampled_rl_size; + // Display + tab_fprintf(stream,"[GEM]>Archive.Text\n"); + tab_fprintf(stream," => Archive.RL.Text %s\n",(archive_text->run_length)?"Yes":"No"); + tab_fprintf(stream," => Archive.ExplicitComplement %s\n",(archive_text->explicit_complement)?"Yes":"No"); + tab_fprintf(stream," => Archive.Length %"PRIu64"\n",dna_text_get_length(archive_text->enc_text)); + tab_fprintf(stream," => Archive.Forward.Length %"PRIu64"\n",archive_text->forward_text_length); + tab_fprintf(stream," => Archive.Text.Size %"PRIu64" MB (100%%)\n",CONVERT_B_TO_MB(archive_text_size)); + tab_fprintf(stream," => Text.Size %"PRIu64" MB (%2.3f%%)\n",CONVERT_B_TO_MB(text_size),PERCENTAGE(text_size,archive_text_size)); + tab_fprintf(stream," => SampledRL.Size %"PRIu64" MB (%2.3f%%)\n",CONVERT_B_TO_MB(sampled_rl_size),PERCENTAGE(sampled_rl_size,archive_text_size)); + /* + * Components Display + */ + // Archive Text + tab_global_inc(); + dna_text_print(stream,archive_text->enc_text); + tab_global_dec(); + // Sampled RL-Text + tab_global_inc(); + if (archive_text->sampled_rl != NULL) { + sampled_rl_print(stream,archive_text->sampled_rl); + } + tab_global_dec(); +} diff --git a/pool/shard003/C/0064999_8250_early.c b/pool/shard003/C/0064999_8250_early.c new file mode 100644 index 0000000000000000000000000000000000000000..cdb6d01a4ec8c581f736da805e187de903e7ae22 --- /dev/null +++ b/pool/shard003/C/0064999_8250_early.c @@ -0,0 +1,287 @@ +/* + * Early serial console for 8250/16550 devices + * + * (c) Copyright 2004 Hewlett-Packard Development Company, L.P. + * Bjorn Helgaas + * + * 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. + * + * Based on the 8250.c serial driver, Copyright (C) 2001 Russell King, + * and on early_printk.c by Andi Kleen. + * + * This is for use before the serial driver has initialized, in + * particular, before the UARTs have been discovered and named. + * Instead of specifying the console device as, e.g., "ttyS0", + * we locate the device directly by its MMIO or I/O port address. + * + * The user can specify the device directly, e.g., + * earlycon=uart8250,io,0x3f8,9600n8 + * earlycon=uart8250,mmio,0xff5e0000,115200n8 + * earlycon=uart8250,mmio32,0xff5e0000,115200n8 + * or + * console=uart8250,io,0x3f8,9600n8 + * console=uart8250,mmio,0xff5e0000,115200n8 + * console=uart8250,mmio32,0xff5e0000,115200n8 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef CONFIG_FIX_EARLYCON_MEM +#include +#include +#endif + +struct early_serial8250_device { + struct uart_port port; + char options[16]; /* e.g., 115200n8 */ + unsigned int baud; +}; + +static struct early_serial8250_device early_device; + +static unsigned int __init serial_in(struct uart_port *port, int offset) +{ + switch (port->iotype) { + case UPIO_MEM: + return readb(port->membase + offset); + case UPIO_MEM32: + return readl(port->membase + (offset << 2)); + case UPIO_PORT: + return inb(port->iobase + offset); + default: + return 0; + } +} + +static void __init serial_out(struct uart_port *port, int offset, int value) +{ + switch (port->iotype) { + case UPIO_MEM: + writeb(value, port->membase + offset); + break; + case UPIO_MEM32: + writel(value, port->membase + (offset << 2)); + break; + case UPIO_PORT: + outb(value, port->iobase + offset); + break; + } +} + +#define BOTH_EMPTY (UART_LSR_TEMT | UART_LSR_THRE) + +static void __init wait_for_xmitr(struct uart_port *port) +{ + unsigned int status; + + for (;;) { + status = serial_in(port, UART_LSR); + if ((status & BOTH_EMPTY) == BOTH_EMPTY) + return; + cpu_relax(); + } +} + +static void __init serial_putc(struct uart_port *port, int c) +{ + wait_for_xmitr(port); + serial_out(port, UART_TX, c); +} + +static void __init early_serial8250_write(struct console *console, + const char *s, unsigned int count, unsigned int loglevel) +{ + struct uart_port *port = &early_device.port; + unsigned int ier; + + /* Save the IER and disable interrupts */ + ier = serial_in(port, UART_IER); + serial_out(port, UART_IER, 0); + + uart_console_write(port, s, count, serial_putc); + + /* Wait for transmitter to become empty and restore the IER */ + wait_for_xmitr(port); + serial_out(port, UART_IER, ier); +} + +static unsigned int __init probe_baud(struct uart_port *port) +{ + unsigned char lcr, dll, dlm; + unsigned int quot; + + lcr = serial_in(port, UART_LCR); + serial_out(port, UART_LCR, lcr | UART_LCR_DLAB); + dll = serial_in(port, UART_DLL); + dlm = serial_in(port, UART_DLM); + serial_out(port, UART_LCR, lcr); + + quot = (dlm << 8) | dll; + return (port->uartclk / 16) / quot; +} + +static void __init init_port(struct early_serial8250_device *device) +{ + struct uart_port *port = &device->port; + unsigned int divisor; + unsigned char c; + + serial_out(port, UART_LCR, 0x3); /* 8n1 */ + serial_out(port, UART_IER, 0); /* no interrupt */ + serial_out(port, UART_FCR, 0); /* no fifo */ + serial_out(port, UART_MCR, 0x3); /* DTR + RTS */ + + divisor = port->uartclk / (16 * device->baud); + c = serial_in(port, UART_LCR); + serial_out(port, UART_LCR, c | UART_LCR_DLAB); + serial_out(port, UART_DLL, divisor & 0xff); + serial_out(port, UART_DLM, (divisor >> 8) & 0xff); + serial_out(port, UART_LCR, c & ~UART_LCR_DLAB); +} + +static int __init parse_options(struct early_serial8250_device *device, + char *options) +{ + struct uart_port *port = &device->port; + int mmio, mmio32, length; + + if (!options) + return -ENODEV; + + port->uartclk = BASE_BAUD * 16; + + mmio = !strncmp(options, "mmio,", 5); + mmio32 = !strncmp(options, "mmio32,", 7); + if (mmio || mmio32) { + port->iotype = (mmio ? UPIO_MEM : UPIO_MEM32); + port->mapbase = simple_strtoul(options + (mmio ? 5 : 7), + &options, 0); + if (mmio32) + port->regshift = 2; +#ifdef CONFIG_FIX_EARLYCON_MEM + set_fixmap_nocache(FIX_EARLYCON_MEM_BASE, + port->mapbase & PAGE_MASK); + port->membase = + (void __iomem *)__fix_to_virt(FIX_EARLYCON_MEM_BASE); + port->membase += port->mapbase & ~PAGE_MASK; +#else + port->membase = ioremap_nocache(port->mapbase, 64); + if (!port->membase) { + printk(KERN_ERR "%s: Couldn't ioremap 0x%llx\n", + __func__, + (unsigned long long) port->mapbase); + return -ENOMEM; + } +#endif + } else if (!strncmp(options, "io,", 3)) { + port->iotype = UPIO_PORT; + port->iobase = simple_strtoul(options + 3, &options, 0); + mmio = 0; + } else + return -EINVAL; + + options = strchr(options, ','); + if (options) { + options++; + device->baud = simple_strtoul(options, NULL, 0); + length = min(strcspn(options, " "), sizeof(device->options)); + strncpy(device->options, options, length); + } else { + device->baud = probe_baud(port); + snprintf(device->options, sizeof(device->options), "%u", + device->baud); + } + + if (mmio || mmio32) + printk(KERN_INFO + "Early serial console at MMIO%s 0x%llx (options '%s')\n", + mmio32 ? "32" : "", + (unsigned long long)port->mapbase, + device->options); + else + printk(KERN_INFO + "Early serial console at I/O port 0x%lx (options '%s')\n", + port->iobase, + device->options); + + return 0; +} + +static struct console early_serial8250_console __initdata = { + .name = "uart", + .write = early_serial8250_write, + .flags = CON_PRINTBUFFER | CON_BOOT, + .index = -1, +}; + +static int __init early_serial8250_setup(char *options) +{ + struct early_serial8250_device *device = &early_device; + int err; + + if (device->port.membase || device->port.iobase) + return 0; + + err = parse_options(device, options); + if (err < 0) + return err; + + init_port(device); + return 0; +} + +int __init setup_early_serial8250_console(char *cmdline) +{ + char *options; + int err; + + options = strstr(cmdline, "uart8250,"); + if (!options) { + options = strstr(cmdline, "uart,"); + if (!options) + return 0; + } + + options = strchr(cmdline, ',') + 1; + err = early_serial8250_setup(options); + if (err < 0) + return err; + + register_console(&early_serial8250_console); + + return 0; +} + +int serial8250_find_port_for_earlycon(void) +{ + struct early_serial8250_device *device = &early_device; + struct uart_port *port = &device->port; + int line; + int ret; + + if (!device->port.membase && !device->port.iobase) + return -ENODEV; + + line = serial8250_find_port(port); + if (line < 0) + return -ENODEV; + + ret = update_console_cmdline("uart", 8250, + "ttyS", line, device->options); + if (ret < 0) + ret = update_console_cmdline("uart", 0, + "ttyS", line, device->options); + + return ret; +} + +early_param("earlycon", setup_early_serial8250_console); diff --git a/pool/shard003/C/0065005_libvirt-sandbox-config-network-route.c b/pool/shard003/C/0065005_libvirt-sandbox-config-network-route.c new file mode 100644 index 0000000000000000000000000000000000000000..621a767848548a5f72bca44141127669b48b6055 --- /dev/null +++ b/pool/shard003/C/0065005_libvirt-sandbox-config-network-route.c @@ -0,0 +1,314 @@ +/* + * libvirt-sandbox-config-network-route.c: libvirt sandbox configuration + * + * Copyright (C) 2011 Red Hat, Inc. + * + * 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 + * + * Author: Daniel P. Berrange + */ + +#include +#include + +#include "libvirt-sandbox/libvirt-sandbox-config-all.h" + +/** + * SECTION: libvirt-sandbox-config-network_route + * @short_description: Route information for an interface + * @include: libvirt-sandbox/libvirt-sandbox.h + * + * Provides an object to store information about a network interface route + * + * The GVirSandboxConfigNetworkRoute object stores the information required + * to configure an route on a network interface. This compises the primary + * route, broadcast route and network route. + */ + +#define GVIR_SANDBOX_CONFIG_NETWORK_ROUTE_GET_PRIVATE(obj) \ + (G_TYPE_INSTANCE_GET_PRIVATE((obj), GVIR_SANDBOX_TYPE_CONFIG_NETWORK_ROUTE, GVirSandboxConfigNetworkRoutePrivate)) + +struct _GVirSandboxConfigNetworkRoutePrivate +{ + guint prefix; + GInetAddress *gateway; + GInetAddress *target; +}; + +G_DEFINE_TYPE_WITH_PRIVATE(GVirSandboxConfigNetworkRoute, gvir_sandbox_config_network_route, G_TYPE_OBJECT); + + +enum { + PROP_0, + PROP_PREFIX, + PROP_GATEWAY, + PROP_TARGET, +}; + +enum { + LAST_SIGNAL +}; + +//static gint signals[LAST_SIGNAL]; + + +static void gvir_sandbox_config_network_route_get_property(GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec) +{ + GVirSandboxConfigNetworkRoute *config = GVIR_SANDBOX_CONFIG_NETWORK_ROUTE(object); + GVirSandboxConfigNetworkRoutePrivate *priv = config->priv; + + switch (prop_id) { + case PROP_PREFIX: + g_value_set_uint(value, priv->prefix); + break; + + case PROP_GATEWAY: + g_value_set_object(value, priv->gateway); + break; + + case PROP_TARGET: + g_value_set_object(value, priv->target); + break; + + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); + } +} + + +static void gvir_sandbox_config_network_route_set_property(GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec) +{ + GVirSandboxConfigNetworkRoute *config = GVIR_SANDBOX_CONFIG_NETWORK_ROUTE(object); + GVirSandboxConfigNetworkRoutePrivate *priv = config->priv; + + switch (prop_id) { + case PROP_PREFIX: + priv->prefix = g_value_get_uint(value); + break; + + case PROP_GATEWAY: + if (priv->gateway) + g_object_unref(priv->gateway); + priv->gateway = g_value_dup_object(value); + break; + + case PROP_TARGET: + if (priv->target) + g_object_unref(priv->target); + priv->target = g_value_dup_object(value); + break; + + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); + } +} + + +static void gvir_sandbox_config_network_route_finalize(GObject *object) +{ + GVirSandboxConfigNetworkRoute *config = GVIR_SANDBOX_CONFIG_NETWORK_ROUTE(object); + GVirSandboxConfigNetworkRoutePrivate *priv = config->priv; + + if (priv->gateway) + g_object_unref(priv->gateway); + if (priv->target) + g_object_unref(priv->target); + + G_OBJECT_CLASS(gvir_sandbox_config_network_route_parent_class)->finalize(object); +} + + +static void gvir_sandbox_config_network_route_class_init(GVirSandboxConfigNetworkRouteClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS(klass); + + object_class->finalize = gvir_sandbox_config_network_route_finalize; + object_class->get_property = gvir_sandbox_config_network_route_get_property; + object_class->set_property = gvir_sandbox_config_network_route_set_property; + + g_object_class_install_property(object_class, + PROP_PREFIX, + g_param_spec_uint("prefix", + "Prefix", + "Prefix length", + 0, 128, 24, + G_PARAM_READABLE | + G_PARAM_WRITABLE | + G_PARAM_CONSTRUCT_ONLY | + G_PARAM_STATIC_NAME | + G_PARAM_STATIC_NICK | + G_PARAM_STATIC_BLURB)); + g_object_class_install_property(object_class, + PROP_GATEWAY, + g_param_spec_object("gateway", + "Gateway", + "Gateway device", + G_TYPE_INET_ADDRESS, + G_PARAM_READABLE | + G_PARAM_WRITABLE | + G_PARAM_CONSTRUCT_ONLY | + G_PARAM_STATIC_NAME | + G_PARAM_STATIC_NICK | + G_PARAM_STATIC_BLURB)); + g_object_class_install_property(object_class, + PROP_TARGET, + g_param_spec_object("target", + "Target", + "Target address", + G_TYPE_INET_ADDRESS, + G_PARAM_READABLE | + G_PARAM_WRITABLE | + G_PARAM_CONSTRUCT_ONLY | + G_PARAM_STATIC_NAME | + G_PARAM_STATIC_NICK | + G_PARAM_STATIC_BLURB)); +} + + +static void gvir_sandbox_config_network_route_init(GVirSandboxConfigNetworkRoute *config) +{ + config->priv = GVIR_SANDBOX_CONFIG_NETWORK_ROUTE_GET_PRIVATE(config); +} + + +/** + * gvir_sandbox_config_network_route_new: + * @target: the target address + * @prefix: the prefix length + * @gateway: the gateway device + * + * Create a new network route config. + * + * Returns: (transfer full): a new sandbox network route object + */ +GVirSandboxConfigNetworkRoute *gvir_sandbox_config_network_route_new(GInetAddress *target, + guint prefix, + GInetAddress *gateway) +{ + return GVIR_SANDBOX_CONFIG_NETWORK_ROUTE(g_object_new(GVIR_SANDBOX_TYPE_CONFIG_NETWORK_ROUTE, + "target", target, + "prefix", prefix, + "gateway", gateway, + NULL)); +} + + +/** + * gvir_sandbox_config_network_route_set_prefix: + * @config: (transfer none): the sandbox network route config + * @prefix: prefix length + * + * Sets the prefix for an interface route + */ +void gvir_sandbox_config_network_route_set_prefix(GVirSandboxConfigNetworkRoute *config, + guint prefix) +{ + GVirSandboxConfigNetworkRoutePrivate *priv = config->priv; + priv->prefix = prefix; +} + + +/** + * gvir_sandbox_config_network_route_get_prefix: + * @config: (transfer none): the sandbox network route config + * + * Retrieves the prefix length of the route + * + * Returns: the prefix length + */ +guint gvir_sandbox_config_network_route_get_prefix(GVirSandboxConfigNetworkRoute *config) +{ + GVirSandboxConfigNetworkRoutePrivate *priv = config->priv; + return priv->prefix; +} + + +/** + * gvir_sandbox_config_network_route_set_gateway: + * @config: (transfer none): the sandbox network route config + * @addr: (transfer none): the gateway device + * + * Sets the interface gateway device + */ +void gvir_sandbox_config_network_route_set_gateway(GVirSandboxConfigNetworkRoute *config, + GInetAddress *addr) +{ + GVirSandboxConfigNetworkRoutePrivate *priv = config->priv; + if (priv->gateway) + g_object_unref(priv->gateway); + priv->gateway = g_object_ref(addr); +} + + +/** + * gvir_sandbox_config_network_route_get_gateway: + * @config: (transfer none): the sandbox network route config + * + * Retrieves the network gateway address + * + * Returns: (transfer none): the gateway address + */ +GInetAddress *gvir_sandbox_config_network_route_get_gateway(GVirSandboxConfigNetworkRoute *config) +{ + GVirSandboxConfigNetworkRoutePrivate *priv = config->priv; + return priv->gateway; +} + + +/** + * gvir_sandbox_config_network_route_set_target: + * @config: (transfer none): the sandbox network route config + * @addr: (transfer none): the target address + * + * Sets the interface route target address + */ +void gvir_sandbox_config_network_route_set_target(GVirSandboxConfigNetworkRoute *config, + GInetAddress *addr) +{ + GVirSandboxConfigNetworkRoutePrivate *priv = config->priv; + if (priv->target) + g_object_unref(priv->target); + priv->target = g_object_ref(addr); +} + + +/** + * gvir_sandbox_config_network_route_get_target: + * @config: (transfer none): the sandbox network route config + * + * Retrieves the route target address + * + * Returns: (transfer none): the target address + */ +GInetAddress *gvir_sandbox_config_network_route_get_target(GVirSandboxConfigNetworkRoute *config) +{ + GVirSandboxConfigNetworkRoutePrivate *priv = config->priv; + return priv->target; +} + +/* + * Local variables: + * c-indent-level: 4 + * c-basic-offset: 4 + * indent-tabs-mode: nil + * tab-width: 8 + * End: + */ diff --git a/pool/shard003/C/0065038_irq_tables.c b/pool/shard003/C/0065038_irq_tables.c new file mode 100644 index 0000000000000000000000000000000000000000..87c414a63f15ea3d06b74e882d1784231801606a --- /dev/null +++ b/pool/shard003/C/0065038_irq_tables.c @@ -0,0 +1,112 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2010 Advanced Micro Devices, 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. + * + * 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 +#include +#include +#include + +#include + + + +static void write_pirq_info(struct irq_info *pirq_info, u8 bus, u8 devfn, + u8 link0, u16 bitmap0, u8 link1, u16 bitmap1, + u8 link2, u16 bitmap2, u8 link3, u16 bitmap3, + u8 slot, u8 rfu) +{ + pirq_info->bus = bus; + pirq_info->devfn = devfn; + pirq_info->irq[0].link = link0; + pirq_info->irq[0].bitmap = bitmap0; + pirq_info->irq[1].link = link1; + pirq_info->irq[1].bitmap = bitmap1; + pirq_info->irq[2].link = link2; + pirq_info->irq[2].bitmap = bitmap2; + pirq_info->irq[3].link = link3; + pirq_info->irq[3].bitmap = bitmap3; + pirq_info->slot = slot; + pirq_info->rfu = rfu; +} +extern u8 bus_rs780[8]; +extern u8 bus_sb700[2]; +extern unsigned long sbdn_sb700; + +unsigned long write_pirq_routing_table(unsigned long addr) +{ + struct irq_routing_table *pirq; + struct irq_info *pirq_info; + u32 slot_num; + u8 *v; + + u8 sum = 0; + int i; + + get_bus_conf(); /* it will find out all bus num and apic that share with mptable.c and mptable.c and acpi_tables.c */ + + /* Align the table to be 16 byte aligned. */ + addr += 15; + addr &= ~15; + + /* This table must be between 0xf0000 & 0x100000 */ + printk(BIOS_INFO, "Writing IRQ routing tables to 0x%lx...", addr); + + pirq = (void *)(addr); + v = (u8 *) (addr); + + pirq->signature = PIRQ_SIGNATURE; + pirq->version = PIRQ_VERSION; + + pirq->rtr_bus = bus_sb700[0]; + pirq->rtr_devfn = ((sbdn_sb700 + 0x14) << 3) | 4; + + pirq->exclusive_irqs = 0; + + pirq->rtr_vendor = 0x1002; + pirq->rtr_device = 0x4384; + + pirq->miniport_data = 0; + + memset(pirq->rfu, 0, sizeof(pirq->rfu)); + + pirq_info = (void *)(&pirq->checksum + 1); + slot_num = 0; + + /* pci bridge */ + write_pirq_info(pirq_info, bus_sb700[0], ((sbdn_sb700 + 0x14) << 3) | 4, + 0x1, 0xdef8, 0x2, 0xdef8, 0x3, 0xdef8, 0x4, 0xdef8, 0, + 0); + pirq_info++; + slot_num++; + + pirq->size = 32 + 16 * slot_num; + + for (i = 0; i < pirq->size; i++) + sum += v[i]; + + sum = pirq->checksum - sum; + if (sum != pirq->checksum) { + pirq->checksum = sum; + } + + printk(BIOS_INFO, "write_pirq_routing_table done.\n"); + + return (unsigned long)pirq_info; +} diff --git a/pool/shard003/C/0065041_mmio.c b/pool/shard003/C/0065041_mmio.c new file mode 100644 index 0000000000000000000000000000000000000000..935ac44aa209e9f8753299f01edbc6476cd7d827 --- /dev/null +++ b/pool/shard003/C/0065041_mmio.c @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * MMIO register bitfield-controlled multiplexer driver + * + * Copyright (C) 2017 Pengutronix, Philipp Zabel + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int mux_mmio_set(struct mux_control *mux, int state) +{ + struct regmap_field **fields = mux_chip_priv(mux->chip); + + return regmap_field_write(fields[mux_control_get_index(mux)], state); +} + +static const struct mux_control_ops mux_mmio_ops = { + .set = mux_mmio_set, +}; + +static const struct of_device_id mux_mmio_dt_ids[] = { + { .compatible = "mmio-mux", }, + { /* sentinel */ } +}; +MODULE_DEVICE_TABLE(of, mux_mmio_dt_ids); + +static int mux_mmio_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct device_node *np = dev->of_node; + struct regmap_field **fields; + struct mux_chip *mux_chip; + struct regmap *regmap; + int num_fields; + int ret; + int i; + + regmap = syscon_node_to_regmap(np->parent); + if (IS_ERR(regmap)) { + ret = PTR_ERR(regmap); + dev_err(dev, "failed to get regmap: %d\n", ret); + return ret; + } + + ret = of_property_count_u32_elems(np, "mux-reg-masks"); + if (ret == 0 || ret % 2) + ret = -EINVAL; + if (ret < 0) { + dev_err(dev, "mux-reg-masks property missing or invalid: %d\n", + ret); + return ret; + } + num_fields = ret / 2; + + mux_chip = devm_mux_chip_alloc(dev, num_fields, num_fields * + sizeof(*fields)); + if (IS_ERR(mux_chip)) + return PTR_ERR(mux_chip); + + fields = mux_chip_priv(mux_chip); + + for (i = 0; i < num_fields; i++) { + struct mux_control *mux = &mux_chip->mux[i]; + struct reg_field field; + s32 idle_state = MUX_IDLE_AS_IS; + u32 reg, mask; + int bits; + + ret = of_property_read_u32_index(np, "mux-reg-masks", + 2 * i, ®); + if (!ret) + ret = of_property_read_u32_index(np, "mux-reg-masks", + 2 * i + 1, &mask); + if (ret < 0) { + dev_err(dev, "bitfield %d: failed to read mux-reg-masks property: %d\n", + i, ret); + return ret; + } + + field.reg = reg; + field.msb = fls(mask) - 1; + field.lsb = ffs(mask) - 1; + + if (mask != GENMASK(field.msb, field.lsb)) { + dev_err(dev, "bitfield %d: invalid mask 0x%x\n", + i, mask); + return -EINVAL; + } + + fields[i] = devm_regmap_field_alloc(dev, regmap, field); + if (IS_ERR(fields[i])) { + ret = PTR_ERR(fields[i]); + dev_err(dev, "bitfield %d: failed allocate: %d\n", + i, ret); + return ret; + } + + bits = 1 + field.msb - field.lsb; + mux->states = 1 << bits; + + of_property_read_u32_index(np, "idle-states", i, + (u32 *)&idle_state); + if (idle_state != MUX_IDLE_AS_IS) { + if (idle_state < 0 || idle_state >= mux->states) { + dev_err(dev, "bitfield: %d: out of range idle state %d\n", + i, idle_state); + return -EINVAL; + } + + mux->idle_state = idle_state; + } + } + + mux_chip->ops = &mux_mmio_ops; + + return devm_mux_chip_register(dev, mux_chip); +} + +static struct platform_driver mux_mmio_driver = { + .driver = { + .name = "mmio-mux", + .of_match_table = of_match_ptr(mux_mmio_dt_ids), + }, + .probe = mux_mmio_probe, +}; +module_platform_driver(mux_mmio_driver); + +MODULE_DESCRIPTION("MMIO register bitfield-controlled multiplexer driver"); +MODULE_AUTHOR("Philipp Zabel "); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard003/C/0065060_x25_dev.c b/pool/shard003/C/0065060_x25_dev.c new file mode 100644 index 0000000000000000000000000000000000000000..a8a236338e61e8c0de3b1d72a00186314dafb487 --- /dev/null +++ b/pool/shard003/C/0065060_x25_dev.c @@ -0,0 +1,230 @@ +/* + * X.25 Packet Layer release 002 + * + * This is ALPHA test software. This code may break your machine, randomly fail to work with new + * releases, misbehave and/or generally screw up. It might even work. + * + * This code REQUIRES 2.1.15 or higher + * + * This module: + * This module 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. + * + * History + * X.25 001 Jonathan Naylor Started coding. + * 2000-09-04 Henner Eisen Prevent freeing a dangling skb. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static int x25_receive_data(struct sk_buff *skb, struct x25_neigh *nb) +{ + struct sock *sk; + unsigned short frametype; + unsigned int lci; + + if (!pskb_may_pull(skb, X25_STD_MIN_LEN)) + return 0; + + frametype = skb->data[2]; + lci = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF); + + /* + * LCI of zero is always for us, and its always a link control + * frame. + */ + if (lci == 0) { + x25_link_control(skb, nb, frametype); + return 0; + } + + /* + * Find an existing socket. + */ + if ((sk = x25_find_socket(lci, nb)) != NULL) { + int queued = 1; + + skb_reset_transport_header(skb); + bh_lock_sock(sk); + if (!sock_owned_by_user(sk)) { + queued = x25_process_rx_frame(sk, skb); + } else { + queued = !sk_add_backlog(sk, skb, sk->sk_rcvbuf); + } + bh_unlock_sock(sk); + sock_put(sk); + return queued; + } + + /* + * Is is a Call Request ? if so process it. + */ + if (frametype == X25_CALL_REQUEST) + return x25_rx_call_request(skb, nb, lci); + + /* + * Its not a Call Request, nor is it a control frame. + * Can we forward it? + */ + + if (x25_forward_data(lci, nb, skb)) { + if (frametype == X25_CLEAR_CONFIRMATION) { + x25_clear_forward_by_lci(lci); + } + kfree_skb(skb); + return 1; + } + +/* + x25_transmit_clear_request(nb, lci, 0x0D); +*/ + + if (frametype != X25_CLEAR_CONFIRMATION) + printk(KERN_DEBUG "x25_receive_data(): unknown frame type %2x\n",frametype); + + return 0; +} + +int x25_lapb_receive_frame(struct sk_buff *skb, struct net_device *dev, + struct packet_type *ptype, struct net_device *orig_dev) +{ + struct sk_buff *nskb; + struct x25_neigh *nb; + + if (!net_eq(dev_net(dev), &init_net)) + goto drop; + + nskb = skb_copy(skb, GFP_ATOMIC); + if (!nskb) + goto drop; + kfree_skb(skb); + skb = nskb; + + /* + * Packet received from unrecognised device, throw it away. + */ + nb = x25_get_neigh(dev); + if (!nb) { + printk(KERN_DEBUG "X.25: unknown neighbour - %s\n", dev->name); + goto drop; + } + + if (!pskb_may_pull(skb, 1)) + return 0; + + switch (skb->data[0]) { + + case X25_IFACE_DATA: + skb_pull(skb, 1); + if (x25_receive_data(skb, nb)) { + x25_neigh_put(nb); + goto out; + } + break; + + case X25_IFACE_CONNECT: + x25_link_established(nb); + break; + + case X25_IFACE_DISCONNECT: + x25_link_terminated(nb); + break; + } + x25_neigh_put(nb); +drop: + kfree_skb(skb); +out: + return 0; +} + +void x25_establish_link(struct x25_neigh *nb) +{ + struct sk_buff *skb; + unsigned char *ptr; + + switch (nb->dev->type) { + case ARPHRD_X25: + if ((skb = alloc_skb(1, GFP_ATOMIC)) == NULL) { + printk(KERN_ERR "x25_dev: out of memory\n"); + return; + } + ptr = skb_put(skb, 1); + *ptr = X25_IFACE_CONNECT; + break; + +#if IS_ENABLED(CONFIG_LLC) + case ARPHRD_ETHER: + return; +#endif + default: + return; + } + + skb->protocol = htons(ETH_P_X25); + skb->dev = nb->dev; + + dev_queue_xmit(skb); +} + +void x25_terminate_link(struct x25_neigh *nb) +{ + struct sk_buff *skb; + unsigned char *ptr; + +#if IS_ENABLED(CONFIG_LLC) + if (nb->dev->type == ARPHRD_ETHER) + return; +#endif + if (nb->dev->type != ARPHRD_X25) + return; + + skb = alloc_skb(1, GFP_ATOMIC); + if (!skb) { + printk(KERN_ERR "x25_dev: out of memory\n"); + return; + } + + ptr = skb_put(skb, 1); + *ptr = X25_IFACE_DISCONNECT; + + skb->protocol = htons(ETH_P_X25); + skb->dev = nb->dev; + dev_queue_xmit(skb); +} + +void x25_send_frame(struct sk_buff *skb, struct x25_neigh *nb) +{ + unsigned char *dptr; + + skb_reset_network_header(skb); + + switch (nb->dev->type) { + case ARPHRD_X25: + dptr = skb_push(skb, 1); + *dptr = X25_IFACE_DATA; + break; + +#if IS_ENABLED(CONFIG_LLC) + case ARPHRD_ETHER: + kfree_skb(skb); + return; +#endif + default: + kfree_skb(skb); + return; + } + + skb->protocol = htons(ETH_P_X25); + skb->dev = nb->dev; + + dev_queue_xmit(skb); +} diff --git a/pool/shard003/C/0065072_sk_event_timer.c b/pool/shard003/C/0065072_sk_event_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..7ecef7a4f7fc66d33646d4108f0626537644e9e4 --- /dev/null +++ b/pool/shard003/C/0065072_sk_event_timer.c @@ -0,0 +1,97 @@ +// Copyright (c) 2013 The Silk Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// Written by qingfeng.wang, some source code form snort,nginx. +// http://www.selinuxplus.com frank.wqf@gmail.com +// Thanks to China Standard software Co.,Ltd ; + +#include "sk_config.h" +#include "sk_core.h" + +sk_rbtree_t sk_event_timer_rbtree; + +static sk_rbtree_node_t sk_event_timer_sentinel; +sk_atomic_t *sk_event_timer_mutex; + + + +sk_ptr_t +sk_init_event_timer(sk_log_t *log) +{ + if(&sk_event_timer_rbtree == NULL) return SK_ERR; + sk_init_rbtree(&sk_event_timer_rbtree,&sk_event_timer_sentinel, + sk_rbtree_insert_timer_value); + return SK_OK; +} + + +sk_msec_t +sk_event_find_timer(void) +{ + sk_msec_int_t timer; + sk_rbtree_node_t *node,*root,*sentinel; + + if(sk_event_timer_rbtree.root == &sk_event_timer_sentinel){ + return SK_TIMER_INFINITE; + } + + root = sk_event_timer_rbtree.root; + sentinel = sk_event_timer_rbtree.sentinel; + + node = sk_rbtree_min(root,sentinel); + + timer = (sk_msec_int_t)node->key - (sk_msec_int_t)sk_current_msec; + + return (sk_msec_t)(timer > 0 ?timer :0); +} + + +void +sk_event_expire_timer(void) +{ + sk_event_t *ev; + sk_rbtree_node_t *node,*root,*sentinel; + + sentinel = sk_event_timer_rbtree.sentinel; + for(;;){ + root = sk_event_timer_rbtree.root; + if(root == sentinel){ + return ; + } + node = sk_rbtree_min(root,sentinel); + + if((sk_msec_int_t)node->key -(sk_msec_int_t)sk_current_msec <= 0){ + ev = (sk_event_t *)((char *)node - offsetof(sk_event_t,timer)); + + sk_rbtree_delete(&sk_event_timer_rbtree,&ev->timer); + ev->timer_set = 0; + ev->timeout = 1; + ev->handler(ev); + continue; + } + break; + } +} + + +void +sk_event_add_timer(sk_event_t *ev,sk_msec_t timer) +{ + sk_msec_t key; + sk_msec_int_t diff; + + key = sk_current_msec + timer; + + if(ev->timer_set){ + diff = (sk_msec_int_t)(key - ev->timer.key); + if(abs(diff) < SK_TIMER_LAZY_DELAY){ + return; + } + sk_event_del_timer(ev); + } + ev->timer.key = key; + + sk_rbtree_insert(&sk_event_timer_rbtree,&ev->timer); + + ev->timer_set = 1; +} diff --git a/pool/shard003/C/0065076_cm_sbs.c b/pool/shard003/C/0065076_cm_sbs.c new file mode 100644 index 0000000000000000000000000000000000000000..114418a767078b14f08e9466d94fcd3464da14f9 --- /dev/null +++ b/pool/shard003/C/0065076_cm_sbs.c @@ -0,0 +1,87 @@ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PREFIX "ACPI: " + +ACPI_MODULE_NAME("cm_sbs"); +#define ACPI_AC_CLASS "ac_adapter" +#define ACPI_BATTERY_CLASS "battery" +#define _COMPONENT ACPI_SBS_COMPONENT +static struct proc_dir_entry *acpi_ac_dir; +static struct proc_dir_entry *acpi_battery_dir; + +static DEFINE_MUTEX(cm_sbs_mutex); + +static int lock_ac_dir_cnt; +static int lock_battery_dir_cnt; + +struct proc_dir_entry *acpi_lock_ac_dir(void) +{ + mutex_lock(&cm_sbs_mutex); + if (!acpi_ac_dir) + acpi_ac_dir = proc_mkdir(ACPI_AC_CLASS, acpi_root_dir); + if (acpi_ac_dir) { + lock_ac_dir_cnt++; + } else { + printk(KERN_ERR PREFIX + "Cannot create %s\n", ACPI_AC_CLASS); + } + mutex_unlock(&cm_sbs_mutex); + return acpi_ac_dir; +} +EXPORT_SYMBOL(acpi_lock_ac_dir); + +void acpi_unlock_ac_dir(struct proc_dir_entry *acpi_ac_dir_param) +{ + mutex_lock(&cm_sbs_mutex); + if (acpi_ac_dir_param) + lock_ac_dir_cnt--; + if (lock_ac_dir_cnt == 0 && acpi_ac_dir_param && acpi_ac_dir) { + remove_proc_entry(ACPI_AC_CLASS, acpi_root_dir); + acpi_ac_dir = NULL; + } + mutex_unlock(&cm_sbs_mutex); +} +EXPORT_SYMBOL(acpi_unlock_ac_dir); + +struct proc_dir_entry *acpi_lock_battery_dir(void) +{ + mutex_lock(&cm_sbs_mutex); + if (!acpi_battery_dir) { + acpi_battery_dir = + proc_mkdir(ACPI_BATTERY_CLASS, acpi_root_dir); + } + if (acpi_battery_dir) { + lock_battery_dir_cnt++; + } else { + printk(KERN_ERR PREFIX + "Cannot create %s\n", ACPI_BATTERY_CLASS); + } + mutex_unlock(&cm_sbs_mutex); + return acpi_battery_dir; +} +EXPORT_SYMBOL(acpi_lock_battery_dir); + +void acpi_unlock_battery_dir(struct proc_dir_entry *acpi_battery_dir_param) +{ + mutex_lock(&cm_sbs_mutex); + if (acpi_battery_dir_param) + lock_battery_dir_cnt--; + if (lock_battery_dir_cnt == 0 && acpi_battery_dir_param + && acpi_battery_dir) { + remove_proc_entry(ACPI_BATTERY_CLASS, acpi_root_dir); + acpi_battery_dir = NULL; + } + mutex_unlock(&cm_sbs_mutex); + return; +} +EXPORT_SYMBOL(acpi_unlock_battery_dir); diff --git a/pool/shard003/C/0065103_dvb-usb-urb.c b/pool/shard003/C/0065103_dvb-usb-urb.c new file mode 100644 index 0000000000000000000000000000000000000000..95f9097498cb86259f0209013ab499894ab39839 --- /dev/null +++ b/pool/shard003/C/0065103_dvb-usb-urb.c @@ -0,0 +1,121 @@ +/* dvb-usb-urb.c is part of the DVB USB library. + * + * Copyright (C) 2004-6 Patrick Boettcher (patrick.boettcher@posteo.de) + * see dvb-usb-init.c for copyright information. + * + * This file keeps functions for initializing and handling the + * USB and URB stuff. + */ +#include "dvb-usb-common.h" + +int dvb_usb_generic_rw(struct dvb_usb_device *d, u8 *wbuf, u16 wlen, u8 *rbuf, + u16 rlen, int delay_ms) +{ + int actlen,ret = -ENOMEM; + + if (!d || wbuf == NULL || wlen == 0) + return -EINVAL; + + if (d->props.generic_bulk_ctrl_endpoint == 0) { + err("endpoint for generic control not specified."); + return -EINVAL; + } + + if ((ret = mutex_lock_interruptible(&d->usb_mutex))) + return ret; + + deb_xfer(">>> "); + debug_dump(wbuf,wlen,deb_xfer); + + ret = usb_bulk_msg(d->udev,usb_sndbulkpipe(d->udev, + d->props.generic_bulk_ctrl_endpoint), wbuf,wlen,&actlen, + 2000); + + if (ret) + err("bulk message failed: %d (%d/%d)",ret,wlen,actlen); + else + ret = actlen != wlen ? -1 : 0; + + /* an answer is expected, and no error before */ + if (!ret && rbuf && rlen) { + if (delay_ms) + msleep(delay_ms); + + ret = usb_bulk_msg(d->udev,usb_rcvbulkpipe(d->udev, + d->props.generic_bulk_ctrl_endpoint_response ? + d->props.generic_bulk_ctrl_endpoint_response : + d->props.generic_bulk_ctrl_endpoint),rbuf,rlen,&actlen, + 2000); + + if (ret) + err("recv bulk message failed: %d",ret); + else { + deb_xfer("<<< "); + debug_dump(rbuf,actlen,deb_xfer); + } + } + + mutex_unlock(&d->usb_mutex); + return ret; +} +EXPORT_SYMBOL(dvb_usb_generic_rw); + +int dvb_usb_generic_write(struct dvb_usb_device *d, u8 *buf, u16 len) +{ + return dvb_usb_generic_rw(d,buf,len,NULL,0,0); +} +EXPORT_SYMBOL(dvb_usb_generic_write); + +static void dvb_usb_data_complete(struct usb_data_stream *stream, u8 *buffer, size_t length) +{ + struct dvb_usb_adapter *adap = stream->user_priv; + if (adap->feedcount > 0 && adap->state & DVB_USB_ADAP_STATE_DVB) + dvb_dmx_swfilter(&adap->demux, buffer, length); +} + +static void dvb_usb_data_complete_204(struct usb_data_stream *stream, u8 *buffer, size_t length) +{ + struct dvb_usb_adapter *adap = stream->user_priv; + if (adap->feedcount > 0 && adap->state & DVB_USB_ADAP_STATE_DVB) + dvb_dmx_swfilter_204(&adap->demux, buffer, length); +} + +static void dvb_usb_data_complete_raw(struct usb_data_stream *stream, + u8 *buffer, size_t length) +{ + struct dvb_usb_adapter *adap = stream->user_priv; + if (adap->feedcount > 0 && adap->state & DVB_USB_ADAP_STATE_DVB) + dvb_dmx_swfilter_raw(&adap->demux, buffer, length); +} + +int dvb_usb_adapter_stream_init(struct dvb_usb_adapter *adap) +{ + int i, ret = 0; + for (i = 0; i < adap->props.num_frontends; i++) { + + adap->fe_adap[i].stream.udev = adap->dev->udev; + if (adap->props.fe[i].caps & DVB_USB_ADAP_RECEIVES_204_BYTE_TS) + adap->fe_adap[i].stream.complete = + dvb_usb_data_complete_204; + else + if (adap->props.fe[i].caps & DVB_USB_ADAP_RECEIVES_RAW_PAYLOAD) + adap->fe_adap[i].stream.complete = + dvb_usb_data_complete_raw; + else + adap->fe_adap[i].stream.complete = dvb_usb_data_complete; + adap->fe_adap[i].stream.user_priv = adap; + ret = usb_urb_init(&adap->fe_adap[i].stream, + &adap->props.fe[i].stream); + if (ret < 0) + break; + } + return ret; +} + +int dvb_usb_adapter_stream_exit(struct dvb_usb_adapter *adap) +{ + int i; + for (i = 0; i < adap->props.num_frontends; i++) + usb_urb_exit(&adap->fe_adap[i].stream); + return 0; +} diff --git a/pool/shard003/C/0065111_mongoc-stream.c b/pool/shard003/C/0065111_mongoc-stream.c new file mode 100644 index 0000000000000000000000000000000000000000..64d276dc9bdf523009ec91c08548d69db909d6c4 --- /dev/null +++ b/pool/shard003/C/0065111_mongoc-stream.c @@ -0,0 +1,341 @@ +/* + * Copyright 2013 MongoDB, 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. + */ + + +#include + +#include "mongoc-array-private.h" +#include "mongoc-buffer-private.h" +#include "mongoc-error.h" +#include "mongoc-flags.h" +#include "mongoc-log.h" +#include "mongoc-opcode.h" +#include "mongoc-rpc-private.h" +#include "mongoc-stream.h" +#include "mongoc-stream-private.h" +#include "mongoc-trace.h" +#include "mongoc-util-private.h" + + +#undef MONGOC_LOG_DOMAIN +#define MONGOC_LOG_DOMAIN "stream" + +#ifndef MONGOC_DEFAULT_TIMEOUT_MSEC +# define MONGOC_DEFAULT_TIMEOUT_MSEC (60L * 60L * 1000L) +#endif + + +/** + * mongoc_stream_close: + * @stream: A mongoc_stream_t. + * + * Closes the underlying file-descriptor used by @stream. + * + * Returns: 0 on success, -1 on failure. + */ +int +mongoc_stream_close (mongoc_stream_t *stream) +{ + int ret; + + ENTRY; + + bson_return_val_if_fail(stream, -1); + + ALWAYS_ASSERT(stream->close); + + ret = stream->close(stream); + + RETURN (ret); +} + + +/** + * mongoc_stream_destroy: + * @stream: A mongoc_stream_t. + * + * Frees any resources referenced by @stream, including the memory allocation + * for @stream. + */ +void +mongoc_stream_destroy (mongoc_stream_t *stream) +{ + ENTRY; + + bson_return_if_fail(stream); + + ALWAYS_ASSERT(stream->destroy); + + stream->destroy(stream); + + EXIT; +} + + +/** + * mongoc_stream_flush: + * @stream: A mongoc_stream_t. + * + * Flushes the data in the underlying stream to the transport. + * + * Returns: 0 on success, -1 on failure. + */ +int +mongoc_stream_flush (mongoc_stream_t *stream) +{ + bson_return_val_if_fail(stream, -1); + return stream->flush(stream); +} + + +/** + * mongoc_stream_writev: + * @stream: A mongoc_stream_t. + * @iov: An array of iovec to write to the stream. + * @iovcnt: The number of elements in @iov. + * + * Writes an array of iovec buffers to the underlying stream. + * + * Returns: the number of bytes written, or -1 upon failure. + */ +ssize_t +mongoc_stream_writev (mongoc_stream_t *stream, + mongoc_iovec_t *iov, + size_t iovcnt, + int32_t timeout_msec) +{ + ssize_t ret; + + ENTRY; + + bson_return_val_if_fail(stream, -1); + bson_return_val_if_fail(iov, -1); + bson_return_val_if_fail(iovcnt, -1); + + BSON_ASSERT(stream->writev); + + if (timeout_msec < 0) { + timeout_msec = MONGOC_DEFAULT_TIMEOUT_MSEC; + } + + ret = stream->writev(stream, iov, iovcnt, timeout_msec); + + RETURN (ret); +} + +/** + * mongoc_stream_write: + * @stream: A mongoc_stream_t. + * @buf: A buffer to write. + * @count: The number of bytes to write into @buf. + * + * Simplified access to mongoc_stream_writev(). Creates a single iovec + * with the buffer provided. + * + * Returns: -1 on failure, otherwise the number of bytes write. + */ +ssize_t +mongoc_stream_write (mongoc_stream_t *stream, + void *buf, + size_t count, + int32_t timeout_msec) +{ + mongoc_iovec_t iov; + ssize_t ret; + + ENTRY; + + bson_return_val_if_fail (stream, -1); + bson_return_val_if_fail (buf, -1); + + iov.iov_base = buf; + iov.iov_len = count; + + BSON_ASSERT (stream->writev); + + ret = mongoc_stream_writev (stream, &iov, 1, timeout_msec); + + RETURN (ret); +} + +/** + * mongoc_stream_readv: + * @stream: A mongoc_stream_t. + * @iov: An array of iovec containing the location and sizes to read. + * @iovcnt: the number of elements in @iov. + * @min_bytes: the minumum number of bytes to return, or -1. + * + * Reads into the various buffers pointed to by @iov and associated + * buffer lengths. + * + * If @min_bytes is specified, then at least min_bytes will be returned unless + * eof is encountered. This may result in ETIMEDOUT + * + * Returns: the number of bytes read or -1 on failure. + */ +ssize_t +mongoc_stream_readv (mongoc_stream_t *stream, + mongoc_iovec_t *iov, + size_t iovcnt, + size_t min_bytes, + int32_t timeout_msec) +{ + ssize_t ret; + + ENTRY; + + bson_return_val_if_fail (stream, -1); + bson_return_val_if_fail (iov, -1); + bson_return_val_if_fail (iovcnt, -1); + + BSON_ASSERT (stream->readv); + + ret = stream->readv (stream, iov, iovcnt, min_bytes, timeout_msec); + + RETURN (ret); +} + + +/** + * mongoc_stream_read: + * @stream: A mongoc_stream_t. + * @buf: A buffer to write into. + * @count: The number of bytes to write into @buf. + * @min_bytes: The minimum number of bytes to receive + * + * Simplified access to mongoc_stream_readv(). Creates a single iovec + * with the buffer provided. + * + * If @min_bytes is specified, then at least min_bytes will be returned unless + * eof is encountered. This may result in ETIMEDOUT + * + * Returns: -1 on failure, otherwise the number of bytes read. + */ +ssize_t +mongoc_stream_read (mongoc_stream_t *stream, + void *buf, + size_t count, + size_t min_bytes, + int32_t timeout_msec) +{ + mongoc_iovec_t iov; + ssize_t ret; + + ENTRY; + + bson_return_val_if_fail (stream, -1); + bson_return_val_if_fail (buf, -1); + + iov.iov_base = buf; + iov.iov_len = count; + + BSON_ASSERT (stream->readv); + + ret = mongoc_stream_readv (stream, &iov, 1, min_bytes, timeout_msec); + + RETURN (ret); +} + + +int +mongoc_stream_setsockopt (mongoc_stream_t *stream, + int level, + int optname, + void *optval, + socklen_t optlen) +{ + bson_return_val_if_fail(stream, -1); + + if (stream->setsockopt) { + return stream->setsockopt(stream, level, optname, optval, optlen); + } + + return 0; +} + + +mongoc_stream_t * +mongoc_stream_get_base_stream (mongoc_stream_t *stream) /* IN */ +{ + bson_return_val_if_fail (stream, NULL); + + if (stream->get_base_stream) { + return stream->get_base_stream (stream); + } + + return NULL; +} + + +bool +mongoc_stream_check_closed (mongoc_stream_t *stream) +{ + int ret; + + ENTRY; + + if (!stream) { + return true; + } + + ret = stream->check_closed(stream); + + RETURN (ret); +} + +bool +_mongoc_stream_writev_full (mongoc_stream_t *stream, + mongoc_iovec_t *iov, + size_t iovcnt, + int32_t timeout_msec, + bson_error_t *error) +{ + size_t total_bytes = 0; + int i; + ssize_t r; + ENTRY; + + for (i = 0; i < iovcnt; i++) { + total_bytes += iov[i].iov_len; + } + + r = mongoc_stream_writev(stream, iov, iovcnt, timeout_msec); + TRACE("writev returned: %d", r); + + if (r < 0) { + if (error) { + char buf[128]; + char * errstr; + + errstr = bson_strerror_r(errno, buf, sizeof(buf)); + + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, + "Failure during socket delivery: %s", errstr); + } + + RETURN(false); + } + + if (r != total_bytes) { + bson_set_error (error, MONGOC_ERROR_STREAM, MONGOC_ERROR_STREAM_SOCKET, + "Failure to send all requested bytes (only sent: %" PRId64 "/%" PRId64 " in %dms) during socket delivery", + (int64_t)r, (int64_t)total_bytes, timeout_msec); + + RETURN(false); + } + + RETURN(true); +} diff --git a/pool/shard003/C/0065115_viewport.c b/pool/shard003/C/0065115_viewport.c new file mode 100644 index 0000000000000000000000000000000000000000..309308c983b34067fb0240912570a8ce06cf0a1f --- /dev/null +++ b/pool/shard003/C/0065115_viewport.c @@ -0,0 +1,180 @@ +/* + * Mesa 3-D graphics library + * Version: 7.5 + * + * Copyright (C) 2009 VMware, Inc. 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 + * BRIAN PAUL 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. + */ + + +/** + * \file viewport.c + * glViewport and glDepthRange functions. + */ + + +#include "context.h" +#include "macros.h" +#include "viewport.h" + + +/** + * Set the viewport. + * \sa Called via glViewport() or display list execution. + * + * Flushes the vertices and calls _mesa_set_viewport() with the given + * parameters. + */ +void GLAPIENTRY +_mesa_Viewport(GLint x, GLint y, GLsizei width, GLsizei height) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx); + _mesa_set_viewport(ctx, x, y, width, height); +} + + +/** + * Set new viewport parameters and update derived state (the _WindowMap + * matrix). Usually called from _mesa_Viewport(). + * + * \param ctx GL context. + * \param x, y coordinates of the lower left corner of the viewport rectangle. + * \param width width of the viewport rectangle. + * \param height height of the viewport rectangle. + */ +void +_mesa_set_viewport(GLcontext *ctx, GLint x, GLint y, + GLsizei width, GLsizei height) +{ + if (MESA_VERBOSE & VERBOSE_API) + _mesa_debug(ctx, "glViewport %d %d %d %d\n", x, y, width, height); + + if (width < 0 || height < 0) { + _mesa_error(ctx, GL_INVALID_VALUE, + "glViewport(%d, %d, %d, %d)", x, y, width, height); + return; + } + + /* clamp width and height to the implementation dependent range */ + width = MIN2(width, (GLsizei) ctx->Const.MaxViewportWidth); + height = MIN2(height, (GLsizei) ctx->Const.MaxViewportHeight); + + ctx->Viewport.X = x; + ctx->Viewport.Width = width; + ctx->Viewport.Y = y; + ctx->Viewport.Height = height; + ctx->NewState |= _NEW_VIEWPORT; + +#if 1 + /* XXX remove this someday. Currently the DRI drivers rely on + * the WindowMap matrix being up to date in the driver's Viewport + * and DepthRange functions. + */ + _math_matrix_viewport(&ctx->Viewport._WindowMap, + ctx->Viewport.X, ctx->Viewport.Y, + ctx->Viewport.Width, ctx->Viewport.Height, + ctx->Viewport.Near, ctx->Viewport.Far, + ctx->DrawBuffer->_DepthMaxF); +#endif + + if (ctx->Driver.Viewport) { + /* Many drivers will use this call to check for window size changes + * and reallocate the z/stencil/accum/etc buffers if needed. + */ + ctx->Driver.Viewport(ctx, x, y, width, height); + } +} + + +/** + * Called by glDepthRange + * + * \param nearval specifies the Z buffer value which should correspond to + * the near clip plane + * \param farval specifies the Z buffer value which should correspond to + * the far clip plane + */ +void GLAPIENTRY +_mesa_DepthRange(GLclampd nearval, GLclampd farval) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx); + + if (MESA_VERBOSE&VERBOSE_API) + _mesa_debug(ctx, "glDepthRange %f %f\n", nearval, farval); + + if (ctx->Viewport.Near == nearval && + ctx->Viewport.Far == farval) + return; + + ctx->Viewport.Near = (GLfloat) CLAMP(nearval, 0.0, 1.0); + ctx->Viewport.Far = (GLfloat) CLAMP(farval, 0.0, 1.0); + ctx->NewState |= _NEW_VIEWPORT; + +#if 1 + /* XXX remove this someday. Currently the DRI drivers rely on + * the WindowMap matrix being up to date in the driver's Viewport + * and DepthRange functions. + */ + _math_matrix_viewport(&ctx->Viewport._WindowMap, + ctx->Viewport.X, ctx->Viewport.Y, + ctx->Viewport.Width, ctx->Viewport.Height, + ctx->Viewport.Near, ctx->Viewport.Far, + ctx->DrawBuffer->_DepthMaxF); +#endif + + if (ctx->Driver.DepthRange) { + ctx->Driver.DepthRange(ctx, nearval, farval); + } +} + + + +/** + * Initialize the context viewport attribute group. + * \param ctx the GL context. + */ +void _mesa_init_viewport(GLcontext *ctx) +{ + GLfloat depthMax = 65535.0F; /* sorf of arbitrary */ + + /* Viewport group */ + ctx->Viewport.X = 0; + ctx->Viewport.Y = 0; + ctx->Viewport.Width = 0; + ctx->Viewport.Height = 0; + ctx->Viewport.Near = 0.0; + ctx->Viewport.Far = 1.0; + _math_matrix_ctr(&ctx->Viewport._WindowMap); + + _math_matrix_viewport(&ctx->Viewport._WindowMap, 0, 0, 0, 0, + 0.0F, 1.0F, depthMax); +} + + +/** + * Free the context viewport attribute group data. + * \param ctx the GL context. + */ +void _mesa_free_viewport_data(GLcontext *ctx) +{ + _math_matrix_dtr(&ctx->Viewport._WindowMap); +} + diff --git a/pool/shard003/C/0065118_iouser-reauth.c b/pool/shard003/C/0065118_iouser-reauth.c new file mode 100644 index 0000000000000000000000000000000000000000..9edab7cf80049b8c94f20d8d937274c982fd3fc8 --- /dev/null +++ b/pool/shard003/C/0065118_iouser-reauth.c @@ -0,0 +1,107 @@ +/* + Copyright (C) 1996,99,2001,02 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 2, or (at + your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ + +#include "iohelp.h" +#include +#include +#include + +/* Conduct a reauthentication transaction, returning a new iouser. + AUTHSERVER is the I/O servers auth port. The rendezvous port + provided by the user is REND_PORT. If the transaction cannot be + completed, return zero, unless PERMIT_FAILURE is non-zero. If + PERMIT_FAILURE is nonzero, then should the transaction fail, return + an iouser that has no ids. The new port to be sent to the user is + newright. */ +error_t iohelp_reauth (struct iouser **user, + auth_t authserver, mach_port_t rend_port, + mach_port_t newright, int permit_failure) +{ + uid_t gubuf[20], ggbuf[20], aubuf[20], agbuf[20]; + uid_t *gen_uids, *gen_gids, *aux_uids, *aux_gids; + size_t genuidlen, gengidlen, auxuidlen, auxgidlen; + error_t err; + struct iouser *new; + + *user = new = malloc (sizeof (struct iouser)); + if (!new) + return ENOMEM; + + new->uids = make_idvec (); + new->gids = make_idvec (); + if (!new->uids || !new->gids) + { + if (new->uids) + idvec_free (new->uids); + if (new->gids) + idvec_free (new->gids); + free (new); + return ENOMEM; + } + + genuidlen = gengidlen = auxuidlen = auxgidlen = 20; + gen_uids = gubuf; + gen_gids = ggbuf; + aux_uids = aubuf; + aux_gids = agbuf; + + do + err = auth_server_authenticate (authserver, + rend_port, + MACH_MSG_TYPE_COPY_SEND, + newright, + MACH_MSG_TYPE_COPY_SEND, + &gen_uids, &genuidlen, + &aux_uids, &auxuidlen, + &gen_gids, &gengidlen, + &aux_gids, &auxgidlen); + while (err == EINTR); + + if (err) + { + if (permit_failure) + genuidlen = gengidlen = 0; + else + goto out; + } + + err = idvec_set_ids (new->uids, gen_uids, genuidlen); + if (!err) + err = idvec_set_ids (new->gids, gen_gids, gengidlen); + + if (gubuf != gen_uids) + munmap ((caddr_t) gen_uids, genuidlen * sizeof (uid_t)); + if (ggbuf != gen_gids) + munmap ((caddr_t) gen_gids, gengidlen * sizeof (uid_t)); + if (aubuf != aux_uids) + munmap ((caddr_t) aux_uids, auxuidlen * sizeof (uid_t)); + if (agbuf != aux_gids) + munmap ((caddr_t) aux_gids, auxgidlen * sizeof (uid_t)); + + if (err) + { + out: + idvec_free (new->uids); + idvec_free (new->gids); + free (new); + *user = 0; + return err; + } + + *user = new; + return 0; +} diff --git a/pool/shard003/C/0065135_memory_manager.c b/pool/shard003/C/0065135_memory_manager.c new file mode 100644 index 0000000000000000000000000000000000000000..2ad96906c8d70f7ef41f4de08fd5d2aac91b6d50 --- /dev/null +++ b/pool/shard003/C/0065135_memory_manager.c @@ -0,0 +1,221 @@ +/* + Copyright (C) 2011 Fredrik Johansson + Copyright (C) 2016 Claus Fieker + Copyright (C) 2016 William Hart. + + This file is part of FLINT. + + FLINT 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.1 of the License, or + (at your option) any later version. See . +*/ + +#include +#include +#include "flint.h" + +#if HAVE_GC +#include "gc.h" +#endif + +static void * _flint_malloc(size_t); +static void * _flint_calloc(size_t, size_t); +static void * _flint_realloc(void *, size_t); +static void _flint_free(void *); + +static void *(*__flint_allocate_func) (size_t) = _flint_malloc; +static void *(*__flint_callocate_func) (size_t, size_t) = _flint_calloc; +static void *(*__flint_reallocate_func) (void *, size_t) = _flint_realloc; +static void (*__flint_free_func) (void *) = _flint_free; + +#if FLINT_REENTRANT && !HAVE_TLS +#include + +static pthread_once_t register_initialised = PTHREAD_ONCE_INIT; +pthread_mutex_t register_lock; + +static pthread_once_t alloc_func_init = PTHREAD_ONCE_INIT; +pthread_mutex_t alloc_func_lock; + +void __flint_set_memory_functions_init() +{ + pthread_mutex_init(&alloc_func_lock, NULL); +} +#endif + +static void flint_memory_error(size_t size) +{ + flint_printf("Exception (FLINT memory_manager). Unable to allocate memory (%ld).\n", size); + flint_abort(); +} + +void __flint_set_memory_functions(void *(*alloc_func) (size_t), + void *(*calloc_func) (size_t, size_t), + void *(*realloc_func) (void *, size_t), + void (*free_func) (void *)) +{ +#if FLINT_REENTRANT && !HAVE_TLS + pthread_once(&alloc_func_init, __flint_set_memory_functions_init); + pthread_mutex_lock(&alloc_func_lock); +#endif + + __flint_allocate_func = alloc_func; + __flint_callocate_func = calloc_func; + __flint_reallocate_func = realloc_func; + __flint_free_func = free_func; + +#if FLINT_REENTRANT && !HAVE_TLS + pthread_mutex_unlock(&alloc_func_lock); +#endif +} + +void * _flint_malloc(size_t size) +{ + void * ptr; + +#if HAVE_GC + ptr = GC_malloc(size); +#else + ptr = malloc(size); +#endif + + return ptr; +} + +void * flint_malloc(size_t size) +{ + void * ptr = (*__flint_allocate_func)(size); + + if (ptr == NULL) + flint_memory_error(size); + + return ptr; +} + +void * _flint_realloc(void * ptr, size_t size) +{ + void * ptr2; + +#if HAVE_GC + ptr2 = GC_realloc(ptr, size); +#else + ptr2 = realloc(ptr, size); +#endif + + return ptr2; +} + + +void * flint_realloc(void * ptr, size_t size) +{ + void * ptr2; + + if (ptr) + ptr2 = (*__flint_reallocate_func)(ptr, size); + else + ptr2 = (*__flint_allocate_func)(size); + + if (ptr2 == NULL) + flint_memory_error(size); + + return ptr2; +} + +void * _flint_calloc(size_t num, size_t size) +{ + void * ptr; + +#if HAVE_GC + ptr = GC_malloc(num*size); +#else + ptr = calloc(num, size); +#endif + + return ptr; +} + +void * flint_calloc(size_t num, size_t size) +{ + void * ptr; + + ptr = (*__flint_callocate_func)(num, size); + + if (ptr == NULL) + flint_memory_error(size); + + return ptr; +} + +void _flint_free(void * ptr) +{ +#if !HAVE_GC + free(ptr); +#endif +} + +void flint_free(void * ptr) +{ + (*__flint_free_func)(ptr); +} + + +FLINT_TLS_PREFIX size_t flint_num_cleanup_functions = 0; + +FLINT_TLS_PREFIX flint_cleanup_function_t * flint_cleanup_functions = NULL; + +#pragma omp threadprivate(flint_num_cleanup_functions, flint_cleanup_functions) + +#if FLINT_REENTRANT && !HAVE_TLS +void register_init() +{ + pthread_mutex_init(®ister_lock, NULL); +} +#endif + +void flint_register_cleanup_function(flint_cleanup_function_t cleanup_function) +{ +#if FLINT_REENTRANT && !HAVE_TLS + pthread_once(®ister_initialised, register_init); + pthread_mutex_lock(®ister_lock); +#endif + + flint_cleanup_functions = flint_realloc(flint_cleanup_functions, + (flint_num_cleanup_functions + 1) * sizeof(flint_cleanup_function_t)); + + flint_cleanup_functions[flint_num_cleanup_functions] = cleanup_function; + + flint_num_cleanup_functions++; + +#if FLINT_REENTRANT && !HAVE_TLS + pthread_mutex_unlock(®ister_lock); +#endif +} + +void _fmpz_cleanup(); + +void flint_cleanup() +{ + size_t i; + +#if FLINT_REENTRANT && !HAVE_TLS + pthread_mutex_lock(®ister_lock); +#endif + + for (i = 0; i < flint_num_cleanup_functions; i++) + flint_cleanup_functions[i](); + + flint_free(flint_cleanup_functions); + flint_cleanup_functions = NULL; + flint_num_cleanup_functions = 0; + + mpfr_free_cache(); + _fmpz_cleanup(); + +#if FLINT_REENTRANT && !HAVE_TLS + pthread_mutex_unlock(®ister_lock); +#endif + +} + + diff --git a/pool/shard003/C/0065149_usrp_txrx.c b/pool/shard003/C/0065149_usrp_txrx.c new file mode 100644 index 0000000000000000000000000000000000000000..b7ba3f15219ad606ef4f420348b1c6f95edcb9a0 --- /dev/null +++ b/pool/shard003/C/0065149_usrp_txrx.c @@ -0,0 +1,235 @@ +/** + * + * \section COPYRIGHT + * + * Copyright 2013-2015 Software Radio Systems Limited + * + * \section LICENSE + * + * This file is part of the srsLTE library. + * + * srsLTE 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. + * + * srsLTE 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. + * + * A copy of the GNU Affero General Public License can be found in + * the LICENSE file in the top-level directory of this distribution + * and at http://www.gnu.org/licenses/. + * + */ + + +#include +#include +#include +#include +#include +#include +#include + +#include "srslte/phy/rf/rf.h" +#include "srslte/srslte.h" + +uint32_t nof_prb = 25; +uint32_t nof_frames = 20; + +int time_adv_samples = 0; +float tone_offset_hz = 1e6; +float rf_rx_gain = 40, srslte_rf_tx_gain = 40, rf_freq = 2.4e9; +char *rf_args = ""; +char *output_filename = NULL; +char *input_filename = NULL; + +//------------------------------------------------------------------------------ +void usage(char *prog) + { + printf("Usage: %s -o [rx_signal_file]\n", prog); + printf("\t-a RF args [Default %s]\n", rf_args); + printf("\t-f RF TX/RX frequency [Default %.2f MHz]\n", rf_freq/1e6); + printf("\t-g RF RX gain [Default %.1f dB]\n", rf_rx_gain); + printf("\t-G RF TX gain [Default %.1f dB]\n", srslte_rf_tx_gain); + printf("\t-t Single tone offset (Hz) [Default %f]\n", tone_offset_hz); + printf("\t-T Time advance samples [Default %d]\n", time_adv_samples); + printf("\t-i File name to read signal from [Default single tone]\n"); + printf("\t-p Number of UL RB [Default %d]\n", nof_prb); + } + +//------------------------------------------------------------------------------ +void parse_args(int argc, char **argv) + { + int opt; + while ((opt = getopt(argc, argv, "ioafgGptT")) != -1) + { + switch (opt) + { + case 'a': + rf_args = argv[optind]; + break; + case 'o': + output_filename = argv[optind]; + break; + case 'i': + input_filename = argv[optind]; + break; + case 't': + tone_offset_hz = atof(argv[optind]); + break; + case 'T': + time_adv_samples = atoi(argv[optind]); + break; + case 'f': + rf_freq = atof(argv[optind]); + break; + case 'g': + rf_rx_gain = atof(argv[optind]); + break; + case 'G': + srslte_rf_tx_gain = atof(argv[optind]); + break; + case 'p': + nof_prb = atoi(argv[optind]); + if (!srslte_nofprb_isvalid(nof_prb)) + { + fprintf(stderr, "Invalid number of UL RB %d\n", nof_prb); + exit(-1); + } + break; + default: + usage(argv[0]); + exit(-1); + } + } + if (!output_filename) + { + usage(argv[0]); + exit(-1); + } + if (time_adv_samples < 0) + { + printf("Time advance must be positive\n"); + usage(argv[0]); + exit(-1); + } + } + +//------------------------------------------------------------------------------ +int main(int argc, char **argv) + { + parse_args(argc, argv); + + uint32_t flen = srslte_sampling_freq_hz(nof_prb) / 1000; + + cf_t *rx_buffer = malloc(sizeof(cf_t) * flen * nof_frames); + if (!rx_buffer) + { + perror("malloc"); + exit(-1); + } + + cf_t *tx_buffer = malloc(sizeof(cf_t) * (flen + time_adv_samples)); + if (!tx_buffer) + { + perror("malloc"); + exit(-1); + } + bzero(tx_buffer, sizeof(cf_t) * (flen + time_adv_samples)); + + cf_t *zeros = calloc(sizeof(cf_t), flen); + if (!zeros) + { + perror("calloc"); + exit(-1); + } + + float time_adv_sec = (float) time_adv_samples / srslte_sampling_freq_hz(nof_prb); + + // Send through RF + srslte_rf_t rf; + printf("Opening RF device...\n"); + if (srslte_rf_open(&rf, rf_args)) + { + fprintf(stderr, "Error opening rf\n"); + exit(-1); + } + srslte_rf_set_master_clock_rate(&rf, 30.72e6); + + int srate = srslte_sampling_freq_hz(nof_prb); + if (srate < 10e6) + { + srslte_rf_set_master_clock_rate(&rf, 4 * srate); + } + else + { + srslte_rf_set_master_clock_rate(&rf, srate); + } + srslte_rf_set_rx_srate(&rf, (double) srate); + srslte_rf_set_tx_srate(&rf, (double) srate); + + + printf("Subframe len: %d samples\n", flen); + printf("Time advance: %f us\n", time_adv_sec * 1e6); + printf("Set TX/RX rate: %.2f MHz\n", (float) srate / 1000000); + printf("Set RX gain: %.1f dB\n", srslte_rf_set_rx_gain(&rf, rf_rx_gain)); + printf("Set TX gain: %.1f dB\n", srslte_rf_set_tx_gain(&rf, srslte_rf_tx_gain)); + printf("Set TX/RX freq: %.2f MHz\n", srslte_rf_set_rx_freq(&rf, rf_freq) / 1000000); + srslte_rf_set_tx_freq(&rf, rf_freq); + + sleep(1); + + if (input_filename) + { + srslte_vec_load_file(input_filename, + &tx_buffer[time_adv_samples], + flen * sizeof(cf_t)); + } + else + { + for (int i = 0; i < flen - time_adv_samples; i++) + { + tx_buffer[i + time_adv_samples] = 0.3 * cexpf(_Complex_I * 2 * M_PI * tone_offset_hz * ((float) i / (float) srate)); + } + srslte_vec_save_file("srslte_rf_txrx_tone", tx_buffer, flen * sizeof(cf_t)); + } + + srslte_timestamp_t tstamp; + + srslte_rf_start_rx_stream(&rf, false); + uint32_t nframe = 0; + + + while(nframe +#include +#include + +#include +#include +#include + +/* cats host-specific stuff */ +static int irqmap_cats[] __initdata = { IRQ_PCI, IRQ_IN0, IRQ_IN1, IRQ_IN3 }; + +static u8 cats_no_swizzle(struct pci_dev *dev, u8 *pin) +{ + return 0; +} + +static int __init cats_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) +{ + if (dev->irq >= 255) + return -1; /* not a valid interrupt. */ + + if (dev->irq >= 128) + return dev->irq & 0x1f; + + if (dev->irq >= 1 && dev->irq <= 4) + return irqmap_cats[dev->irq - 1]; + + if (dev->irq != 0) + printk("PCI: device %02x:%02x has unknown irq line %x\n", + dev->bus->number, dev->devfn, dev->irq); + + return -1; +} + +/* + * why not the standard PCI swizzle? does this prevent 4-port tulip + * cards being used (ie, pci-pci bridge based cards)? + */ +static struct hw_pci cats_pci __initdata = { + .swizzle = cats_no_swizzle, + .map_irq = cats_map_irq, + .nr_controllers = 1, + .ops = &dc21285_ops, + .setup = dc21285_setup, + .preinit = dc21285_preinit, + .postinit = dc21285_postinit, +}; + +static int __init cats_pci_init(void) +{ + if (machine_is_cats()) + pci_common_init(&cats_pci); + return 0; +} + +subsys_initcall(cats_pci_init); diff --git a/pool/shard003/C/0065204_semtest.c b/pool/shard003/C/0065204_semtest.c new file mode 100644 index 0000000000000000000000000000000000000000..c6d9f9d1afe03029b847f56c7a39d4935a400902 --- /dev/null +++ b/pool/shard003/C/0065204_semtest.c @@ -0,0 +1,324 @@ +/* + FreeRTOS V7.1.1 - Copyright (C) 2012 Real Time Engineers Ltd. + + + *************************************************************************** + * * + * FreeRTOS tutorial books are available in pdf and paperback. * + * Complete, revised, and edited pdf reference manuals are also * + * available. * + * * + * Purchasing FreeRTOS documentation will not only help you, by * + * ensuring you get running as quickly as possible and with an * + * in-depth knowledge of how to use FreeRTOS, it will also help * + * the FreeRTOS project to continue with its mission of providing * + * professional grade, cross platform, de facto standard solutions * + * for microcontrollers - completely free of charge! * + * * + * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * + * * + * Thank you for using FreeRTOS, and thank you for your support! * + * * + *************************************************************************** + + + 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. See the GNU General Public License for + more details. You should have received a copy of the GNU General Public + License and the FreeRTOS license exception along with FreeRTOS; if not it + can be viewed here: http://www.freertos.org/a00114.html and also obtained + by writing to Richard Barry, contact details for whom are available on the + FreeRTOS WEB site. + + 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, training, latest information, + license and contact details. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool. + + Real Time Engineers ltd license FreeRTOS to High Integrity Systems, who sell + the code with commercial support, indemnification, and middleware, under + the OpenRTOS brand: http://www.OpenRTOS.com. High Integrity Systems also + provide a safety engineered and independently SIL3 certified version under + the SafeRTOS brand: http://www.SafeRTOS.com. +*/ + +/** + * Creates two sets of two tasks. The tasks within a set share a variable, access + * to which is guarded by a semaphore. + * + * Each task starts by attempting to obtain the semaphore. On obtaining a + * semaphore a task checks to ensure that the guarded variable has an expected + * value. It then clears the variable to zero before counting it back up to the + * expected value in increments of 1. After each increment the variable is checked + * to ensure it contains the value to which it was just set. When the starting + * value is again reached the task releases the semaphore giving the other task in + * the set a chance to do exactly the same thing. The starting value is high + * enough to ensure that a tick is likely to occur during the incrementing loop. + * + * An error is flagged if at any time during the process a shared variable is + * found to have a value other than that expected. Such an occurrence would + * suggest an error in the mutual exclusion mechanism by which access to the + * variable is restricted. + * + * The first set of two tasks poll their semaphore. The second set use blocking + * calls. + * + * \page SemTestC semtest.c + * \ingroup DemoFiles + *
    + */ + +/* +Changes from V1.2.0: + + + The tasks that operate at the idle priority now use a lower expected + count than those running at a higher priority. This prevents the low + priority tasks from signaling an error because they have not been + scheduled enough time for each of them to count the shared variable to + the high value. + +Changes from V2.0.0 + + + Delay periods are now specified using variables and constants of + portTickType rather than unsigned long. + +Changes from V2.1.1 + + + The stack size now uses configMINIMAL_STACK_SIZE. + + String constants made file scope to decrease stack depth on 8051 port. +*/ + +#include + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" +#include "semphr.h" + +/* Demo app include files. */ +#include "semtest.h" +#include "print.h" + +/* The value to which the shared variables are counted. */ +#define semtstBLOCKING_EXPECTED_VALUE ( ( unsigned long ) 0xfff ) +#define semtstNON_BLOCKING_EXPECTED_VALUE ( ( unsigned long ) 0xff ) + +#define semtstSTACK_SIZE configMINIMAL_STACK_SIZE + +#define semtstNUM_TASKS ( 4 ) + +#define semtstDELAY_FACTOR ( ( portTickType ) 10 ) + +/* The task function as described at the top of the file. */ +static void prvSemaphoreTest( void *pvParameters ); + +/* Structure used to pass parameters to each task. */ +typedef struct SEMAPHORE_PARAMETERS +{ + xSemaphoreHandle xSemaphore; + volatile unsigned long *pulSharedVariable; + portTickType xBlockTime; +} xSemaphoreParameters; + +/* Variables used to check that all the tasks are still running without errors. */ +static volatile short sCheckVariables[ semtstNUM_TASKS ] = { 0 }; +static volatile short sNextCheckVariable = 0; + +/* Strings to print if USE_STDIO is defined. */ +const char * const pcPollingSemaphoreTaskError = "Guarded shared variable in unexpected state.\r\n"; +const char * const pcSemaphoreTaskStart = "Guarded shared variable task started.\r\n"; + +/*-----------------------------------------------------------*/ + +void vStartSemaphoreTasks( unsigned portBASE_TYPE uxPriority ) +{ +xSemaphoreParameters *pxFirstSemaphoreParameters, *pxSecondSemaphoreParameters; +const portTickType xBlockTime = ( portTickType ) 100; + + /* Create the structure used to pass parameters to the first two tasks. */ + pxFirstSemaphoreParameters = ( xSemaphoreParameters * ) pvPortMalloc( sizeof( xSemaphoreParameters ) ); + + if( pxFirstSemaphoreParameters != NULL ) + { + /* Create the semaphore used by the first two tasks. */ + vSemaphoreCreateBinary( pxFirstSemaphoreParameters->xSemaphore ); + + if( pxFirstSemaphoreParameters->xSemaphore != NULL ) + { + /* Create the variable which is to be shared by the first two tasks. */ + pxFirstSemaphoreParameters->pulSharedVariable = ( unsigned long * ) pvPortMalloc( sizeof( unsigned long ) ); + + /* Initialise the share variable to the value the tasks expect. */ + *( pxFirstSemaphoreParameters->pulSharedVariable ) = semtstNON_BLOCKING_EXPECTED_VALUE; + + /* The first two tasks do not block on semaphore calls. */ + pxFirstSemaphoreParameters->xBlockTime = ( portTickType ) 0; + + /* Spawn the first two tasks. As they poll they operate at the idle priority. */ + xTaskCreate( prvSemaphoreTest, "PolSEM1", semtstSTACK_SIZE, ( void * ) pxFirstSemaphoreParameters, tskIDLE_PRIORITY, ( xTaskHandle * ) NULL ); + xTaskCreate( prvSemaphoreTest, "PolSEM2", semtstSTACK_SIZE, ( void * ) pxFirstSemaphoreParameters, tskIDLE_PRIORITY, ( xTaskHandle * ) NULL ); + } + } + + /* Do exactly the same to create the second set of tasks, only this time + provide a block time for the semaphore calls. */ + pxSecondSemaphoreParameters = ( xSemaphoreParameters * ) pvPortMalloc( sizeof( xSemaphoreParameters ) ); + if( pxSecondSemaphoreParameters != NULL ) + { + vSemaphoreCreateBinary( pxSecondSemaphoreParameters->xSemaphore ); + + if( pxSecondSemaphoreParameters->xSemaphore != NULL ) + { + pxSecondSemaphoreParameters->pulSharedVariable = ( unsigned long * ) pvPortMalloc( sizeof( unsigned long ) ); + *( pxSecondSemaphoreParameters->pulSharedVariable ) = semtstBLOCKING_EXPECTED_VALUE; + pxSecondSemaphoreParameters->xBlockTime = xBlockTime / portTICK_RATE_MS; + + xTaskCreate( prvSemaphoreTest, "BlkSEM1", semtstSTACK_SIZE, ( void * ) pxSecondSemaphoreParameters, uxPriority, ( xTaskHandle * ) NULL ); + xTaskCreate( prvSemaphoreTest, "BlkSEM2", semtstSTACK_SIZE, ( void * ) pxSecondSemaphoreParameters, uxPriority, ( xTaskHandle * ) NULL ); + } + } +} +/*-----------------------------------------------------------*/ + +static void prvSemaphoreTest( void *pvParameters ) +{ +xSemaphoreParameters *pxParameters; +volatile unsigned long *pulSharedVariable, ulExpectedValue; +unsigned long ulCounter; +short sError = pdFALSE, sCheckVariableToUse; + + /* See which check variable to use. sNextCheckVariable is not semaphore + protected! */ + portENTER_CRITICAL(); + sCheckVariableToUse = sNextCheckVariable; + sNextCheckVariable++; + portEXIT_CRITICAL(); + + /* Queue a message for printing to say the task has started. */ + vPrintDisplayMessage( &pcSemaphoreTaskStart ); + + /* A structure is passed in as the parameter. This contains the shared + variable being guarded. */ + pxParameters = ( xSemaphoreParameters * ) pvParameters; + pulSharedVariable = pxParameters->pulSharedVariable; + + /* If we are blocking we use a much higher count to ensure loads of context + switches occur during the count. */ + if( pxParameters->xBlockTime > ( portTickType ) 0 ) + { + ulExpectedValue = semtstBLOCKING_EXPECTED_VALUE; + } + else + { + ulExpectedValue = semtstNON_BLOCKING_EXPECTED_VALUE; + } + + for( ;; ) + { + /* Try to obtain the semaphore. */ + if( xSemaphoreTake( pxParameters->xSemaphore, pxParameters->xBlockTime ) == pdPASS ) + { + /* We have the semaphore and so expect any other tasks using the + shared variable to have left it in the state we expect to find + it. */ + if( *pulSharedVariable != ulExpectedValue ) + { + vPrintDisplayMessage( &pcPollingSemaphoreTaskError ); + sError = pdTRUE; + } + + /* Clear the variable, then count it back up to the expected value + before releasing the semaphore. Would expect a context switch or + two during this time. */ + for( ulCounter = ( unsigned long ) 0; ulCounter <= ulExpectedValue; ulCounter++ ) + { + *pulSharedVariable = ulCounter; + if( *pulSharedVariable != ulCounter ) + { + if( sError == pdFALSE ) + { + vPrintDisplayMessage( &pcPollingSemaphoreTaskError ); + } + sError = pdTRUE; + } + } + + /* Release the semaphore, and if no errors have occurred increment the check + variable. */ + if( xSemaphoreGive( pxParameters->xSemaphore ) == pdFALSE ) + { + vPrintDisplayMessage( &pcPollingSemaphoreTaskError ); + sError = pdTRUE; + } + + if( sError == pdFALSE ) + { + if( sCheckVariableToUse < semtstNUM_TASKS ) + { + ( sCheckVariables[ sCheckVariableToUse ] )++; + } + } + + /* If we have a block time then we are running at a priority higher + than the idle priority. This task takes a long time to complete + a cycle (deliberately so to test the guarding) so will be starving + out lower priority tasks. Block for some time to allow give lower + priority tasks some processor time. */ + vTaskDelay( pxParameters->xBlockTime * semtstDELAY_FACTOR ); + } + else + { + if( pxParameters->xBlockTime == ( portTickType ) 0 ) + { + /* We have not got the semaphore yet, so no point using the + processor. We are not blocking when attempting to obtain the + semaphore. */ + taskYIELD(); + } + } + } +} +/*-----------------------------------------------------------*/ + +/* This is called to check that all the created tasks are still running. */ +portBASE_TYPE xAreSemaphoreTasksStillRunning( void ) +{ +static short sLastCheckVariables[ semtstNUM_TASKS ] = { 0 }; +portBASE_TYPE xTask, xReturn = pdTRUE; + + for( xTask = 0; xTask < semtstNUM_TASKS; xTask++ ) + { + if( sLastCheckVariables[ xTask ] == sCheckVariables[ xTask ] ) + { + xReturn = pdFALSE; + } + + sLastCheckVariables[ xTask ] = sCheckVariables[ xTask ]; + } + + return xReturn; +} + + diff --git a/pool/shard003/C/0065215_str.c b/pool/shard003/C/0065215_str.c new file mode 100644 index 0000000000000000000000000000000000000000..5465e28a85bc1725ef16820ace0f91b128fcd624 --- /dev/null +++ b/pool/shard003/C/0065215_str.c @@ -0,0 +1,68 @@ +#include "str.h" + +#include "debug.h" + +umm StringLength(const char* string) +{ + umm result = 0; + for (; *string != '\0'; string++) + { + result++; + } + + return result; +} + +b32 StringsEqual_(char* string, umm stringLength, const char* other, u32 flags) +{ + Assert(string != NULL); + Assert(other != NULL); + + for (umm i = 0; i < stringLength; i++) + { + if (*string == '\0' || *other == '\0') + { + break; + } + + if (*string != *other) + { + return false; + } + + string++; + other++; + } + + if (flags & StringsEqualFlags_CheckNilTerminator) + { + if (*string != '\0' || *other != '\0') + { + return false; + } + } + + return true; +} + +b32 StringStartsWith(char* string, const char* other) +{ + Assert(string != NULL); + Assert(other != NULL); + + umm len = StringLength(other); + + for (umm i = 0; i < len; i++) + { + // Two failure cases: + // - `string` ends in the loop. `other` is guaranteed to be longer. + // - the current chars are different + + if ((*string == '\0') || *string != *other) + { + return false; + } + } + + return true; +} diff --git a/pool/shard003/C/0065235_msgutil.c b/pool/shard003/C/0065235_msgutil.c new file mode 100644 index 0000000000000000000000000000000000000000..c8804cd6ca2d5b1eac20eb5370f7fe4aa122b1b6 --- /dev/null +++ b/pool/shard003/C/0065235_msgutil.c @@ -0,0 +1,193 @@ + +/* + * msgutil.c -- System V IPC message queue utility + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "msgq.h" + +int open_queue( key_t keyval, int flag ) +{ + int qid; + + if (flag == MQ_CREATE) { + /* Create the queue - fail if exists */ + if((qid = msgget( keyval, IPC_CREAT |IPC_EXCL | 0660 )) == -1) + { + return(-1); + } + } + else { + /* Get the queue id - fail if not exists */ + if((qid = msgget( keyval, 0660 )) == -1) + { + return(-1); + } + } + + return(qid); +} + +void send_message_nonblock(int qid, long type, long req, MSG_T *msg) +{ + struct mymsgbuf qbuf; + long time_start; + struct sysinfo systeminfo; + int showmsg=0; + + /* Send a message to the queue */ + //printf("Sending a message ... qid=%d, mtype=%d\n", qid, type); + qbuf.mtype = type; + qbuf.request = req; + qbuf.msg.cmd = msg->cmd; + qbuf.msg.arg1 = msg->arg1; + qbuf.msg.arg2 = msg->arg2; + memcpy(qbuf.msg.mtext, msg->mtext, MAX_SEND_SIZE); + + sysinfo(&systeminfo); + time_start=systeminfo.uptime; +callmsgsnd: + if((msgsnd(qid, &qbuf, sizeof(struct mymsgbuf)-sizeof(long), IPC_NOWAIT)) == -1) + { + if(errno==EAGAIN) + { + sysinfo(&systeminfo); + if( (showmsg==0)&&(systeminfo.uptime-time_start>120) ) + { + fprintf( stderr, "\nsend_message_nonblock: call msgsnd timeout and errno==EAGAIN\n" ); + showmsg=1; + } + goto callmsgsnd; + }else{ + perror("msgsnd"); + exit(1); + } + } + + return; +} + +void send_message(int qid, long type, long req, MSG_T *msg) +{ + struct mymsgbuf qbuf; + + /* Send a message to the queue */ + //printf("Sending a message ... qid=%d, mtype=%d\n", qid, type); + qbuf.mtype = type; + qbuf.request = req; + qbuf.msg.cmd = msg->cmd; + qbuf.msg.arg1 = msg->arg1; + qbuf.msg.arg2 = msg->arg2; + memcpy(qbuf.msg.mtext, msg->mtext, MAX_SEND_SIZE); + + if((msgsnd(qid, &qbuf, sizeof(struct mymsgbuf)-sizeof(long), 0)) == -1) + { + perror("msgsnd"); + exit(1); + } + return; +} + +/* + Return Value: + Return -1 on failure; + otherwise return the number of bytes actually copied into the mtext array. +*/ +int read_message(int qid, struct mymsgbuf *qbuf, long type) +{ + int ret; + + /* Read a message from the queue */ + //printf("Reading a message ...\n"); + qbuf->mtype = type; + +read_retry: + ret=msgrcv(qid, (struct msgbuf *)qbuf, + sizeof(struct mymsgbuf)-sizeof(long), type, 0); + if (ret == -1 && errno == EINTR) { + //printf("EINTR\n"); + goto read_retry; + } +/* + if (ret == -1) { + switch (errno) { + case E2BIG : + printf("E2BIG \n"); + break; + case EACCES : + printf("EACCES \n"); + break; + case EFAULT : + printf("EFAULT \n"); + break; + case EIDRM : + printf("EIDRM \n"); + break; + case EINTR : + printf("EINTR \n"); + break; + case EINVAL : + printf("EINVAL \n"); + break; + case ENOMSG : + printf("ENOMSG \n"); + break; + default: + printf("unknown\n"); + } + } + printf("Type: %ld Text: %s\n", qbuf->mtype, qbuf->mtext); +*/ + return ret; +} + +int peek_message( int qid, long type ) +{ + int result, length; + + if((result = msgrcv( qid, NULL, 0, type, IPC_NOWAIT)) == -1) + { + if(errno == E2BIG) + return(1); + } + + return(0); +} + +void remove_queue(int qid) +{ + /* Remove the queue */ + msgctl(qid, IPC_RMID, 0); +} + +int set_msgqueue_max_size(int qid, unsigned short msgmaxsize) +{ + int ret=-1; + struct msqid_ds msgqidds; + + //fprintf(stderr, "%s:%d>qid=%d, msgmaxsize=%d\n", __FUNCTION__, __LINE__, qid, msgmaxsize); + if( msgctl(qid, IPC_STAT, &msgqidds)==0 ) + { + msgqidds.msg_qbytes = msgmaxsize; + if( msgctl(qid, IPC_SET, &msgqidds)==0 ) + ret=0; + else + perror( "msgctl,IPC_SET" ); + + if( (msgctl(qid, IPC_STAT, &msgqidds)==0) &&(msgqidds.msg_qbytes == msgmaxsize) ) + fprintf(stderr, "%s:%d> set msgqidds.msg_qbytes=%d OK\n", __FUNCTION__, __LINE__, msgmaxsize); + }else + perror( "msgctl,IPC_STAT" ); + + return ret; +} + + diff --git a/pool/shard003/C/0065237_dirblock.c b/pool/shard003/C/0065237_dirblock.c new file mode 100644 index 0000000000000000000000000000000000000000..73e1f0abe5f6e050417dd23291bbd98b62a620c0 --- /dev/null +++ b/pool/shard003/C/0065237_dirblock.c @@ -0,0 +1,126 @@ +/* + * dirblock.c --- directory block routines. + * + * Copyright (C) 1995, 1996 Theodore Ts'o. + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Library + * General Public License, version 2. + * %End-Header% + */ + +#include +#if HAVE_UNISTD_H +#include +#endif +#include +#include + +#include "ext2_fs.h" +#include "ext2fs.h" + +errcode_t ext2fs_read_dir_block3(ext2_filsys fs, blk64_t block, + void *buf, int flags EXT2FS_ATTR((unused))) +{ + errcode_t retval; + char *p, *end; + struct ext2_dir_entry *dirent; + unsigned int name_len, rec_len; + + + retval = io_channel_read_blk64(fs->io, block, 1, buf); + if (retval) + return retval; + + p = (char *) buf; + end = (char *) buf + fs->blocksize; + while (p < end-8) { + dirent = (struct ext2_dir_entry *) p; +#ifdef WORDS_BIGENDIAN + dirent->inode = ext2fs_swab32(dirent->inode); + dirent->rec_len = ext2fs_swab16(dirent->rec_len); + dirent->name_len = ext2fs_swab16(dirent->name_len); +#endif + name_len = dirent->name_len; +#ifdef WORDS_BIGENDIAN + if (flags & EXT2_DIRBLOCK_V2_STRUCT) + dirent->name_len = ext2fs_swab16(dirent->name_len); +#endif + if ((retval = ext2fs_get_rec_len(fs, dirent, &rec_len)) != 0) + return retval; + if ((rec_len < 8) || (rec_len % 4)) { + rec_len = 8; + retval = EXT2_ET_DIR_CORRUPTED; + } else if (((name_len & 0xFF) + 8) > rec_len) + retval = EXT2_ET_DIR_CORRUPTED; + p += rec_len; + } + return retval; +} + +errcode_t ext2fs_read_dir_block2(ext2_filsys fs, blk_t block, + void *buf, int flags EXT2FS_ATTR((unused))) +{ + return ext2fs_read_dir_block3(fs, block, buf, flags); +} + +errcode_t ext2fs_read_dir_block(ext2_filsys fs, blk_t block, + void *buf) +{ + return ext2fs_read_dir_block3(fs, block, buf, 0); +} + + +errcode_t ext2fs_write_dir_block3(ext2_filsys fs, blk64_t block, + void *inbuf, int flags EXT2FS_ATTR((unused))) +{ +#ifdef WORDS_BIGENDIAN + errcode_t retval; + char *p, *end; + char *buf = 0; + unsigned int rec_len; + struct ext2_dir_entry *dirent; + + retval = ext2fs_get_mem(fs->blocksize, &buf); + if (retval) + return retval; + memcpy(buf, inbuf, fs->blocksize); + p = buf; + end = buf + fs->blocksize; + while (p < end) { + dirent = (struct ext2_dir_entry *) p; + if ((retval = ext2fs_get_rec_len(fs, dirent, &rec_len)) != 0) + return retval; + if ((rec_len < 8) || + (rec_len % 4)) { + ext2fs_free_mem(&buf); + return (EXT2_ET_DIR_CORRUPTED); + } + p += rec_len; + dirent->inode = ext2fs_swab32(dirent->inode); + dirent->rec_len = ext2fs_swab16(dirent->rec_len); + dirent->name_len = ext2fs_swab16(dirent->name_len); + + if (flags & EXT2_DIRBLOCK_V2_STRUCT) + dirent->name_len = ext2fs_swab16(dirent->name_len); + } + retval = io_channel_write_blk64(fs->io, block, 1, buf); + ext2fs_free_mem(&buf); + return retval; +#else + return io_channel_write_blk64(fs->io, block, 1, (char *) inbuf); +#endif +} + +errcode_t ext2fs_write_dir_block2(ext2_filsys fs, blk_t block, + void *inbuf, int flags EXT2FS_ATTR((unused))) +{ + return ext2fs_write_dir_block3(fs, block, inbuf, flags); +} + +errcode_t ext2fs_write_dir_block(ext2_filsys fs, blk_t block, + void *inbuf) +{ + return ext2fs_write_dir_block3(fs, block, inbuf, 0); +} + diff --git a/pool/shard003/C/0065241_caam_init.c b/pool/shard003/C/0065241_caam_init.c new file mode 100644 index 0000000000000000000000000000000000000000..b96cc42bcb3bd4448e408cfac52893dba88b0316 --- /dev/null +++ b/pool/shard003/C/0065241_caam_init.c @@ -0,0 +1,289 @@ +/* caam_init.c + * + * Copyright (C) 2006-2017 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL 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. + * + * wolfSSL 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-1335, USA + */ + + +#include + +#if defined(WOLFSSL_IMX6_CAAM) || defined(WOLFSSL_IMX6_CAAM_RNG) || \ + defined(WOLFSSL_IMX6_CAAM_BLOB) + +#include +#include +#include + +#define WC_CAAM_BLOB_SZ 48 + +#ifndef WC_CAAM_PASSWORD + #define WC_CAAM_PASSWORD "!systempassword" +#endif + +#if defined(__INTEGRITY) || defined(INTEGRITY) + #include + #include + static IODevice caam = NULLIODevice; +#endif + +#if defined(WOLFSSL_CAAM_PRINT) || defined(WOLFSSL_CAAM_DEBUG) +#include +#include + +static void wc_caamBanner(void) +{ + printf("********* wolfSSL Version %s : Printing Out CAAM Information ********\n", + LIBWOLFSSL_VERSION_STRING); + printf("CAAM Status [0x%8.8x] = 0x%8.8x\n", + CAAM_STATUS, WC_CAAM_READ(CAAM_STATUS)); + printf("CAAM Version MS Register [0x%8.8x] = 0x%8.8x\n", + CAAM_VERSION_MS, WC_CAAM_READ(CAAM_VERSION_MS)); + printf("CAAM Version LS Register [0x%8.8x] = 0x%8.8x\n", + CAAM_VERSION_LS, WC_CAAM_READ(CAAM_VERSION_LS)); + printf("CAAM Support MS Register [0x%8.8x] = 0x%8.8x\n", + CAMM_SUPPORT_MS, WC_CAAM_READ(CAMM_SUPPORT_MS)); + printf("CAAM Support LS [0x%8.8x] = 0x%8.8x\n", + CAMM_SUPPORT_LS, WC_CAAM_READ(CAMM_SUPPORT_LS)); + printf("********************************************************************\n\n"); +} +#endif + + +/* Allow runtime setting for CAAM IODevice in case user wants to use password + * at run time. + * + * returns 0 on success + * + * NOTE this is how IODevice is defined in INTEGRITY "typedef struct + * IODeviceStruct *IODevice;" + */ +int wc_caamSetResource(IODevice ioDev) +{ + WOLFSSL_MSG("Setting CAAM driver"); + caam = ioDev; + + return 0; +} + +/* Check hardware support + * + * returns 0 on success + */ +int wc_caamInit() +{ + int ret; + word32 reg; + + /* get the driver up */ + if (caam == NULLIODevice) { + WOLFSSL_MSG("Starting CAAM driver"); + if ((ret = (int)RequestResource((Object *)&caam, "wolfSSL_CAAM_Driver", + WC_CAAM_PASSWORD)) != (int)Success) { + WOLFSSL_MSG("Unable to get the CAAM IODevice, check password?"); + WOLFSSL_LEAVE("wc_caamInit: error from driver = ", ret); + ret = 0; /* not a hard failure because user can set resource */ + } + } + +#if defined(WOLFSSL_CAAM_PRINT) || defined(WOLFSSL_CAAM_DEBUG) + /* print out CAAM version/info and wolfSSL version */ + wc_caamBanner(); +#endif + + /* check that for implemented modules + * bits 0-3 AES, 4-7 DES, 12-15 Hashing , 16-19 RNG */ + reg = WC_CAAM_READ(CAMM_SUPPORT_LS); + + #ifndef WC_NO_RNG + if (((reg & 0x000F0000) >> 16) > 0) { + WOLFSSL_MSG("Found CAAM RNG hardware module"); + if ((WC_CAAM_READ(CAAM_RTMCTL) & 0x40000001) != 0x40000001) { + WOLFSSL_MSG("Error CAAM RNG has not been set up"); + } + } + #endif + + #ifndef NO_SHA256 + if ((reg & 0x0000F000) > 0) { + WOLFSSL_MSG("Found CAAM MDHA module"); + } + else { + WOLFSSL_MSG("Hashing not supported by CAAM"); + return WC_HW_E; + } + #endif + + #ifndef NO_AES + if ((reg & 0x0000000F) > 0) { + WOLFSSL_MSG("Found CAAM AES module"); + } + else { + WOLFSSL_MSG("AES not supported by CAAM"); + return WC_HW_E; + } + #endif + + (void)ret; + return 0; +} + + +int wc_caamFree() +{ + return 0; +} + + +word32 wc_caamReadRegister(word32 reg) +{ + Value out = 0; + + if (caam == NULLIODevice) { + WOLFSSL_MSG("Error CAAM IODevice not found! Bad password?"); + return 0; + } + + if (ReadIODeviceRegister(caam, reg, &out) != Success) { + WOLFSSL_MSG("Error reading register\n"); + } + + return (word32)out; +} + +void wc_caamWriteRegister(word32 reg, word32 value) +{ + if (caam == NULLIODevice) { + WOLFSSL_MSG("Error CAAM IODevice not found! Bad password?"); + return; + } + + if (WriteIODeviceRegister(caam, reg, value) != Success) { + WOLFSSL_MSG("Error writing to register\n"); + } +} + + +/* return 0 on success and WC_HW_E on failure. Can also return WC_HW_WAIT_E + * in the case that the driver is waiting for a resource or RAN_BLOCK_E if + * waiting for entropy. */ +int wc_caamAddAndWait(Buffer* buf, word32 arg[4], word32 type) +{ + int ret; + if (caam == NULLIODevice) { + WOLFSSL_MSG("Error CAAM IODevice not found! Bad password?"); + return WC_HW_E; + } + + if ((ret = SynchronousSendIORequest(caam, type, (const Value*)arg, buf)) + != Success) { + #if defined(WOLFSSL_CAAM_PRINT) || defined(WOLFSSL_CAAM_DEBUG) + printf("ret of SynchronousSendIORequest = %d type = %d\n", ret, type); + #endif + + /* if waiting for resource or RNG return waiting */ + if (ret == Waiting) { + WOLFSSL_MSG("Waiting on entropy from driver"); + return RAN_BLOCK_E; + } + + if (ret == ResourceNotAvailable) { + WOLFSSL_MSG("Waiting on CAAM driver"); + return WC_HW_WAIT_E; + } + + return WC_HW_E; + } + + (void)ret; + return 0; +} + + +int wc_caamCreateBlob(byte* data, word32 dataSz, byte* out, word32* outSz) +{ + Buffer in[3]; + word32 arg[4]; + int ret; + word32 local[2] = {0,0}; + + if (data == NULL || out == NULL || outSz == NULL || + *outSz < dataSz + WC_CAAM_BLOB_SZ) { + return BAD_FUNC_ARG; + } + + in[0].BufferType = DataBuffer; + in[0].TheAddress = (Address)local; + in[0].Length = sizeof(local); + + in[1].BufferType = DataBuffer; + in[1].TheAddress = (Address)data; + in[1].Length = dataSz; + + in[2].BufferType = DataBuffer | LastBuffer; + in[2].TheAddress = (Address)out; + in[2].Length = dataSz + WC_CAAM_BLOB_SZ; + + arg[2] = dataSz; + + if ((ret = wc_caamAddAndWait(in, arg, CAAM_BLOB_ENCAP)) != 0) { + WOLFSSL_MSG("Error with CAAM blob create"); + return ret; + } + + *outSz = dataSz + WC_CAAM_BLOB_SZ; + return 0; +} + + +int wc_caamOpenBlob(byte* data, word32 dataSz, byte* out, word32* outSz) +{ + Buffer in[3]; + word32 arg[4]; + int ret; + word32 local[2] = {0,0}; + + if (data == NULL || out == NULL || outSz == NULL || + *outSz < dataSz - WC_CAAM_BLOB_SZ) { + return BAD_FUNC_ARG; + } + + in[0].BufferType = DataBuffer; + in[0].TheAddress = (Address)local; + in[0].Length = sizeof(local); + + in[0].BufferType = DataBuffer; + in[0].TheAddress = (Address)data; + in[0].Length = dataSz; + + in[1].BufferType = DataBuffer | LastBuffer; + in[1].TheAddress = (Address)out; + in[1].Length = dataSz - WC_CAAM_BLOB_SZ; + + arg[2] = dataSz; + + if ((ret = wc_caamAddAndWait(in, arg, CAAM_BLOB_DECAP)) != 0) { + WOLFSSL_MSG("Error with CAAM blob create"); + return ret; + } + + *outSz = dataSz - WC_CAAM_BLOB_SZ; + return 0; +} + +#endif /* WOLFSSL_IMX6_CAAM */ + diff --git a/pool/shard003/C/0065263_cat.c b/pool/shard003/C/0065263_cat.c new file mode 100644 index 0000000000000000000000000000000000000000..060a810817db08a5f476c992988ebb040e5b70d9 --- /dev/null +++ b/pool/shard003/C/0065263_cat.c @@ -0,0 +1,36 @@ +#include + +char buf[8192]; + +void +cat(int f, char *s) +{ + long n; + int r; + + while ((n = read(f, buf, (long)sizeof(buf))) > 0) + if ((r = write(1, buf, n)) != n) + panic("write error copying %s: %e", s, r); + if (n < 0) + panic("error reading %s: %e", s, n); +} + +void +umain(int argc, char **argv) +{ + int f, i; + + argv0 = "cat"; + if (argc == 1) + cat(0, ""); + else + for (i = 1; i < argc; i++) { + f = open(argv[i], O_RDONLY); + if (f < 0) + panic("can't open %s: %e", argv[i], f); + else { + cat(f, argv[i]); + close(f); + } + } +} diff --git a/pool/shard003/C/0065270_paravirt-smp.c b/pool/shard003/C/0065270_paravirt-smp.c new file mode 100644 index 0000000000000000000000000000000000000000..b77e0295fa93a4afa28e562a2bc92e70a15ac3e2 --- /dev/null +++ b/pool/shard003/C/0065270_paravirt-smp.c @@ -0,0 +1,143 @@ +/* + * This file is subject to the terms and conditions of the GNU General Public + * License. See the file "COPYING" in the main directory of this archive + * for more details. + * + * Copyright (C) 2013 Cavium, Inc. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include + +/* + * Writing the sp releases the CPU, so writes must be ordered, gp + * first, then sp. + */ +unsigned long paravirt_smp_sp[NR_CPUS]; +unsigned long paravirt_smp_gp[NR_CPUS]; + +static int numcpus = 1; + +static int __init set_numcpus(char *str) +{ + int newval; + + if (get_option(&str, &newval)) { + if (newval < 1 || newval >= NR_CPUS) + goto bad; + numcpus = newval; + return 0; + } +bad: + return -EINVAL; +} +early_param("numcpus", set_numcpus); + + +static void paravirt_smp_setup(void) +{ + int id; + unsigned int cpunum = get_ebase_cpunum(); + + if (WARN_ON(cpunum >= NR_CPUS)) + return; + + /* The present CPUs are initially just the boot cpu (CPU 0). */ + for (id = 0; id < NR_CPUS; id++) { + set_cpu_possible(id, id == 0); + set_cpu_present(id, id == 0); + } + __cpu_number_map[cpunum] = 0; + __cpu_logical_map[0] = cpunum; + + for (id = 0; id < numcpus; id++) { + set_cpu_possible(id, true); + set_cpu_present(id, true); + __cpu_number_map[id] = id; + __cpu_logical_map[id] = id; + } +} + +void irq_mbox_ipi(int cpu, unsigned int actions); +static void paravirt_send_ipi_single(int cpu, unsigned int action) +{ + irq_mbox_ipi(cpu, action); +} + +static void paravirt_send_ipi_mask(const struct cpumask *mask, unsigned int action) +{ + unsigned int cpu; + + for_each_cpu_mask(cpu, *mask) + paravirt_send_ipi_single(cpu, action); +} + +static void paravirt_init_secondary(void) +{ + unsigned int sr; + + sr = set_c0_status(ST0_BEV); + write_c0_ebase((u32)ebase); + + sr |= STATUSF_IP2; /* Interrupt controller on IP2 */ + write_c0_status(sr); + + irq_cpu_online(); +} + +static void paravirt_smp_finish(void) +{ + /* to generate the first CPU timer interrupt */ + write_c0_compare(read_c0_count() + mips_hpt_frequency / HZ); + local_irq_enable(); +} + +static void paravirt_boot_secondary(int cpu, struct task_struct *idle) +{ + paravirt_smp_gp[cpu] = (unsigned long)task_thread_info(idle); + smp_wmb(); + paravirt_smp_sp[cpu] = __KSTK_TOS(idle); +} + +static irqreturn_t paravirt_reched_interrupt(int irq, void *dev_id) +{ + scheduler_ipi(); + return IRQ_HANDLED; +} + +static irqreturn_t paravirt_function_interrupt(int irq, void *dev_id) +{ + generic_smp_call_function_interrupt(); + return IRQ_HANDLED; +} + +static void paravirt_prepare_cpus(unsigned int max_cpus) +{ + if (request_irq(MIPS_IRQ_MBOX0, paravirt_reched_interrupt, + IRQF_PERCPU | IRQF_NO_THREAD, "Scheduler", + paravirt_reched_interrupt)) { + panic("Cannot request_irq for SchedulerIPI"); + } + if (request_irq(MIPS_IRQ_MBOX1, paravirt_function_interrupt, + IRQF_PERCPU | IRQF_NO_THREAD, "SMP-Call", + paravirt_function_interrupt)) { + panic("Cannot request_irq for SMP-Call"); + } +} + +struct plat_smp_ops paravirt_smp_ops = { + .send_ipi_single = paravirt_send_ipi_single, + .send_ipi_mask = paravirt_send_ipi_mask, + .init_secondary = paravirt_init_secondary, + .smp_finish = paravirt_smp_finish, + .boot_secondary = paravirt_boot_secondary, + .smp_setup = paravirt_smp_setup, + .prepare_cpus = paravirt_prepare_cpus, +}; diff --git a/pool/shard003/C/0065284_filter_resample.c b/pool/shard003/C/0065284_filter_resample.c new file mode 100644 index 0000000000000000000000000000000000000000..9ff4d9e17a64b9d90c67f1ec97b07c83751f71b5 --- /dev/null +++ b/pool/shard003/C/0065284_filter_resample.c @@ -0,0 +1,198 @@ +/* + * filter_resample.c -- adjust audio sample frequency + * Copyright (C) 2003-2004 Ushodaya Enterprises Limited + * Author: Dan Dennedy + * + * 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 + +#define BUFFER_LEN 20480 +#define RESAMPLE_TYPE SRC_SINC_FASTEST + +/** Get the audio. +*/ + +static int resample_get_audio( mlt_frame frame, int16_t **buffer, mlt_audio_format *format, int *frequency, int *channels, int *samples ) +{ + // Get the properties of the frame + mlt_properties properties = MLT_FRAME_PROPERTIES( frame ); + + // Get the filter service + mlt_filter filter = mlt_frame_pop_audio( frame ); + + // Get the filter properties + mlt_properties filter_properties = MLT_FILTER_PROPERTIES( filter ); + + // Get the resample information + int output_rate = mlt_properties_get_int( filter_properties, "frequency" ); + SRC_STATE *state = mlt_properties_get_data( filter_properties, "state", NULL ); + float *input_buffer = mlt_properties_get_data( filter_properties, "input_buffer", NULL ); + float *output_buffer = mlt_properties_get_data( filter_properties, "output_buffer", NULL ); + int channels_avail = *channels; + SRC_DATA data; + int i; + + // If no resample frequency is specified, default to requested value + if ( output_rate == 0 ) + output_rate = *frequency; + + // Get the producer's audio + mlt_frame_get_audio( frame, buffer, format, frequency, &channels_avail, samples ); + + // Duplicate channels as necessary + if ( channels_avail < *channels ) + { + int size = *channels * *samples * sizeof( int16_t ); + int16_t *new_buffer = mlt_pool_alloc( size ); + int j, k = 0; + + // Duplicate the existing channels + for ( i = 0; i < *samples; i++ ) + { + for ( j = 0; j < *channels; j++ ) + { + new_buffer[ ( i * *channels ) + j ] = (*buffer)[ ( i * channels_avail ) + k ]; + k = ( k + 1 ) % channels_avail; + } + } + + // Update the audio buffer now - destroys the old + mlt_properties_set_data( properties, "audio", new_buffer, size, ( mlt_destructor )mlt_pool_release, NULL ); + + *buffer = new_buffer; + } + else if ( channels_avail == 6 && *channels == 2 ) + { + // Nasty hack for ac3 5.1 audio - may be a cause of failure? + int size = *channels * *samples * sizeof( int16_t ); + int16_t *new_buffer = mlt_pool_alloc( size ); + + // Drop all but the first *channels + for ( i = 0; i < *samples; i++ ) + { + new_buffer[ ( i * *channels ) + 0 ] = (*buffer)[ ( i * channels_avail ) + 2 ]; + new_buffer[ ( i * *channels ) + 1 ] = (*buffer)[ ( i * channels_avail ) + 3 ]; + } + + // Update the audio buffer now - destroys the old + mlt_properties_set_data( properties, "audio", new_buffer, size, ( mlt_destructor )mlt_pool_release, NULL ); + + *buffer = new_buffer; + } + + // Return now if no work to do + if ( output_rate != *frequency ) + { + float *p = input_buffer; + float *end = p + *samples * *channels; + int16_t *q = *buffer; + + // Convert to floating point + while( p != end ) + *p ++ = ( float )( *q ++ ) / 32768.0; + + // Resample + data.data_in = input_buffer; + data.data_out = output_buffer; + data.src_ratio = ( float ) output_rate / ( float ) *frequency; + data.input_frames = *samples; + data.output_frames = BUFFER_LEN / *channels; + data.end_of_input = 0; + i = src_process( state, &data ); + if ( i == 0 ) + { + if ( data.output_frames_gen > *samples ) + { + *buffer = mlt_pool_realloc( *buffer, data.output_frames_gen * *channels * sizeof( int16_t ) ); + mlt_properties_set_data( properties, "audio", *buffer, *channels * data.output_frames_gen * 2, mlt_pool_release, NULL ); + } + + *samples = data.output_frames_gen; + *frequency = output_rate; + + p = output_buffer; + q = *buffer; + end = p + *samples * *channels; + + // Convert from floating back to signed 16bit + while( p != end ) + { + if ( *p > 1.0 ) + *p = 1.0; + if ( *p < -1.0 ) + *p = -1.0; + if ( *p > 0 ) + *q ++ = 32767 * *p ++; + else + *q ++ = 32768 * *p ++; + } + } + else + fprintf( stderr, "resample_get_audio: %s %d,%d,%d\n", src_strerror( i ), *frequency, *samples, output_rate ); + } + + return 0; +} + +/** Filter processing. +*/ + +static mlt_frame filter_process( mlt_filter this, mlt_frame frame ) +{ + if ( mlt_frame_is_test_audio( frame ) == 0 ) + { + mlt_frame_push_audio( frame, this ); + mlt_frame_push_audio( frame, resample_get_audio ); + } + + return frame; +} + +/** Constructor for the filter. +*/ + +mlt_filter filter_resample_init( mlt_profile profile, mlt_service_type type, const char *id, char *arg ) +{ + mlt_filter this = mlt_filter_new( ); + if ( this != NULL ) + { + int error; + SRC_STATE *state = src_new( RESAMPLE_TYPE, 2 /* channels */, &error ); + if ( error == 0 ) + { + void *input_buffer = mlt_pool_alloc( BUFFER_LEN ); + void *output_buffer = mlt_pool_alloc( BUFFER_LEN ); + this->process = filter_process; + if ( arg != NULL ) + mlt_properties_set_int( MLT_FILTER_PROPERTIES( this ), "frequency", atoi( arg ) ); + mlt_properties_set_int( MLT_FILTER_PROPERTIES( this ), "channels", 2 ); + mlt_properties_set_data( MLT_FILTER_PROPERTIES( this ), "state", state, 0, (mlt_destructor)src_delete, NULL ); + mlt_properties_set_data( MLT_FILTER_PROPERTIES( this ), "input_buffer", input_buffer, BUFFER_LEN, mlt_pool_release, NULL ); + mlt_properties_set_data( MLT_FILTER_PROPERTIES( this ), "output_buffer", output_buffer, BUFFER_LEN, mlt_pool_release, NULL ); + } + else + { + fprintf( stderr, "filter_resample_init: %s\n", src_strerror( error ) ); + } + } + return this; +} diff --git a/pool/shard003/C/0065296_gconverter.c b/pool/shard003/C/0065296_gconverter.c new file mode 100644 index 0000000000000000000000000000000000000000..3e47b1fa18e0b095678cd17c968b638c0189b521 --- /dev/null +++ b/pool/shard003/C/0065296_gconverter.c @@ -0,0 +1,202 @@ +/* GIO - GLib Input, Output and Streaming Library + * + * Copyright (C) 2009 Red Hat, Inc. + * + * 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, write to the + * Free Software Foundation, Inc., 59 Temple Place, Suite 330, + * Boston, MA 02111-1307, USA. + * + * Author: Alexander Larsson + */ + +#include "config.h" +#include "gconverter.h" +#include "glibintl.h" + + +/** + * SECTION:gconverter + * @short_description: Data conversion interface + * @include: gio/gio.h + * @see_also: #GInputStream, #GOutputStream + * + * #GConverter is implemented by objects that convert + * binary data in various ways. The conversion can be + * stateful and may fail at any place. + * + * Some example conversions are: character set conversion, + * compression, decompression and regular expression + * replace. + * + * Since: 2.24 + **/ + + +typedef GConverterIface GConverterInterface; +G_DEFINE_INTERFACE (GConverter, g_converter, G_TYPE_OBJECT) + +static void +g_converter_default_init (GConverterInterface *iface) +{ +} + +/** + * g_converter_convert: + * @converter: a #GConverter. + * @inbuf: (array length=inbuf_size) (element-type guint8): the buffer + * containing the data to convert. + * @inbuf_size: the number of bytes in @inbuf + * @outbuf: a buffer to write converted data in. + * @outbuf_size: the number of bytes in @outbuf, must be at least one + * @flags: a #GConvertFlags controlling the conversion details + * @bytes_read: (out): will be set to the number of bytes read from @inbuf on success + * @bytes_written: (out): will be set to the number of bytes written to @outbuf on success + * @error: location to store the error occurring, or %NULL to ignore + * + * This is the main operation used when converting data. It is to be called + * multiple times in a loop, and each time it will do some work, i.e. + * producing some output (in @outbuf) or consuming some input (from @inbuf) or + * both. If its not possible to do any work an error is returned. + * + * Note that a single call may not consume all input (or any input at all). + * Also a call may produce output even if given no input, due to state stored + * in the converter producing output. + * + * If any data was either produced or consumed, and then an error happens, then + * only the successful conversion is reported and the error is returned on the + * next call. + * + * A full conversion loop involves calling this method repeatedly, each time + * giving it new input and space output space. When there is no more input + * data after the data in @inbuf, the flag %G_CONVERTER_INPUT_AT_END must be set. + * The loop will be (unless some error happens) returning %G_CONVERTER_CONVERTED + * each time until all data is consumed and all output is produced, then + * %G_CONVERTER_FINISHED is returned instead. Note, that %G_CONVERTER_FINISHED + * may be returned even if %G_CONVERTER_INPUT_AT_END is not set, for instance + * in a decompression converter where the end of data is detectable from the + * data (and there might even be other data after the end of the compressed data). + * + * When some data has successfully been converted @bytes_read and is set to + * the number of bytes read from @inbuf, and @bytes_written is set to indicate + * how many bytes was written to @outbuf. If there are more data to output + * or consume (i.e. unless the %G_CONVERTER_INPUT_AT_END is specified) then + * %G_CONVERTER_CONVERTED is returned, and if no more data is to be output + * then %G_CONVERTER_FINISHED is returned. + * + * On error %G_CONVERTER_ERROR is returned and @error is set accordingly. + * Some errors need special handling: + * + * %G_IO_ERROR_NO_SPACE is returned if there is not enough space + * to write the resulting converted data, the application should + * call the function again with a larger @outbuf to continue. + * + * %G_IO_ERROR_PARTIAL_INPUT is returned if there is not enough + * input to fully determine what the conversion should produce, + * and the %G_CONVERTER_INPUT_AT_END flag is not set. This happens for + * example with an incomplete multibyte sequence when converting text, + * or when a regexp matches up to the end of the input (and may match + * further input). It may also happen when @inbuf_size is zero and + * there is no more data to produce. + * + * When this happens the application should read more input and then + * call the function again. If further input shows that there is no + * more data call the function again with the same data but with + * the %G_CONVERTER_INPUT_AT_END flag set. This may cause the conversion + * to finish as e.g. in the regexp match case (or, to fail again with + * %G_IO_ERROR_PARTIAL_INPUT in e.g. a charset conversion where the + * input is actually partial). + * + * After g_converter_convert() has returned %G_CONVERTER_FINISHED the + * converter object is in an invalid state where its not allowed + * to call g_converter_convert() anymore. At this time you can only + * free the object or call g_converter_reset() to reset it to the + * initial state. + * + * If the flag %G_CONVERTER_FLUSH is set then conversion is modified + * to try to write out all internal state to the output. The application + * has to call the function multiple times with the flag set, and when + * the available input has been consumed and all internal state has + * been produced then %G_CONVERTER_FLUSHED (or %G_CONVERTER_FINISHED if + * really at the end) is returned instead of %G_CONVERTER_CONVERTED. + * This is somewhat similar to what happens at the end of the input stream, + * but done in the middle of the data. + * + * This has different meanings for different conversions. For instance + * in a compression converter it would mean that we flush all the + * compression state into output such that if you uncompress the + * compressed data you get back all the input data. Doing this may + * make the final file larger due to padding though. Another example + * is a regexp conversion, where if you at the end of the flushed data + * have a match, but there is also a potential longer match. In the + * non-flushed case we would ask for more input, but when flushing we + * treat this as the end of input and do the match. + * + * Flushing is not always possible (like if a charset converter flushes + * at a partial multibyte sequence). Converters are supposed to try + * to produce as much output as possible and then return an error + * (typically %G_IO_ERROR_PARTIAL_INPUT). + * + * Returns: a #GConverterResult, %G_CONVERTER_ERROR on error. + * + * Since: 2.24 + **/ +GConverterResult +g_converter_convert (GConverter *converter, + const void *inbuf, + gsize inbuf_size, + void *outbuf, + gsize outbuf_size, + GConverterFlags flags, + gsize *bytes_read, + gsize *bytes_written, + GError **error) +{ + GConverterIface *iface; + + g_return_val_if_fail (G_IS_CONVERTER (converter), G_CONVERTER_ERROR); + g_return_val_if_fail (outbuf_size > 0, G_CONVERTER_ERROR); + + *bytes_read = 0; + *bytes_written = 0; + + iface = G_CONVERTER_GET_IFACE (converter); + + return (* iface->convert) (converter, + inbuf, inbuf_size, + outbuf, outbuf_size, + flags, + bytes_read, bytes_written, error); +} + +/** + * g_converter_reset: + * @converter: a #GConverter. + * + * Resets all internal state in the converter, making it behave + * as if it was just created. If the converter has any internal + * state that would produce output then that output is lost. + * + * Since: 2.24 + **/ +void +g_converter_reset (GConverter *converter) +{ + GConverterIface *iface; + + g_return_if_fail (G_IS_CONVERTER (converter)); + + iface = G_CONVERTER_GET_IFACE (converter); + + (* iface->reset) (converter); +} diff --git a/pool/shard003/C/0065307_test-stylescheme.c b/pool/shard003/C/0065307_test-stylescheme.c new file mode 100644 index 0000000000000000000000000000000000000000..a6246fb3058a3737600145cb16e13929aece0c5f --- /dev/null +++ b/pool/shard003/C/0065307_test-stylescheme.c @@ -0,0 +1,160 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8; coding: utf-8 -*- */ +/* + * This file is part of GtkSourceView + * + * Copyright (C) 2015 - Paolo Borelli + * + * GtkSourceView 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. + * + * GtkSourceView 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 . + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +typedef struct _TestFixture TestFixture; + +struct _TestFixture { + GtkSourceStyleSchemeManager *manager; +}; + +/* If we are running from the source dir (e.g. during make check) + * we override the path to read from the data dir + */ +static void +test_fixture_setup (TestFixture *fixture, + gconstpointer data) +{ + gchar *dir; + gchar **style_dirs; + + dir = g_build_filename (TOP_SRCDIR, "data", "styles", NULL); + + fixture->manager = gtk_source_style_scheme_manager_get_default (); + + if (g_file_test (dir, G_FILE_TEST_IS_DIR)) + { + style_dirs = g_new0 (gchar *, 3); + style_dirs[0] = dir; + style_dirs[1] = g_test_build_filename (G_TEST_DIST, "styles", NULL); + } + else + { + const gchar * const *current; + int i; + + g_free (dir); + + current = gtk_source_style_scheme_manager_get_search_path (fixture->manager); + style_dirs = g_new0 (gchar *, g_strv_length ((gchar **)current) + 2); + for (i = 0; current[i] != NULL; i++) + { + style_dirs[i] = g_strdup(current[i]); + } + style_dirs[i] = g_test_build_filename (G_TEST_DIST, "styles", NULL); + } + + gtk_source_style_scheme_manager_set_search_path (fixture->manager, style_dirs); + g_strfreev (style_dirs); +} + +static void +test_fixture_teardown (TestFixture *fixture, + gconstpointer data) +{ +} + +static void +compare_strv (const gchar **strv, + const gchar **expected_strv) +{ + if (expected_strv != NULL) + { + guint n, i; + + n = g_strv_length ((gchar **) expected_strv); + for (i = 0; i < n; i++) + { + g_assert_cmpstr (strv[i], ==, expected_strv[i]); + } + } + else + { + g_assert (strv == NULL); + } +} + +static void +check_scheme (GtkSourceStyleScheme *scheme, + const gchar *expected_id, + const gchar *expected_name, + const gchar *expected_description, + const gchar **expected_authors, + const gchar *style_id) +{ + GtkSourceStyle *style; + + g_assert_cmpstr (gtk_source_style_scheme_get_id (scheme), ==, expected_id); + g_assert_cmpstr (gtk_source_style_scheme_get_name (scheme), ==, expected_name); + g_assert_cmpstr (gtk_source_style_scheme_get_description (scheme), ==, expected_description); + compare_strv ((const gchar **)gtk_source_style_scheme_get_authors (scheme), expected_authors); + + style = gtk_source_style_scheme_get_style (scheme, style_id); + g_assert (GTK_SOURCE_IS_STYLE (style)); +} + +static void +test_scheme_properties (TestFixture *fixture, + gconstpointer data) +{ + GtkSourceStyleScheme *scheme; + const gchar *authors[] = { "Paolo Borelli", "John Doe", NULL}; + + scheme = gtk_source_style_scheme_manager_get_scheme (fixture->manager, "test"); + check_scheme (scheme, "test", "Test", "Test color scheme", authors, "def:comment"); +} + +static void +test_named_color_alpha (TestFixture *fixture, + gconstpointer data) +{ + GtkSourceStyleScheme *scheme; + GdkRGBA color1, color2; + gboolean res; + + scheme = gtk_source_style_scheme_manager_get_scheme (fixture->manager, "test"); + + /* Use these two semi private methods to compare a named color and a normal one */ + res = _gtk_source_style_scheme_get_current_line_color (scheme, &color1); + g_assert (res); + + res = _gtk_source_style_scheme_get_background_pattern_color (scheme, &color2); + g_assert (res); + + g_assert (gdk_rgba_equal (&color1, &color2)); +} + +int +main (int argc, char** argv) +{ + gtk_test_init (&argc, &argv); + + g_test_add ("/StyleScheme/scheme-properties", TestFixture, NULL, test_fixture_setup, test_scheme_properties, test_fixture_teardown); + g_test_add ("/StyleScheme/named-colors-alpha", TestFixture, NULL, test_fixture_setup, test_named_color_alpha, test_fixture_teardown); + + return g_test_run(); +} diff --git a/pool/shard003/C/0065309_bufferDebug.c b/pool/shard003/C/0065309_bufferDebug.c new file mode 100644 index 0000000000000000000000000000000000000000..0aa01c19c6e7f5652ee759da06f00e21e8d2e7e3 --- /dev/null +++ b/pool/shard003/C/0065309_bufferDebug.c @@ -0,0 +1,80 @@ +#include + +#include "bufferDebug.h" +#include "buffer.h" +#include "outputStream.h" +#include "printWriter.h" + +void printDebugBuffer(OutputStream* outputStream, Buffer* buffer) { + if (!checkBufferNotNull(buffer)) { + return; + } + if (buffer == NULL) { + println(outputStream); + appendStringLN(outputStream, "Buffer is NULL !"); + return; + } + println(outputStream); + appendString(outputStream, "Buffer:"); + + if (buffer->name != NULL) { + appendKeyAndName(outputStream, "name=", buffer->name); + } + + if (buffer->type) { + appendKeyAndName(outputStream, ", type=", buffer->type); + } + + appendStringAndDec(outputStream, ", length=", buffer->length); + appendStringAndDec(outputStream, ", writeIdx=", buffer->writeIndex); + appendStringAndDec(outputStream, ", readIdx=", buffer->readIndex); + appendCRLF(outputStream); + // FULL DUMP + appendString(outputStream, "---START---"); + appendCRLF(outputStream); + unsigned int i; + char* sPointer = (char*) buffer->s; + unsigned int noLineCount = 0; + for (i = 0; i < buffer->length; i++) { + // Shift to the right cell index + unsigned char c = *sPointer; + if (c == 0) { + // To avoid [00] on Console + append(outputStream, '#'); + } else { + append(outputStream, c); + } + if (c != LF) { + noLineCount++; + } + else { + noLineCount = 0; + } + sPointer++; + // Multi line management : we create line if there is no line feed in the buffer + if (noLineCount % CONSOLE_MAX_WIDTH == CONSOLE_MAX_WIDTH - 1) { + appendCRLF(outputStream); + } + } + appendCRLF(outputStream); + appendString(outputStream, "---END---"); + appendCRLF(outputStream); + + // LOGICAL COUNT + appendString(outputStream, "---FROM READ_INDEX TO WRITE_INDEX ---"); + appendCRLF(outputStream); + for (i = 0; i < buffer->readIndex; i++) { + append(outputStream, ' '); + } + unsigned elementCount = getBufferElementsCount(buffer); + for (i = 0; i < elementCount; i++) { + unsigned char c = bufferGetCharAtIndex(buffer, i); + append(outputStream, c); + // Multi line management + if (i % CONSOLE_MAX_WIDTH == CONSOLE_MAX_WIDTH - 1) { + appendCRLF(outputStream); + } + } + appendCRLF(outputStream); + +} diff --git a/pool/shard003/C/0065315_camio_istream.c b/pool/shard003/C/0065315_camio_istream.c new file mode 100644 index 0000000000000000000000000000000000000000..10613104cf40cd8b2f2eba55f581a0013c40eee8 --- /dev/null +++ b/pool/shard003/C/0065315_camio_istream.c @@ -0,0 +1,84 @@ +/* + * Copyright (C) Matthew P. Grosvenor, 2012, All Rights Reserved + * + * Input stream factory definition + * + */ + +#include + +#include "camio_istream.h" +#include "../camio_errors.h" + +#include "camio_istream_log.h" +#include "camio_istream_raw.h" +#include "camio_istream_udp.h" +#include "camio_istream_ring.h" +#include "camio_istream_pcap.h" +#include "camio_istream_periodic_timeout.h" +#include "camio_istream_periodic_timeout_fast.h" +#include "camio_istream_blob.h" +#include "camio_istream_netmap.h" + +//#ifdef HAVE_DAG_ +#include "camio_istream_dag.h" +//#endif //HAVE_DAG_ + + +#include "camio_istream_exa.h" +camio_istream_t* camio_istream_new(const char* description, void* parameters){ + camio_istream_t* result = NULL; + camio_descr_t descr; + camio_descr_construct(&descr); + camio_descr_parse(description,&descr); + + if(strcmp(descr.protocol,"log") == 0 ){ + result = camio_istream_log_new(&descr,parameters); + } + else if(strcmp(descr.protocol,"std-log") == 0 ){ + camio_istream_log_params_t params = { .fd = STDIN_FILENO}; + result = camio_istream_log_new(&descr, ¶ms); + } + else if(strcmp(descr.protocol,"raw") == 0 ){ + result = camio_istream_raw_new(&descr,parameters); + } + else if(strcmp(descr.protocol,"ring") == 0 ){ + result = camio_istream_ring_new(&descr,parameters); + } + else if(strcmp(descr.protocol,"udp") == 0 ){ + result = camio_istream_udp_new(&descr,parameters); + } + else if(strcmp(descr.protocol,"periodic") == 0 ){ + result = camio_istream_periodic_timeout_new(&descr,parameters); + } + else if(strcmp(descr.protocol,"period_fast") == 0 ){ + result = camio_istream_periodic_timeout_fast_new(&descr,parameters); + } + else if(strcmp(descr.protocol,"blob") == 0 ){ + result = camio_istream_blob_new(&descr,parameters); + } + +// else if(strcmp(descr.protocol,"pcap") == 0 ){ +// result = camio_istream_pcap_new(&descr,NULL); +// } +//#ifdef HAVE_DAG_ + else if(strcmp(descr.protocol,"dag") == 0 ){ + result = camio_istream_dag_new(&descr,parameters); + } + else if(strcmp(descr.protocol,"exa") == 0 ){ + result = camio_istream_exa_new(&descr,parameters); + } + else if(strcmp(descr.protocol,"nmap") == 0 ){ + result = camio_istream_netmap_new(&descr,parameters); + } +//#endif /*camio_ISTREAM_BUILD_WITH_DAG_*/ + else{ + eprintf_exit(CAMIO_ERR_UNKNOWN_ISTREAM,"Could not create istream from description \"%s\" \n", description); + } + + camio_descr_destroy(&descr); + return result; + +} + + diff --git a/pool/shard003/C/0065321_time.c b/pool/shard003/C/0065321_time.c new file mode 100644 index 0000000000000000000000000000000000000000..46f7cb0c80088f102400410284a9cea8b5d2a481 --- /dev/null +++ b/pool/shard003/C/0065321_time.c @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2008-2009 Apple Inc. All rights reserved. + * + * @APPLE_APACHE_LICENSE_HEADER_START@ + * + * 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. + * + * @APPLE_APACHE_LICENSE_HEADER_END@ + */ + +#include "internal.h" + +static const unsigned __int64 intervals_per_second = 10000000ULL; +static const unsigned __int64 microseconds_per_second = 1000000ULL; +static const unsigned __int64 nanoseconds_per_second = 1000000000ULL; +static const unsigned __int64 intervals_per_microsecond = 10ULL; +static const unsigned __int64 intervals_since_epoch = 116444736000000000ULL; +static const unsigned __int64 microseconds_since_epoch = 11644473600000000ULL; + +uint64_t +_dispatch_get_nanoseconds(void) +{ +#if !TARGET_OS_WIN32 + struct timeval now; + int r = gettimeofday(&now, NULL); + dispatch_assert_zero(r); + dispatch_assert(sizeof(NSEC_PER_SEC) == 8); + dispatch_assert(sizeof(NSEC_PER_USEC) == 8); + return now.tv_sec * NSEC_PER_SEC + now.tv_usec * NSEC_PER_USEC; +#else /* TARGET_OS_WIN32 */ + // FILETIME is 100-nanosecond intervals since January 1, 1601 (UTC). + FILETIME ft; + ULARGE_INTEGER li; + GetSystemTimeAsFileTime(&ft); + li.LowPart = ft.dwLowDateTime; + li.HighPart = ft.dwHighDateTime; + li.QuadPart -= intervals_since_epoch; + return li.QuadPart * (nanoseconds_per_second / intervals_per_second); +#endif /* TARGET_OS_WIN32 */ +} + +dispatch_time_t +dispatch_time(dispatch_time_t inval, int64_t delta) +{ + if (inval == DISPATCH_TIME_FOREVER) { + return DISPATCH_TIME_FOREVER; + } + if ((int64_t)inval < 0) { + // wall clock + if (delta >= 0) { + if ((int64_t)(inval -= delta) >= 0) { + return DISPATCH_TIME_FOREVER; // overflow + } + return inval; + } + if ((int64_t)(inval -= delta) >= -1) { + // -1 is special == DISPATCH_TIME_FOREVER == forever + return (dispatch_time_t)-2; // underflow + } + return inval; + } + // mach clock + delta = _dispatch_time_nano2mach(delta); + if (inval == 0) { + inval = _dispatch_absolute_time(); + } + if (delta >= 0) { + if ((int64_t)(inval += delta) <= 0) { + return DISPATCH_TIME_FOREVER; // overflow + } + return inval; + } + if ((int64_t)(inval += delta) < 1) { + return 1; // underflow + } + return inval; +} + +dispatch_time_t +dispatch_walltime(const struct timespec *inval, int64_t delta) +{ + int64_t nsec; + + if (inval) { + nsec = inval->tv_sec * 1000000000ull + inval->tv_nsec; + } else { + nsec = _dispatch_get_nanoseconds(); + } + + nsec += delta; + if (nsec <= 1) { + // -1 is special == DISPATCH_TIME_FOREVER == forever + return delta >= 0 ? DISPATCH_TIME_FOREVER : (uint64_t)-2ll; + } + + return -nsec; +} + +uint64_t +_dispatch_timeout(dispatch_time_t when) +{ + uint64_t now; + + if (when == DISPATCH_TIME_FOREVER) { + return DISPATCH_TIME_FOREVER; + } + if (when == 0) { + return 0; + } + if ((int64_t)when < 0) { + when = -(int64_t)when; + now = _dispatch_get_nanoseconds(); + return now >= when ? 0 : when - now; + } + now = _dispatch_absolute_time(); + return now >= when ? 0 : _dispatch_time_mach2nano(when - now); +} + +#if USE_POSIX_SEM +/* + * Unlike Mach semaphores, POSIX semaphores take an absolute, real time as an + * argument to sem_timedwait(). This routine converts from dispatch_time_t + * but assumes the caller has already handled the possibility of + * DISPATCH_TIME_FOREVER. + */ +struct timespec +_dispatch_timeout_ts(dispatch_time_t when) +{ + struct timespec ts_realtime; + uint64_t abstime, realtime; + int ret; + + if (when == 0) { + ret = clock_gettime(CLOCK_REALTIME, &ts_realtime); + dispatch_assume_zero(ret); + return (ts_realtime); + } + if ((int64_t)when < 0) { + ret = clock_gettime(CLOCK_REALTIME, &ts_realtime); + dispatch_assume_zero(ret); + when = -(int64_t)when + ts_realtime.tv_sec * NSEC_PER_SEC + + ts_realtime.tv_nsec; + ts_realtime.tv_sec = when / NSEC_PER_SEC; + ts_realtime.tv_nsec = when % NSEC_PER_SEC; + return (ts_realtime); + } + + /* + * Rebase 'when': (when - abstime) + realtime. + * + * XXXRW: Should we cache this delta to avoid system calls? + */ + abstime = _dispatch_absolute_time(); + ret = clock_gettime(CLOCK_REALTIME, &ts_realtime); + dispatch_assume_zero(ret); + realtime = ts_realtime.tv_sec * NSEC_PER_SEC + ts_realtime.tv_nsec + + (when - abstime); + ts_realtime.tv_sec = realtime / NSEC_PER_SEC; + ts_realtime.tv_nsec = realtime % NSEC_PER_SEC; + return (ts_realtime); +} +#endif diff --git a/pool/shard003/C/0065323_cycle-check.c b/pool/shard003/C/0065323_cycle-check.c new file mode 100644 index 0000000000000000000000000000000000000000..f7b3d078856d25cc6dcefad59064e3f08f5050e9 --- /dev/null +++ b/pool/shard003/C/0065323_cycle-check.c @@ -0,0 +1,85 @@ +/* help detect directory cycles efficiently + + Copyright (C) 2003-2006, 2009-2014 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 . */ + +/* Written by Jim Meyering */ + +#include + +#include +#include +#include +#include +#include + +#include + +#include "cycle-check.h" + +#define CC_MAGIC 9827862 + +/* Return true if I is a power of 2, or is zero. */ + +static bool +is_zero_or_power_of_two (uintmax_t i) +{ + return (i & (i - 1)) == 0; +} + +void +cycle_check_init (struct cycle_check_state *state) +{ + state->chdir_counter = 0; + state->magic = CC_MAGIC; +} + +/* In traversing a directory hierarchy, call this function once for each + descending chdir call, with SB corresponding to the chdir operand. + If SB corresponds to a directory that has already been seen, + return true to indicate that there is a directory cycle. + Note that this is done "lazily", which means that some of + the directories in the cycle may be processed twice before + the cycle is detected. */ + +bool +cycle_check (struct cycle_check_state *state, struct stat const *sb) +{ + assert (state->magic == CC_MAGIC); + + /* If the current directory ever happens to be the same + as the one we last recorded for the cycle detection, + then it's obviously part of a cycle. */ + if (state->chdir_counter && SAME_INODE (*sb, state->dev_ino)) + return true; + + /* If the number of "descending" chdir calls is a power of two, + record the dev/ino of the current directory. */ + if (is_zero_or_power_of_two (++(state->chdir_counter))) + { + /* On all architectures that we know about, if the counter + overflows then there is a directory cycle here somewhere, + even if we haven't detected it yet. Typically this happens + only after the counter is incremented 2**64 times, so it's a + fairly theoretical point. */ + if (state->chdir_counter == 0) + return true; + + state->dev_ino.st_dev = sb->st_dev; + state->dev_ino.st_ino = sb->st_ino; + } + + return false; +} diff --git a/pool/shard003/C/0065324_core.c b/pool/shard003/C/0065324_core.c new file mode 100644 index 0000000000000000000000000000000000000000..98229f34a0e90a468edd3d889179ea613c7c23b8 --- /dev/null +++ b/pool/shard003/C/0065324_core.c @@ -0,0 +1,92 @@ +#include "core.h" + +double *values, + *oldval, + *newval; + +int arrLen, mode = 0; +double c = 0.1, shift; + +void init(double cFactor, unsigned int tPoints, double shiftFactor) +{ + arrLen = tPoints; + values = malloc(tPoints * sizeof(double)); + oldval = malloc(tPoints * sizeof(double)); + newval = malloc(tPoints * sizeof(double)); + + memset(values, 0, tPoints); + memset(oldval, 0, tPoints); + memset(newval, 0, tPoints); + + c = cFactor; + shift = shiftFactor; + + for (int i = 0; i < arrLen; i++) + { + oldval[i] = sin(i*0.02); + values[i] = sin((i+shift)*0.02); + } +} + +void simulate() +{ + #pragma omp parallel for + for (int i = 1; i < arrLen-1; i++) + { + if (0 == mode) + { + newval[i] = (2 * values[i]) - oldval[i] + c * (values[i-1] - (2 * values[i]) + values[i+1]); + } + else if (1 == mode) + { + oldval[i] = (2 * newval[i]) - values[i] + c * (newval[i-1] - (2 * newval[i]) + newval[i+1]); + } + else + { + values[i] = (2 * oldval[i]) - newval[i] + c * (oldval[i-1] - (2 * oldval[i]) + oldval[i+1]); + } + } + + mode++; + if (2 < mode) + { + mode = 0; + } +} + +void output() +{ + for (int i = 0; i < arrLen; i++) + { + printf("%f\n",values[i]); + } +} + +double* getNewValues() +{ + if (0 == mode) + { + return newval; + } + else if (1 == mode) + { + return oldval; + } + else + { + return values; + } +} + +int getArraySize() +{ + return arrLen; +} + +void terminate() +{ + free(newval); + free(oldval); + free(values); +} + diff --git a/pool/shard003/C/0065340_ns558.c b/pool/shard003/C/0065340_ns558.c new file mode 100644 index 0000000000000000000000000000000000000000..bc3efdf39f8d9c9171a014b4c08465ef41ef6e36 --- /dev/null +++ b/pool/shard003/C/0065340_ns558.c @@ -0,0 +1,291 @@ +/* + * $Id$ + * + * Copyright (c) 1999-2001 Vojtech Pavlik + * Copyright (c) 1999 Brian Gerst + */ + +/* + * NS558 based standard IBM game port driver for Linux + */ + +/* + * 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 + * + * Should you need to contact me, the author, you can do so either by + * e-mail - mail your message to , or by paper mail: + * Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +MODULE_AUTHOR("Vojtech Pavlik "); +MODULE_DESCRIPTION("Classic gameport (ISA/PnP) driver"); +MODULE_LICENSE("GPL"); + +static int ns558_isa_portlist[] = { 0x201, 0x200, 0x202, 0x203, 0x204, 0x205, 0x207, 0x209, + 0x20b, 0x20c, 0x20e, 0x20f, 0x211, 0x219, 0x101, 0 }; + +struct ns558 { + int type; + int io; + int size; + struct pnp_dev *dev; + struct gameport *gameport; + struct list_head node; +}; + +static LIST_HEAD(ns558_list); + +/* + * ns558_isa_probe() tries to find an isa gameport at the + * specified address, and also checks for mirrors. + * A joystick must be attached for this to work. + */ + +static int ns558_isa_probe(int io) +{ + int i, j, b; + unsigned char c, u, v; + struct ns558 *ns558; + struct gameport *port; + +/* + * No one should be using this address. + */ + + if (!request_region(io, 1, "ns558-isa")) + return -EBUSY; + +/* + * We must not be able to write arbitrary values to the port. + * The lower two axis bits must be 1 after a write. + */ + + c = inb(io); + outb(~c & ~3, io); + if (~(u = v = inb(io)) & 3) { + outb(c, io); + release_region(io, 1); + return -ENODEV; + } +/* + * After a trigger, there must be at least some bits changing. + */ + + for (i = 0; i < 1000; i++) v &= inb(io); + + if (u == v) { + outb(c, io); + release_region(io, 1); + return -ENODEV; + } + msleep(3); +/* + * After some time (4ms) the axes shouldn't change anymore. + */ + + u = inb(io); + for (i = 0; i < 1000; i++) + if ((u ^ inb(io)) & 0xf) { + outb(c, io); + release_region(io, 1); + return -ENODEV; + } +/* + * And now find the number of mirrors of the port. + */ + + for (i = 1; i < 5; i++) { + + release_region(io & (-1 << (i - 1)), (1 << (i - 1))); + + if (!request_region(io & (-1 << i), (1 << i), "ns558-isa")) + break; /* Don't disturb anyone */ + + outb(0xff, io & (-1 << i)); + for (j = b = 0; j < 1000; j++) + if (inb(io & (-1 << i)) != inb((io & (-1 << i)) + (1 << i) - 1)) b++; + msleep(3); + + if (b > 300) { /* We allow 30% difference */ + release_region(io & (-1 << i), (1 << i)); + break; + } + } + + i--; + + if (i != 4) { + if (!request_region(io & (-1 << i), (1 << i), "ns558-isa")) + return -EBUSY; + } + + ns558 = kzalloc(sizeof(struct ns558), GFP_KERNEL); + port = gameport_allocate_port(); + if (!ns558 || !port) { + printk(KERN_ERR "ns558: Memory allocation failed.\n"); + release_region(io & (-1 << i), (1 << i)); + kfree(ns558); + gameport_free_port(port); + return -ENOMEM; + } + + memset(ns558, 0, sizeof(struct ns558)); + ns558->io = io; + ns558->size = 1 << i; + ns558->gameport = port; + + port->io = io; + gameport_set_name(port, "NS558 ISA Gameport"); + gameport_set_phys(port, "isa%04x/gameport0", io & (-1 << i)); + + gameport_register_port(port); + + list_add(&ns558->node, &ns558_list); + + return 0; +} + +#ifdef CONFIG_PNP + +static struct pnp_device_id pnp_devids[] = { + { .id = "@P@0001", .driver_data = 0 }, /* ALS 100 */ + { .id = "@P@0020", .driver_data = 0 }, /* ALS 200 */ + { .id = "@P@1001", .driver_data = 0 }, /* ALS 100+ */ + { .id = "@P@2001", .driver_data = 0 }, /* ALS 120 */ + { .id = "ASB16fd", .driver_data = 0 }, /* AdLib NSC16 */ + { .id = "AZT3001", .driver_data = 0 }, /* AZT1008 */ + { .id = "CDC0001", .driver_data = 0 }, /* Opl3-SAx */ + { .id = "CSC0001", .driver_data = 0 }, /* CS4232 */ + { .id = "CSC000f", .driver_data = 0 }, /* CS4236 */ + { .id = "CSC0101", .driver_data = 0 }, /* CS4327 */ + { .id = "CTL7001", .driver_data = 0 }, /* SB16 */ + { .id = "CTL7002", .driver_data = 0 }, /* AWE64 */ + { .id = "CTL7005", .driver_data = 0 }, /* Vibra16 */ + { .id = "ENS2020", .driver_data = 0 }, /* SoundscapeVIVO */ + { .id = "ESS0001", .driver_data = 0 }, /* ES1869 */ + { .id = "ESS0005", .driver_data = 0 }, /* ES1878 */ + { .id = "ESS6880", .driver_data = 0 }, /* ES688 */ + { .id = "IBM0012", .driver_data = 0 }, /* CS4232 */ + { .id = "OPT0001", .driver_data = 0 }, /* OPTi Audio16 */ + { .id = "YMH0006", .driver_data = 0 }, /* Opl3-SA */ + { .id = "YMH0022", .driver_data = 0 }, /* Opl3-SAx */ + { .id = "PNPb02f", .driver_data = 0 }, /* Generic */ + { .id = "", }, +}; + +MODULE_DEVICE_TABLE(pnp, pnp_devids); + +static int ns558_pnp_probe(struct pnp_dev *dev, const struct pnp_device_id *did) +{ + int ioport, iolen; + struct ns558 *ns558; + struct gameport *port; + + if (!pnp_port_valid(dev, 0)) { + printk(KERN_WARNING "ns558: No i/o ports on a gameport? Weird\n"); + return -ENODEV; + } + + ioport = pnp_port_start(dev, 0); + iolen = pnp_port_len(dev, 0); + + if (!request_region(ioport, iolen, "ns558-pnp")) + return -EBUSY; + + ns558 = kzalloc(sizeof(struct ns558), GFP_KERNEL); + port = gameport_allocate_port(); + if (!ns558 || !port) { + printk(KERN_ERR "ns558: Memory allocation failed\n"); + kfree(ns558); + gameport_free_port(port); + return -ENOMEM; + } + + ns558->io = ioport; + ns558->size = iolen; + ns558->dev = dev; + ns558->gameport = port; + + gameport_set_name(port, "NS558 PnP Gameport"); + gameport_set_phys(port, "pnp%s/gameport0", dev->dev.bus_id); + port->dev.parent = &dev->dev; + port->io = ioport; + + gameport_register_port(port); + + list_add_tail(&ns558->node, &ns558_list); + return 0; +} + +static struct pnp_driver ns558_pnp_driver = { + .name = "ns558", + .id_table = pnp_devids, + .probe = ns558_pnp_probe, +}; + +#else + +static struct pnp_driver ns558_pnp_driver; + +#endif + +static int pnp_registered = 0; + +static int __init ns558_init(void) +{ + int i = 0; + + if (pnp_register_driver(&ns558_pnp_driver) >= 0) + pnp_registered = 1; + +/* + * Probe ISA ports after PnP, so that PnP ports that are already + * enabled get detected as PnP. This may be suboptimal in multi-device + * configurations, but saves hassle with simple setups. + */ + + while (ns558_isa_portlist[i]) + ns558_isa_probe(ns558_isa_portlist[i++]); + + return (list_empty(&ns558_list) && !pnp_registered) ? -ENODEV : 0; +} + +static void __exit ns558_exit(void) +{ + struct ns558 *ns558, *safe; + + list_for_each_entry_safe(ns558, safe, &ns558_list, node) { + gameport_unregister_port(ns558->gameport); + release_region(ns558->io & ~(ns558->size - 1), ns558->size); + kfree(ns558); + } + + if (pnp_registered) + pnp_unregister_driver(&ns558_pnp_driver); +} + +module_init(ns558_init); +module_exit(ns558_exit); diff --git a/pool/shard003/C/0065345_halt.c b/pool/shard003/C/0065345_halt.c new file mode 100644 index 0000000000000000000000000000000000000000..785c3813018f9905d0ba5f3f39fa4705accaf833 --- /dev/null +++ b/pool/shard003/C/0065345_halt.c @@ -0,0 +1,249 @@ +/* vi: set sw=4 ts=4: */ +/* + * Poweroff reboot and halt, oh my. + * + * Copyright 2006 by Rob Landley + * + * Licensed under GPLv2, see file LICENSE in this source tree. + */ +//config:config HALT +//config: bool "halt (4 kb)" +//config: default y +//config: help +//config: Stop all processes and halt the system. +//config: +//config:config POWEROFF +//config: bool "poweroff (4 kb)" +//config: default y +//config: help +//config: Stop all processes and power off the system. +//config: +//config:config REBOOT +//config: bool "reboot (4 kb)" +//config: default y +//config: help +//config: Stop all processes and reboot the system. +//config: +//config:config FEATURE_WAIT_FOR_INIT +//config: bool "Before signaling init, make sure it is ready for it" +//config: default y +//config: depends on HALT || POWEROFF || REBOOT +//config: help +//config: In rare cases, poweroff may be commanded by firmware to OS +//config: even before init process exists. On Linux, this spawns +//config: "/sbin/poweroff" very early. This option adds code +//config: which checks that init is ready to receive poweroff +//config: commands. Code size increase of ~80 bytes. +//config: +//config:config FEATURE_CALL_TELINIT +//config: bool "Call telinit on shutdown and reboot" +//config: default y +//config: depends on (HALT || POWEROFF || REBOOT) && !INIT +//config: help +//config: Call an external program (normally telinit) to facilitate +//config: a switch to a proper runlevel. +//config: +//config: This option is only available if you selected halt and friends, +//config: but did not select init. +//config: +//config:config TELINIT_PATH +//config: string "Path to telinit executable" +//config: default "/sbin/telinit" +//config: depends on FEATURE_CALL_TELINIT +//config: help +//config: When busybox halt and friends have to call external telinit +//config: to facilitate proper shutdown, this path is to be used when +//config: locating telinit executable. + +//applet:IF_HALT(APPLET(halt, BB_DIR_SBIN, BB_SUID_DROP)) +// APPLET_ODDNAME:name main location suid_type help +//applet:IF_POWEROFF(APPLET_ODDNAME(poweroff, halt, BB_DIR_SBIN, BB_SUID_DROP, poweroff)) +//applet:IF_REBOOT( APPLET_ODDNAME(reboot, halt, BB_DIR_SBIN, BB_SUID_DROP, reboot)) + +//kbuild:lib-$(CONFIG_HALT) += halt.o +//kbuild:lib-$(CONFIG_POWEROFF) += halt.o +//kbuild:lib-$(CONFIG_REBOOT) += halt.o + +//usage:#define halt_trivial_usage +//usage: "[-d DELAY] [-n] [-f]" IF_FEATURE_WTMP(" [-w]") +//usage:#define halt_full_usage "\n\n" +//usage: "Halt the system\n" +//usage: "\n -d SEC Delay interval" +//usage: "\n -n Do not sync" +//usage: "\n -f Force (don't go through init)" +//usage: IF_FEATURE_WTMP( +//usage: "\n -w Only write a wtmp record" +//usage: ) +//usage: +//usage:#define poweroff_trivial_usage +//usage: "[-d DELAY] [-n] [-f]" +//usage:#define poweroff_full_usage "\n\n" +//usage: "Halt and shut off power\n" +//usage: "\n -d SEC Delay interval" +//usage: "\n -n Do not sync" +//usage: "\n -f Force (don't go through init)" +//usage: +//usage:#define reboot_trivial_usage +//usage: "[-d DELAY] [-n] [-f]" +//usage:#define reboot_full_usage "\n\n" +//usage: "Reboot the system\n" +//usage: "\n -d SEC Delay interval" +//usage: "\n -n Do not sync" +//usage: "\n -f Force (don't go through init)" + +#include "libbb.h" +#include "reboot.h" + +#if ENABLE_FEATURE_WTMP +#include + +static void write_wtmp(void) +{ + struct utmpx utmp; + struct utsname uts; + /* "man utmp" says wtmp file should *not* be created automagically */ + /*if (access(bb_path_wtmp_file, R_OK|W_OK) == -1) { + close(creat(bb_path_wtmp_file, 0664)); + }*/ + memset(&utmp, 0, sizeof(utmp)); + utmp.ut_tv.tv_sec = time(NULL); + strcpy(utmp.ut_user, "shutdown"); /* it is wide enough */ + utmp.ut_type = RUN_LVL; + utmp.ut_id[0] = '~'; utmp.ut_id[1] = '~'; /* = strcpy(utmp.ut_id, "~~"); */ + utmp.ut_line[0] = '~'; utmp.ut_line[1] = '~'; /* = strcpy(utmp.ut_line, "~~"); */ + uname(&uts); + safe_strncpy(utmp.ut_host, uts.release, sizeof(utmp.ut_host)); + updwtmpx(bb_path_wtmp_file, &utmp); +} +#else +#define write_wtmp() ((void)0) +#endif + +#if ENABLE_FEATURE_WAIT_FOR_INIT +/* In Linux, "poweroff" may be spawned even before init. + * For example, with ACPI: + * linux/drivers/acpi/bus.c: + * static void sb_notify_work(struct work_struct *dummy) + * orderly_poweroff(true); + * linux/kernel/reboot.c: + * static int run_cmd(const char *cmd) + * ret = call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC); + * poweroff_cmd[] = "/sbin/poweroff"; + * static int __orderly_poweroff(bool force) + * ret = run_cmd(poweroff_cmd); + * + * We want to make sure init exists and listens to signals. + */ +static int init_was_not_there(void) +{ + enum { initial = 5 }; /* 5 seconds should be plenty for timeout */ + int cnt = initial - 1; + + /* Just existence of PID 1 does not mean it installed + * the handlers already. + */ +#if 0 + while (kill(1, 0) != 0 && --cnt >= 0) + sleep(1); +#endif + /* ... so let's wait for some evidence a usual startup event, + * mounting of /proc, happened. By that time init should be ready + * for signals. + */ + while (access("/proc/meminfo", F_OK) != 0 && --cnt >= 0) + sleep(1); + + /* Does it look like init wasn't there? */ + return (cnt != initial - 1); +} +#else + /* Assume it's always there */ +# define init_was_not_there() 0 +#endif + +int halt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int halt_main(int argc UNUSED_PARAM, char **argv) +{ + static const int magic[] = { + RB_HALT_SYSTEM, + RB_POWER_OFF, + RB_AUTOBOOT + }; + static const smallint signals[] = { SIGUSR1, SIGUSR2, SIGTERM }; + + int delay = 0; + int which, flags, rc; + + /* Figure out which applet we're running */ + if (ENABLE_HALT && !ENABLE_POWEROFF && !ENABLE_REBOOT) + which = 0; + else + if (!ENABLE_HALT && ENABLE_POWEROFF && !ENABLE_REBOOT) + which = 1; + else + if (!ENABLE_HALT && !ENABLE_POWEROFF && ENABLE_REBOOT) + which = 2; + else + for (which = 0; "hpr"[which] != applet_name[0]; which++) + continue; + + /* Parse and handle arguments */ + /* We support -w even if !ENABLE_FEATURE_WTMP, + * in order to not break scripts. + * -i (shut down network interfaces) is ignored. + */ + flags = getopt32(argv, "d:+nfwi", &delay); + + sleep(delay); + + write_wtmp(); + + if (flags & 8) /* -w */ + return EXIT_SUCCESS; + + if (!(flags & 2)) /* no -n */ + sync(); + + /* Perform action. */ + rc = 1; + if (!(flags & 4)) { /* no -f */ +//TODO: I tend to think that signalling linuxrc is wrong +// pity original author didn't comment on it... + if (ENABLE_LINUXRC) { + /* talk to linuxrc */ + /* bbox init/linuxrc assumed */ + pid_t *pidlist = find_pid_by_name("linuxrc"); + if (pidlist[0] > 0) + rc = kill(pidlist[0], signals[which]); + if (ENABLE_FEATURE_CLEAN_UP) + free(pidlist); + } + if (rc) { + /* talk to init */ + if (!ENABLE_FEATURE_CALL_TELINIT) { + /* bbox init assumed */ + rc = kill(1, signals[which]); + if (init_was_not_there()) + rc = kill(1, signals[which]); + } else { + /* SysV style init assumed */ + /* runlevels: + * 0 == shutdown + * 6 == reboot */ + execlp(CONFIG_TELINIT_PATH, + CONFIG_TELINIT_PATH, + which == 2 ? "6" : "0", + (char *)NULL + ); + bb_perror_msg_and_die("can't execute '%s'", + CONFIG_TELINIT_PATH); + } + } + } else { + rc = reboot(magic[which]); + } + + if (rc) + bb_perror_nomsg_and_die(); + return rc; +} diff --git a/pool/shard003/C/0065350_fexecve.c b/pool/shard003/C/0065350_fexecve.c new file mode 100644 index 0000000000000000000000000000000000000000..40d2b5b46de0cc001165c7aa22ba13e57751df15 --- /dev/null +++ b/pool/shard003/C/0065350_fexecve.c @@ -0,0 +1,56 @@ +/* liblxcapi + * + * Copyright © 2019 Christian Brauner . + * Copyright © 2019 Canonical Ltd. + * + * 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 + */ + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE 1 +#endif + +#include +#include +#include + +#include +#include "config.h" +#include "macro.h" +#include "process_utils.h" + +int fexecve(int fd, char *const argv[], char *const envp[]) +{ + char procfd[LXC_PROC_PID_FD_LEN]; + int ret; + + if (fd < 0 || !argv || !envp) { + errno = EINVAL; + return -1; + } + + execveat(fd, "", argv, envp, AT_EMPTY_PATH); + if (errno != ENOSYS) + return -1; + + ret = snprintf(procfd, sizeof(procfd), "/proc/self/fd/%d", fd); + if (ret < 0 || (size_t)ret >= sizeof(procfd)) { + errno = ENAMETOOLONG; + return -1; + } + + execve(procfd, argv, envp); + return -1; +} diff --git a/pool/shard003/C/0065367_sse2-psllw-2.c b/pool/shard003/C/0065367_sse2-psllw-2.c new file mode 100644 index 0000000000000000000000000000000000000000..e3170405e637d0a9989390b14f34c8554320916c --- /dev/null +++ b/pool/shard003/C/0065367_sse2-psllw-2.c @@ -0,0 +1,43 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -msse2" } */ +/* { dg-require-effective-target sse2 } */ + +#ifndef CHECK_H +#define CHECK_H "sse2-check.h" +#endif + +#ifndef TEST +#define TEST sse2_test +#endif + +#include CHECK_H + +#include + +static __m128i +__attribute__((noinline, unused)) +test (__m128i s1, __m128i c) +{ + return _mm_sll_epi16 (s1, c); +} + +static void +TEST (void) +{ + union128i_w u, s; + union128i_q c; + short e[8] = {0}; + int i; + + s.x = _mm_set_epi16 (1, 2, 3, 4, 5, 6, 0x7000, 0x9000); + c.x = _mm_set_epi64x (12, 13); + + u.x = test (s.x, c.x); + + if (c.a[0] < 16) + for (i = 0; i < 8; i++) + e[i] = s.a[i] << c.a[0]; + + if (check_union128i_w (u, e)) + abort (); +} diff --git a/pool/shard003/C/0065380_JES605.c b/pool/shard003/C/0065380_JES605.c new file mode 100644 index 0000000000000000000000000000000000000000..fd2a89097f15f42d7f7be8833b8cb5dbfc3c7b28 --- /dev/null +++ b/pool/shard003/C/0065380_JES605.c @@ -0,0 +1,39 @@ +/* Universidade Estadual do Ceara +Introducao a Computacao 2016.2 - Prof. Gildacio +Jessica Cristina Cacau Patricio (1388627) +Exercicio 605 */ + +#include +#include +#include + +void main () { + int i, A[500], inf, sup, meio, p; + + for (i=0; i<500; i++) + A[i] = i*3; + + printf("Digite um numero inteiro: "); + scanf("%d", &p); + + inf = 0; + sup = sizeof(A)/4 - 1; + + while (inf<=sup) { + meio = (inf+sup)/2; + + if (A[meio] == p) { + printf("Numero encontrado na posicao %d.\n", meio); + inf = sup+1; + } + else { + if (A[meio] < p) + inf = meio+1; + else + sup = meio-1; + + if (inf>sup) + printf("Numero nao existe no vetor. Deveria estar entre posicoes %d e %d.\n", sup, inf); + } + } +} diff --git a/pool/shard003/C/0065384_file.c b/pool/shard003/C/0065384_file.c new file mode 100644 index 0000000000000000000000000000000000000000..127263cc865715de2d3f42f6658320ac89a5106e --- /dev/null +++ b/pool/shard003/C/0065384_file.c @@ -0,0 +1,146 @@ +/* + * Copyright (C) International Business Machines Corp., 2000-2002 + * Portions Copyright (C) Christoph Hellwig, 2001-2002 + * + * 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 "jfs_incore.h" +#include "jfs_inode.h" +#include "jfs_dmap.h" +#include "jfs_txnmgr.h" +#include "jfs_xattr.h" +#include "jfs_acl.h" +#include "jfs_debug.h" + +int jfs_fsync(struct file *file, int datasync) +{ + struct inode *inode = file->f_mapping->host; + int rc = 0; + + if (!(inode->i_state & I_DIRTY) || + (datasync && !(inode->i_state & I_DIRTY_DATASYNC))) { + /* Make sure committed changes hit the disk */ + jfs_flush_journal(JFS_SBI(inode->i_sb)->log, 1); + return rc; + } + + rc |= jfs_commit_inode(inode, 1); + + return rc ? -EIO : 0; +} + +static int jfs_open(struct inode *inode, struct file *file) +{ + int rc; + + if ((rc = dquot_file_open(inode, file))) + return rc; + + /* + * We attempt to allow only one "active" file open per aggregate + * group. Otherwise, appending to files in parallel can cause + * fragmentation within the files. + * + * If the file is empty, it was probably just created and going + * to be written to. If it has a size, we'll hold off until the + * file is actually grown. + */ + if (S_ISREG(inode->i_mode) && file->f_mode & FMODE_WRITE && + (inode->i_size == 0)) { + struct jfs_inode_info *ji = JFS_IP(inode); + spin_lock_irq(&ji->ag_lock); + if (ji->active_ag == -1) { + ji->active_ag = ji->agno; + atomic_inc( + &JFS_SBI(inode->i_sb)->bmap->db_active[ji->agno]); + } + spin_unlock_irq(&ji->ag_lock); + } + + return 0; +} +static int jfs_release(struct inode *inode, struct file *file) +{ + struct jfs_inode_info *ji = JFS_IP(inode); + + spin_lock_irq(&ji->ag_lock); + if (ji->active_ag != -1) { + struct bmap *bmap = JFS_SBI(inode->i_sb)->bmap; + atomic_dec(&bmap->db_active[ji->active_ag]); + ji->active_ag = -1; + } + spin_unlock_irq(&ji->ag_lock); + + return 0; +} + +int jfs_setattr(struct dentry *dentry, struct iattr *iattr) +{ + struct inode *inode = dentry->d_inode; + int rc; + + rc = inode_change_ok(inode, iattr); + if (rc) + return rc; + + if (is_quota_modification(inode, iattr)) + dquot_initialize(inode); + if ((iattr->ia_valid & ATTR_UID && iattr->ia_uid != inode->i_uid) || + (iattr->ia_valid & ATTR_GID && iattr->ia_gid != inode->i_gid)) { + rc = dquot_transfer(inode, iattr); + if (rc) + return rc; + } + + rc = inode_setattr(inode, iattr); + + if (!rc && (iattr->ia_valid & ATTR_MODE)) + rc = jfs_acl_chmod(inode); + + return rc; +} + +const struct inode_operations jfs_file_inode_operations = { + .truncate = jfs_truncate, + .setxattr = jfs_setxattr, + .getxattr = jfs_getxattr, + .listxattr = jfs_listxattr, + .removexattr = jfs_removexattr, + .setattr = jfs_setattr, +#ifdef CONFIG_JFS_POSIX_ACL + .check_acl = jfs_check_acl, +#endif +}; + +const struct file_operations jfs_file_operations = { + .open = jfs_open, + .llseek = generic_file_llseek, + .write = do_sync_write, + .read = do_sync_read, + .aio_read = generic_file_aio_read, + .aio_write = generic_file_aio_write, + .mmap = generic_file_mmap, + .splice_read = generic_file_splice_read, + .splice_write = generic_file_splice_write, + .fsync = jfs_fsync, + .release = jfs_release, + .unlocked_ioctl = jfs_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = jfs_compat_ioctl, +#endif +}; diff --git a/pool/shard003/C/0065388_mpls_iptunnel.c b/pool/shard003/C/0065388_mpls_iptunnel.c new file mode 100644 index 0000000000000000000000000000000000000000..67591aef9cae6fb203ef802272baad6e5b191000 --- /dev/null +++ b/pool/shard003/C/0065388_mpls_iptunnel.c @@ -0,0 +1,231 @@ +/* + * mpls tunnels An implementation mpls tunnels using the light weight tunnel + * infrastructure + * + * Authors: Roopa Prabhu, + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "internal.h" + +static const struct nla_policy mpls_iptunnel_policy[MPLS_IPTUNNEL_MAX + 1] = { + [MPLS_IPTUNNEL_DST] = { .type = NLA_U32 }, +}; + +static unsigned int mpls_encap_size(struct mpls_iptunnel_encap *en) +{ + /* The size of the layer 2.5 labels to be added for this route */ + return en->labels * sizeof(struct mpls_shim_hdr); +} + +int mpls_output(struct net *net, struct sock *sk, struct sk_buff *skb) +{ + struct mpls_iptunnel_encap *tun_encap_info; + struct mpls_shim_hdr *hdr; + struct net_device *out_dev; + unsigned int hh_len; + unsigned int new_header_size; + unsigned int mtu; + struct dst_entry *dst = skb_dst(skb); + struct rtable *rt = NULL; + struct rt6_info *rt6 = NULL; + int err = 0; + bool bos; + int i; + unsigned int ttl; + + /* Obtain the ttl */ + if (skb->protocol == htons(ETH_P_IP)) { + ttl = ip_hdr(skb)->ttl; + rt = (struct rtable *)dst; + } else if (skb->protocol == htons(ETH_P_IPV6)) { + ttl = ipv6_hdr(skb)->hop_limit; + rt6 = (struct rt6_info *)dst; + } else { + goto drop; + } + + skb_orphan(skb); + + /* Find the output device */ + out_dev = dst->dev; + if (!mpls_output_possible(out_dev) || + !dst->lwtstate || skb_warn_if_lro(skb)) + goto drop; + + skb_forward_csum(skb); + + tun_encap_info = mpls_lwtunnel_encap(dst->lwtstate); + + /* Verify the destination can hold the packet */ + new_header_size = mpls_encap_size(tun_encap_info); + mtu = mpls_dev_mtu(out_dev); + if (mpls_pkt_too_big(skb, mtu - new_header_size)) + goto drop; + + hh_len = LL_RESERVED_SPACE(out_dev); + if (!out_dev->header_ops) + hh_len = 0; + + /* Ensure there is enough space for the headers in the skb */ + if (skb_cow(skb, hh_len + new_header_size)) + goto drop; + + skb_push(skb, new_header_size); + skb_reset_network_header(skb); + + skb->dev = out_dev; + skb->protocol = htons(ETH_P_MPLS_UC); + + /* Push the new labels */ + hdr = mpls_hdr(skb); + bos = true; + for (i = tun_encap_info->labels - 1; i >= 0; i--) { + hdr[i] = mpls_entry_encode(tun_encap_info->label[i], + ttl, 0, bos); + bos = false; + } + + if (rt) + err = neigh_xmit(NEIGH_ARP_TABLE, out_dev, &rt->rt_gateway, + skb); + else if (rt6) + err = neigh_xmit(NEIGH_ND_TABLE, out_dev, &rt6->rt6i_gateway, + skb); + if (err) + net_dbg_ratelimited("%s: packet transmission failed: %d\n", + __func__, err); + + return 0; + +drop: + kfree_skb(skb); + return -EINVAL; +} + +static int mpls_build_state(struct net_device *dev, struct nlattr *nla, + unsigned int family, const void *cfg, + struct lwtunnel_state **ts) +{ + struct mpls_iptunnel_encap *tun_encap_info; + struct nlattr *tb[MPLS_IPTUNNEL_MAX + 1]; + struct lwtunnel_state *newts; + int tun_encap_info_len; + int ret; + + ret = nla_parse_nested(tb, MPLS_IPTUNNEL_MAX, nla, + mpls_iptunnel_policy); + if (ret < 0) + return ret; + + if (!tb[MPLS_IPTUNNEL_DST]) + return -EINVAL; + + tun_encap_info_len = sizeof(*tun_encap_info); + + newts = lwtunnel_state_alloc(tun_encap_info_len); + if (!newts) + return -ENOMEM; + + newts->len = tun_encap_info_len; + tun_encap_info = mpls_lwtunnel_encap(newts); + ret = nla_get_labels(tb[MPLS_IPTUNNEL_DST], MAX_NEW_LABELS, + &tun_encap_info->labels, tun_encap_info->label); + if (ret) + goto errout; + newts->type = LWTUNNEL_ENCAP_MPLS; + newts->flags |= LWTUNNEL_STATE_OUTPUT_REDIRECT; + + *ts = newts; + + return 0; + +errout: + kfree(newts); + *ts = NULL; + + return ret; +} + +static int mpls_fill_encap_info(struct sk_buff *skb, + struct lwtunnel_state *lwtstate) +{ + struct mpls_iptunnel_encap *tun_encap_info; + + tun_encap_info = mpls_lwtunnel_encap(lwtstate); + + if (nla_put_labels(skb, MPLS_IPTUNNEL_DST, tun_encap_info->labels, + tun_encap_info->label)) + goto nla_put_failure; + + return 0; + +nla_put_failure: + return -EMSGSIZE; +} + +static int mpls_encap_nlsize(struct lwtunnel_state *lwtstate) +{ + struct mpls_iptunnel_encap *tun_encap_info; + + tun_encap_info = mpls_lwtunnel_encap(lwtstate); + + return nla_total_size(tun_encap_info->labels * 4); +} + +static int mpls_encap_cmp(struct lwtunnel_state *a, struct lwtunnel_state *b) +{ + struct mpls_iptunnel_encap *a_hdr = mpls_lwtunnel_encap(a); + struct mpls_iptunnel_encap *b_hdr = mpls_lwtunnel_encap(b); + int l; + + if (a_hdr->labels != b_hdr->labels) + return 1; + + for (l = 0; l < MAX_NEW_LABELS; l++) + if (a_hdr->label[l] != b_hdr->label[l]) + return 1; + return 0; +} + +static const struct lwtunnel_encap_ops mpls_iptun_ops = { + .build_state = mpls_build_state, + .output = mpls_output, + .fill_encap = mpls_fill_encap_info, + .get_encap_size = mpls_encap_nlsize, + .cmp_encap = mpls_encap_cmp, +}; + +static int __init mpls_iptunnel_init(void) +{ + return lwtunnel_encap_add_ops(&mpls_iptun_ops, LWTUNNEL_ENCAP_MPLS); +} +module_init(mpls_iptunnel_init); + +static void __exit mpls_iptunnel_exit(void) +{ + lwtunnel_encap_del_ops(&mpls_iptun_ops, LWTUNNEL_ENCAP_MPLS); +} +module_exit(mpls_iptunnel_exit); + +MODULE_DESCRIPTION("MultiProtocol Label Switching IP Tunnels"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard003/C/0065397_atividade14e4.c b/pool/shard003/C/0065397_atividade14e4.c new file mode 100644 index 0000000000000000000000000000000000000000..23e8cc3b625c3d4efd3cb4f90de3b326b4ee3e83 --- /dev/null +++ b/pool/shard003/C/0065397_atividade14e4.c @@ -0,0 +1,42 @@ +#include +#include +#include + +double f(double y) +{ + return 1.0-0.4*y; +} + +int main() +{ + int j; + double h, x0, y, xf; + + //Valor do passo de integração (DELTAx) + printf("Escolha o passo de integração: "); + scanf("%lf" ,&h); + + /*Condições iniciais das variáveis dependente y(x) e independente x*/ + + printf("\nInforme o valor inicial x0: "); + scanf("%lf" ,&x0); + + printf("\nInforme o valor inicial y(x0):"); + scanf("%lf" ,&y); + + /*printf("\nInforme o valor final de x: x(xf):\n"); + scanf("%lf" ,&xf);*/ + + //Etapa de integração, método de Euler + printf(" X Y \n"); + + j=0; + while (x0<=40.0) + { + j++; + x0=x0+h; //Atualiza x em 1 passo + y=y+h*f(y); //Calcula aproximação de y(x) + printf("%d %lf %lf \n",j,x0,y);//Imprime x e y na tela + } + +} diff --git a/pool/shard003/C/0065409_omp_for_bigbounds.c b/pool/shard003/C/0065409_omp_for_bigbounds.c new file mode 100644 index 0000000000000000000000000000000000000000..901d760832776f8ed67c15ef480244b18769fea6 --- /dev/null +++ b/pool/shard003/C/0065409_omp_for_bigbounds.c @@ -0,0 +1,70 @@ +// RUN: %libomp-compile -DMY_SCHEDULE=static && %libomp-run +// RUN: %libomp-compile -DMY_SCHEDULE=dynamic && %libomp-run +// RUN: %libomp-compile -DMY_SCHEDULE=guided && %libomp-run + +// Only works with Intel Compiler since at least version 15.0 +// XFAIL: gcc, clang + +/* + * Test that large bounds are handled properly and calculations of + * loop iterations don't accidently overflow + */ +#include +#include +#include +#include +#include "omp_testsuite.h" + +#define INCR 50000000 +#define MY_MAX 2000000000 +#define MY_MIN -2000000000 +#ifndef MY_SCHEDULE +# define MY_SCHEDULE static +#endif + +int a, b, a_known_value, b_known_value; + +int test_omp_for_bigbounds() +{ + a = 0; + b = 0; + #pragma omp parallel + { + int i; + #pragma omp for schedule(MY_SCHEDULE) + for (i = INT_MIN; i < MY_MAX; i+=INCR) { + #pragma omp atomic + a++; + } + #pragma omp for schedule(MY_SCHEDULE) + for (i = INT_MAX; i >= MY_MIN; i-=INCR) { + #pragma omp atomic + b++; + } + } + printf("a = %d (should be %d), b = %d (should be %d)\n", a, a_known_value, b, b_known_value); + return (a == a_known_value && b == b_known_value); +} + +int main() +{ + int i; + int num_failed=0; + + a_known_value = 0; + for (i = INT_MIN; i < MY_MAX; i+=INCR) { + a_known_value++; + } + + b_known_value = 0; + for (i = INT_MAX; i >= MY_MIN; i-=INCR) { + b_known_value++; + } + + for(i = 0; i < REPETITIONS; i++) { + if(!test_omp_for_bigbounds()) { + num_failed++; + } + } + return num_failed; +} diff --git a/pool/shard003/C/0065420_cpuidle.c b/pool/shard003/C/0065420_cpuidle.c new file mode 100644 index 0000000000000000000000000000000000000000..08794f3b629753018f146c28dafbf249c0706574 --- /dev/null +++ b/pool/shard003/C/0065420_cpuidle.c @@ -0,0 +1,159 @@ +/* Copyright (c) 2010, Code Aurora Forum. 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 version 2 and + * only 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. + */ + +#include +#include +#include +#include +#include + +#include "cpuidle.h" +#include "pm.h" + +static DEFINE_PER_CPU_SHARED_ALIGNED(struct cpuidle_device, msm_cpuidle_devs); +static struct cpuidle_driver msm_cpuidle_driver = { + .name = "msm_idle", + .owner = THIS_MODULE, +}; + +#ifdef CONFIG_MSM_SLEEP_STATS +static DEFINE_PER_CPU(struct atomic_notifier_head, msm_cpuidle_notifiers); + +int msm_cpuidle_register_notifier(unsigned int cpu, struct notifier_block *nb) +{ + struct atomic_notifier_head *head = + &per_cpu(msm_cpuidle_notifiers, cpu); + + return atomic_notifier_chain_register(head, nb); +} +EXPORT_SYMBOL(msm_cpuidle_register_notifier); + +int msm_cpuidle_unregister_notifier(unsigned int cpu, struct notifier_block *nb) +{ + struct atomic_notifier_head *head = + &per_cpu(msm_cpuidle_notifiers, cpu); + + return atomic_notifier_chain_unregister(head, nb); +} +EXPORT_SYMBOL(msm_cpuidle_unregister_notifier); +#endif + +static int msm_cpuidle_enter( + struct cpuidle_device *dev, struct cpuidle_state *state) +{ + struct cpuidle_state_usage *usage; + int ret; +#ifdef CONFIG_MSM_SLEEP_STATS + struct atomic_notifier_head *head = + &__get_cpu_var(msm_cpuidle_notifiers); +#endif + + local_irq_disable(); + +#ifdef CONFIG_MSM_SLEEP_STATS + atomic_notifier_call_chain(head, MSM_CPUIDLE_STATE_ENTER, NULL); +#endif + +#ifdef CONFIG_CPU_PM + cpu_pm_enter(); +#endif + ret = msm_pm_idle_enter((enum msm_pm_sleep_mode) (usage->driver_data)); + +#ifdef CONFIG_CPU_PM + cpu_pm_exit(); +#endif + +#ifdef CONFIG_MSM_SLEEP_STATS + atomic_notifier_call_chain(head, MSM_CPUIDLE_STATE_EXIT, NULL); +#endif + + local_irq_enable(); + + return ret; +} + +void __init msm_cpuidle_set_states(struct msm_cpuidle_state *states, + int nr_states, struct msm_pm_platform_data *pm_data) +{ + unsigned int cpu; + for_each_possible_cpu(cpu) { + struct cpuidle_device *dev = &per_cpu(msm_cpuidle_devs, cpu); + int i; + + dev->cpu = cpu; + dev->prepare = msm_pm_idle_prepare; + + for (i = 0; i < nr_states; i++) { + struct msm_cpuidle_state *cstate = &states[i]; + struct cpuidle_state *state; + struct msm_pm_platform_data *pm_mode; + + if (cstate->cpu != cpu) + continue; + + state = &dev->states[cstate->state_nr]; + pm_mode = &pm_data[MSM_PM_MODE(cpu, cstate->mode_nr)]; + + snprintf(state->name, CPUIDLE_NAME_LEN, cstate->name); + snprintf(state->desc, CPUIDLE_DESC_LEN, cstate->desc); + state->driver_data = (void *) cstate->mode_nr; + state->flags = CPUIDLE_FLAG_TIME_VALID; + state->exit_latency = pm_mode->latency; + state->power_usage = 0; + state->target_residency = pm_mode->residency; + state->enter = msm_cpuidle_enter; + } + + for (i = 0; i < CPUIDLE_STATE_MAX; i++) { + if (dev->states[i].enter == NULL) + break; + dev->state_count = i + 1; + } + } +} + +int __init msm_cpuidle_init(void) +{ + unsigned int cpu; + int ret; + + ret = cpuidle_register_driver(&msm_cpuidle_driver); + if (ret) + pr_err("%s: failed to register cpuidle driver: %d\n", + __func__, ret); + + for_each_possible_cpu(cpu) { + struct cpuidle_device *dev = &per_cpu(msm_cpuidle_devs, cpu); + + ret = cpuidle_register_device(dev); + if (ret) { + pr_err("%s: failed to register cpuidle device for " + "cpu %u: %d\n", __func__, cpu, ret); + return ret; + } + } + + return 0; +} + +static int __init msm_cpuidle_early_init(void) +{ +#ifdef CONFIG_MSM_SLEEP_STATS + unsigned int cpu; + + for_each_possible_cpu(cpu) + ATOMIC_INIT_NOTIFIER_HEAD(&per_cpu(msm_cpuidle_notifiers, cpu)); +#endif + return 0; +} + +early_initcall(msm_cpuidle_early_init); diff --git a/pool/shard003/C/0065449_tst-mmap-fflushsync.c b/pool/shard003/C/0065449_tst-mmap-fflushsync.c new file mode 100644 index 0000000000000000000000000000000000000000..24ae33cae7f38645fa34b21a0435c0fde5b8b230 --- /dev/null +++ b/pool/shard003/C/0065449_tst-mmap-fflushsync.c @@ -0,0 +1,99 @@ +/* Test program for synchronization of stdio state with file after fflush. */ + +#include +#include +#include + +static void do_prepare (void); +#define PREPARE(argc, argv) do_prepare () +static int do_test (void); +#define TEST_FUNCTION do_test () +#include + +static char *temp_file; +static int temp_fd; + +static char text1[] = "Line the first\n"; +static char text2[] = "Line the second\n"; + +static void +do_prepare (void) +{ + temp_fd = create_temp_file ("tst-mmap-eofsync.", &temp_file); + if (temp_fd == -1) + error (1, errno, "cannot create temporary file"); + else + { + ssize_t cc = write (temp_fd, text1, sizeof text1 - 1); + if (cc != sizeof text1 - 1) + error (1, errno, "cannot write to temporary file"); + } +} + +static int +do_test (void) +{ + FILE *f; + char buf[128]; + int result = 0; + int c; + + f = fopen (temp_file, "rm"); + if (f == NULL) + { + perror (temp_file); + return 1; + } + + if (fgets (buf, sizeof buf, f) == NULL) + { + perror ("fgets"); + return 1; + } + + if (strcmp (buf, text1)) + { + printf ("read \"%s\", expected \"%s\"\n", buf, text1); + result = 1; + } + + printf ("feof = %d, ferror = %d immediately after fgets\n", + feof (f), ferror (f)); + + if (fflush (f) != 0) + { + printf ("fflush failed! %m\n"); + result = 1; + } + + c = write (temp_fd, text2, sizeof text2 - 1); + if (c == sizeof text2 - 1) + printf ("wrote more to file\n"); + else + { + printf ("wrote %d != %zd (%m)\n", c, sizeof text2 - 1); + result = 1; + } + + if (fgets (buf, sizeof buf, f) == NULL) + { + printf ("second fgets fails: feof = %d, ferror = %d (%m)\n", + feof (f), ferror (f)); + clearerr (f); + if (fgets (buf, sizeof buf, f) == NULL) + { + printf ("retry fgets fails: feof = %d, ferror = %d (%m)\n", + feof (f), ferror (f)); + result = 1; + } + } + if (result == 0 && strcmp (buf, text2)) + { + printf ("second time read \"%s\", expected \"%s\"\n", buf, text2); + result = 1; + } + + fclose (f); + + return result; +} diff --git a/pool/shard003/C/0065450_FieldType.c b/pool/shard003/C/0065450_FieldType.c new file mode 100644 index 0000000000000000000000000000000000000000..5faf1885a67f4bd5fab9e58220caa8bfd79c71a8 --- /dev/null +++ b/pool/shard003/C/0065450_FieldType.c @@ -0,0 +1,116 @@ +/* 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. + */ + +#define C_LUCY_FIELDTYPE +#include "Lucy/Util/ToolSet.h" + +#include "Lucy/Plan/FieldType.h" +#include "Lucy/Analysis/Analyzer.h" +#include "Lucy/Index/Posting.h" +#include "Lucy/Index/Similarity.h" + +FieldType* +FType_init(FieldType *self) { + return FType_init2(self, 1.0f, false, false, false); +} + +FieldType* +FType_init2(FieldType *self, float boost, bool indexed, bool stored, + bool sortable) { + FieldTypeIVARS *const ivars = FType_IVARS(self); + ivars->boost = boost; + ivars->indexed = indexed; + ivars->stored = stored; + ivars->sortable = sortable; + ABSTRACT_CLASS_CHECK(self, FIELDTYPE); + return self; +} + +void +FType_Set_Boost_IMP(FieldType *self, float boost) { + FType_IVARS(self)->boost = boost; +} + +void +FType_Set_Indexed_IMP(FieldType *self, bool indexed) { + FType_IVARS(self)->indexed = !!indexed; +} + +void +FType_Set_Stored_IMP(FieldType *self, bool stored) { + FType_IVARS(self)->stored = !!stored; +} + +void +FType_Set_Sortable_IMP(FieldType *self, bool sortable) { + FType_IVARS(self)->sortable = !!sortable; +} + +float +FType_Get_Boost_IMP(FieldType *self) { + return FType_IVARS(self)->boost; +} + +bool +FType_Indexed_IMP(FieldType *self) { + return FType_IVARS(self)->indexed; +} + +bool +FType_Stored_IMP(FieldType *self) { + return FType_IVARS(self)->stored; +} + +bool +FType_Sortable_IMP(FieldType *self) { + return FType_IVARS(self)->sortable; +} + +bool +FType_Binary_IMP(FieldType *self) { + UNUSED_VAR(self); + return false; +} + +Similarity* +FType_Similarity_IMP(FieldType *self) { + UNUSED_VAR(self); + return NULL; +} + +int32_t +FType_Compare_Values_IMP(FieldType *self, Obj *a, Obj *b) { + UNUSED_VAR(self); + return Obj_Compare_To(a, b); +} + +bool +FType_Equals_IMP(FieldType *self, Obj *other) { + if ((FieldType*)other == self) { return true; } + if (FType_get_class(self) != Obj_get_class(other)) { return false; } + FieldTypeIVARS *const ivars = FType_IVARS(self); + FieldTypeIVARS *const ovars = FType_IVARS((FieldType*)other); + if (ivars->boost != ovars->boost) { return false; } + if (!!ivars->indexed != !!ovars->indexed) { return false; } + if (!!ivars->stored != !!ovars->stored) { return false; } + if (!!ivars->sortable != !!ovars->sortable) { return false; } + if (!!FType_Binary(self) != !!FType_Binary((FieldType*)other)) { + return false; + } + return true; +} + + diff --git a/pool/shard003/C/0065454_win-settings.c b/pool/shard003/C/0065454_win-settings.c new file mode 100644 index 0000000000000000000000000000000000000000..6c51e78bc5dd2e36e50563fff453788751ffa1a0 --- /dev/null +++ b/pool/shard003/C/0065454_win-settings.c @@ -0,0 +1,38 @@ +#include +#include "win-settings.h" +#include "libs/pebble-assist.h" +#include "tinder.h" + +static void window_load(Window *window); +static void window_unload(Window *window); + +static Window* window = NULL; + +void win_settings_init(void) { + window = window_create(); + window_set_fullscreen(window, true); + window_set_background_color(window, GColorBlack); + window_set_window_handlers(window, (WindowHandlers) { + .load = window_load, + .unload = window_unload, + }); +} + +void win_settings_push(void) { + window_stack_push(window, true); +} + +void win_settings_deinit(void) { + window_destroy_safe(window); +} + +void win_settings_reload_data_and_mark_dirty(void) { +} + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // + +static void window_load(Window *window) { +} + +static void window_unload(Window *window) { +} diff --git a/pool/shard003/C/0065456_array_decl.c b/pool/shard003/C/0065456_array_decl.c new file mode 100644 index 0000000000000000000000000000000000000000..1e182060cf1880cca4f8c7e4b7016246b5ea1a41 --- /dev/null +++ b/pool/shard003/C/0065456_array_decl.c @@ -0,0 +1,17 @@ + +// this creates a new abstract memory location, just like malloc! +int* x[10]; +int* y[10][20]; + +int** z; + +void main_array_decl() { + x[0] = malloc(sizeof(int)); + *(x[0]) = 42; + + // I used to have a point_to/2 and array_point_to/2, but this can not + // work because of such code. Array and pointers are very equivalent + // and you can't use different predicates. + z = x; + *(z[0]) = 43; +} diff --git a/pool/shard003/C/0065463_axim_gpb.c b/pool/shard003/C/0065463_axim_gpb.c new file mode 100644 index 0000000000000000000000000000000000000000..a931ba0331a95323d6e22476fc862f25049f1bc8 --- /dev/null +++ b/pool/shard003/C/0065463_axim_gpb.c @@ -0,0 +1,174 @@ +/* + + Track reader for "Dell Axim Navigation System" GPB files, + + Copyright (C) 2006 Olaf Klein, o.b.klein@gpsbabel.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 USA + + */ + +#include "defs.h" +#include +#include +#include + +#define MYNAME "axim_gpb" + +#define RECORD_LEN 344 + +static gbfile *fin; + +static +arglist_t axim_gpb_args[] = { + ARG_TERMINATOR +}; + +static float +le_read32_float(const void *src) +{ + float f; + gbint32 i; + + i = le_read32(src); + memcpy(&f, &i, 4); + + return f; +} + +static void +decode_buff(const char *buff, route_head *track) +{ + struct tm tm; + double lat, lon, alt, dir; + float vdop, hdop, pdop, spd, Uf1; + int sats; + waypoint *wpt; + + wpt = waypt_new(); + + memset(&tm, '\0', sizeof(tm)); + + tm.tm_year = le_read16((void *) (buff + 16)); + tm.tm_mon = le_read16((void *) (buff + 18)); + tm.tm_mday = le_read16((void *) (buff + 22)); + tm.tm_hour = le_read16((void *) (buff + 24)); + tm.tm_min = le_read16((void *) (buff + 26)); + tm.tm_sec = le_read16((void *) (buff + 28)); + lat = le_read_double( (void *) (buff + 32)); + lon = le_read_double( (void *) (buff + 40)); + spd = le_read32_float((void *) (buff + 48)); + dir = le_read32_float((void *) (buff + 52)); + + alt = le_read32_float((void *) (buff + 64)); + Uf1 = le_read32_float((void *) (buff + 68)); + + hdop = le_read32_float((void *) (buff + 84)); + vdop = le_read32_float((void *) (buff + 88)); + pdop = le_read32_float((void *) (buff + 92)); + sats = le_read16((void *) (buff + 96)); + + wpt->latitude = lat; + wpt->longitude = lon; + wpt->altitude = alt; +#if 0 + /* These values can be, but must not be right. */ + /* Further checks are needed to verify that. */ + /* (!!! reference data !!!) */ + WAYPT_SET(wpt, course, dir); + wpt->hdop = hdop; + wpt->vdop = vdop; + wpt->pdop = pdop; + wpt->sat = sats; + WAYPT_SET(wpt, speed, spd * 10); +#endif + /* We don't have a header with some magic fixed numbers or strings. */ + /* So let us check the range for some basic values */ + + is_fatal( + (tm.tm_year < 2005) || + (tm.tm_mon < 1) || (tm.tm_mon > 12) || + (tm.tm_mday < 1) || (tm.tm_mday > 31) || + (tm.tm_hour > 23) || (tm.tm_min > 60) || (tm.tm_sec > 60), + MYNAME ": Invalid or unsupported file (invalid time-stamp)."); + is_fatal( + (fabs(wpt->latitude) > 90) || + (fabs(wpt->longitude) > 180), + MYNAME ": Invalid or unsupported file (lat or/and lon out of range)."); + + /* post work */ + + tm.tm_year-=1900; + tm.tm_mon--; + wpt->creation_time = mkgmtime(&tm); + + track_add_wpt(track, wpt); +} + +/******************************************************************************* +* %%% global callbacks called by gpsbabel main process %%% * +*******************************************************************************/ + +static void +axim_gpb_rd_init(const char *fname) +{ + fin = gbfopen(fname, "rb", MYNAME); +} + +static void +axim_gpb_rd_deinit(void) +{ + gbfclose(fin); +} + +static void +axim_gpb_read(void) +{ + char buff[RECORD_LEN]; + route_head *track = NULL; + size_t bytes; + + while ((bytes = gbfread(buff, 1, RECORD_LEN, fin))) + { + is_fatal((bytes != RECORD_LEN), MYNAME ": Invalid or unsupported file (filesize)."); + if (track == NULL) + { + track = route_head_alloc(); + track_add_head(track); + } + decode_buff(buff, track); + } +} + +/**************************************************************************/ + +ff_vecs_t axim_gpb_vecs = { + ff_type_file, + { + ff_cap_none /* waypoints */, + ff_cap_read /* tracks */, + ff_cap_none /* routes */, + }, + axim_gpb_rd_init, + NULL, + axim_gpb_rd_deinit, + NULL, + axim_gpb_read, + NULL, + NULL, + axim_gpb_args, + CET_CHARSET_ASCII, 0 +}; +/**************************************************************************/ diff --git a/pool/shard003/C/0065471_pshift.c b/pool/shard003/C/0065471_pshift.c new file mode 100644 index 0000000000000000000000000000000000000000..68bcb2678eddaaad97fc551bd9d533dcb5003969 --- /dev/null +++ b/pool/shard003/C/0065471_pshift.c @@ -0,0 +1,159 @@ +/* Common phase-shift computation. */ +/* + Copyright (C) 2004 University of Texas at Austin + + 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 "pshift.h" + +static bool depth; +static char rule; + +void pshift_init(bool depth1 /* depth (or time) */, + char rule1 /* interpolation rule */) +/*< Initialize >*/ +{ + depth = depth1; + rule = rule1; +} + +sf_complex pshift(sf_complex w2, float k2, float v1, float v2, float vz, float n) +/*< phase shift for different rules >*/ +{ + sf_complex cshift, cshift1, cshift2, y; + float x; + +#ifdef SF_HAS_COMPLEX_H + w2 *= w2; +#else + w2 = sf_cmul(w2,w2); +#endif + + switch (rule) { + case 'a': /* VTI anisotropy */ +#ifdef SF_HAS_COMPLEX_H + if (depth) { + w2 = w2 * vz * (1. + k2 / (w2 * v1 + 2.*n*k2)); + } else { + w2 = w2 * (1. + v1 * k2 / (w2 + 2.*n*k2 * v1)); + } +#else + if (depth) { + w2 = sf_cmul(sf_crmul(w2,vz), + sf_cadd(sf_cmplx(1.,0.), + sf_cdiv(sf_cmplx(k2,0.), + sf_cadd(sf_crmul(w2,v1), + sf_cmplx(2.*n*k2,0.))))); + } else { + w2 = sf_cmul(w2, + sf_cadd(sf_cmplx(1.,0.), + sf_cdiv(sf_cmplx(v1*k2,0.), + sf_cadd(w2, + sf_cmplx(2.*n*k2 * v1,0.))))); + } +#endif + cshift = csqrtf(w2); + break; + case 's': /* simple */ +#ifdef SF_HAS_COMPLEX_H + if (depth) { + w2 = w2 * v1 + k2; + } else { + w2 = w2 + v1 * k2; + } +#else + if (depth) { + w2.r = w2.r * v1 + k2; + w2.i = w2.i * v1; + } else { + w2.r += v1 * k2; + } +#endif + cshift = csqrtf(w2); + break; + case 'm': /* midpoint */ +#ifdef SF_HAS_COMPLEX_H + if (depth) { + w2 = 0.5 * w2 * (v1+v2) + k2; + } else { + w2 = w2 + 0.5 * (v1+v2) * k2; + } +#else + if (depth) { + w2.r = 0.5 * w2.r * (v1+v2) + k2; + w2.i = 0.5 * w2.i * (v1+v2); + } else { + w2.r += 0.5 * (v1+v2) * k2; + } +#endif + cshift = csqrtf(w2); + break; + case 'l': /* linear slowth */ + default: +#ifdef SF_HAS_COMPLEX_H + if (depth) { + cshift1 = csqrtf(w2 * v1 + k2); + cshift2 = csqrtf(w2 * v2 + k2); + + cshift = (cshift1 + cshift2 - + 1./(1./cshift1+1./cshift2))/1.5; + } else { + cshift1 = csqrtf(w2 + v1 * k2); + cshift2 = csqrtf(w2 + v2 * k2); + + x = 1./(1.+v2/v1); + cshift = cshift1 + x*(cshift2-cshift1); + y = x*cshift2/cshift; + cshift *= (1.-y*(1.-y))/(1.-x*(1.-x)); + } +#else + if (depth) { + cshift1 = csqrtf(sf_cadd(sf_crmul(w2,v1), + sf_cmplx(k2,0.))); + cshift2 = csqrtf(sf_cadd(sf_crmul(w2,v2), + sf_cmplx(k2,0.))); + + cshift = sf_crmul( + sf_csub(sf_cadd(cshift1,cshift2), + sf_cdiv(sf_cmplx(1.,0.), + sf_cadd(sf_cdiv(sf_cmplx(1.,0.), + cshift1), + sf_cdiv(sf_cmplx(1.,0.), + cshift2)))),1.5); + } else { + cshift1 = csqrtf(sf_cadd(w2,sf_cmplx(v1 * k2,0.))); + cshift2 = csqrtf(sf_cadd(w2,sf_cmplx(v2 * k2,0.))); + + x = 1./(1.+v2/v1); + cshift = sf_cadd(cshift1, + sf_crmul(sf_csub(cshift2,cshift1),x)); + y = sf_crmul(sf_cdiv(cshift2,cshift),x); + cshift = sf_cmul(cshift, + sf_crmul( + sf_csub( + sf_cmplx(1.,0.), + sf_cmul(y, + sf_csub(sf_cmplx(1.,0.),y))), + 1./(1.-x*(1.-x)))); + } +#endif + break; + } + return cshift; +} diff --git a/pool/shard003/C/0065477_process_helper.c b/pool/shard003/C/0065477_process_helper.c new file mode 100644 index 0000000000000000000000000000000000000000..81cfd0bafad039bacc2ba72c542b5395c28df3a4 --- /dev/null +++ b/pool/shard003/C/0065477_process_helper.c @@ -0,0 +1,198 @@ +/* + * process_helper.c + * + * Created on: 2014骞�7鏈�26鏃� + * Author: lbh + */ + +#include +#include "process_helper.h" + + +#ifdef __cplusplus +extern "C" { +#endif + +void InstallSignal() +{ + signal(SIGHUP ,SIG_IGN ); /* hangup, generated when terminal disconnects */ + signal(SIGINT ,SIG_IGN ); /* interrupt, generated from terminal special char */ + signal(SIGQUIT ,SIG_IGN ); /* (*) quit, generated from terminal special char */ + signal(SIGILL ,SIG_IGN ); /* (*) illegal instruction (not reset when caught)*/ + signal(SIGTRAP ,SIG_IGN ); /* (*) trace trap (not reset when caught) */ + signal(SIGABRT ,SIG_IGN ); /* (*) abort process */ +#ifdef D_AIX + signal(SIGEMT ,SIG_IGN ); /* EMT intruction */ +#endif + signal(SIGFPE ,SIG_IGN ); /* (*) floating point exception */ + signal(SIGKILL ,SIG_IGN ); /* kill (cannot be caught or ignored) */ + signal(SIGBUS ,SIG_IGN ); /* (*) bus error (specification exception) */ + signal(SIGSEGV ,SIG_IGN ); /* (*) segmentation violation */ + signal(SIGSYS ,SIG_IGN ); /* (*) bad argument to system call */ + signal(SIGPIPE ,SIG_IGN ); /* write on a pipe with no one to read it */ + signal(SIGALRM ,SIG_IGN ); /* alarm clock timeout */ + //signal(SIGTERM ,stopproc ); /* software termination signal */ + signal(SIGURG ,SIG_IGN ); /* (+) urgent contition on I/O channel */ + signal(SIGSTOP ,SIG_IGN ); /* (@) stop (cannot be caught or ignored) */ + signal(SIGTSTP ,SIG_IGN ); /* (@) interactive stop */ + signal(SIGCONT ,SIG_IGN ); /* (!) continue (cannot be caught or ignored) */ + //signal(SIGCHLD ,SIG_IGN); /* (+) sent to parent on child stop or exit */ + signal(SIGTTIN ,SIG_IGN); /* (@) background read attempted from control terminal*/ + signal(SIGTTOU ,SIG_IGN); /* (@) background write attempted to control terminal */ + signal(SIGIO ,SIG_IGN); /* (+) I/O possible, or completed */ + signal(SIGXCPU ,SIG_IGN); /* cpu time limit exceeded (see setrlimit()) */ + signal(SIGXFSZ ,SIG_IGN); /* file size limit exceeded (see setrlimit()) */ + +#ifdef D_AIX + signal(SIGMSG ,SIG_IGN); /* input data is in the ring buffer */ +#endif + + signal(SIGWINCH,SIG_IGN); /* (+) window size changed */ + signal(SIGPWR ,SIG_IGN); /* (+) power-fail restart */ + signal(SIGUSR1 ,SIG_IGN); /* user defined signal 1 */ + signal(SIGUSR2 ,SIG_IGN); /* user defined signal 2 */ + signal(SIGPROF ,SIG_IGN); /* profiling time alarm (see setitimer) */ + +#ifdef D_AIX + signal(SIGDANGER,SIG_IGN); /* system crash imminent; free up some page space */ +#endif + + signal(SIGVTALRM,SIG_IGN); /* virtual time alarm (see setitimer) */ + +#ifdef D_AIX + signal(SIGMIGRATE,SIG_IGN); /* migrate process */ + signal(SIGPRE ,SIG_IGN); /* programming exception */ + signal(SIGVIRT ,SIG_IGN); /* AIX virtual time alarm */ + signal(SIGALRM1,SIG_IGN); /* m:n condition variables - RESERVED - DON'T USE */ + signal(SIGWAITING,SIG_IGN); /* m:n scheduling - RESERVED - DON'T USE */ + signal(SIGCPUFAIL ,SIG_IGN); /* Predictive De-configuration of Processors - */ + signal(SIGKAP,SIG_IGN); /* keep alive poll from native keyboard */ + signal(SIGRETRACT,SIG_IGN); /* monitor mode should be relinguished */ + signal(SIGSOUND ,SIG_IGN); /* sound control has completed */ + signal(SIGSAK ,SIG_IGN); /* secure attention key */ +#endif +} + +void daemonize(const char* cmd) +{ +// int i, fd0, fd1, fd2; + pid_t pid; + struct rlimit rl; + struct sigaction sa; + + if (getrlimit(RLIMIT_NOFILE, &rl) < 0) + { +// m_pLog->WriteLog(ERROR, "%s: error %d can't get file limit: %s", cmd, +// errno, strerror_r(errno, m_szErrBuffer, loss::gc_uiMaxErrBufferLength)); + } + + // fork锛岀粓姝㈢埗杩涚▼ + if((pid = fork()) < 0) + { +// m_pLog->WriteLog(ERROR, "%s error %d can't fork: %s", cmd, +// errno, strerror_r(errno, m_szErrBuffer, loss::gc_uiMaxErrBufferLength)); + } + else if (pid != 0) + { + exit(0); + } + + // 璁剧疆绗竴瀛愯繘绋� + setsid(); + + sa.sa_handler = SIG_IGN; + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + if (sigaction(SIGHUP, &sa, NULL) < 0) + { +// m_pLog->WriteLog(ERROR, "%s error %d can't ignore SIGHUP: %s", cmd, +// errno, strerror_r(errno, m_szErrBuffer, loss::gc_uiMaxErrBufferLength)); + } + + // fork锛岀粓姝㈢涓�瀛愯繘绋� + if ((pid = fork()) < 0) + { +// m_pLog->WriteLog(ERROR, "%s error %d can't fork: %s", cmd, +// errno, strerror_r(errno, m_szErrBuffer, loss::gc_uiMaxErrBufferLength)); + } + else if (pid != 0) + { + exit(0); + } + + InstallSignal(); + +// // 灏嗗伐浣滅洰褰曡缃负鈥�/鈥� +// if (chdir("/") < 0) +// { +// m_pLog->WriteLog(ERROR, "%s error %d can't change directory to /: %s", +// errno, strerror_r(errno, m_szErrBuffer, loss::gc_uiMaxErrBufferLength)); +// } + + // 娓呴櫎鏂囦欢鎺╃爜 + umask(0); + +// // 鍏抽棴鎵�鏈夋枃浠跺彞鏌� +// for (i=0; i + +#include + +#include +#include +#include + +#include "internal.h" +#include "../internal.h" + + +#define BN_BLINDING_COUNTER 32 + +struct bn_blinding_st { + BIGNUM *A; /* The base blinding factor, Montgomery-encoded. */ + BIGNUM *Ai; /* The inverse of the blinding factor, Montgomery-encoded. */ + unsigned counter; +}; + +static int bn_blinding_create_param(BN_BLINDING *b, const BIGNUM *e, + const BN_MONT_CTX *mont, BN_CTX *ctx); + +BN_BLINDING *BN_BLINDING_new(void) { + BN_BLINDING *ret = OPENSSL_malloc(sizeof(BN_BLINDING)); + if (ret == NULL) { + OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE); + return NULL; + } + OPENSSL_memset(ret, 0, sizeof(BN_BLINDING)); + + ret->A = BN_new(); + if (ret->A == NULL) { + goto err; + } + + ret->Ai = BN_new(); + if (ret->Ai == NULL) { + goto err; + } + + /* The blinding values need to be created before this blinding can be used. */ + ret->counter = BN_BLINDING_COUNTER - 1; + + return ret; + +err: + BN_BLINDING_free(ret); + return NULL; +} + +void BN_BLINDING_free(BN_BLINDING *r) { + if (r == NULL) { + return; + } + + BN_free(r->A); + BN_free(r->Ai); + OPENSSL_free(r); +} + +static int bn_blinding_update(BN_BLINDING *b, const BIGNUM *e, + const BN_MONT_CTX *mont, BN_CTX *ctx) { + if (++b->counter == BN_BLINDING_COUNTER) { + /* re-create blinding parameters */ + if (!bn_blinding_create_param(b, e, mont, ctx)) { + goto err; + } + b->counter = 0; + } else { + if (!BN_mod_mul_montgomery(b->A, b->A, b->A, mont, ctx) || + !BN_mod_mul_montgomery(b->Ai, b->Ai, b->Ai, mont, ctx)) { + goto err; + } + } + + return 1; + +err: + /* |A| and |Ai| may be in an inconsistent state so they both need to be + * replaced the next time this blinding is used. Note that this is only + * sufficient because support for |BN_BLINDING_NO_UPDATE| and + * |BN_BLINDING_NO_RECREATE| was previously dropped. */ + b->counter = BN_BLINDING_COUNTER - 1; + + return 0; +} + +int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, const BIGNUM *e, + const BN_MONT_CTX *mont, BN_CTX *ctx) { + /* |n| is not Montgomery-encoded and |b->A| is. |BN_mod_mul_montgomery| + * cancels one Montgomery factor, so the resulting value of |n| is unencoded. + */ + if (!bn_blinding_update(b, e, mont, ctx) || + !BN_mod_mul_montgomery(n, n, b->A, mont, ctx)) { + return 0; + } + + return 1; +} + +int BN_BLINDING_invert(BIGNUM *n, const BN_BLINDING *b, BN_MONT_CTX *mont, + BN_CTX *ctx) { + /* |n| is not Montgomery-encoded and |b->A| is. |BN_mod_mul_montgomery| + * cancels one Montgomery factor, so the resulting value of |n| is unencoded. + */ + return BN_mod_mul_montgomery(n, n, b->Ai, mont, ctx); +} + +static int bn_blinding_create_param(BN_BLINDING *b, const BIGNUM *e, + const BN_MONT_CTX *mont, BN_CTX *ctx) { + int retry_counter = 32; + + do { + if (!BN_rand_range_ex(b->A, 1, &mont->N)) { + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + } + + /* |BN_from_montgomery| + |BN_mod_inverse_blinded| is equivalent to, but + * more efficient than, |BN_mod_inverse_blinded| + |BN_to_montgomery|. */ + if (!BN_from_montgomery(b->Ai, b->A, mont, ctx)) { + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + } + + int no_inverse; + if (BN_mod_inverse_blinded(b->Ai, &no_inverse, b->Ai, mont, ctx)) { + break; + } + + if (!no_inverse) { + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + } + + /* For reasonably-sized RSA keys, it should almost never be the case that a + * random value doesn't have an inverse. */ + if (retry_counter-- == 0) { + OPENSSL_PUT_ERROR(RSA, RSA_R_TOO_MANY_ITERATIONS); + return 0; + } + ERR_clear_error(); + } while (1); + + if (!BN_mod_exp_mont(b->A, b->A, e, &mont->N, ctx, mont)) { + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + } + + if (!BN_to_montgomery(b->A, b->A, mont, ctx)) { + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + } + + return 1; +} diff --git a/pool/shard003/C/0065482_gss_krb5_seal.c b/pool/shard003/C/0065482_gss_krb5_seal.c new file mode 100644 index 0000000000000000000000000000000000000000..280d82d7c6dc19ca9249d093190140b07c463562 --- /dev/null +++ b/pool/shard003/C/0065482_gss_krb5_seal.c @@ -0,0 +1,214 @@ +/* + * linux/net/sunrpc/gss_krb5_seal.c + * + * Adapted from MIT Kerberos 5-1.2.1 lib/gssapi/krb5/k5seal.c + * + * Copyright (c) 2000 The Regents of the University of Michigan. + * All rights reserved. + * + * Andy Adamson + * J. Bruce Fields + */ + +/* + * Copyright 1993 by OpenVision Technologies, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appears in all copies and + * that both that copyright notice and this permission notice appear in + * supporting documentation, and that the name of OpenVision not be used + * in advertising or publicity pertaining to distribution of the software + * without specific, written prior permission. OpenVision makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * OPENVISION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL OPENVISION BE LIABLE FOR ANY SPECIAL, 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. + */ + +/* + * Copyright (C) 1998 by the FundsXpress, INC. + * + * All rights reserved. + * + * Export of this software from the United States of America may require + * a specific license from the United States Government. It is the + * responsibility of any person or organization contemplating export to + * obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of FundsXpress. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. FundsXpress makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +#include +#include +#include +#include +#include +#include + +#ifdef RPC_DEBUG +# define RPCDBG_FACILITY RPCDBG_AUTH +#endif + +#define CKSUM_SIZE 8 + +static inline int +gss_krb5_padding(int blocksize, int length) { + /* Most of the code is block-size independent but in practice we + * use only 8: */ + BUG_ON(blocksize != 8); + return 8 - (length & 7); +} + +/* checksum the plaintext data and the first 8 bytes of the krb5 token header, + * as specified by the rfc: */ +static u32 +compute_checksum(s32 checksum_type, char *header, char *body, int body_len, + struct xdr_netobj *md5cksum) { + char *data_ptr; + struct xdr_netobj plaind; + u32 code = GSS_S_FAILURE; + + if (!(data_ptr = kmalloc(8 + body_len, GFP_KERNEL))) + goto out; + memcpy(data_ptr, header, 8); + memcpy(data_ptr + 8, body, body_len); + plaind.len = 8 + body_len; + plaind.data = data_ptr; + code = krb5_make_checksum(checksum_type, &plaind, md5cksum); + kfree(data_ptr); + code = 0; + +out: + return code; +} + +u32 +krb5_make_token(struct krb5_ctx *ctx, int qop_req, + struct xdr_netobj * text, struct xdr_netobj * token, + int toktype) +{ + s32 checksum_type; + struct xdr_netobj md5cksum = {.len = 0, .data = NULL}; + int blocksize = 0, tmsglen; + unsigned char *ptr, *krb5_hdr, *msg_start; + s32 now; + + dprintk("RPC: gss_krb5_seal"); + + now = jiffies; + + if (qop_req != 0) + goto out_err; + + switch (ctx->signalg) { + case SGN_ALG_DES_MAC_MD5: + checksum_type = CKSUMTYPE_RSA_MD5; + break; + default: + dprintk("RPC: gss_krb5_seal: ctx->signalg %d not" + " supported\n", ctx->signalg); + goto out_err; + } + if (ctx->sealalg != SEAL_ALG_NONE && ctx->sealalg != SEAL_ALG_DES) { + dprintk("RPC: gss_krb5_seal: ctx->sealalg %d not supported\n", + ctx->sealalg); + goto out_err; + } + + if (toktype == KG_TOK_WRAP_MSG) { + blocksize = crypto_tfm_alg_blocksize(ctx->enc); + tmsglen = blocksize + text->len + + gss_krb5_padding(blocksize, blocksize + text->len); + } else { + tmsglen = 0; + } + + token->len = g_token_size(&ctx->mech_used, 22 + tmsglen); + if ((token->data = kmalloc(token->len, GFP_KERNEL)) == NULL) + goto out_err; + + ptr = token->data; + g_make_token_header(&ctx->mech_used, 22 + tmsglen, &ptr, toktype); + + /* ptr now at byte 2 of header described in rfc 1964, section 1.2.1: */ + krb5_hdr = ptr - 2; + msg_start = krb5_hdr + 24; + + *(u16 *)(krb5_hdr + 2) = htons(ctx->signalg); + memset(krb5_hdr + 4, 0xff, 4); + if (toktype == KG_TOK_WRAP_MSG) + *(u16 *)(krb5_hdr + 4) = htons(ctx->sealalg); + + if (toktype == KG_TOK_WRAP_MSG) { + unsigned char pad = gss_krb5_padding(blocksize, text->len); + + get_random_bytes(msg_start, blocksize); /* "confounder" */ + memcpy(msg_start + blocksize, text->data, text->len); + + memset(msg_start + blocksize + text->len, pad, pad); + + if (compute_checksum(checksum_type, krb5_hdr, msg_start, + tmsglen, &md5cksum)) + goto out_err; + + if (krb5_encrypt(ctx->enc, NULL, msg_start, msg_start, + tmsglen)) + goto out_err; + + } else { /* Sign only. */ + if (compute_checksum(checksum_type, krb5_hdr, text->data, + text->len, &md5cksum)) + goto out_err; + } + + switch (ctx->signalg) { + case SGN_ALG_DES_MAC_MD5: + if (krb5_encrypt(ctx->seq, NULL, md5cksum.data, + md5cksum.data, md5cksum.len)) + goto out_err; + memcpy(krb5_hdr + 16, + md5cksum.data + md5cksum.len - CKSUM_SIZE, CKSUM_SIZE); + + dprintk("make_seal_token: cksum data: \n"); + print_hexl((u32 *) (krb5_hdr + 16), CKSUM_SIZE, 0); + break; + default: + BUG(); + } + + kfree(md5cksum.data); + + if ((krb5_make_seq_num(ctx->seq, ctx->initiate ? 0 : 0xff, + ctx->seq_send, krb5_hdr + 16, krb5_hdr + 8))) + goto out_err; + + ctx->seq_send++; + + return ((ctx->endtime < now) ? GSS_S_CONTEXT_EXPIRED : GSS_S_COMPLETE); +out_err: + if (md5cksum.data) kfree(md5cksum.data); + if (token->data) kfree(token->data); + token->data = 0; + token->len = 0; + return GSS_S_FAILURE; +} diff --git a/pool/shard003/C/0065483_2.c b/pool/shard003/C/0065483_2.c new file mode 100644 index 0000000000000000000000000000000000000000..99ef976eb6798aac2f28f7d650a06cd424e99cbe --- /dev/null +++ b/pool/shard003/C/0065483_2.c @@ -0,0 +1,51 @@ +// +// Created by zhangrongxiang on 2017/10/26 15:19 +// File 2 +// + +#include +#include +#include +#include + +int main() { + + sqlite3 *db; + char *zErrMsg = 0; + int rc; + /* 数据库创建或打开 */ + rc = sqlite3_open("test.db", &db); + if (rc) { + fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); + exit(0); + } else { + fprintf(stderr, "Opened database successfully\n"); + } + + char sql5[256]; + char *tname = "ttt"; + sprintf(sql5, "create table if not exists %s ("\ + "id int not null," \ + "name text not null);", tname); + printf("%s\n", sql5); + + /* 创建表 */ + rc = sqlite3_exec(db, sql5, NULL, NULL, &zErrMsg); + if (rc != SQLITE_OK) { + fprintf(stderr, "SQL error: %s\n", zErrMsg); + sqlite3_free(zErrMsg); + } else { + fprintf(stdout, "Table created successfully\n"); + } + + char *sql = "insert into ttt (id, name) values(22,'fuck')"; + rc = sqlite3_exec(db, sql, NULL, NULL, &zErrMsg); + if (rc != SQLITE_OK) { + fprintf(stderr, "SQL error: %s\n", zErrMsg); + sqlite3_free(zErrMsg); + } else { + fprintf(stdout, "Table insert data successfully\n"); + } + sqlite3_close(db); + +} \ No newline at end of file diff --git a/pool/shard003/C/0065491_statusbar.c b/pool/shard003/C/0065491_statusbar.c new file mode 100644 index 0000000000000000000000000000000000000000..07cdad28196b99ea646590ed9d0d28b7f38e5aca --- /dev/null +++ b/pool/shard003/C/0065491_statusbar.c @@ -0,0 +1,130 @@ +/* -*- mode: C -*- */ +/* + IGraph library. + Copyright (C) 2010-2012 Gabor Csardi + 334 Harvard street, Cambridge, MA 02139 USA + + 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 "igraph_statusbar.h" +#include "igraph_error.h" + +#include "config.h" + +#include +#include + +static IGRAPH_THREAD_LOCAL igraph_status_handler_t *igraph_i_status_handler = 0; + +/** + * \function igraph_status + * Report status from an igraph function. + * + * It calls the installed status handler function, if there is + * one. Otherwise it does nothing. Note that the standard way to + * report the status from an igraph function is the + * \ref IGRAPH_STATUS or \ref IGRAPH_STATUSF macro, as these + * take care of the termination of the calling function if the + * status handler returns with \c IGRAPH_INTERRUPTED. + * \param message The status message. + * \param data Additional context, with user-defined semantics. + * Existing igraph functions pass a null pointer here. + * \return Error code. If a status handler function was called + * and it did not return with \c IGRAPH_SUCCESS, then + * \c IGRAPH_INTERRUPTED is returned by \c igraph_status(). + * + * Time complexity: O(1). + */ + +int igraph_status(const char *message, void *data) { + if (igraph_i_status_handler) { + if (igraph_i_status_handler(message, data) != IGRAPH_SUCCESS) { + return IGRAPH_INTERRUPTED; + } + } + return IGRAPH_SUCCESS; +} + +/** + * \function igraph_statusf + * Report status, more flexible printf-like version. + * + * This is the more flexible version of \ref igraph_status(), + * that has a syntax similar to the \c printf standard C library function. + * It substitutes the values of the additional arguments into the + * \p message template string and calls \ref igraph_status(). + * \param message Status message template string, the syntax is the same + * as for the \c printf function. + * \param data Additional context, with user-defined semantics. + * Existing igraph functions pass a null pointer here. + * \param ... The additional arguments to fill the template given in the + * \p message argument. + * \return Error code. If a status handler function was called + * and it did not return with \c IGRAPH_SUCCESS, then + * \c IGRAPH_INTERRUPTED is returned by \c igraph_status(). + */ + +int igraph_statusf(const char *message, void *data, ...) { + char buffer[300]; + va_list ap; + va_start(ap, data); + vsnprintf(buffer, sizeof(buffer) - 1, message, ap); + return igraph_status(buffer, data); +} + +#ifndef USING_R + +/** + * \function igraph_status_handler_stderr + * A simple predefined status handler function. + * + * A simple status handler function, that writes the status + * message to the standard errror. + * \param message The status message. + * \param data Additional context, with user-defined semantics. + * Existing igraph functions pass a null pointer here. + * \return Error code. + * + * Time complexity: O(1). + */ + +int igraph_status_handler_stderr(const char *message, void *data) { + IGRAPH_UNUSED(data); + fputs(message, stderr); + return 0; +} +#endif + +/** + * \function igraph_set_status_handler + * Install of uninstall a status handler function. + * + * To uninstall the currently installed status handler, call + * this function with a null pointer. + * \param new_handler The status handler function to install. + * \return The previously installed status handler function. + * + * Time complexity: O(1). + */ + +igraph_status_handler_t * +igraph_set_status_handler(igraph_status_handler_t new_handler) { + igraph_status_handler_t *previous_handler = igraph_i_status_handler; + igraph_i_status_handler = new_handler; + return previous_handler; +} diff --git a/pool/shard003/C/0065492_file.c b/pool/shard003/C/0065492_file.c new file mode 100644 index 0000000000000000000000000000000000000000..7c7a1b39d56c9071cd28370f92b1945e659aa702 --- /dev/null +++ b/pool/shard003/C/0065492_file.c @@ -0,0 +1,254 @@ +/* + * file.c + * + * PURPOSE + * File handling routines for the OSTA-UDF(tm) filesystem. + * + * COPYRIGHT + * This file is distributed under the terms of the GNU General Public + * License (GPL). Copies of the GPL can be obtained from: + * ftp://prep.ai.mit.edu/pub/gnu/GPL + * Each contributing author retains all rights to their own work. + * + * (C) 1998-1999 Dave Boynton + * (C) 1998-2004 Ben Fennema + * (C) 1999-2000 Stelias Computing Inc + * + * HISTORY + * + * 10/02/98 dgb Attempt to integrate into udf.o + * 10/07/98 Switched to using generic_readpage, etc., like isofs + * And it works! + * 12/06/98 blf Added udf_file_read. uses generic_file_read for all cases but + * ICBTAG_FLAG_AD_IN_ICB. + * 04/06/99 64 bit file handling on 32 bit systems taken from ext2 file.c + * 05/12/99 Preliminary file write support + */ + +#include "udfdecl.h" +#include +#include +#include +#include +#include /* memset */ +#include +#include +#include +#include +#include +#include + +#include "udf_i.h" +#include "udf_sb.h" + +static int udf_adinicb_readpage(struct file *file, struct page *page) +{ + struct inode *inode = page->mapping->host; + char *kaddr; + + BUG_ON(!PageLocked(page)); + + kaddr = kmap(page); + memset(kaddr, 0, PAGE_CACHE_SIZE); + memcpy(kaddr, UDF_I_DATA(inode) + UDF_I_LENEATTR(inode), inode->i_size); + flush_dcache_page(page); + SetPageUptodate(page); + kunmap(page); + unlock_page(page); + + return 0; +} + +static int udf_adinicb_writepage(struct page *page, struct writeback_control *wbc) +{ + struct inode *inode = page->mapping->host; + char *kaddr; + + BUG_ON(!PageLocked(page)); + + kaddr = kmap(page); + memcpy(UDF_I_DATA(inode) + UDF_I_LENEATTR(inode), kaddr, inode->i_size); + mark_inode_dirty(inode); + SetPageUptodate(page); + kunmap(page); + unlock_page(page); + + return 0; +} + +static int udf_adinicb_write_end(struct file *file, + struct address_space *mapping, + loff_t pos, unsigned len, unsigned copied, + struct page *page, void *fsdata) +{ + struct inode *inode = mapping->host; + unsigned offset = pos & (PAGE_CACHE_SIZE - 1); + char *kaddr; + + kaddr = kmap_atomic(page, KM_USER0); + memcpy(UDF_I_DATA(inode) + UDF_I_LENEATTR(inode) + offset, + kaddr + offset, copied); + kunmap_atomic(kaddr, KM_USER0); + + return simple_write_end(file, mapping, pos, len, copied, page, fsdata); +} + +const struct address_space_operations udf_adinicb_aops = { + .readpage = udf_adinicb_readpage, + .writepage = udf_adinicb_writepage, + .sync_page = block_sync_page, + .write_begin = simple_write_begin, + .write_end = udf_adinicb_write_end, +}; + +static ssize_t udf_file_aio_write(struct kiocb *iocb, const struct iovec *iov, + unsigned long nr_segs, loff_t ppos) +{ + ssize_t retval; + struct file *file = iocb->ki_filp; + struct inode *inode = file->f_path.dentry->d_inode; + int err, pos; + size_t count = iocb->ki_left; + + if (UDF_I_ALLOCTYPE(inode) == ICBTAG_FLAG_AD_IN_ICB) { + if (file->f_flags & O_APPEND) + pos = inode->i_size; + else + pos = ppos; + + if (inode->i_sb->s_blocksize < (udf_file_entry_alloc_offset(inode) + + pos + count)) { + udf_expand_file_adinicb(inode, pos + count, &err); + if (UDF_I_ALLOCTYPE(inode) == ICBTAG_FLAG_AD_IN_ICB) { + udf_debug("udf_expand_adinicb: err=%d\n", err); + return err; + } + } else { + if (pos + count > inode->i_size) + UDF_I_LENALLOC(inode) = pos + count; + else + UDF_I_LENALLOC(inode) = inode->i_size; + } + } + + retval = generic_file_aio_write(iocb, iov, nr_segs, ppos); + if (retval > 0) + mark_inode_dirty(inode); + + return retval; +} + +/* + * udf_ioctl + * + * PURPOSE + * Issue an ioctl. + * + * DESCRIPTION + * Optional - sys_ioctl() will return -ENOTTY if this routine is not + * available, and the ioctl cannot be handled without filesystem help. + * + * sys_ioctl() handles these ioctls that apply only to regular files: + * FIBMAP [requires udf_block_map()], FIGETBSZ, FIONREAD + * These ioctls are also handled by sys_ioctl(): + * FIOCLEX, FIONCLEX, FIONBIO, FIOASYNC + * All other ioctls are passed to the filesystem. + * + * Refer to sys_ioctl() in fs/ioctl.c + * sys_ioctl() -> . + * + * PRE-CONDITIONS + * inode Pointer to inode that ioctl was issued on. + * filp Pointer to file that ioctl was issued on. + * cmd The ioctl command. + * arg The ioctl argument [can be interpreted as a + * user-space pointer if desired]. + * + * POST-CONDITIONS + * Success (>=0) or an error code (<=0) that + * sys_ioctl() will return. + * + * HISTORY + * July 1, 1997 - Andrew E. Mileski + * Written, tested, and released. + */ +int udf_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, + unsigned long arg) +{ + long old_block, new_block; + int result = -EINVAL; + + if (file_permission(filp, MAY_READ) != 0) { + udf_debug("no permission to access inode %lu\n", + inode->i_ino); + return -EPERM; + } + + if (!arg) { + udf_debug("invalid argument to udf_ioctl\n"); + return -EINVAL; + } + + switch (cmd) { + case UDF_GETVOLIDENT: + return copy_to_user((char __user *)arg, + UDF_SB_VOLIDENT(inode->i_sb), 32) ? -EFAULT : 0; + case UDF_RELOCATE_BLOCKS: + if (!capable(CAP_SYS_ADMIN)) + return -EACCES; + if (get_user(old_block, (long __user *)arg)) + return -EFAULT; + if ((result = udf_relocate_blocks(inode->i_sb, + old_block, &new_block)) == 0) + result = put_user(new_block, (long __user *)arg); + return result; + case UDF_GETEASIZE: + result = put_user(UDF_I_LENEATTR(inode), (int __user *)arg); + break; + case UDF_GETEABLOCK: + result = copy_to_user((char __user *)arg, UDF_I_DATA(inode), + UDF_I_LENEATTR(inode)) ? -EFAULT : 0; + break; + } + + return result; +} + +/* + * udf_release_file + * + * PURPOSE + * Called when all references to the file are closed + * + * DESCRIPTION + * Discard prealloced blocks + * + * HISTORY + * + */ +static int udf_release_file(struct inode *inode, struct file *filp) +{ + if (filp->f_mode & FMODE_WRITE) { + lock_kernel(); + udf_discard_prealloc(inode); + unlock_kernel(); + } + return 0; +} + +const struct file_operations udf_file_operations = { + .read = do_sync_read, + .aio_read = generic_file_aio_read, + .ioctl = udf_ioctl, + .open = generic_file_open, + .mmap = generic_file_mmap, + .write = do_sync_write, + .aio_write = udf_file_aio_write, + .release = udf_release_file, + .fsync = udf_fsync_file, + .splice_read = generic_file_splice_read, +}; + +const struct inode_operations udf_file_inode_operations = { + .truncate = udf_truncate, +}; diff --git a/pool/shard003/C/0065493_assocdlg.c b/pool/shard003/C/0065493_assocdlg.c new file mode 100644 index 0000000000000000000000000000000000000000..e65e643340d5e30c7c7d6a9b3a5cd8d31132dc24 --- /dev/null +++ b/pool/shard003/C/0065493_assocdlg.c @@ -0,0 +1,178 @@ +#include +#include +#include "assoc.h" +#include "wimgres.h" +#include "strconv.h" +#include "../imgtool.h" + +#define CONTROL_START 10000 + +struct assocdlg_info +{ + imgtool_library *library; + int extension_count; + const char *extensions[128]; +}; + +static const struct win_association_info assoc_info = +{ + TEXT("ImgtoolImage"), + 0, + TEXT("%1") +}; + + +static INT_PTR CALLBACK win_association_dialog_proc(HWND dialog, UINT message, + WPARAM wparam, LPARAM lparam) +{ + INT_PTR rc = 0; + struct assocdlg_info *dlginfo; + HWND ok_button, cancel_button, control; + LRESULT font; + LONG_PTR l; + RECT r1, r2; + int xmargin, ymargin, y, width, i; + int height = 20; + int id; + DWORD style; + TCHAR buf[32]; + BOOL is_set; + BOOL currently_set; + + switch(message) + { + case WM_INITDIALOG: + dlginfo = (struct assocdlg_info *) lparam; + ok_button = GetDlgItem(dialog, IDOK); + cancel_button = GetDlgItem(dialog, IDCANCEL); + font = SendMessage(ok_button, WM_GETFONT, 0, 0); + l = (LONG_PTR) dlginfo; + SetWindowLongPtr(dialog, GWLP_USERDATA, l); + + GetWindowRect(cancel_button, &r1); + GetWindowRect(dialog, &r2); + xmargin = r1.left - r2.left; + ymargin = y = r1.top - r2.top - 20; + width = r2.right - r2.left - xmargin * 2; + + for (i = 0; i < dlginfo->extension_count; i++) + { + style = WS_CHILD | WS_VISIBLE | BS_CHECKBOX | BS_AUTOCHECKBOX; + _sntprintf(buf, sizeof(buf) / sizeof(buf[0]), TEXT(".%s"), U2T(dlginfo->extensions[i])); + + control = CreateWindow(TEXT("BUTTON"), buf, style, + xmargin, y, width, height, dialog, NULL, NULL, NULL); + if (!control) + return -1; + + if (win_is_extension_associated(&assoc_info, buf)) + SendMessage(control, BM_SETCHECK, TRUE, 0); + SendMessage(control, WM_SETFONT, font, 0); + SetWindowLong(control, GWL_ID, CONTROL_START + i); + + y += height; + } + + r1.top += y; + r1.bottom += y; + SetWindowPos(cancel_button, NULL, r1.left - r2.left, r1.top - r2.top, + 0, 0, SWP_NOZORDER | SWP_NOSIZE); + GetWindowRect(ok_button, &r1); + r1.top += y; + r1.bottom += y; + SetWindowPos(ok_button, NULL, r1.left - r2.left, r1.top - r2.top, + 0, 0, SWP_NOZORDER | SWP_NOSIZE); + r2.bottom += y + r1.bottom - r1.top; + SetWindowPos(dialog, NULL, 0, 0, r2.right - r2.left, r2.bottom - r2.top, SWP_NOZORDER | SWP_NOMOVE); + break; + + case WM_COMMAND: + if (HIWORD(wparam) == BN_CLICKED) + { + l = GetWindowLongPtr(dialog, GWLP_USERDATA); + dlginfo = (struct assocdlg_info *) l; + id = LOWORD(wparam); + + if ((id == IDOK) || (id == IDCANCEL)) + { + if (id == IDOK) + { + for (i = 0; i < dlginfo->extension_count; i++) + { + is_set = SendMessage(GetDlgItem(dialog, CONTROL_START + i), BM_GETCHECK, 0, 0); + + _sntprintf(buf, sizeof(buf) / sizeof(buf[0]), TEXT(".%s"), U2T(dlginfo->extensions[i])); + currently_set = win_is_extension_associated(&assoc_info, buf); + + if (is_set && !currently_set) + win_associate_extension(&assoc_info, buf, TRUE); + else if (!is_set && currently_set) + win_associate_extension(&assoc_info, buf, FALSE); + } + } + + EndDialog(dialog, id); + } + } + break; + } + return rc; +} + + + +static int CLIB_DECL extension_compare(const void *p1, const void *p2) +{ + const char *e1 = *((const char **) p1); + const char *e2 = *((const char **) p2); + return strcmp(e1, e2); +} + + + +static void setup_extensions(struct assocdlg_info *dlginfo) +{ + const struct ImageModule *module = NULL; + const char *ext; + int i; + + dlginfo->extension_count = 0; + + while((module = imgtool_library_iterate(dlginfo->library, module)) != NULL) + { + ext = module->extensions; + while(ext[0]) + { + for (i = 0; i < dlginfo->extension_count; i++) + { + if (!strcmp(dlginfo->extensions[i], ext)) + break; + } + if (i >= dlginfo->extension_count) + { + assert(dlginfo->extension_count < sizeof(dlginfo->extensions) / sizeof(dlginfo->extensions[0])); + if (dlginfo->extension_count < sizeof(dlginfo->extensions) / sizeof(dlginfo->extensions[0])) + { + dlginfo->extensions[dlginfo->extension_count++] = ext; + } + } + ext = ext + strlen(ext) + 1; + } + } + + qsort((void *) dlginfo->extensions, dlginfo->extension_count, + sizeof(dlginfo->extensions[0]), extension_compare); +} + + + +void win_association_dialog(HWND parent, imgtool_library *library) +{ + struct assocdlg_info dlginfo; + + dlginfo.library = library; + setup_extensions(&dlginfo); + + DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ASSOCIATIONS), parent, + win_association_dialog_proc, (LPARAM) &dlginfo); +} diff --git a/pool/shard003/C/0065496_estaciones.c b/pool/shard003/C/0065496_estaciones.c new file mode 100644 index 0000000000000000000000000000000000000000..6cced1e6c1ad72cc445ee8ce86f6ea542df3b4c3 --- /dev/null +++ b/pool/shard003/C/0065496_estaciones.c @@ -0,0 +1,37 @@ +// Carlos Rodríguez Hernández +// Estaciones +// Según el mes introducido, imprime en qué estación se encuentra + +//Ficheros include del sistema +#include + +//Ficheros include de la aplicacion + +//Constantes de la aplicacion +#define ERROR 0 +#define INVIERNO 1 +#define PRIMAVERA 2 +#define VERANO 3 +#define OTONO 4 + +int main () +{ + int mes; + int estacion; + + printf("Introduzca un mes: "); + scanf("%d", &mes); + if (mes == 12 || mes == 1 || mes == 2) + estacion = INVIERNO; + else if (mes == 3 || mes == 4 || mes == 5) + estacion = PRIMAVERA; + else if (mes == 6 || mes == 7 || mes == 8) + estacion = VERANO; + else if (mes == 9 || mes == 10 || mes == 11) + estacion = OTONO; + else + estacion = ERROR; + printf("El mes %d pertenece a la estacion %d\n", mes, estacion); + +return 0; +} diff --git a/pool/shard003/C/0065504_check_all.c b/pool/shard003/C/0065504_check_all.c new file mode 100644 index 0000000000000000000000000000000000000000..43db5c16f80648eb657adde5025156b9e943896b --- /dev/null +++ b/pool/shard003/C/0065504_check_all.c @@ -0,0 +1,36 @@ +#ifndef __STDLIB_H__ +#define __STDLIB_H__ +#include +#endif + +#ifndef __CHECK_MERGESORT_H__ +#include "check_mergesort.h" +#endif + +#ifndef __CHECK_CLOSEST_H__ +#include "check_closest.h" +#endif + +static int run_suite(Suite *s) +{ + int number_failed; + SRunner *sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return number_failed; +} + +int main(void) +{ + int number_failed = 0; + + Suite *ms = mergesort_suite(); + Suite *cs = closest_suite(); + + number_failed += run_suite(ms); + number_failed += run_suite(cs); + + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/pool/shard003/C/0065523_google.c b/pool/shard003/C/0065523_google.c new file mode 100644 index 0000000000000000000000000000000000000000..2805aa1ec668836e3a5eac55a276a7eb7a9cbe7b --- /dev/null +++ b/pool/shard003/C/0065523_google.c @@ -0,0 +1,151 @@ +/*********************************************************** +* This file is part of glyr +* + a commnadline tool and library to download various sort of music related metadata. +* + Copyright (C) [2011] [Christopher Pahl] +* + Hosted at: https://github.com/sahib/glyr +* +* glyr 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. +* +* glyr 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 glyr. If not, see . +**************************************************************/ + +#include "google.h" +#include "../../stringlib.h" +#include "../../core.h" + +///////////////////////////////// + +/* Methods used by more than one provider go here */ +const gchar * generic_google_url (GlyrQuery * sets, const gchar * searchterm) +{ + const gchar * lang = NULL; + if (!g_ascii_strncasecmp (sets->lang,"us",2) ) + lang = "com" ; + else if (!g_ascii_strncasecmp (sets->lang,"ca",2) ) + lang = "ca" ; + else if (!g_ascii_strncasecmp (sets->lang,"uk",2) ) + lang = "co.uk"; + else if (!g_ascii_strncasecmp (sets->lang,"fr",2) ) + lang = "fr" ; + else if (!g_ascii_strncasecmp (sets->lang,"de",2) ) + lang = "de" ; + else if (!g_ascii_strncasecmp (sets->lang,"jp",2) ) + lang = "co.jp"; + else + lang = "com"; + + const gchar * back = NULL; + if (sets->img_min_size == -1) + { + back = ""; + } + else if (sets->img_min_size < 75) + { + back = "&tbs=isz:i"; + } + else if (sets->img_min_size < 300) + { + back = "&tbs=isz:m"; + } + else if (sets->img_min_size < 450) + { + back = "&tbs=isz:lt,islt:qsvga"; + } + else if (sets->img_min_size < 550) + { + back = "&tbs=isz:lt,islt:vg/a"; + } + else if (sets->img_min_size < 700) + { + back = "&tbs=isz:lt,islt:svga"; + } + else /* High enough. */ + { + back = "&tbs=isz:lt,islt:xga"; + } + + return g_strdup_printf ("http://www.google.%s/images?q=%s&safe=off%s%s",lang,searchterm, (back!=NULL) ? "" : "&", back); +} + +///////////////////////////////// + +#define IMG_SRC_START "&usg=" +#define WIDTH_START "&w=" +#define HEIGHT_START "&h=" +#define MAX_NUM_BUF 16 + +static gint google_get_size_value (gchar * ref, gchar * name) +{ + gint number = 0; + gchar * start = g_strstr_len (ref,256,name); + if (start != NULL) + { + start += strlen (name); + gchar * end = strchr (start,' '); + if (end != NULL) + { + gchar numbuf[MAX_NUM_BUF] = {}; + gsize span = MIN (end - start,MAX_NUM_BUF-1); + strncpy (numbuf,start,span); + number = strtol (numbuf,NULL,10); + } + } + return number; +} + +///////////////////////////////// + +static gboolean google_check_image_size (GlyrQuery * s, gchar * ref) +{ + gboolean result = FALSE; + gchar * img_src_after = strstr (ref,IMG_SRC_START); + if (img_src_after != NULL) + { + gint width = google_get_size_value (img_src_after,WIDTH_START); + gint height = google_get_size_value (img_src_after,HEIGHT_START); + gint ratio = (width+height) /2; + + result = size_is_okay (ratio,s->img_min_size,s->img_max_size); + } + return result; +} + +///////////////////////////////// + +#define FIRST_RESULT "setup.supersampling = DEFAULT_SUPERSAMPLING; +} + +/* +** take : "origin: 3 0 -10" +** returns "origin" and put "3 0 -10" into arg +*/ + +char *trim_option(t_env *e, char *option, char **arg) +{ + char **line; + char *trimmed_option; + + line = ft_strsplit(option, ':'); + if (len_of_tab(line) != 2) + syntax_error(option, "Multiple settings", e->nbline); + trimmed_option = ft_strtrim(line[0]); + *arg = ft_strdup(line[1]); + free_splited_str(line); + return (trimmed_option); +} + +/* +** take : "camera:" +** returns "camera" +*/ + +char *trim_setting(t_env *e, char *setting) +{ + char *trimmed_setting; + + if (!setting || setting[0] == '\0') + return ("\0"); + trimmed_setting = ft_strtrim(setting); + if (trimmed_setting[0] == '#') + return (trimmed_setting); + if (trimmed_setting[ft_strlen(trimmed_setting) - 1] != ':' && + trimmed_setting[ft_strlen(trimmed_setting) - 1] != '1' && + trimmed_setting[ft_strlen(trimmed_setting) - 1] != '0') + syntax_error(setting, "Missing ':'", e->nbline); + trimmed_setting[ft_strlen(trimmed_setting) - 1] = '\0'; + return (trimmed_setting); +} + +/* +** Library of function, dispatch lines to the right handler +*/ + +void dispatch(t_env *e, char *line) +{ + char *setting; + + setting = trim_setting(e, line); + if (!ft_strcmp(setting, "supersampling: ")) + set_supersampling(e, line); + else if (!ft_strcmp(setting, "light")) + set_light(e); + else if (!ft_strcmp(setting, "sphere")) + set_sphere(e); + else if (!ft_strcmp(setting, "plane")) + set_plane(e); + else if (!ft_strcmp(setting, "cylinder")) + set_cylinder(e); + else if (!ft_strcmp(setting, "cone")) + set_cone(e); + else if (!setting || setting[0] == '\0' || setting[0] == '#') + return ; + else + unknown_setting(setting, e->nbline); + free(setting); +} + +/* +** take a .rtv1 file as parameter and parse the content into the t_env +*/ + +t_env *parse(char *scene) +{ + t_env *e; + char *line; + + e = (t_env *)semalloc(sizeof(t_env)); + set_default(e); + if ((e->fd = open(scene, O_RDONLY)) == -1) + err_found("open failed"); + e->nbline = 0; + e->obj = NULL; + while (get_next_line(e->fd, &line)) + { + e->nbline += 1; + dispatch(e, line); + free(line); + } + if (close(e->fd) == -1) + err_found("close failed"); + e->setup.camera = c_vector(0, 0, 0); + return (e); +} diff --git a/pool/shard003/C/0065535_ft_lstmap.c b/pool/shard003/C/0065535_ft_lstmap.c new file mode 100644 index 0000000000000000000000000000000000000000..dcfb50a717582302f525f3ec2ac002c165d600e5 --- /dev/null +++ b/pool/shard003/C/0065535_ft_lstmap.c @@ -0,0 +1,31 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_lstmap.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: schiad +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2015/12/04 22:32:53 by schiad #+# #+# */ +/* Updated: 2017/04/25 19:04:01 by schiad ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" + +t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *elem)) +{ + t_list *new; + t_list *tmp; + + if (!(new = f(lst))) + return (NULL); + tmp = new; + lst = lst->next; + while (lst) + { + tmp->next = f(lst); + tmp = tmp->next; + lst = lst->next; + } + return (new); +} diff --git a/pool/shard003/C/0065545_umount.c b/pool/shard003/C/0065545_umount.c new file mode 100644 index 0000000000000000000000000000000000000000..92c60760ba5262a9737af6251c9d68734b4d9a3e --- /dev/null +++ b/pool/shard003/C/0065545_umount.c @@ -0,0 +1,74 @@ + +#include +#include +#include +#include +#include +#include +#include + +// FIXME - only one loop mount is supported at a time +#define LOOP_DEVICE "/dev/block/loop0" + +static int is_loop_mount(const char* path) +{ + FILE* f; + int count; + char device[256]; + char mount_path[256]; + char rest[256]; + int result = 0; + int path_length = strlen(path); + + f = fopen("/proc/mounts", "r"); + if (!f) { + fprintf(stdout, "could not open /proc/mounts\n"); + return -1; + } + + do { + count = fscanf(f, "%255s %255s %255s\n", device, mount_path, rest); + if (count == 3) { + if (strcmp(LOOP_DEVICE, device) == 0 && strcmp(path, mount_path) == 0) { + result = 1; + break; + } + } + } while (count == 3); + + fclose(f); + return result; +} + +int umount_main(int argc, char *argv[]) +{ + int loop, loop_fd; + + if(argc != 2) { + fprintf(stderr,"umount \n"); + return 1; + } + + loop = is_loop_mount(argv[1]); + if(umount(argv[1])){ + fprintf(stderr,"failed.\n"); + return 1; + } + + if (loop) { + // free the loop device + loop_fd = open(LOOP_DEVICE, O_RDONLY); + if (loop_fd < -1) { + perror("open loop device failed"); + return 1; + } + if (ioctl(loop_fd, LOOP_CLR_FD, 0) < 0) { + perror("ioctl LOOP_CLR_FD failed"); + return 1; + } + + close(loop_fd); + } + + return 0; +} diff --git a/pool/shard003/C/0065556_test-proc.c b/pool/shard003/C/0065556_test-proc.c new file mode 100644 index 0000000000000000000000000000000000000000..ed028d59899ef3a2e477452e0d1cde8327fa8b99 --- /dev/null +++ b/pool/shard003/C/0065556_test-proc.c @@ -0,0 +1,113 @@ +/* -*- c-basic-offset: 2; coding: utf-8 -*- */ +/* + Copyright (C) 2013 Kouhei Sutou + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License version 2.1 as published by the Free Software Foundation. + + 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 +*/ + +#include + +#include +#include + +#include "../lib/grn-assertions.h" + +void data_path(void); +void test_path(gconstpointer data); + +static gchar *tmp_directory; + +static grn_logger_info *logger; +static grn_ctx *context; +static grn_obj *database, *proc; + +void +cut_startup(void) +{ + tmp_directory = g_build_filename(grn_test_get_tmp_dir(), + "test-proc", + NULL); +} + +void +cut_shutdown(void) +{ + g_free(tmp_directory); +} + +static void +remove_tmp_directory(void) +{ + cut_remove_path(tmp_directory, NULL); +} + +void +cut_setup(void) +{ + remove_tmp_directory(); + g_mkdir_with_parents(tmp_directory, 0700); + + context = NULL; + logger = setup_grn_logger(); + + context = g_new0(grn_ctx, 1); + grn_ctx_init(context, 0); + + database = grn_db_create(context, + cut_build_path(tmp_directory, "proc.db", NULL), + NULL); + + proc = NULL; +} + +void +cut_teardown(void) +{ + if (proc) { + grn_obj_unlink(context, proc); + } + + grn_obj_close(context, database); + grn_ctx_fin(context); + g_free(context); + + teardown_grn_logger(logger); + cut_remove_path(tmp_directory, NULL); +} + +void +data_path(void) +{ +#define ADD_DATA(label, expected, name) \ + gcut_add_datum(label, \ + "expected", G_TYPE_STRING, expected, \ + "name", G_TYPE_STRING, name, \ + NULL) + + ADD_DATA("built-in", NULL, "select"); + +#undef ADD_DATA +} + +void +test_path(gconstpointer data) +{ + const gchar *expected; + const gchar *name; + + expected = gcut_data_get_string(data, "expected"); + name = gcut_data_get_string(data, "name"); + proc = grn_ctx_get(context, name, -1); + cut_assert_equal_string(expected, grn_obj_path(context, proc)); +} diff --git a/pool/shard003/C/0065559_test-push-buffer.c b/pool/shard003/C/0065559_test-push-buffer.c new file mode 100644 index 0000000000000000000000000000000000000000..2b4201468cb707dc5dac9d44c7564ed4605d869f --- /dev/null +++ b/pool/shard003/C/0065559_test-push-buffer.c @@ -0,0 +1,167 @@ +/*=== +*** test_1a (duk_safe_call) +fixed size, 0 bytes (no guarantee whether ptr NULL or non-NULL) +buffer should be all zeroes +buffer should be writable +fixed size, 1024 bytes +ptr is non-NULL: 1 +buffer should be all zeroes +buffer should be writable +dynamic size, 0 bytes (no guarantee whether ptr NULL or non-NULL) +buffer should be all zeroes +buffer should be writable +dynamic size, 1024 bytes +ptr is non-NULL: 1 +buffer should be all zeroes +buffer should be writable +final top: 4 +==> rc=0, result='undefined' +*** test_1b (duk_safe_call) +fixed size, 0 bytes (no guarantee whether ptr NULL or non-NULL) +buffer should be all zeroes +buffer should be writable +fixed size, 1024 bytes +ptr is non-NULL: 1 +buffer should be all zeroes +buffer should be writable +dynamic size, 0 bytes (no guarantee whether ptr NULL or non-NULL) +buffer should be all zeroes +buffer should be writable +dynamic size, 1024 bytes +ptr is non-NULL: 1 +buffer should be all zeroes +buffer should be writable +final top: 4 +==> rc=0, result='undefined' +*** test_2 (duk_safe_call) +fixed size buffer, close to maximum size_t (should fail) +==> rc=1, result='RangeError: buffer too long' +*** test_3 (duk_safe_call) +dynamic size buffer, close to maximum size_t (should fail) +==> rc=1, result='RangeError: buffer too long' +===*/ + +#ifndef SIZE_MAX +#define SIZE_MAX ((size_t) -1) +#endif + +static void rw_test(unsigned char *p, size_t sz) { + int i; + + printf("buffer should be all zeroes\n"); + for (i = 0; i < sz; i++) { + if (p[i] != 0) { + printf("buffer non-zero at index %d: 0x%02x\n", i, (int) p[i]); + } + } + + printf("buffer should be writable\n"); + for (i = 0; i < sz; i++) { + p[i] = 0xff; + } +} + +/* Basic success test. */ +static duk_ret_t test_1a(duk_context *ctx, void *udata) { + void *buf; + + (void) udata; + + duk_set_top(ctx, 0); + + printf("fixed size, 0 bytes (no guarantee whether ptr NULL or non-NULL)\n"); + buf = duk_push_buffer(ctx, 0, 0); + rw_test((unsigned char *) buf, 0); + + printf("fixed size, 1024 bytes\n"); + buf = duk_push_buffer(ctx, 1024, 0); + printf("ptr is non-NULL: %d\n", (buf != NULL ? 1 : 0)); + rw_test((unsigned char *) buf, 1024); + + printf("dynamic size, 0 bytes (no guarantee whether ptr NULL or non-NULL)\n"); + buf = duk_push_buffer(ctx, 0, 1); + rw_test((unsigned char *) buf, 0); + + printf("dynamic size, 1024 bytes\n"); + buf = duk_push_buffer(ctx, 1024, 1); + printf("ptr is non-NULL: %d\n", (buf != NULL ? 1 : 0)); + rw_test((unsigned char *) buf, 1024); + + printf("final top: %ld\n", (long) duk_get_top(ctx)); + return 0; +} + +/* Same test, using shortcut functions. */ +static duk_ret_t test_1b(duk_context *ctx, void *udata) { + void *buf; + + (void) udata; + + duk_set_top(ctx, 0); + + printf("fixed size, 0 bytes (no guarantee whether ptr NULL or non-NULL)\n"); + buf = duk_push_fixed_buffer(ctx, 0); + rw_test((unsigned char *) buf, 0); + + printf("fixed size, 1024 bytes\n"); + buf = duk_push_fixed_buffer(ctx, 1024); + printf("ptr is non-NULL: %d\n", (buf != NULL ? 1 : 0)); + rw_test((unsigned char *) buf, 1024); + + printf("dynamic size, 0 bytes (no guarantee whether ptr NULL or non-NULL)\n"); + buf = duk_push_dynamic_buffer(ctx, 0); + rw_test((unsigned char *) buf, 0); + + printf("dynamic size, 1024 bytes\n"); + buf = duk_push_dynamic_buffer(ctx, 1024); + printf("ptr is non-NULL: %d\n", (buf != NULL ? 1 : 0)); + rw_test((unsigned char *) buf, 1024); + + printf("final top: %ld\n", (long) duk_get_top(ctx)); + return 0; +} + + +/* Ensure that insanely large alloation fails. Don't use SIZE_MAX, as + * a current bug makes the allocated size wrap and actually causes + * other trouble (separate bug testcase exists for that: + * test-bug-push-buffer-maxsize.c). + */ +static duk_ret_t test_2(duk_context *ctx, void *udata) { + void *buf; + + (void) udata; + + duk_set_top(ctx, 0); + + printf("fixed size buffer, close to maximum size_t (should fail)\n"); + buf = duk_push_buffer(ctx, SIZE_MAX - 1024, 0); + printf("ptr is non-NULL: %d\n", (buf != NULL ? 1 : 0)); + + printf("final top: %ld\n", (long) duk_get_top(ctx)); + return 0; +} + +static duk_ret_t test_3(duk_context *ctx, void *udata) { + void *buf; + + (void) udata; + + duk_set_top(ctx, 0); + + printf("dynamic size buffer, close to maximum size_t (should fail)\n"); + buf = duk_push_buffer(ctx, SIZE_MAX - 1024, 1); + printf("ptr is non-NULL: %d\n", (buf != NULL ? 1 : 0)); + + printf("final top: %ld\n", (long) duk_get_top(ctx)); + return 0; +} + +void test(duk_context *ctx) { + /*printf("DUK_SIZE_MAX=%lf\n", (double) DUK_SIZE_MAX);*/ + + TEST_SAFE_CALL(test_1a); + TEST_SAFE_CALL(test_1b); + TEST_SAFE_CALL(test_2); + TEST_SAFE_CALL(test_3); +} diff --git a/pool/shard003/C/0065568_parser.c b/pool/shard003/C/0065568_parser.c new file mode 100644 index 0000000000000000000000000000000000000000..a724981277b10b099fafec65e4a6bd2962f965ea --- /dev/null +++ b/pool/shard003/C/0065568_parser.c @@ -0,0 +1,168 @@ +/************************************************************************ + * Copyright (C) 2013, Felix Bytow * + * * + * This file is part of dbfi. * + * * + * dbfi 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. * + * * + * dbfi 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 dbfi. If not, see . * + ************************************************************************/ + +#include "parser.h" + +#include +#include +#include + +struct dbfi_parser +{ + dbfi_parser_tree_t current_scope_; +}; + +dbfi_parser_t dbfi_parser_init(void) +{ + dbfi_parser_t parser = malloc(sizeof(struct dbfi_parser)); + if (!parser) + return NULL; + + parser->current_scope_ = NULL; + return parser; +} + +void dbfi_parser_release(dbfi_parser_t _this) +{ + free(_this); +} + +dbfi_parser_tree_t dbfi_parser_generate_tree(dbfi_parser_t _this, dbfi_lexer_t lexer) +{ + dbfi_parser_tree_t result; + dbfi_token_info_t * tok; + int is_root = 0; + int param = 0; + dbfi_command_t last_command = DBFI_COMMAND_NONE; + + assert(_this); + assert(lexer); + + result = _this->current_scope_; + if (!result) + { + is_root = 1; + + result = dbfi_parser_tree_init(); + if (!result) + return NULL; + } + + /* walk through tokens till end of file or end of scope */ + tok = dbfi_lexer_next_token(lexer); + while (tok->type_ != DBFI_TOKEN_BRIGHT && tok->type_ != DBFI_TOKEN_EOF) + { + if (tok->type_ == DBFI_TOKEN_BLEFT) + { + dbfi_parser_tree_t subtree; + + dbfi_parser_tree_add_command(result, last_command, param); + subtree = dbfi_parser_tree_add_scope(result); + assert(subtree); + + _this->current_scope_ = subtree; + dbfi_parser_generate_tree(_this, lexer); + _this->current_scope_ = result; + + last_command = DBFI_COMMAND_NONE; + } + else + { + switch (tok->type_) + { + case DBFI_TOKEN_PLUS: + case DBFI_TOKEN_MINUS: + { + if (last_command == DBFI_COMMAND_MODIFY_VALUE) + { + if (tok->type_ == DBFI_TOKEN_PLUS) + ++param; + else + --param; + } + else + { + dbfi_parser_tree_add_command(result, last_command, param); + last_command = DBFI_COMMAND_MODIFY_VALUE; + param = (tok->type_ == DBFI_TOKEN_PLUS ? 1 : -1); + } + } break; + case DBFI_TOKEN_LT: + case DBFI_TOKEN_GT: + { + if (last_command == DBFI_COMMAND_MODIFY_PTR) + { + if (tok->type_ == DBFI_TOKEN_GT) + ++param; + else + --param; + } + else + { + dbfi_parser_tree_add_command(result, last_command, param); + last_command = DBFI_COMMAND_MODIFY_PTR; + param = (tok->type_ == DBFI_TOKEN_GT ? 1 : -1); + } + } break; + case DBFI_TOKEN_DOT: + case DBFI_TOKEN_COMMA: + { + dbfi_parser_tree_add_command(result, last_command, param); + last_command = (tok->type_ == DBFI_TOKEN_DOT ? DBFI_COMMAND_PRINT : DBFI_COMMAND_READ); + } break; + } + } + + tok = dbfi_lexer_next_token(lexer); + } + + dbfi_parser_tree_add_command(result, last_command, param); + + if (is_root) + { + _this->current_scope_ = NULL; + + /* we are at root scope... the scope has ended... but not the file + * thus there has to be an unexpected ] (right bracket) */ + if (tok->type_ != DBFI_TOKEN_EOF) + { + fprintf(stderr, + "Error: Unexpected closing bracket.\n" + "At: %s - Line: %u - Column: %u.\n" + , tok->filename_, (unsigned)(tok->row_ + 1), (unsigned)(tok->column_ + 1)); + exit(-1); + } + } + else + { + /* we are in a sub scope but already encountered the end of file + * instead of a closing bracked... */ + if (tok->type_ == DBFI_TOKEN_EOF) + { + fprintf(stderr, + "Error: Unexpected end of file. (Closing bracket expected.)\n" + "At: %s - Line: %u - Column: %u.\n" + , tok->filename_, (unsigned)(tok->row_ + 1), (unsigned)(tok->column_ + 1)); + exit(-1); + } + } + + return result; +} + diff --git a/pool/shard003/C/0065569_Org.c b/pool/shard003/C/0065569_Org.c new file mode 100644 index 0000000000000000000000000000000000000000..e2fc2f38efaf9fe5b214d9b8381821b01bf804ce --- /dev/null +++ b/pool/shard003/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 + +unsigned int djb2(char code[]) { + unsigned int h = 0; + int len = strlen(code); + for(int i = 0; i < len; i++) { + h = (h << 6) + (h << 16) - h + code[i]; + } + return h; +}; + +int main() { + char s[] = "a14bcef"; + printf("hash(%s) = %u\n", s, djb2(s)); +} \ No newline at end of file diff --git a/pool/shard003/C/0065581_smp.c b/pool/shard003/C/0065581_smp.c new file mode 100644 index 0000000000000000000000000000000000000000..273d7b46f72ac22ff238cd10dc978eaf8610d32b --- /dev/null +++ b/pool/shard003/C/0065581_smp.c @@ -0,0 +1,246 @@ +/* + * SMP support for PowerNV machines. + * + * Copyright 2011 IBM Corp. + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "powernv.h" + +#ifdef DEBUG +#include +#define DBG(fmt...) udbg_printf(fmt) +#else +#define DBG(fmt...) +#endif + +static void pnv_smp_setup_cpu(int cpu) +{ + if (cpu != boot_cpuid) + xics_setup_cpu(); + +#ifdef CONFIG_PPC_DOORBELL + if (cpu_has_feature(CPU_FTR_DBELL)) + doorbell_setup_this_cpu(); +#endif +} + +static int pnv_smp_kick_cpu(int nr) +{ + unsigned int pcpu = get_hard_smp_processor_id(nr); + unsigned long start_here = + __pa(ppc_function_entry(generic_secondary_smp_init)); + long rc; + + BUG_ON(nr < 0 || nr >= NR_CPUS); + + /* + * If we already started or OPALv2 is not supported, we just + * kick the CPU via the PACA + */ + if (paca[nr].cpu_start || !firmware_has_feature(FW_FEATURE_OPALv2)) + goto kick; + + /* + * At this point, the CPU can either be spinning on the way in + * from kexec or be inside OPAL waiting to be started for the + * first time. OPAL v3 allows us to query OPAL to know if it + * has the CPUs, so we do that + */ + if (firmware_has_feature(FW_FEATURE_OPALv3)) { + uint8_t status; + + rc = opal_query_cpu_status(pcpu, &status); + if (rc != OPAL_SUCCESS) { + pr_warn("OPAL Error %ld querying CPU %d state\n", + rc, nr); + return -ENODEV; + } + + /* + * Already started, just kick it, probably coming from + * kexec and spinning + */ + if (status == OPAL_THREAD_STARTED) + goto kick; + + /* + * Available/inactive, let's kick it + */ + if (status == OPAL_THREAD_INACTIVE) { + pr_devel("OPAL: Starting CPU %d (HW 0x%x)...\n", + nr, pcpu); + rc = opal_start_cpu(pcpu, start_here); + if (rc != OPAL_SUCCESS) { + pr_warn("OPAL Error %ld starting CPU %d\n", + rc, nr); + return -ENODEV; + } + } else { + /* + * An unavailable CPU (or any other unknown status) + * shouldn't be started. It should also + * not be in the possible map but currently it can + * happen + */ + pr_devel("OPAL: CPU %d (HW 0x%x) is unavailable" + " (status %d)...\n", nr, pcpu, status); + return -ENODEV; + } + } else { + /* + * On OPAL v2, we just kick it and hope for the best, + * we must not test the error from opal_start_cpu() or + * we would fail to get CPUs from kexec. + */ + opal_start_cpu(pcpu, start_here); + } + kick: + return smp_generic_kick_cpu(nr); +} + +#ifdef CONFIG_HOTPLUG_CPU + +static int pnv_smp_cpu_disable(void) +{ + int cpu = smp_processor_id(); + + /* This is identical to pSeries... might consolidate by + * moving migrate_irqs_away to a ppc_md with default to + * the generic fixup_irqs. --BenH. + */ + set_cpu_online(cpu, false); + vdso_data->processorCount--; + if (cpu == boot_cpuid) + boot_cpuid = cpumask_any(cpu_online_mask); + xics_migrate_irqs_away(); + return 0; +} + +static void pnv_smp_cpu_kill_self(void) +{ + unsigned int cpu; + unsigned long srr1; + u32 idle_states; + + /* Standard hot unplug procedure */ + local_irq_disable(); + idle_task_exit(); + current->active_mm = NULL; /* for sanity */ + cpu = smp_processor_id(); + DBG("CPU%d offline\n", cpu); + generic_set_cpu_dead(cpu); + smp_wmb(); + + idle_states = pnv_get_supported_cpuidle_states(); + /* We don't want to take decrementer interrupts while we are offline, + * so clear LPCR:PECE1. We keep PECE2 enabled. + */ + mtspr(SPRN_LPCR, mfspr(SPRN_LPCR) & ~(u64)LPCR_PECE1); + while (!generic_check_cpu_restart(cpu)) { + + ppc64_runlatch_off(); + + if (idle_states & OPAL_PM_WINKLE_ENABLED) + srr1 = power7_winkle(); + else if ((idle_states & OPAL_PM_SLEEP_ENABLED) || + (idle_states & OPAL_PM_SLEEP_ENABLED_ER1)) + srr1 = power7_sleep(); + else + srr1 = power7_nap(1); + + ppc64_runlatch_on(); + + /* + * If the SRR1 value indicates that we woke up due to + * an external interrupt, then clear the interrupt. + * We clear the interrupt before checking for the + * reason, so as to avoid a race where we wake up for + * some other reason, find nothing and clear the interrupt + * just as some other cpu is sending us an interrupt. + * If we returned from power7_nap as a result of + * having finished executing in a KVM guest, then srr1 + * contains 0. + */ + if ((srr1 & SRR1_WAKEMASK) == SRR1_WAKEEE) { + icp_native_flush_interrupt(); + local_paca->irq_happened &= PACA_IRQ_HARD_DIS; + smp_mb(); + } + + if (cpu_core_split_required()) + continue; + + if (!generic_check_cpu_restart(cpu)) + DBG("CPU%d Unexpected exit while offline !\n", cpu); + } + mtspr(SPRN_LPCR, mfspr(SPRN_LPCR) | LPCR_PECE1); + DBG("CPU%d coming online...\n", cpu); +} + +#endif /* CONFIG_HOTPLUG_CPU */ + +static int pnv_cpu_bootable(unsigned int nr) +{ + /* + * Starting with POWER8, the subcore logic relies on all threads of a + * core being booted so that they can participate in split mode + * switches. So on those machines we ignore the smt_enabled_at_boot + * setting (smt-enabled on the kernel command line). + */ + if (cpu_has_feature(CPU_FTR_ARCH_207S)) + return 1; + + return smp_generic_cpu_bootable(nr); +} + +static struct smp_ops_t pnv_smp_ops = { + .message_pass = smp_muxed_ipi_message_pass, + .cause_ipi = NULL, /* Filled at runtime by xics_smp_probe() */ + .probe = xics_smp_probe, + .kick_cpu = pnv_smp_kick_cpu, + .setup_cpu = pnv_smp_setup_cpu, + .cpu_bootable = pnv_cpu_bootable, +#ifdef CONFIG_HOTPLUG_CPU + .cpu_disable = pnv_smp_cpu_disable, + .cpu_die = generic_cpu_die, +#endif /* CONFIG_HOTPLUG_CPU */ +}; + +/* This is called very early during platform setup_arch */ +void __init pnv_smp_init(void) +{ + smp_ops = &pnv_smp_ops; + +#ifdef CONFIG_HOTPLUG_CPU + ppc_md.cpu_die = pnv_smp_cpu_kill_self; +#endif +} diff --git a/pool/shard003/C/0065600_sttype-function.c b/pool/shard003/C/0065600_sttype-function.c new file mode 100644 index 0000000000000000000000000000000000000000..d2d181d5f33180c89582cab4f6c5633e53d211db --- /dev/null +++ b/pool/shard003/C/0065600_sttype-function.c @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2006 by Gilbert Ramirez + * + * Wireshark - Network traffic analyzer + * + * SPDX-License-Identifier: GPL-2.0-or-later + */ + +#include "config.h" + +#include "syntax-tree.h" +#include "sttype-function.h" + +typedef struct { + guint32 magic; + df_func_def_t *funcdef; + GSList *params; +} function_t; + +#define FUNCTION_MAGIC 0xe10f0f99 + +static gpointer +function_new(gpointer funcdef) +{ + function_t *stfuncrec; + + g_assert(funcdef != NULL); + + stfuncrec = g_new(function_t, 1); + + stfuncrec->magic = FUNCTION_MAGIC; + stfuncrec->funcdef = (df_func_def_t *)funcdef; + stfuncrec->params = NULL; + + return (gpointer) stfuncrec; +} + +static gpointer +function_dup(gconstpointer data) +{ + const function_t *org = (const function_t *)data; + function_t *stfuncrec; + GSList *p; + + stfuncrec = (function_t *)function_new(org->funcdef); + + for (p = org->params; p; p = p->next) { + const stnode_t *param = (const stnode_t *)p->data; + stfuncrec->params = g_slist_append(stfuncrec->params, stnode_dup(param)); + } + return (gpointer) stfuncrec; +} + +static void +slist_stnode_free(gpointer data) +{ + stnode_free((stnode_t *)data); +} + +void +st_funcparams_free(GSList *params) +{ + g_slist_free_full(params, slist_stnode_free); +} + +static void +function_free(gpointer value) +{ + function_t *stfuncrec = (function_t*)value; + assert_magic(stfuncrec, FUNCTION_MAGIC); + st_funcparams_free(stfuncrec->params); + g_free(stfuncrec); +} + + +/* Set the parameters for a function stnode_t. */ +void +sttype_function_set_params(stnode_t *node, GSList *params) +{ + + function_t *stfuncrec; + + stfuncrec = (function_t*)stnode_data(node); + assert_magic(stfuncrec, FUNCTION_MAGIC); + + stfuncrec->params = params; +} + +/* Get the function-definition record for a function stnode_t. */ +df_func_def_t* +sttype_function_funcdef(stnode_t *node) +{ + function_t *stfuncrec; + + stfuncrec = (function_t*)stnode_data(node); + assert_magic(stfuncrec, FUNCTION_MAGIC); + return stfuncrec->funcdef; +} + +/* Get the parameters for a function stnode_t. */ +GSList* +sttype_function_params(stnode_t *node) +{ + function_t *stfuncrec; + + stfuncrec = (function_t*)stnode_data(node); + assert_magic(stfuncrec, FUNCTION_MAGIC); + return stfuncrec->params; +} + + +void +sttype_register_function(void) +{ + static sttype_t function_type = { + STTYPE_FUNCTION, + "FUNCTION", + function_new, + function_free, + function_dup + }; + + sttype_register(&function_type); +} + +/* + * Editor modelines - https://www.wireshark.org/tools/modelines.html + * + * Local variables: + * c-basic-offset: 8 + * tab-width: 8 + * indent-tabs-mode: t + * End: + * + * vi: set shiftwidth=8 tabstop=8 noexpandtab: + * :indentSize=8:tabSize=8:noTabs=false: + */ diff --git a/pool/shard003/C/0065601_t-solve_triu.c b/pool/shard003/C/0065601_t-solve_triu.c new file mode 100644 index 0000000000000000000000000000000000000000..3f3e2e080e4200f74893198fa77952d70c742f0d --- /dev/null +++ b/pool/shard003/C/0065601_t-solve_triu.c @@ -0,0 +1,67 @@ +/* + Copyright (C) 2010, 2011 Fredrik Johansson + Copyright (C) 2013 Mike Hansen + Copyright (C) 2021 Daniel Schultz + + This file is part of FLINT. + + FLINT 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.1 of the License, or + (at your option) any later version. See . +*/ + +#include "fmpz_mod_mat.h" +#include "test_helpers.h" + +int main(void) +{ + slong i; + FLINT_TEST_INIT(state); + + flint_printf("solve_triu...."); + fflush(stdout); + + for (i = 0; i < 5 * flint_test_multiplier(); i++) + { + fmpz_mod_ctx_t ctx; + fmpz_mod_mat_t A, X, B, Y; + slong rows, cols; + int unit; + + fmpz_mod_ctx_init_rand_bits_prime(ctx, state, 200); + + rows = n_randint(state, 50); + cols = n_randint(state, 50); + unit = n_randint(state, 2); + + fmpz_mod_mat_init(A, rows, rows, fmpz_mod_ctx_modulus(ctx)); + fmpz_mod_mat_init(B, rows, cols, fmpz_mod_ctx_modulus(ctx)); + fmpz_mod_mat_init(X, rows, cols, fmpz_mod_ctx_modulus(ctx)); + fmpz_mod_mat_init(Y, rows, cols, fmpz_mod_ctx_modulus(ctx)); + + fmpz_mod_mat_randtriu(A, state, unit); + fmpz_mod_mat_randtest(X, state); + fmpz_mod_mat_mul(B, A, X); + + /* Check Y = A^(-1) * (A * X) = X */ + fmpz_mod_mat_solve_triu(Y, A, B, unit); + FLINT_TEST(fmpz_mod_mat_equal(Y, X)); + + /* Check aliasing */ + fmpz_mod_mat_solve_triu(B, A, B, unit); + FLINT_TEST(fmpz_mod_mat_equal(B, X)); + + fmpz_mod_mat_clear(A); + fmpz_mod_mat_clear(B); + fmpz_mod_mat_clear(X); + fmpz_mod_mat_clear(Y); + + fmpz_mod_ctx_clear(ctx); + } + + FLINT_TEST_CLEANUP(state); + flint_printf("PASS\n"); + return 0; +} + diff --git a/pool/shard003/C/0065613_hid-picolcd_leds.c b/pool/shard003/C/0065613_hid-picolcd_leds.c new file mode 100644 index 0000000000000000000000000000000000000000..6b505a75351126888ee73a90625760e1b9f15c8f --- /dev/null +++ b/pool/shard003/C/0065613_hid-picolcd_leds.c @@ -0,0 +1,163 @@ +// SPDX-License-Identifier: GPL-2.0-only +/*************************************************************************** + * Copyright (C) 2010-2012 by Bruno Prémont * + * * + * Based on Logitech G13 driver (v0.4) * + * Copyright (C) 2009 by Rick L. Vinyard, Jr. * + * * + ***************************************************************************/ + +#include +#include +#include +#include "hid-ids.h" + +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include + +#include "hid-picolcd.h" + + +void picolcd_leds_set(struct picolcd_data *data) +{ + struct hid_report *report; + unsigned long flags; + + if (!data->led[0]) + return; + report = picolcd_out_report(REPORT_LED_STATE, data->hdev); + if (!report || report->maxfield != 1 || report->field[0]->report_count != 1) + return; + + spin_lock_irqsave(&data->lock, flags); + hid_set_field(report->field[0], 0, data->led_state); + if (!(data->status & PICOLCD_FAILED)) + hid_hw_request(data->hdev, report, HID_REQ_SET_REPORT); + spin_unlock_irqrestore(&data->lock, flags); +} + +static void picolcd_led_set_brightness(struct led_classdev *led_cdev, + enum led_brightness value) +{ + struct device *dev; + struct hid_device *hdev; + struct picolcd_data *data; + int i, state = 0; + + dev = led_cdev->dev->parent; + hdev = to_hid_device(dev); + data = hid_get_drvdata(hdev); + if (!data) + return; + for (i = 0; i < 8; i++) { + if (led_cdev != data->led[i]) + continue; + state = (data->led_state >> i) & 1; + if (value == LED_OFF && state) { + data->led_state &= ~(1 << i); + picolcd_leds_set(data); + } else if (value != LED_OFF && !state) { + data->led_state |= 1 << i; + picolcd_leds_set(data); + } + break; + } +} + +static enum led_brightness picolcd_led_get_brightness(struct led_classdev *led_cdev) +{ + struct device *dev; + struct hid_device *hdev; + struct picolcd_data *data; + int i, value = 0; + + dev = led_cdev->dev->parent; + hdev = to_hid_device(dev); + data = hid_get_drvdata(hdev); + for (i = 0; i < 8; i++) + if (led_cdev == data->led[i]) { + value = (data->led_state >> i) & 1; + break; + } + return value ? LED_FULL : LED_OFF; +} + +int picolcd_init_leds(struct picolcd_data *data, struct hid_report *report) +{ + struct device *dev = &data->hdev->dev; + struct led_classdev *led; + size_t name_sz = strlen(dev_name(dev)) + 8; + char *name; + int i, ret = 0; + + if (!report) + return -ENODEV; + if (report->maxfield != 1 || report->field[0]->report_count != 1 || + report->field[0]->report_size != 8) { + dev_err(dev, "unsupported LED_STATE report"); + return -EINVAL; + } + + for (i = 0; i < 8; i++) { + led = kzalloc(sizeof(struct led_classdev)+name_sz, GFP_KERNEL); + if (!led) { + dev_err(dev, "can't allocate memory for LED %d\n", i); + ret = -ENOMEM; + goto err; + } + name = (void *)(&led[1]); + snprintf(name, name_sz, "%s::GPO%d", dev_name(dev), i); + led->name = name; + led->brightness = 0; + led->max_brightness = 1; + led->brightness_get = picolcd_led_get_brightness; + led->brightness_set = picolcd_led_set_brightness; + + data->led[i] = led; + ret = led_classdev_register(dev, data->led[i]); + if (ret) { + data->led[i] = NULL; + kfree(led); + dev_err(dev, "can't register LED %d\n", i); + goto err; + } + } + return 0; +err: + for (i = 0; i < 8; i++) + if (data->led[i]) { + led = data->led[i]; + data->led[i] = NULL; + led_classdev_unregister(led); + kfree(led); + } + return ret; +} + +void picolcd_exit_leds(struct picolcd_data *data) +{ + struct led_classdev *led; + int i; + + for (i = 0; i < 8; i++) { + led = data->led[i]; + data->led[i] = NULL; + if (!led) + continue; + led_classdev_unregister(led); + kfree(led); + } +} + + diff --git a/pool/shard003/C/0065614_testheap.c b/pool/shard003/C/0065614_testheap.c new file mode 100644 index 0000000000000000000000000000000000000000..4a8eeb063a2017e4a20fe12207eee58285c02d80 --- /dev/null +++ b/pool/shard003/C/0065614_testheap.c @@ -0,0 +1,159 @@ +/* + ChibiOS - Copyright (C) 2006..2016 Giovanni Di Sirio + + 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 "ch.h" +#include "test.h" + +/** + * @page test_heap Memory Heap test + * + * File: @ref testheap.c + * + *

    Description

    + * This module implements the test sequence for the @ref heaps subsystem. + * + *

    Objective

    + * Objective of the test module is to cover 100% of the @ref heaps subsystem. + * + *

    Preconditions

    + * The module requires the following kernel options: + * - @p CH_CFG_USE_HEAP + * . + * In case some of the required options are not enabled then some or all tests + * may be skipped. + * + *

    Test Cases

    + * - @subpage test_heap_001 + * . + * @file testheap.c + * @brief Heap test source file + * @file testheap.h + * @brief Heap header file + */ + +#if CH_CFG_USE_HEAP || defined(__DOXYGEN__) + +#define SIZE 16 + +static memory_heap_t test_heap; + +/** + * @page test_heap_001 Allocation and fragmentation test + * + *

    Description

    + * Series of allocations/deallocations are performed in carefully designed + * sequences in order to stimulate all the possible code paths inside the + * allocator.
    + * The test expects to find the heap back to the initial status after each + * sequence. + */ + +static void heap1_setup(void) { + + chHeapObjectInit(&test_heap, test.buffer, sizeof(union test_buffers)); +} + +static void heap1_execute(void) { + void *p1, *p2, *p3; + size_t n, sz; + + /* Unrelated, for coverage only.*/ + (void)chCoreGetStatusX(); + + /* + * Test on the default heap in order to cover the core allocator at + * least one time. + */ + (void)chHeapStatus(NULL, &sz, NULL); + p1 = chHeapAlloc(NULL, SIZE); + test_assert(1, p1 != NULL, "allocation failed"); + chHeapFree(p1); + p1 = chHeapAlloc(NULL, (size_t)-256); + test_assert(2, p1 == NULL, "allocation not failed"); + + /* Initial local heap state.*/ + (void)chHeapStatus(&test_heap, &sz, NULL); + + /* Same order.*/ + p1 = chHeapAlloc(&test_heap, SIZE); + p2 = chHeapAlloc(&test_heap, SIZE); + p3 = chHeapAlloc(&test_heap, SIZE); + chHeapFree(p1); /* Does not merge.*/ + chHeapFree(p2); /* Merges backward.*/ + chHeapFree(p3); /* Merges both sides.*/ + test_assert(3, chHeapStatus(&test_heap, &n, NULL) == 1, "heap fragmented"); + + /* Reverse order.*/ + p1 = chHeapAlloc(&test_heap, SIZE); + p2 = chHeapAlloc(&test_heap, SIZE); + p3 = chHeapAlloc(&test_heap, SIZE); + chHeapFree(p3); /* Merges forward.*/ + chHeapFree(p2); /* Merges forward.*/ + chHeapFree(p1); /* Merges forward.*/ + test_assert(4, chHeapStatus(&test_heap, &n, NULL) == 1, "heap fragmented"); + + /* Small fragments handling.*/ + p1 = chHeapAlloc(&test_heap, SIZE + 1); + p2 = chHeapAlloc(&test_heap, SIZE); + chHeapFree(p1); + test_assert(5, chHeapStatus(&test_heap, &n, NULL) == 2, "invalid state"); + p1 = chHeapAlloc(&test_heap, SIZE); + /* Note, the first situation happens when the alignment size is smaller + than the header size, the second in the other cases.*/ + test_assert(6, (chHeapStatus(&test_heap, &n, NULL) == 1) || + (chHeapStatus(&test_heap, &n, NULL) == 2), "heap fragmented"); + chHeapFree(p2); + chHeapFree(p1); + test_assert(7, chHeapStatus(&test_heap, &n, NULL) == 1, "heap fragmented"); + + /* Skip fragment handling.*/ + p1 = chHeapAlloc(&test_heap, SIZE); + p2 = chHeapAlloc(&test_heap, SIZE); + chHeapFree(p1); + test_assert(8, chHeapStatus(&test_heap, &n, NULL) == 2, "invalid state"); + p1 = chHeapAlloc(&test_heap, SIZE * 2); /* Skips first fragment.*/ + chHeapFree(p1); + chHeapFree(p2); + test_assert(9, chHeapStatus(&test_heap, &n, NULL) == 1, "heap fragmented"); + + /* Allocate all handling.*/ + (void)chHeapStatus(&test_heap, &n, NULL); + p1 = chHeapAlloc(&test_heap, n); + test_assert(10, chHeapStatus(&test_heap, &n, NULL) == 0, "not empty"); + chHeapFree(p1); + + test_assert(11, chHeapStatus(&test_heap, &n, NULL) == 1, "heap fragmented"); + test_assert(12, n == sz, "size changed"); +} + +ROMCONST struct testcase testheap1 = { + "Heap, allocation and fragmentation test", + heap1_setup, + NULL, + heap1_execute +}; + +#endif /* CH_CFG_USE_HEAP.*/ + +/** + * @brief Test sequence for heap. + */ +ROMCONST struct testcase * ROMCONST patternheap[] = { +#if CH_CFG_USE_HEAP || defined(__DOXYGEN__) + &testheap1, +#endif + NULL +}; diff --git a/pool/shard003/C/0065632_calcular_clnt.c b/pool/shard003/C/0065632_calcular_clnt.c new file mode 100644 index 0000000000000000000000000000000000000000..ecaf10c78a747cbe88f46b2e7fba2b1bcb2ecd5f --- /dev/null +++ b/pool/shard003/C/0065632_calcular_clnt.c @@ -0,0 +1,38 @@ +/* +* Please do not edit this file. +* It was generated using rpcgen. +*/ + +#include /* for memset */ +#include "calcular.h" + +/* Default timeout can be changed using clnt_control() */ +static struct timeval TIMEOUT = { 25, 0 }; + +int * sumar_1(int a, int b, CLIENT *clnt) +{ + sumar_1_argument arg; + static int clnt_res; + + memset((char *)&clnt_res, 0, sizeof(clnt_res)); + arg.a = a; + arg.b = b; + if (clnt_call (clnt, sumar, (xdrproc_t) xdr_sumar_1_argument, (caddr_t) &arg,(xdrproc_t) xdr_int, (caddr_t) &clnt_res,TIMEOUT) != RPC_SUCCESS) { + return (NULL); + } + return (&clnt_res); +} + +int * restar_1(int a, int b, CLIENT *clnt) +{ + restar_1_argument arg; + static int clnt_res; + + memset((char *)&clnt_res, 0, sizeof(clnt_res)); + arg.a = a; + arg.b = b; + if (clnt_call (clnt, restar, (xdrproc_t) xdr_restar_1_argument, (caddr_t) &arg,(xdrproc_t) xdr_int, (caddr_t) &clnt_res,TIMEOUT) != RPC_SUCCESS) { + return (NULL); + } + return (&clnt_res); +} diff --git a/pool/shard003/C/0065647_uart.c b/pool/shard003/C/0065647_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..7f1cfb0edaf4de429b1e71e35bad637782414271 --- /dev/null +++ b/pool/shard003/C/0065647_uart.c @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2020 Tridonic GmbH & Co KG + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#define LOG_LEVEL CONFIG_OPENTHREAD_LOG_LEVEL +#define LOG_MODULE_NAME net_otPlat_uart + +#include +LOG_MODULE_REGISTER(LOG_MODULE_NAME); + +#include +#include +#include + +#include + +#include +#include + +#include + +#include +#include +#include + +#include "platform-zephyr.h" + +struct openthread_uart { + struct ring_buf *rx_ringbuf; + const struct device *dev; + atomic_t tx_busy; + atomic_t tx_finished; +}; + +#define OT_UART_DEFINE(_name, _ringbuf_size) \ + RING_BUF_DECLARE(_name##_rx_ringbuf, _ringbuf_size); \ + static struct openthread_uart _name = { \ + .rx_ringbuf = &_name##_rx_ringbuf, \ + } + +OT_UART_DEFINE(ot_uart, CONFIG_OPENTHREAD_COPROCESSOR_UART_RING_BUFFER_SIZE); + +#define RX_FIFO_SIZE 128 + +static bool is_panic_mode; +static const uint8_t *write_buffer; +static uint16_t write_length; + +static void uart_rx_handle(const struct device *dev) +{ + uint8_t *data; + uint32_t len; + uint32_t rd_len; + bool new_data = false; + + do { + len = ring_buf_put_claim( + ot_uart.rx_ringbuf, &data, + ot_uart.rx_ringbuf->size); + if (len > 0) { + rd_len = uart_fifo_read(dev, data, len); + if (rd_len > 0) { + new_data = true; + } + + int err = ring_buf_put_finish( + ot_uart.rx_ringbuf, rd_len); + (void)err; + __ASSERT_NO_MSG(err == 0); + } else { + uint8_t dummy; + + /* No space in the ring buffer - consume byte. */ + LOG_WRN("RX ring buffer full."); + + rd_len = uart_fifo_read(dev, &dummy, 1); + } + } while (rd_len && (rd_len == len)); + + if (new_data) { + otSysEventSignalPending(); + } +} + +static void uart_tx_handle(const struct device *dev) +{ + uint32_t len; + + if (write_length) { + len = uart_fifo_fill(dev, write_buffer, write_length); + write_buffer += len; + write_length -= len; + } else { + uart_irq_tx_disable(dev); + ot_uart.tx_busy = 0; + atomic_set(&(ot_uart.tx_finished), 1); + otSysEventSignalPending(); + } +} + +static void uart_callback(const struct device *dev, void *user_data) +{ + ARG_UNUSED(user_data); + + while (uart_irq_update(dev) && uart_irq_is_pending(dev)) { + + if (uart_irq_rx_ready(dev)) { + uart_rx_handle(dev); + } + + if (uart_irq_tx_ready(dev) && + atomic_get(&ot_uart.tx_busy) == 1) { + uart_tx_handle(dev); + } + } +} + +void otPlatUartReceived(const uint8_t *aBuf, uint16_t aBufLength) +{ + otNcpHdlcReceive(aBuf, aBufLength); +} + +void otPlatUartSendDone(void) +{ + otNcpHdlcSendDone(); +} + +void platformUartProcess(otInstance *aInstance) +{ + uint32_t len = 0; + const uint8_t *data; + + /* Process UART RX */ + while ((len = ring_buf_get_claim( + ot_uart.rx_ringbuf, + (uint8_t **)&data, + ot_uart.rx_ringbuf->size)) > 0) { + int err; + + otPlatUartReceived(data, len); + err = ring_buf_get_finish( + ot_uart.rx_ringbuf, + len); + (void)err; + __ASSERT_NO_MSG(err == 0); + } + + /* Process UART TX */ + if (ot_uart.tx_finished) { + LOG_DBG("UART TX done"); + otPlatUartSendDone(); + ot_uart.tx_finished = 0; + } +} + +otError otPlatUartEnable(void) +{ + ot_uart.dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_ot_uart)); + + if (!device_is_ready(ot_uart.dev)) { + LOG_ERR("UART device not ready"); + return OT_ERROR_FAILED; + } + + uart_irq_callback_user_data_set(ot_uart.dev, + uart_callback, + (void *)&ot_uart); + + if (DT_NODE_HAS_COMPAT(DT_CHOSEN(zephyr_ot_uart), zephyr_cdc_acm_uart)) { + int ret; + uint32_t dtr = 0U; + + ret = usb_enable(NULL); + if (ret != 0) { + LOG_ERR("Failed to enable USB"); + return OT_ERROR_FAILED; + } + + LOG_INF("Waiting for host to be ready to communicate"); + + /* Data Terminal Ready - check if host is ready to communicate */ + while (!dtr) { + ret = uart_line_ctrl_get(ot_uart.dev, + UART_LINE_CTRL_DTR, &dtr); + if (ret) { + LOG_ERR("Failed to get Data Terminal Ready line state: %d", + ret); + continue; + } + k_msleep(100); + } + + /* Data Carrier Detect Modem - mark connection as established */ + (void)uart_line_ctrl_set(ot_uart.dev, UART_LINE_CTRL_DCD, 1); + /* Data Set Ready - the NCP SoC is ready to communicate */ + (void)uart_line_ctrl_set(ot_uart.dev, UART_LINE_CTRL_DSR, 1); + } + + uart_irq_rx_enable(ot_uart.dev); + + return OT_ERROR_NONE; +} + +otError otPlatUartDisable(void) +{ + if (DT_NODE_HAS_COMPAT(DT_CHOSEN(zephyr_ot_uart), zephyr_cdc_acm_uart)) { + int ret = usb_disable(); + + if (ret) { + LOG_WRN("Failed to disable USB (%d)", ret); + } + } + + uart_irq_tx_disable(ot_uart.dev); + uart_irq_rx_disable(ot_uart.dev); + return OT_ERROR_NONE; +} + +otError otPlatUartSend(const uint8_t *aBuf, uint16_t aBufLength) +{ + if (aBuf == NULL) { + return OT_ERROR_FAILED; + } + + if (atomic_cas(&(ot_uart.tx_busy), 0, 1)) { + write_buffer = aBuf; + write_length = aBufLength; + + if (is_panic_mode) { + /* In panic mode all data have to be send immediately + * without using interrupts + */ + otPlatUartFlush(); + } else { + uart_irq_tx_enable(ot_uart.dev); + } + return OT_ERROR_NONE; + } + + return OT_ERROR_BUSY; +} + +otError otPlatUartFlush(void) +{ + otError result = OT_ERROR_NONE; + + if (write_length) { + for (size_t i = 0; i < write_length; i++) { + uart_poll_out(ot_uart.dev, *(write_buffer+i)); + } + } + + ot_uart.tx_busy = 0; + atomic_set(&(ot_uart.tx_finished), 1); + otSysEventSignalPending(); + return result; +} + +void platformUartPanic(void) +{ + is_panic_mode = true; + /* In panic mode data are send without using interrupts. + * Reception in this mode is not supported. + */ + uart_irq_tx_disable(ot_uart.dev); + uart_irq_rx_disable(ot_uart.dev); +} diff --git a/pool/shard003/C/0065650_ss_context_mgr.c b/pool/shard003/C/0065650_ss_context_mgr.c new file mode 100644 index 0000000000000000000000000000000000000000..de62378a53853abc2bdfe1fd24b260f6ad008034 --- /dev/null +++ b/pool/shard003/C/0065650_ss_context_mgr.c @@ -0,0 +1,178 @@ +/**************************************************************** + * * + * Copyright 2009, 2014 Fidelity Information Services, Inc * + * * + * This source code contains the intellectual property * + * of its copyright holder(s), and is made available * + * under a license. If you do not know the terms of * + * the license, please stop and do not read further. * + * * + ****************************************************************/ +#include "mdef.h" + +#include "gtm_fcntl.h" +#include "gtm_stat.h" +#include "gtm_unistd.h" +#include +#include +#include "gtm_permissions.h" +#include "gtm_string.h" +#include "gtm_stdio.h" +#include "gtm_stdlib.h" +#include "gtm_tempnam.h" +#include "gtm_time.h" +#ifdef DEBUG +#include "gtm_ipc.h" +#endif + +#include "gdsroot.h" +#include "gdskill.h" +#include "gtm_facility.h" +#include "fileinfo.h" +#include "gdsbt.h" +#include "gdsblk.h" +#include "gdsfhead.h" +#include "filestruct.h" +#include "iosp.h" +#include "error.h" +#include "cli.h" +#include "eintr_wrappers.h" +#include "gtmio.h" +#include "repl_sp.h" +#include "gtm_file_stat.h" +#include "util.h" +#include "gtm_caseconv.h" +#include "gt_timer.h" +#include "is_proc_alive.h" +#include "is_file_identical.h" +#include "dbfilop.h" +#include "wcs_flu.h" +#include "jnl.h" +#include "interlock.h" +#include "sleep_cnt.h" +#include "mupip_exit.h" +#include "trans_log_name.h" +#include "gtmimagename.h" +#include "send_msg.h" +#include "gtm_logicals.h" +#include "memcoherency.h" +#ifdef __MVS__ +#include "gtm_zos_io.h" +#endif +#include "shmpool.h" +#include "db_snapshot.h" +#include "do_shmat.h" + +GBLREF sgmnt_addrs *cs_addrs; +GBLREF enum gtmImageTypes image_type; +GBLREF uint4 process_id; + +error_def(ERR_SYSCALL); + +boolean_t ss_create_context(snapshot_context_ptr_t lcl_ss_ctx, int ss_shmcycle) +{ + shm_snapshot_ptr_t ss_shm_ptr; + node_local_ptr_t cnl; + sgmnt_addrs *csa; + int shdw_fd, status; + void *ss_shmaddr; + ZOS_ONLY(int realfiletag;) + + ZOS_ONLY(error_def(ERR_BADTAG);) + ZOS_ONLY(error_def(ERR_TEXT);) + + assert(NULL != cs_addrs); + csa = cs_addrs; + cnl = csa->nl; + + ss_destroy_context(lcl_ss_ctx); /* Before creating a new one relinquish the existing one */ + lcl_ss_ctx->ss_shmcycle = ss_shmcycle; + /* SS_MULTI: In case of multiple snapshots, we can't assume that the first index of the snapshot structure in the db + * shared memory is the currently active snapshot. + */ + assert(1 == MAX_SNAPSHOTS); /* This assert will fail when we increase the MAX_SNAPSHOTS per region */ + ss_shm_ptr = (shm_snapshot_ptr_t)SS_GETSTARTPTR(csa); + DBG_ENSURE_PTR_WITHIN_SS_BOUNDS(csa, (sm_uc_ptr_t)ss_shm_ptr); + /* The below memory barrier will ensure that if ever the shmcycle is modified in ss_initiate, we get the up to date + * values of the other members in the snapshot structure (copied below). + */ + SHM_READ_MEMORY_BARRIER; + STRCPY(lcl_ss_ctx->shadow_file, ss_shm_ptr->ss_info.shadow_file); + lcl_ss_ctx->total_blks = ss_shm_ptr->ss_info.total_blks; + lcl_ss_ctx->shadow_vbn = ss_shm_ptr->ss_info.shadow_vbn; + lcl_ss_ctx->ss_shm_ptr = ss_shm_ptr; + lcl_ss_ctx->nl_shmid = cnl->ss_shmid; + /* Attach to the shared memory created by snapshot */ + if (INVALID_SHMID != lcl_ss_ctx->nl_shmid) + { + if (-1 == (sm_long_t)(ss_shmaddr = do_shmat(lcl_ss_ctx->nl_shmid, 0, 0))) + { + status = errno; + /* It's possible that by the time we attach to the shared memory, the identifier has been removed from the + * system by INTEG which completed it's processing. + */ + assert(SHM_REMOVED(status)); + assert(INVALID_SHMID == lcl_ss_ctx->attach_shmid); + lcl_ss_ctx->cur_state = SNAPSHOT_SHM_ATTACH_FAIL; + lcl_ss_ctx->failure_errno = status; + return FALSE; + } + lcl_ss_ctx->attach_shmid = lcl_ss_ctx->nl_shmid; + lcl_ss_ctx->start_shmaddr = (sm_uc_ptr_t)ss_shmaddr; + lcl_ss_ctx->bitmap_addr = ((sm_uc_ptr_t)ss_shmaddr + SNAPSHOT_HDR_SIZE); + } else + { /* No ongoing snapshots. Do early return. t_end and tp_tend during validation will identify this change in state + * and will turn off snapshot activities + */ + lcl_ss_ctx->start_shmaddr = NULL; + lcl_ss_ctx->bitmap_addr = NULL; + lcl_ss_ctx->cur_state = SNAPSHOT_NOT_INITED; + return FALSE; + } + OPENFILE(lcl_ss_ctx->shadow_file, O_RDWR, shdw_fd); + lcl_ss_ctx->shdw_fd = shdw_fd; + if (FD_INVALID == shdw_fd) + { + assert((NULL != ss_shmaddr) + && (-1 != lcl_ss_ctx->attach_shmid)); /* shared memory attach SHOULD have succeeded */ + if (-1 == SHMDT(ss_shmaddr)) + { + status = errno; + assert(FALSE); + rts_error_csa(CSA_ARG(NULL) VARLSTCNT(8) ERR_SYSCALL, 5, LEN_AND_LIT("Error with shmdt"), CALLFROM, status); + } + lcl_ss_ctx->attach_shmid = lcl_ss_ctx->nl_shmid = INVALID_SHMID; /* reset shmid since we failed */ + lcl_ss_ctx->cur_state = SHADOW_FIL_OPEN_FAIL; + lcl_ss_ctx->failure_errno = errno; + return FALSE; + } +# ifdef __MVS__ + if (-1 == gtm_zos_tag_to_policy(shdw_fd, TAG_BINARY, &realfiletag)) + TAG_POLICY_SEND_MSG(ss_shm_ptr->ss_info.shadow_file, errno, realfiletag, TAG_BINARY); +# endif + lcl_ss_ctx->cur_state = SNAPSHOT_INIT_DONE; + return TRUE; +} + +boolean_t ss_destroy_context(snapshot_context_ptr_t lcl_ss_ctx) +{ + int status; + + assert(NULL != lcl_ss_ctx); + if (FD_INVALID != lcl_ss_ctx->shdw_fd) + { + CLOSEFILE_RESET(lcl_ss_ctx->shdw_fd, status); + } + if (INVALID_SHMID != lcl_ss_ctx->attach_shmid) + { + if (0 != SHMDT((void *)(lcl_ss_ctx->start_shmaddr))) + { + status = errno; + assert(FALSE); + rts_error_csa(CSA_ARG(NULL) VARLSTCNT(8) ERR_SYSCALL, 5, LEN_AND_LIT("Error with shmdt"), CALLFROM, status); + } + } + /* Invalidate the context */ + DEFAULT_INIT_SS_CTX(lcl_ss_ctx); + return TRUE; +} diff --git a/pool/shard003/C/0065672_MathUtility.c b/pool/shard003/C/0065672_MathUtility.c new file mode 100644 index 0000000000000000000000000000000000000000..acec9f5abc07b7c1abdb2090648a891cd2acc2af --- /dev/null +++ b/pool/shard003/C/0065672_MathUtility.c @@ -0,0 +1,138 @@ +#include "MathUtility.h" +#include "TypeConvertor.h" +#include + +double LOG_LOW_BOUND = -700; +double LOG_ARG_BOUND = 1e-300; +double EXP_LOW_BOUND = 1e-300; +double EXP_ARG_BOUND = -700.0; + +double +SafeLog(double arg) +{ + return arg < LOG_ARG_BOUND ? LOG_LOW_BOUND : log(arg); +} + +double +SafeExp(double arg) +{ + return arg < EXP_ARG_BOUND ? EXP_LOW_BOUND : exp(arg); +} + +double +ToSafeLog(double arg) +{ + return arg < LOG_LOW_BOUND ? LOG_LOW_BOUND : arg; +} + +double +LogSum(double a, double b) +{ + if (a < b) + { + return ToSafeLog((a - b) < EXP_ARG_BOUND ? b : (b + SafeLog(1 + SafeExp(a - b)))); + } + else + { + return ToSafeLog((b - a) < EXP_ARG_BOUND ? a : (a + SafeLog(1 + SafeExp(b - a)))); + } +} + +static double LOG_2_PI = 1.8378770664093453; + +double +LogGaussian(const double *x, const double *mean, const double *log_var, int dim) +{ + double sharpness = 1e5; + //double log_prob = -LOG_2_PI * dim; + double log_prob = 0.0; + + double diff; + int k; + for (k = 0; k < dim; k++) + { + diff = x[k] - mean[k]; + log_prob -= diff * diff / SafeExp(log_var[k]) / sharpness; + } + return ToSafeLog(0.5 * log_prob); +} + +void LogEmitProb(Array *log_b, const Array *mean, const Array *log_var, const Matrix *observations) +{ + int N, M, T, L; + N = mean->row; + M = mean->col; + T = observations->row; + L = observations->col; + double temp; + int i, m, t; + for (i = 0; i < N; i++) + { + for (m = 0; m < M; m++) + { + for (t = 0; t < T; t++) + { + log_b->array[i * M * T + m * T + t] = LogGaussian(&observations->mat[t * L], &mean->array[i * M * L + m * L], &log_var->array[i * M * L + m * L], L); + } + } + } + return; +} + +void LogMixEmitProb(Matrix *log_mix_b, const Array *log_b, const Matrix *log_coef) +{ + int N, M, T; + N = log_b->row; + M = log_b->col; + T = log_b->lay; + int i, m, t; + double temp; + for (i = 0; i < N; i++) + { + for (t = 0; t < T; t++) + { + temp = ToSafeLog(log_coef->mat[i * M] + log_b->array[i * M * T + t]); + for (m = 1; m < M; m++) + { + temp = LogSum(temp, log_coef->mat[i * M + m] + log_b->array[i * M * T + m * T + t]); + } + log_mix_b->mat[i * T + t] = temp; + } + } + return; +} + +double +GetLogTrans(const CSRMatrix *log_trans, int i, int j) +{ + int k; + for (k = log_trans->row_ptr[i]; k < log_trans->row_ptr[i + 1]; k++) + { + if (log_trans->col_idx[k] == j) + { + return log_trans->val[k]; + } + } + return LOG_LOW_BOUND; +} + +double +GetLogInit(const SparseVector *log_init, int i) +{ + int k; + for (k = 0; k < log_init->nnz; k++) + { + if (log_init->idx[k] == i) + { + return log_init->data[k]; + } + } + return LOG_LOW_BOUND; +} + +double +RandRange(double a, double b) +{ + srand(time(NULL)); + return a + (b - a) * rand() * 1.0 / RAND_MAX; +} diff --git a/pool/shard003/C/0065681_teaambient.c b/pool/shard003/C/0065681_teaambient.c new file mode 100644 index 0000000000000000000000000000000000000000..62c091c70a614d17972324bdc1b8fab2b375eedd --- /dev/null +++ b/pool/shard003/C/0065681_teaambient.c @@ -0,0 +1,148 @@ + +/* Copyright (c) Mark J. Kilgard, 1994. */ + +/** + * (c) Copyright 1993, Silicon Graphics, Inc. + * ALL RIGHTS RESERVED + * Permission to use, copy, modify, and distribute this software for + * any purpose and without fee is hereby granted, provided that the above + * copyright notice appear in all copies and that both the copyright notice + * and this permission notice appear in supporting documentation, and that + * the name of Silicon Graphics, Inc. not be used in advertising + * or publicity pertaining to distribution of the software without specific, + * written prior permission. + * + * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" + * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR + * FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON + * GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, + * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY + * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, + * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF + * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN + * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE + * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. + * + * US Government Users Restricted Rights + * Use, duplication, or disclosure by the Government is subject to + * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph + * (c)(1)(ii) of the Rights in Technical Data and Computer Software + * clause at DFARS 252.227-7013 and/or in similar or successor + * clauses in the FAR or the DOD or NASA FAR Supplement. + * Unpublished-- rights reserved under the copyright laws of the + * United States. Contractor/manufacturer is Silicon Graphics, + * Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311. + * + * OpenGL(TM) is a trademark of Silicon Graphics, Inc. + */ +/** + * teaambient.c + * This program renders three lighted, shaded teapots, with + * different ambient values. + */ +#include +#include + +/* Initialize light source and lighting model. + */ +void +myinit(void) +{ + GLfloat light_ambient[] = + {0.0, 0.0, 0.0, 1.0}; + GLfloat light_diffuse[] = + {1.0, 1.0, 1.0, 1.0}; + GLfloat light_specular[] = + {1.0, 1.0, 1.0, 1.0}; +/* light_position is NOT default value */ + GLfloat light_position[] = + {1.0, 0.0, 0.0, 0.0}; + GLfloat global_ambient[] = + {0.75, 0.75, 0.75, 1.0}; + + glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); + glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); + glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); + glLightfv(GL_LIGHT0, GL_POSITION, light_position); + + glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); + + glFrontFace(GL_CW); + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT0); + glEnable(GL_AUTO_NORMAL); + glEnable(GL_NORMALIZE); + glDepthFunc(GL_LESS); + glEnable(GL_DEPTH_TEST); +} + +void +display(void) +{ + GLfloat low_ambient[] = + {0.1, 0.1, 0.1, 1.0}; + GLfloat more_ambient[] = + {0.4, 0.4, 0.4, 1.0}; + GLfloat most_ambient[] = + {1.0, 1.0, 1.0, 1.0}; + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + /* material has small ambient reflection */ + glMaterialfv(GL_FRONT, GL_AMBIENT, low_ambient); + glMaterialf(GL_FRONT, GL_SHININESS, 40.0); + glPushMatrix(); + glTranslatef(0.0, 2.0, 0.0); + glutSolidTeapot(1.0); + glPopMatrix(); + + /* material has moderate ambient reflection */ + glMaterialfv(GL_FRONT, GL_AMBIENT, more_ambient); + glPushMatrix(); + glTranslatef(0.0, 0.0, 0.0); + glutSolidTeapot(1.0); + glPopMatrix(); + + /* material has large ambient reflection */ + glMaterialfv(GL_FRONT, GL_AMBIENT, most_ambient); + glPushMatrix(); + glTranslatef(0.0, -2.0, 0.0); + glutSolidTeapot(1.0); + glPopMatrix(); + glFlush(); +} + +void +myReshape(int w, int h) +{ + glViewport(0, 0, w, h); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + if (w <= h) + glOrtho(-4.0, 4.0, -4.0 * (GLfloat) h / (GLfloat) w, + 4.0 * (GLfloat) h / (GLfloat) w, -10.0, 10.0); + else + glOrtho(-4.0 * (GLfloat) w / (GLfloat) h, + 4.0 * (GLfloat) w / (GLfloat) h, -4.0, 4.0, -10.0, 10.0); + glMatrixMode(GL_MODELVIEW); +} + +/* Main Loop + * Open window with initial window size, title bar, + * RGBA display mode, and handle input events. + */ +int +main(int argc, char **argv) +{ + glutInit(&argc, argv); + glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH); + glutInitWindowSize(500, 500); + glutCreateWindow(argv[0]); + myinit(); + glutReshapeFunc(myReshape); + glutDisplayFunc(display); + glutMainLoop(); + return 0; /* ANSI C requires main to return int. */ +} diff --git a/pool/shard003/C/0065685_debug.c b/pool/shard003/C/0065685_debug.c new file mode 100644 index 0000000000000000000000000000000000000000..fc990430677c776432a613ef227ac66469944d4a --- /dev/null +++ b/pool/shard003/C/0065685_debug.c @@ -0,0 +1,107 @@ +/********************************************************************* + * + * Copyright (C) 2006, Blekinge Institute of Technology + * + * Filename: debug.c + * Author: Simon Kagstrom + * Description: Cibyl debugging stuff + * + * $Id:$ + * + ********************************************************************/ +#include +#include + +#include + +unsigned long cibyl_debug_regs[NREGS]; +static unsigned long stack_start; + +static const char *regnr_to_name[NREGS] = +{ + [R_ZERO] = "zero", [R_AT] = " at", [R_V0] = " v0", + [R_V1] = " v1", [R_A0] = " a0", [R_A1] = " a1", + [R_A2] = " a2", [R_A3] = " a3", [R_T0] = " t0", + [R_T1] = " t1", [R_T2] = " t2", [R_T3] = " t3", + [R_T4] = " t4", [R_T5] = " t5", [R_T6] = " t6", + [R_T7] = " t7", [R_S0] = " s0", [R_S1] = " s1", + [R_S2] = " s2", [R_S3] = " s3", [R_S4] = " s4", + [R_S5] = " s5", [R_S6] = " s6", [R_S7] = " s7", + [R_T8] = " t8", [R_T9] = " t9", [R_K0] = " k0", + [R_K1] = " k1", [R_GP] = " gp", [R_SP] = " sp", + [R_FP] = " fp", [R_RA] = " ra", +}; + +static void __attribute__((constructor)) setup_debug_support(void) +{ + register unsigned long sp asm("$29"); + + stack_start = sp; +} + + +static int is_valid(unsigned int addr) +{ + if (addr <= stack_start) + return 1; + return 0; +} + + +void cibyl_dump_stack_helper(void) +{ + int i; + unsigned long *regs = cibyl_debug_regs; + unsigned long *p_stk = (unsigned long*)regs[R_SP]; + + printf("Registers:"); + for (i=0; i < NREGS; i++) + { + if (i % 4 == 0) + printf("\n"); + printf("%s: 0x%08x ", regnr_to_name[i], (unsigned int)regs[i]); + } + + printf("\n\nStack (starts at 0x%lx):", stack_start); + for (i=0; i < 16; i++) + { + /* Check that the stack pointer is within valid memory */ + if (!is_valid( (unsigned long)&p_stk[i]) ) + break; + if (i % 5 == 0) + printf("\n" + "0x%08x: ", (unsigned int)&(p_stk[i])); + printf("0x%08x ", (unsigned int)p_stk[i]); + } + printf("\n"); +} + +/* --- Cibyl/Qemu implementation --- */ +volatile uint32_t *cibyl_device = (volatile uint32_t*)0x10000000; + +/* Exception handler for reserved instructions */ +uint32_t __qemu_reserved(uint32_t *saved_regs, + uint32_t c0_status, uint32_t c0_cause, uint32_t c0_epc) +{ + uint32_t *insn = (uint32_t*)c0_epc; + + /* FIXME: Check if this really is valid */ + if ( (((*insn) >> 24) & 0xfe) == 0xfe ) + *cibyl_device = saved_regs[(*insn) & 0xffff]; + + if ( (((*insn) >> 24) & 0xff) == 0xff ) + { + *(cibyl_device+1) = *insn; + /* This was a call, now read the return value */ + saved_regs[R_V0] = *cibyl_device; + } + + return c0_epc + 4; +} + +uint32_t __qemu_default(uint32_t *saved_regs, + uint32_t c0_status, uint32_t c0_cause, uint32_t c0_epc) +{ + return c0_epc + 4; +} + diff --git a/pool/shard003/C/0065687_tzeta_ui.c b/pool/shard003/C/0065687_tzeta_ui.c new file mode 100644 index 0000000000000000000000000000000000000000..7b0696432bded6014b99c8403444eb9d3ee71a54 --- /dev/null +++ b/pool/shard003/C/0065687_tzeta_ui.c @@ -0,0 +1,205 @@ +/* Test file for mpfr_zeta_ui. + +Copyright 2005-2021 Free Software Foundation, Inc. +Contributed by the AriC and Caramba projects, INRIA. + +This file is part of the GNU MPFR Library. + +The GNU MPFR 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 3 of the License, or (at your +option) any later version. + +The GNU MPFR 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 the GNU MPFR Library; see the file COPYING.LESSER. If not, see +https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#include "mpfr-test.h" + +#define TEST_FUNCTION mpfr_zeta_ui + +int +main (int argc, char *argv[]) +{ + unsigned int prec, yprec; + int rnd; + mpfr_t x, y, z, t; + unsigned long n; + int inex; + mpfr_exp_t emin, emax; + mpfr_flags_t flags, ex_flags; + int i; + + tests_start_mpfr (); + + emin = mpfr_get_emin (); + emax = mpfr_get_emax (); + + mpfr_init (x); + mpfr_init (y); + mpfr_init (z); + mpfr_init (t); + + if (argc >= 3) /* tzeta_ui n prec [rnd] */ + { + mpfr_set_prec (x, atoi (argv[2])); + mpfr_zeta_ui (x, atoi (argv[1]), + argc > 3 ? (mpfr_rnd_t) atoi (argv[3]) : MPFR_RNDN); + mpfr_out_str (stdout, 10, 0, x, MPFR_RNDN); + printf ("\n"); + goto clear_and_exit; + } + + mpfr_set_prec (x, 33); + mpfr_set_prec (y, 33); + mpfr_zeta_ui (x, 3, MPFR_RNDZ); + mpfr_set_str_binary (y, "0.100110011101110100000000001001111E1"); + if (mpfr_cmp (x, y)) + { + printf ("Error for zeta(3), prec=33, MPFR_RNDZ\n"); + printf ("expected "); mpfr_dump (y); + printf ("got "); mpfr_dump (x); + exit (1); + } + + mpfr_clear_flags (); + inex = mpfr_zeta_ui (x, 0, MPFR_RNDN); + flags = __gmpfr_flags; + MPFR_ASSERTN (inex == 0 && mpfr_cmp_si_2exp (x, -1, -1) == 0 && flags == 0); + + for (i = -2; i <= 2; i += 2) + RND_LOOP_NO_RNDF (rnd) + { + int ex_inex; + + set_emin (i); + set_emax (i); + mpfr_clear_flags (); + inex = mpfr_zeta_ui (x, 0, (mpfr_rnd_t) rnd); + flags = __gmpfr_flags; + if (i < 0) + { + mpfr_set_inf (y, -1); + if (rnd == MPFR_RNDU || rnd == MPFR_RNDZ) + { + mpfr_nextabove (y); + ex_inex = 1; + } + else + { + ex_inex = -1; + } + ex_flags = MPFR_FLAGS_OVERFLOW | MPFR_FLAGS_INEXACT; + } + else if (i > 0) + { + mpfr_set_zero (y, -1); + if (rnd == MPFR_RNDD || rnd == MPFR_RNDA) + { + mpfr_nextbelow (y); + ex_inex = -1; + } + else + { + ex_inex = 1; + } + ex_flags = MPFR_FLAGS_UNDERFLOW | MPFR_FLAGS_INEXACT; + } + else + { + mpfr_set_str_binary (y, "-1e-1"); + ex_inex = 0; + ex_flags = 0; + } + set_emin (emin); + set_emax (emax); + if (! (mpfr_equal_p (x, y) && MPFR_IS_NEG (x) && + SAME_SIGN (inex, ex_inex) && flags == ex_flags)) + { + printf ("Failure for zeta(0) in %s, exponent range [%d,%d]\n", + mpfr_print_rnd_mode ((mpfr_rnd_t) rnd), i, i); + printf ("Expected "); + mpfr_dump (y); + printf (" with inex ~ %d, flags =", ex_inex); + flags_out (ex_flags); + printf ("Got "); + mpfr_dump (x); + printf (" with inex = %d, flags =", inex); + flags_out (flags); + exit (1); + } + } + + mpfr_clear_divby0 (); + inex = mpfr_zeta_ui (x, 1, MPFR_RNDN); + MPFR_ASSERTN (inex == 0 && MPFR_IS_INF (x) && MPFR_IS_POS (x) + && mpfr_divby0_p ()); + + for (prec = MPFR_PREC_MIN; prec <= 100; prec++) + { + mpfr_set_prec (x, prec); + mpfr_set_prec (z, prec); + mpfr_set_prec (t, prec); + yprec = prec + 10; + mpfr_set_prec (y, yprec); + + for (n = 0; n < 50; n++) + RND_LOOP_NO_RNDF (rnd) + { + mpfr_zeta_ui (y, n, MPFR_RNDN); + if (mpfr_can_round (y, yprec, MPFR_RNDN, MPFR_RNDZ, prec + + (rnd == MPFR_RNDN))) + { + mpfr_set (t, y, (mpfr_rnd_t) rnd); + for (i = 0; i <= 1; i++) + { + if (i) + { + mpfr_exp_t e; + + if (MPFR_IS_SINGULAR (t)) + break; + e = mpfr_get_exp (t); + set_emin (e); + set_emax (e); + } + mpfr_zeta_ui (z, n, (mpfr_rnd_t) rnd); + if (i) + { + set_emin (emin); + set_emax (emax); + } + if (mpfr_cmp (t, z)) + { + printf ("results differ for n = %lu, prec = %u," + " %s%s\n", n, prec, + mpfr_print_rnd_mode ((mpfr_rnd_t) rnd), + i ? ", reduced exponent range" : ""); + printf (" got "); + mpfr_dump (z); + printf (" expected "); + mpfr_dump (t); + printf (" approx "); + mpfr_dump (y); + exit (1); + } + } + } + } + } + + clear_and_exit: + mpfr_clear (x); + mpfr_clear (y); + mpfr_clear (z); + mpfr_clear (t); + + tests_end_mpfr (); + return 0; +} diff --git a/pool/shard003/C/0065691_ecc-384.c b/pool/shard003/C/0065691_ecc-384.c new file mode 100644 index 0000000000000000000000000000000000000000..94b8af91354e767b7a7232d955218226f9588730 --- /dev/null +++ b/pool/shard003/C/0065691_ecc-384.c @@ -0,0 +1,215 @@ +/* ecc-384.c + + Compile time constant (but machine dependent) tables. + + Copyright (C) 2013, 2014 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * 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. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +/* Development of Nettle's ECC support was funded by the .SE Internet Fund. */ + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include + +#include "ecc.h" +#include "ecc-internal.h" + +#define USE_REDC 0 + +#include "ecc-384.h" + +#if HAVE_NATIVE_ecc_384_modp +#define ecc_384_modp nettle_ecc_384_modp +void +ecc_384_modp (const struct ecc_modulo *m, mp_limb_t *rp); +#elif GMP_NUMB_BITS == 32 + +/* Use that 2^{384} = 2^{128} + 2^{96} - 2^{32} + 1, and eliminate 256 + bits at a time. + + We can get carry == 2 in the first iteration, and I think *only* in + the first iteration. */ + +/* p is 12 limbs, and B^12 - p = B^4 + B^3 - B + 1. We can eliminate + almost 8 at a time. Do only 7, to avoid additional carry + propagation, followed by 5. */ +static void +ecc_384_modp (const struct ecc_modulo *p, mp_limb_t *rp) +{ + mp_limb_t cy, bw; + + /* Reduce from 24 to 17 limbs. */ + cy = mpn_add_n (rp + 4, rp + 4, rp + 16, 8); + cy = sec_add_1 (rp + 12, rp + 12, 3, cy); + + bw = mpn_sub_n (rp + 5, rp + 5, rp + 16, 8); + bw = sec_sub_1 (rp + 13, rp + 13, 3, bw); + + cy += mpn_add_n (rp + 7, rp + 7, rp + 16, 8); + cy = sec_add_1 (rp + 15, rp + 15, 1, cy); + + cy += mpn_add_n (rp + 8, rp + 8, rp + 16, 8); + assert (bw <= cy); + cy -= bw; + + assert (cy <= 2); + rp[16] = cy; + + /* Reduce from 17 to 12 limbs */ + cy = mpn_add_n (rp, rp, rp + 12, 5); + cy = sec_add_1 (rp + 5, rp + 5, 3, cy); + + bw = mpn_sub_n (rp + 1, rp + 1, rp + 12, 5); + bw = sec_sub_1 (rp + 6, rp + 6, 6, bw); + + cy += mpn_add_n (rp + 3, rp + 3, rp + 12, 5); + cy = sec_add_1 (rp + 8, rp + 8, 1, cy); + + cy += mpn_add_n (rp + 4, rp + 4, rp + 12, 5); + cy = sec_add_1 (rp + 9, rp + 9, 3, cy); + + assert (cy >= bw); + cy -= bw; + assert (cy <= 1); + cy = cnd_add_n (cy, rp, p->B, ECC_LIMB_SIZE); + assert (cy == 0); +} +#elif GMP_NUMB_BITS == 64 +/* p is 6 limbs, and B^6 - p = B^2 + 2^32 (B - 1) + 1. Eliminate 3 + (almost 4) limbs at a time. */ +static void +ecc_384_modp (const struct ecc_modulo *p, mp_limb_t *rp) +{ + mp_limb_t tp[6]; + mp_limb_t cy; + + /* Reduce from 12 to 9 limbs */ + tp[0] = 0; /* FIXME: Could use mpn_sub_nc */ + mpn_copyi (tp + 1, rp + 8, 3); + tp[4] = rp[11] - mpn_sub_n (tp, tp, rp + 8, 4); + tp[5] = mpn_lshift (tp, tp, 5, 32); + + cy = mpn_add_n (rp + 2, rp + 2, rp + 8, 4); + cy = sec_add_1 (rp + 6, rp + 6, 2, cy); + + cy += mpn_add_n (rp + 2, rp + 2, tp, 6); + cy += mpn_add_n (rp + 4, rp + 4, rp + 8, 4); + + assert (cy <= 2); + rp[8] = cy; + + /* Reduce from 9 to 6 limbs */ + tp[0] = 0; + mpn_copyi (tp + 1, rp + 6, 2); + tp[3] = rp[8] - mpn_sub_n (tp, tp, rp + 6, 3); + tp[4] = mpn_lshift (tp, tp, 4, 32); + + cy = mpn_add_n (rp, rp, rp + 6, 3); + cy = sec_add_1 (rp + 3, rp + 3, 2, cy); + cy += mpn_add_n (rp, rp, tp, 5); + cy += mpn_add_n (rp + 2, rp + 2, rp + 6, 3); + + cy = sec_add_1 (rp + 5, rp + 5, 1, cy); + assert (cy <= 1); + + cy = cnd_add_n (cy, rp, p->B, ECC_LIMB_SIZE); + assert (cy == 0); +} +#else +#define ecc_384_modp ecc_mod +#endif + +const struct ecc_curve _nettle_secp_384r1 = +{ + { + 384, + ECC_LIMB_SIZE, + ECC_BMODP_SIZE, + ECC_REDC_SIZE, + ECC_MOD_INV_ITCH (ECC_LIMB_SIZE), + 0, + + ecc_p, + ecc_Bmodp, + ecc_Bmodp_shifted, + ecc_redc_ppm1, + ecc_pp1h, + + ecc_384_modp, + ecc_384_modp, + ecc_mod_inv, + NULL, + }, + { + 384, + ECC_LIMB_SIZE, + ECC_BMODQ_SIZE, + 0, + ECC_MOD_INV_ITCH (ECC_LIMB_SIZE), + 0, + + ecc_q, + ecc_Bmodq, + ecc_Bmodq_shifted, + NULL, + ecc_qp1h, + + ecc_mod, + ecc_mod, + ecc_mod_inv, + NULL, + }, + + USE_REDC, + ECC_PIPPENGER_K, + ECC_PIPPENGER_C, + + ECC_ADD_JJJ_ITCH (ECC_LIMB_SIZE), + ECC_MUL_A_ITCH (ECC_LIMB_SIZE), + ECC_MUL_G_ITCH (ECC_LIMB_SIZE), + ECC_J_TO_A_ITCH (ECC_LIMB_SIZE), + + ecc_add_jjj, + ecc_mul_a, + ecc_mul_g, + ecc_j_to_a, + + ecc_b, + ecc_g, + NULL, + ecc_unit, + ecc_table +}; + +const struct ecc_curve *nettle_get_secp_384r1(void) +{ + return &_nettle_secp_384r1; +} diff --git a/pool/shard003/C/0065714_tps65911-comparator.c b/pool/shard003/C/0065714_tps65911-comparator.c new file mode 100644 index 0000000000000000000000000000000000000000..3700c79fdc4e01f37b2b171a4899fc518ce5a1d0 --- /dev/null +++ b/pool/shard003/C/0065714_tps65911-comparator.c @@ -0,0 +1,224 @@ +/* + * tps65910.c -- TI TPS6591x + * + * Copyright 2010 Texas Instruments Inc. + * + * Author: Jorge Eduardo Candelaria + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define COMP 0 +#define COMP1 1 +#define COMP2 2 + +/* Comparator 1 voltage selection table in millivolts */ +static const u16 COMP_VSEL_TABLE[] = +{ + 0, 2500, 2500, 2500, 2500, 2550, 2600, 2650, + 2700, 2750, 2800, 2850, 2900, 2950, 3000, 3050, + 3100, 3150, 3200, 3250, 3300, 3350, 3400, 3450, + 3500, +}; + +struct comparator +{ + const char *name; + int reg; + int uV_max; + const u16 *vsel_table; +}; + +static struct comparator tps_comparators[] = +{ + { + .name = "COMP1", + .reg = TPS65911_VMBCH, + .uV_max = 3500, + .vsel_table = COMP_VSEL_TABLE, + }, + { + .name = "COMP2", + .reg = TPS65911_VMBCH2, + .uV_max = 3500, + .vsel_table = COMP_VSEL_TABLE, + }, +}; + +static int comp_threshold_set(struct tps65910 *tps65910, int id, int voltage) +{ + struct comparator tps_comp = tps_comparators[id]; + int curr_voltage = 0; + int ret; + u8 index = 0, val; + + if (id == COMP) + { + return 0; + } + + while (curr_voltage < tps_comp.uV_max) + { + curr_voltage = tps_comp.vsel_table[index]; + + if (curr_voltage >= voltage) + { + break; + } + else if (curr_voltage < voltage) + { + index ++; + } + } + + if (curr_voltage > tps_comp.uV_max) + { + return -EINVAL; + } + + val = index << 1; + ret = tps65910->write(tps65910, tps_comp.reg, 1, &val); + + return ret; +} + +static int comp_threshold_get(struct tps65910 *tps65910, int id) +{ + struct comparator tps_comp = tps_comparators[id]; + int ret; + u8 val; + + if (id == COMP) + { + return 0; + } + + ret = tps65910->read(tps65910, tps_comp.reg, 1, &val); + + if (ret < 0) + { + return ret; + } + + val >>= 1; + return tps_comp.vsel_table[val]; +} + +static ssize_t comp_threshold_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct tps65910 *tps65910 = dev_get_drvdata(dev->parent); + struct attribute comp_attr = attr->attr; + int id, uVolt; + + if (!strcmp(comp_attr.name, "comp1_threshold")) + { + id = COMP1; + } + else if (!strcmp(comp_attr.name, "comp2_threshold")) + { + id = COMP2; + } + else + { + return -EINVAL; + } + + uVolt = comp_threshold_get(tps65910, id); + + return sprintf(buf, "%d\n", uVolt); +} + +static DEVICE_ATTR(comp1_threshold, S_IRUGO, comp_threshold_show, NULL); +static DEVICE_ATTR(comp2_threshold, S_IRUGO, comp_threshold_show, NULL); + +static int tps65911_comparator_probe(struct platform_device *pdev) +{ + struct tps65910 *tps65910 = dev_get_drvdata(pdev->dev.parent); + struct tps65910_board *pdata = dev_get_platdata(tps65910->dev); + int ret; + + ret = comp_threshold_set(tps65910, COMP1, pdata->vmbch_threshold); + + if (ret < 0) + { + dev_err(&pdev->dev, "cannot set COMP1 threshold\n"); + return ret; + } + + ret = comp_threshold_set(tps65910, COMP2, pdata->vmbch2_threshold); + + if (ret < 0) + { + dev_err(&pdev->dev, "cannot set COMP2 threshold\n"); + return ret; + } + + /* Create sysfs entry */ + ret = device_create_file(&pdev->dev, &dev_attr_comp1_threshold); + + if (ret < 0) + { + dev_err(&pdev->dev, "failed to add COMP1 sysfs file\n"); + } + + ret = device_create_file(&pdev->dev, &dev_attr_comp2_threshold); + + if (ret < 0) + { + dev_err(&pdev->dev, "failed to add COMP2 sysfs file\n"); + } + + return ret; +} + +static int tps65911_comparator_remove(struct platform_device *pdev) +{ + struct tps65910 *tps65910; + + tps65910 = dev_get_drvdata(pdev->dev.parent); + device_remove_file(&pdev->dev, &dev_attr_comp2_threshold); + device_remove_file(&pdev->dev, &dev_attr_comp1_threshold); + + return 0; +} + +static struct platform_driver tps65911_comparator_driver = +{ + .driver = { + .name = "tps65911-comparator", + }, + .probe = tps65911_comparator_probe, + .remove = tps65911_comparator_remove, +}; + +static int __init tps65911_comparator_init(void) +{ + return platform_driver_register(&tps65911_comparator_driver); +} +subsys_initcall(tps65911_comparator_init); + +static void __exit tps65911_comparator_exit(void) +{ + platform_driver_unregister(&tps65911_comparator_driver); +} +module_exit(tps65911_comparator_exit); + +MODULE_AUTHOR("Jorge Eduardo Candelaria "); +MODULE_DESCRIPTION("TPS65911 comparator driver"); +MODULE_LICENSE("GPL v2"); +MODULE_ALIAS("platform:tps65911-comparator"); diff --git a/pool/shard003/C/0065719_aux.c b/pool/shard003/C/0065719_aux.c new file mode 100644 index 0000000000000000000000000000000000000000..5ef5aa79627480a33cb5919657091a84567b91e4 --- /dev/null +++ b/pool/shard003/C/0065719_aux.c @@ -0,0 +1,54 @@ +/* + * This file is part of the UCB release of Plan 9. It is subject to the license + * terms in the LICENSE file found in the top-level directory of this + * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No + * part of the UCB release of Plan 9, including this file, may be copied, + * modified, propagated, or distributed except according to the terms contained + * in the LICENSE file. + */ + +#include +#include +#include +#include +#include +#include "9p.h" + +void* +emalloc9p(ulong sz) +{ + void *v; + + if((v = malloc(sz)) == nil) { + fprint(2, "out of memory allocating %lud\n", sz); + exits("mem"); + } + memset(v, 0, sz); + setmalloctag(v, getcallerpc(&sz)); + return v; +} + +void* +erealloc9p(void *v, ulong sz) +{ + if((v = realloc(v, sz)) == nil) { + fprint(2, "out of memory allocating %lud\n", sz); + exits("mem"); + } + setrealloctag(v, getcallerpc(&v)); + return v; +} + +char* +estrdup9p(char *s) +{ + char *t; + + if((t = strdup(s)) == nil) { + fprint(2, "out of memory in strdup(%.10s)\n", s); + exits("mem"); + } + setmalloctag(t, getcallerpc(&s)); + return t; +} + diff --git a/pool/shard003/C/0065730_playlist.c b/pool/shard003/C/0065730_playlist.c new file mode 100644 index 0000000000000000000000000000000000000000..1077310c590b177c2ff1fb93bda37baabe534313 --- /dev/null +++ b/pool/shard003/C/0065730_playlist.c @@ -0,0 +1,158 @@ +/* + * MPlayer GUI for Win32 + * Copyright (C) 2003 Sascha Sommer + * Copyright (C) 2006 Erik Augustson + * Copyright (C) 2006 Gianluigi Tiesi + * + * This file is part of MPlayer. + * + * MPlayer 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. + * + * MPlayer 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 MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include "mp_msg.h" +#include "playlist.h" + +/* TODO: implement sort_playlist */ + +int adddirtoplaylist(playlist_t *playlist, const char *path, int recursive) +{ + HANDLE findHandle = INVALID_HANDLE_VALUE; + WIN32_FIND_DATA finddata; + char findpath[MAX_PATH], filename[MAX_PATH]; + char *filepart; + + sprintf(findpath, "%s/*.*", path); + + findHandle = FindFirstFile(findpath, &finddata); + + if (findHandle == INVALID_HANDLE_VALUE) return FALSE; + do + { + if (finddata.cFileName[0] == '.' || strstr(finddata.cFileName, "Thumbs.db")) continue; + sprintf(findpath, "%s/%s", path, finddata.cFileName); + + if (GetFileAttributes(findpath) & FILE_ATTRIBUTE_DIRECTORY) + { + if(recursive) + adddirtoplaylist(playlist, findpath, recursive); + } + else + { + if (GetFullPathName(findpath, MAX_PATH, filename, &filepart)) + playlist->add_track(playlist, filename, NULL, filepart, 0); + } + } while (FindNextFile(findHandle, &finddata)); + FindClose(findHandle); + return TRUE; +} + +static void add_track(playlist_t *playlist, const char *filename, const char *artist, const char *title, int duration) +{ + (playlist->trackcount)++; + playlist->tracks = realloc(playlist->tracks, playlist->trackcount * sizeof(pl_track_t *)); + playlist->tracks[playlist->trackcount - 1] = calloc(1, sizeof(pl_track_t)); + if(filename) playlist->tracks[playlist->trackcount - 1]->filename = strdup(filename); + if(artist) playlist->tracks[playlist->trackcount - 1]->artist = strdup(artist); + if(title) playlist->tracks[playlist->trackcount - 1]->title = strdup(title); + if(duration) playlist->tracks[playlist->trackcount - 1]->duration = duration; +} + +static void remove_track(playlist_t *playlist, int number) +{ + pl_track_t **tmp = calloc(1, playlist->trackcount * sizeof(pl_track_t *)); + int i, p = 0; + memcpy(tmp, playlist->tracks, playlist->trackcount * sizeof(pl_track_t *)); + (playlist->trackcount)--; + playlist->tracks = realloc(playlist->tracks, playlist->trackcount * sizeof(pl_track_t *)); + for(i=0; itrackcount + 1; i++) + { + if(i != (number - 1)) + { + playlist->tracks[p] = tmp[i]; + p++; + } + else + { + free(tmp[i]->filename); + free(tmp[i]->artist); + free(tmp[i]->title); + free(tmp[i]); + } + } + free(tmp); +} + +static void moveup_track(playlist_t *playlist, int number) +{ + pl_track_t *tmp; + if(number == 1) return; /* already first */ + tmp = playlist->tracks[number - 2]; + playlist->tracks[number - 2] = playlist->tracks[number - 1]; + playlist->tracks[number - 1] = tmp; +} + +static void movedown_track(playlist_t *playlist, int number) +{ + pl_track_t *tmp; + if(number == playlist->trackcount) return; /* already latest */ + tmp = playlist->tracks[number]; + playlist->tracks[number] = playlist->tracks[number - 1]; + playlist->tracks[number - 1] = tmp; +} + +static void sort_playlist(/*playlist_t *playlist, int opt*/) {} + +static void clear_playlist(playlist_t *playlist) +{ + while(playlist->trackcount) playlist->remove_track(playlist, 1); + playlist->tracks = NULL; + playlist->current = 0; +} + +static void free_playlist(playlist_t *playlist) +{ + if(playlist->tracks) playlist->clear_playlist(playlist); + free(playlist); +} + +static void dump_playlist(playlist_t *playlist) +{ + int i; + for (i=0; itrackcount; i++) + { + mp_msg(MSGT_GPLAYER, MSGL_V, "track %i %s ", i + 1, playlist->tracks[i]->filename); + if(playlist->tracks[i]->artist) mp_msg(MSGT_GPLAYER, MSGL_V, "%s ", playlist->tracks[i]->artist); + if(playlist->tracks[i]->title) mp_msg(MSGT_GPLAYER, MSGL_V, "- %s ", playlist->tracks[i]->title); + if(playlist->tracks[i]->duration) mp_msg(MSGT_GPLAYER, MSGL_V, "%i ", playlist->tracks[i]->duration); + mp_msg(MSGT_GPLAYER, MSGL_V, "\n"); + } +} + +playlist_t *create_playlist(void) +{ + playlist_t *playlist = calloc(1, sizeof(playlist_t)); + playlist->add_track = add_track; + playlist->remove_track = remove_track; + playlist->moveup_track = moveup_track; + playlist->movedown_track = movedown_track; + playlist->dump_playlist = dump_playlist; + playlist->sort_playlist = sort_playlist; + playlist->clear_playlist = clear_playlist; + playlist->free_playlist = free_playlist; + return playlist; +} diff --git a/pool/shard003/C/0065731_test_c_example1.c b/pool/shard003/C/0065731_test_c_example1.c new file mode 100644 index 0000000000000000000000000000000000000000..1ffc8dbf0097cc49db61aa70db5b7505cff188fe --- /dev/null +++ b/pool/shard003/C/0065731_test_c_example1.c @@ -0,0 +1,104 @@ +/* + * This file is part of qpOASES. + * + * qpOASES -- An Implementation of the Online Active Set Strategy. + * Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka, + * Christian Kirches et al. All rights reserved. + * + * qpOASES 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. + * + * qpOASES 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 qpOASES; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + + +/** + * \file testing/c/test_c_example1.c + * \author Hans Joachim Ferreau + * \version 3.1 + * \date 2014-2015 + * + * Very simple example for testing qpOASES (using QProblem class through C interface). + */ + +#include + +#include + + +/** Example for qpOASES main function using the QProblem class. */ +int main( ) +{ + /* Setup data of first QP. */ + real_t H[2*2] = { 1.0, 0.0, 0.0, 0.5 }; + real_t A[1*2] = { 1.0, 1.0 }; + real_t g[2] = { 1.5, 1.0 }; + real_t lb[2] = { 0.5, -2.0 }; + real_t ub[2] = { 5.0, 2.0 }; + real_t lbA[1] = { -1.0 }; + real_t ubA[1] = { 2.0 }; + + /* Setup data of second QP. */ + real_t g_new[2] = { 1.0, 1.5 }; + real_t lb_new[2] = { 0.0, -1.0 }; + real_t ub_new[2] = { 5.0, -0.5 }; + real_t lbA_new[1] = { -2.0 }; + real_t ubA_new[1] = { 1.0 }; + + int nWSR; + qpOASES_Options options; + + real_t xOpt[2]; + real_t yOpt[2+1]; + real_t obj; + int status; + + qpOASES_Options_init( &options,0 ); + options.printLevel = PL_MEDIUM; + + + QProblem_setup( 2,1,HST_UNKNOWN ); + + /* Solve first QP. */ + nWSR = 10; + QProblem_init( H,g,A,lb,ub,lbA,ubA, + &nWSR,0,&options, + xOpt,yOpt,&obj,&status + ); + + /* Print solution of first QP. */ + printf( "\nxOpt = [ %e, %e ]; yOpt = [ %e, %e, %e ]; objVal = %e\n\n", + xOpt[0],xOpt[1],yOpt[0],yOpt[1],yOpt[2], obj ); + + + /* Solve second QP. */ + nWSR = 10; + QProblem_hotstart( g_new,lb_new,ub_new,lbA_new,ubA_new, + &nWSR,0, + xOpt,yOpt,&obj,&status + ); + + /* Print solution of first QP. */ + printf( "\nxOpt = [ %e, %e ]; yOpt = [ %e, %e, %e ]; objVal = %e\n\n", + xOpt[0],xOpt[1],yOpt[0],yOpt[1],yOpt[2], obj ); + + + QProblem_cleanup(); + + return 0; +} + + +/* + * end of file + */ diff --git a/pool/shard003/C/0065746_wcslcat.c b/pool/shard003/C/0065746_wcslcat.c new file mode 100644 index 0000000000000000000000000000000000000000..2df94777d51f9c6bde84a963dad053da5296b196 --- /dev/null +++ b/pool/shard003/C/0065746_wcslcat.c @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1998 Todd C. Miller + * 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. 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 ``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 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. + * + * from OpenBSD: strlcat.c,v 1.3 2000/11/24 11:10:02 itojun Exp + */ + +#include +#if 0 +#if defined(LIBC_SCCS) && !defined(lint) +__RCSID("$NetBSD: wcslcat.c,v 1.1 2000/12/23 23:14:36 itojun Exp $"); +#endif /* LIBC_SCCS and not lint */ +#endif +__FBSDID("$FreeBSD$"); + +#include +#include + +/* + * Appends src to string dst of size siz (unlike wcsncat, siz is the + * full size of dst, not space left). At most siz-1 characters + * will be copied. Always NUL terminates (unless siz == 0). + * Returns wcslen(initial dst) + wcslen(src); if retval >= siz, + * truncation occurred. + */ +size_t +wcslcat(wchar_t *dst, const wchar_t *src, size_t siz) +{ + wchar_t *d = dst; + const wchar_t *s = src; + size_t n = siz; + size_t dlen; + + /* Find the end of dst and adjust bytes left but don't go past end */ + while (n-- != 0 && *d != '\0') + d++; + dlen = d - dst; + n = siz - dlen; + + if (n == 0) + return(dlen + wcslen(s)); + while (*s != '\0') { + if (n != 1) { + *d++ = *s; + n--; + } + s++; + } + *d = '\0'; + + return(dlen + (s - src)); /* count does not include NUL */ +} diff --git a/pool/shard003/C/0065758_CWE127_Buffer_Underread__wchar_t_declare_cpy_67b.c b/pool/shard003/C/0065758_CWE127_Buffer_Underread__wchar_t_declare_cpy_67b.c new file mode 100644 index 0000000000000000000000000000000000000000..d6dc609abaedcf85e83951283f80280f9f0d03f8 --- /dev/null +++ b/pool/shard003/C/0065758_CWE127_Buffer_Underread__wchar_t_declare_cpy_67b.c @@ -0,0 +1,59 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE127_Buffer_Underread__wchar_t_declare_cpy_67b.c +Label Definition File: CWE127_Buffer_Underread.stack.label.xml +Template File: sources-sink-67b.tmpl.c +*/ +/* + * @description + * CWE: 127 Buffer Under-read + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sinks: cpy + * BadSink : Copy data to string using wcscpy + * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +typedef struct _CWE127_Buffer_Underread__wchar_t_declare_cpy_67_structType +{ + wchar_t * structFirst; +} CWE127_Buffer_Underread__wchar_t_declare_cpy_67_structType; + +#ifndef OMITBAD + +void CWE127_Buffer_Underread__wchar_t_declare_cpy_67b_badSink(CWE127_Buffer_Underread__wchar_t_declare_cpy_67_structType myStruct) +{ + wchar_t * data = myStruct.structFirst; + { + wchar_t dest[100*2]; + wmemset(dest, L'C', 100*2-1); /* fill with 'C's */ + dest[100*2-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + wcscpy(dest, data); + printWLine(dest); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE127_Buffer_Underread__wchar_t_declare_cpy_67b_goodG2BSink(CWE127_Buffer_Underread__wchar_t_declare_cpy_67_structType myStruct) +{ + wchar_t * data = myStruct.structFirst; + { + wchar_t dest[100*2]; + wmemset(dest, L'C', 100*2-1); /* fill with 'C's */ + dest[100*2-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + wcscpy(dest, data); + printWLine(dest); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard003/C/0065763_test-torture.c b/pool/shard003/C/0065763_test-torture.c new file mode 100644 index 0000000000000000000000000000000000000000..31b803b53bc179f642d4cb19d0dddd7e3a6cc334 --- /dev/null +++ b/pool/shard003/C/0065763_test-torture.c @@ -0,0 +1,85 @@ +/*Tourture test for entire compsl system. + * + */ + +#include +#include +#include "compsl.h" + +static const char *test2 = +"declare \n\ +{ \n\ + global int foo; \n\ + int x,y,z;\n\ + float a,b,c;\n\ +}\n\ + cubbyhole init {\n\ + test_reset(); foo = 1;\n\ + b=c=(float)foo;testeqf(1.0,b); testeqf(1.0,c);\n\ + a = 2.0;\n\ + x = y = (int)(c=a); testeqf(2.0,c);testeqi(2,x);testeqi(2,y);\n\ + test_summary();\n\ + }\ + cubby foo { \n\ + x=0;\n\ + while(x<3)\n\ + x+=1;}\n\ + cubby bar {\n\ + x=y=0;\n\ + z = 1;\n\ + x = y+z;\n\ + }"; + +int main() +{ + puts("Running Torture Test"); + + VM *vm=createVM(); + if(vm == NULL) { fprintf(stderr,"Error initializing compsl"); exit(1);} + + addPrintLibToVm(vm); + addDebugLibToVm(vm); + + compart *com1=createComp(vm); + compart *com2=createComp(vm); + int compret1,compret2; // return code of compiler + if(com1 == NULL || com2 == NULL) + { + fprintf(stderr,"Error initializing compsl"); + exit(1); + } + + //TODO: add variables to compartments here + int32_t *x = com_addInt(com1,"x"); + puts("Compiling file"); + compret1 = fileCompile("src/test/torture.csl", com1); + puts("Compiling string"); + compret2 = stringCompile(test2, com2); + if(compret1 != 0 || compret2 != 0) { + fputs("Bad compsl!",stderr); + exit(1); + } + int16_t cubbyid; + + cubbyid = getCubbyID(com1,"init"); + runCubbyhole(com1, cubbyid); + puts("Done first init"); + + cubbyid = getCubbyID(com2,"init"); + runCubbyhole(com2, cubbyid); + puts("Done second init"); + + //TODO: check value of foo global in cubbys + cubbyid = getCubbyID(com1,"run"); + runCubbyhole(com1, cubbyid); + //TODO: other tests + + cubbyid = getCubbyID(com1,"runlots"); + *x = 0; + while(*x < 1000000) + runCubbyhole(com1, cubbyid); + + destroyComp(com1); + destroyComp(com2); + destroyVM(vm); +} diff --git a/pool/shard003/C/0065765_linux_wlan_spi.c b/pool/shard003/C/0065765_linux_wlan_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..f3ffc9e6d6262b6fdbe55846d8c1b492ae455a9d --- /dev/null +++ b/pool/shard003/C/0065765_linux_wlan_spi.c @@ -0,0 +1,191 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "linux_wlan_spi.h" +#include "wilc_wfi_netdevice.h" +#include "linux_wlan_common.h" +#include "wilc_wlan_if.h" + +#define USE_SPI_DMA 0 /* johnny add */ + +static const struct wilc1000_ops wilc1000_spi_ops; + +static int wilc_bus_probe(struct spi_device *spi) +{ + int ret, gpio; + struct wilc *wilc; + + gpio = of_get_gpio(spi->dev.of_node, 0); + if (gpio < 0) + gpio = GPIO_NUM; + + ret = wilc_netdev_init(&wilc, NULL, HIF_SPI, GPIO_NUM, &wilc_hif_spi); + if (ret) + return ret; + + spi_set_drvdata(spi, wilc); + wilc->dev = &spi->dev; + + return 0; +} + +static int wilc_bus_remove(struct spi_device *spi) +{ + wilc_netdev_cleanup(spi_get_drvdata(spi)); + return 0; +} + +static const struct of_device_id wilc1000_of_match[] = { + { .compatible = "atmel,wilc_spi", }, + {} +}; +MODULE_DEVICE_TABLE(of, wilc1000_of_match); + +struct spi_driver wilc1000_spi_driver = { + .driver = { + .name = MODALIAS, + .of_match_table = wilc1000_of_match, + }, + .probe = wilc_bus_probe, + .remove = wilc_bus_remove, +}; +module_spi_driver(wilc1000_spi_driver); +MODULE_LICENSE("GPL"); + +int wilc_spi_init(void) +{ + return 1; +} + +int wilc_spi_write(struct wilc *wilc, u8 *b, u32 len) +{ + struct spi_device *spi = to_spi_device(wilc->dev); + int ret; + struct spi_message msg; + + if (len > 0 && b != NULL) { + struct spi_transfer tr = { + .tx_buf = b, + .len = len, + .delay_usecs = 0, + }; + char *r_buffer = kzalloc(len, GFP_KERNEL); + if (!r_buffer) + return -ENOMEM; + + tr.rx_buf = r_buffer; + PRINT_D(BUS_DBG, "Request writing %d bytes\n", len); + + memset(&msg, 0, sizeof(msg)); + spi_message_init(&msg); +/* [[johnny add */ + msg.spi = spi; + msg.is_dma_mapped = USE_SPI_DMA; +/* ]] */ + spi_message_add_tail(&tr, &msg); + + ret = spi_sync(spi, &msg); + if (ret < 0) { + PRINT_ER("SPI transaction failed\n"); + } + + kfree(r_buffer); + } else { + PRINT_ER("can't write data with the following length: %d\n", len); + PRINT_ER("FAILED due to NULL buffer or ZERO length check the following length: %d\n", len); + ret = -1; + } + + /* change return value to match WILC interface */ + (ret < 0) ? (ret = 0) : (ret = 1); + + + return ret; +} + +int wilc_spi_read(struct wilc *wilc, u8 *rb, u32 rlen) +{ + struct spi_device *spi = to_spi_device(wilc->dev); + int ret; + + if (rlen > 0) { + struct spi_message msg; + struct spi_transfer tr = { + .rx_buf = rb, + .len = rlen, + .delay_usecs = 0, + + }; + char *t_buffer = kzalloc(rlen, GFP_KERNEL); + if (!t_buffer) + return -ENOMEM; + + tr.tx_buf = t_buffer; + + memset(&msg, 0, sizeof(msg)); + spi_message_init(&msg); +/* [[ johnny add */ + msg.spi = spi; + msg.is_dma_mapped = USE_SPI_DMA; +/* ]] */ + spi_message_add_tail(&tr, &msg); + + ret = spi_sync(spi, &msg); + if (ret < 0) { + PRINT_ER("SPI transaction failed\n"); + } + kfree(t_buffer); + } else { + PRINT_ER("can't read data with the following length: %u\n", rlen); + ret = -1; + } + /* change return value to match WILC interface */ + (ret < 0) ? (ret = 0) : (ret = 1); + + return ret; +} + +int wilc_spi_write_read(struct wilc *wilc, u8 *wb, u8 *rb, u32 rlen) +{ + struct spi_device *spi = to_spi_device(wilc->dev); + int ret; + + if (rlen > 0) { + struct spi_message msg; + struct spi_transfer tr = { + .rx_buf = rb, + .tx_buf = wb, + .len = rlen, + .bits_per_word = 8, + .delay_usecs = 0, + + }; + + memset(&msg, 0, sizeof(msg)); + spi_message_init(&msg); + msg.spi = spi; + msg.is_dma_mapped = USE_SPI_DMA; + + spi_message_add_tail(&tr, &msg); + ret = spi_sync(spi, &msg); + if (ret < 0) { + PRINT_ER("SPI transaction failed\n"); + } + } else { + PRINT_ER("can't read data with the following length: %u\n", rlen); + ret = -1; + } + /* change return value to match WILC interface */ + (ret < 0) ? (ret = 0) : (ret = 1); + + return ret; +} diff --git a/pool/shard003/C/0065786_etime.c b/pool/shard003/C/0065786_etime.c new file mode 100644 index 0000000000000000000000000000000000000000..b3cd7e0edf6347da3c0ae2dcad8daac0a86f646f --- /dev/null +++ b/pool/shard003/C/0065786_etime.c @@ -0,0 +1,72 @@ +/* Implementation of the ETIME intrinsic. + Copyright (C) 2004-2021 Free Software Foundation, Inc. + Contributed by Steven G. Kargl . + +This file is part of the GNU Fortran runtime library (libgfortran). + +Libgfortran 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. + +Libgfortran 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. + +Under Section 7 of GPL version 3, you are granted additional +permissions described in the GCC Runtime Library Exception, version +3.1, as published by the Free Software Foundation. + +You should have received a copy of the GNU General Public License and +a copy of the GCC Runtime Library Exception along with this program; +see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +. */ + +#include "libgfortran.h" +#include "time_1.h" + +extern void etime_sub (gfc_array_r4 *t, GFC_REAL_4 *result); +iexport_proto(etime_sub); + +void +etime_sub (gfc_array_r4 *t, GFC_REAL_4 *result) +{ + GFC_REAL_4 tu, ts, tt, *tp; + long user_sec, user_usec, system_sec, system_usec; + + if (((GFC_DESCRIPTOR_EXTENT(t,0))) < 2) + runtime_error ("Insufficient number of elements in TARRAY."); + + if (gf_cputime (&user_sec, &user_usec, &system_sec, &system_usec) == 0) + { + tu = (GFC_REAL_4)(user_sec + 1.e-6 * user_usec); + ts = (GFC_REAL_4)(system_sec + 1.e-6 * system_usec); + tt = tu + ts; + } + else + { + tu = (GFC_REAL_4)-1.0; + ts = (GFC_REAL_4)-1.0; + tt = (GFC_REAL_4)-1.0; + } + + tp = t->base_addr; + + *tp = tu; + tp += GFC_DESCRIPTOR_STRIDE(t,0); + *tp = ts; + *result = tt; +} +iexport(etime_sub); + +extern GFC_REAL_4 etime (gfc_array_r4 *t); +export_proto(etime); + +GFC_REAL_4 +etime (gfc_array_r4 *t) +{ + GFC_REAL_4 val; + etime_sub (t, &val); + return val; +} diff --git a/pool/shard003/C/0065787_msgpack.c b/pool/shard003/C/0065787_msgpack.c new file mode 100644 index 0000000000000000000000000000000000000000..ffb44ecda57dbd97782200cefebc86c11ce6a4df --- /dev/null +++ b/pool/shard003/C/0065787_msgpack.c @@ -0,0 +1,257 @@ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "php.h" +#include "php_ini.h" +#include "ext/standard/info.h" /* for php_info */ +#include "ext/standard/php_incomplete_class.h" /* for incomplete_class */ +#include "ext/standard/php_var.h" /* for PHP_VAR_SERIALIZE */ +#include "ext/session/php_session.h" /* for php_session_register_serializer */ + +#include "php_msgpack.h" +#include "msgpack_pack.h" +#include "msgpack_unpack.h" +#include "msgpack_class.h" +#include "msgpack_convert.h" +#include "msgpack_errors.h" +#include "msgpack/version.h" + +ZEND_DECLARE_MODULE_GLOBALS(msgpack) + +//static ZEND_FUNCTION(msgpack_serialize); +//static ZEND_FUNCTION(msgpack_unserialize); +// +//ZEND_BEGIN_ARG_INFO_EX(arginfo_msgpack_serialize, 0, 0, 1) +// ZEND_ARG_INFO(0, value) +//ZEND_END_ARG_INFO() +// +//ZEND_BEGIN_ARG_INFO_EX(arginfo_msgpack_unserialize, 0, 0, 1) +// ZEND_ARG_INFO(0, str) +// ZEND_ARG_INFO(0, object) +//ZEND_END_ARG_INFO() + +PHP_INI_BEGIN() +STD_PHP_INI_BOOLEAN( + "msgpack.error_display", "1", PHP_INI_ALL, OnUpdateBool, + error_display, zend_msgpack_globals, msgpack_globals) +STD_PHP_INI_BOOLEAN( + "msgpack.php_only", "1", PHP_INI_ALL, OnUpdateBool, + php_only, zend_msgpack_globals, msgpack_globals) +STD_PHP_INI_BOOLEAN( + "msgpack.illegal_key_insert", "0", PHP_INI_ALL, OnUpdateBool, + illegal_key_insert, zend_msgpack_globals, msgpack_globals) +PHP_INI_END() + +#if HAVE_PHP_SESSION +PS_SERIALIZER_FUNCS(msgpack); +#endif + +static zend_function_entry msgpack_functions[] = { +// ZEND_FE(msgpack_serialize, arginfo_msgpack_serialize) +// ZEND_FE(msgpack_unserialize, arginfo_msgpack_unserialize) +// ZEND_FALIAS(msgpack_pack, msgpack_serialize, arginfo_msgpack_serialize) +// ZEND_FALIAS(msgpack_unpack, msgpack_unserialize, arginfo_msgpack_unserialize) + {NULL, NULL, NULL} +}; + +static void msgpack_init_globals(zend_msgpack_globals *msgpack_globals) +{ + TSRMLS_FETCH(); + + if (PG(display_errors)) + { + msgpack_globals->error_display = 1; + } + else + { + msgpack_globals->error_display = 0; + } + + msgpack_globals->php_only = 1; + + msgpack_globals->illegal_key_insert = 0; + msgpack_globals->serialize.var_hash = NULL; + msgpack_globals->serialize.level = 0; +} + +static ZEND_MINIT_FUNCTION(msgpack) +{ + ZEND_INIT_MODULE_GLOBALS(msgpack, msgpack_init_globals, NULL); + + REGISTER_INI_ENTRIES(); + + +// msgpack_init_class(); + +#if (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION < 1) + REGISTER_LONG_CONSTANT( + "MESSAGEPACK_OPT_PHPONLY", MSGPACK_CLASS_OPT_PHPONLY, + CONST_CS | CONST_PERSISTENT); +#endif + + return SUCCESS; +} + +static ZEND_MSHUTDOWN_FUNCTION(msgpack) +{ + UNREGISTER_INI_ENTRIES(); + + return SUCCESS; +} + +static ZEND_MINFO_FUNCTION(msgpack) +{ + php_info_print_table_start(); + php_info_print_table_row(2, "MessagePack Support", "enabled"); +#if HAVE_PHP_SESSION + php_info_print_table_row(2, "Session Support", "enabled" ); +#endif + php_info_print_table_row(2, "extension Version", MSGPACK_EXTENSION_VERSION); + php_info_print_table_row(2, "header Version", MSGPACK_VERSION); + php_info_print_table_end(); + + DISPLAY_INI_ENTRIES(); +} + +zend_module_entry msgpack_module_entry = { +#if ZEND_MODULE_API_NO >= 20010901 + STANDARD_MODULE_HEADER, +#endif + "msgpack", + msgpack_functions, + ZEND_MINIT(msgpack), + ZEND_MSHUTDOWN(msgpack), + NULL, + NULL, + ZEND_MINFO(msgpack), +#if ZEND_MODULE_API_NO >= 20010901 + MSGPACK_EXTENSION_VERSION, +#endif + STANDARD_MODULE_PROPERTIES +}; + +#ifdef COMPILE_DL_MSGPACK +ZEND_GET_MODULE(msgpack) +#endif + + +PHP_MSGPACK_API void php_msgpack_serialize(instead_smart *buf, zval *val TSRMLS_DC) +//PHP_MSGPACK_API void php_msgpack_serialize(smart_str *buf, zval *val TSRMLS_DC) +{ + msgpack_serialize_data_t var_hash; + + msgpack_serialize_var_init(&var_hash); + + msgpack_serialize_zval(buf, val, var_hash TSRMLS_CC); + + msgpack_serialize_var_destroy(&var_hash); +} + +PHP_MSGPACK_API void php_msgpack_unserialize( + zval *return_value, char *str, size_t str_len TSRMLS_DC) +{ + int ret; + size_t off = 0; + msgpack_unpack_t mp; + msgpack_unserialize_data_t var_hash; + + if (str_len <= 0) + { + RETURN_NULL(); + } + + template_init(&mp); + + msgpack_unserialize_var_init(&var_hash); + + mp.user.retval = (zval *)return_value; + mp.user.var_hash = (msgpack_unserialize_data_t *)&var_hash; + + ret = template_execute(&mp, str, (size_t)str_len, &off); + + switch (ret) + { + case MSGPACK_UNPACK_PARSE_ERROR: + zval_dtor(return_value); + ZVAL_FALSE(return_value); + msgpack_unserialize_var_destroy(&var_hash, 1); + MSGPACK_WARNING("[msgpack] (%s) Parse error", __FUNCTION__); + break; + case MSGPACK_UNPACK_CONTINUE: + zval_dtor(return_value); + ZVAL_FALSE(return_value); + msgpack_unserialize_var_destroy(&var_hash, 1); + MSGPACK_WARNING( + "[msgpack] (%s) Insufficient data for unserializing", + __FUNCTION__); + break; + case MSGPACK_UNPACK_EXTRA_BYTES: + case MSGPACK_UNPACK_SUCCESS: + msgpack_unserialize_var_destroy(&var_hash, 0); + if (off < (size_t)str_len) + { + MSGPACK_WARNING("[msgpack] (%s) Extra bytes", __FUNCTION__); + } + break; + default: + msgpack_unserialize_var_destroy(&var_hash, 0); + MSGPACK_WARNING("[msgpack] (%s) Unknown result", __FUNCTION__); + break; + } +} + +//static ZEND_FUNCTION(msgpack_serialize) +//{ +// zval *parameter; +// smart_str buf = {0}; +// +// if (zend_parse_parameters( +// ZEND_NUM_ARGS() TSRMLS_CC, "z", ¶meter) == FAILURE) +// { +// return; +// } +// +// php_msgpack_serialize(&buf, parameter TSRMLS_CC); +// +// ZVAL_STRINGL(return_value, buf.c, buf.len, 1); +// +// smart_str_free(&buf); +//} + +//static ZEND_FUNCTION(msgpack_unserialize) +//{ +// char *str; +// int str_len; +// zval *object = NULL; +// +// if (zend_parse_parameters( +// ZEND_NUM_ARGS() TSRMLS_CC, "s|z", +// &str, &str_len, &object) == FAILURE) +// { +// return; +// } +// +// if (!str_len) +// { +// RETURN_NULL(); +// } +// +// if (object == NULL) +// { +// php_msgpack_unserialize(return_value, str, str_len TSRMLS_CC); +// } +// else +// { +// zval *zv; +// +// ALLOC_INIT_ZVAL(zv); +// php_msgpack_unserialize(zv, str, str_len TSRMLS_CC); +// +// if (msgpack_convert_template(return_value, object, &zv) != SUCCESS) +// { +// RETURN_NULL(); +// } +// } +//} diff --git a/pool/shard003/C/0065789_ijson_pretty.c b/pool/shard003/C/0065789_ijson_pretty.c new file mode 100644 index 0000000000000000000000000000000000000000..87b21d337ab11d8c762dc655fe021357be4ed594 --- /dev/null +++ b/pool/shard003/C/0065789_ijson_pretty.c @@ -0,0 +1,110 @@ +#include "indolentjson/compact.h" +#include "indolentjson/parse.h" +#include "readfile.c" +#include +#include +#include +#include + +static char BUFFER[4096]; + +static void print_indent( + int fd, unsigned indent, char start1, char start2, char end +) { + BUFFER[0] = BUFFER[1] = '\t'; + if (start1) { + BUFFER[0] = start1; + indent += 1; + if (start2) { + BUFFER[1] = start2; + indent += 1; + } + } + if (end) indent += 1; + while(indent > sizeof(BUFFER)) { + write(fd, BUFFER, sizeof(BUFFER)); + indent -= sizeof(BUFFER); + BUFFER[0] = BUFFER[1] = '\t'; + } + if (end) BUFFER[indent - 1] = end; + write(fd, BUFFER, indent); + if (end) BUFFER[indent - 1] = '\t'; +} + +static struct ijnode * print_pretty( + int fd, struct ijnode * node, uint8_t * data, + unsigned indent1, unsigned indent2, char start1, char start2 +) { + if (node->children && *data == '{') { + print_indent(fd, indent1, start1, start2, 0); + struct ijnode * child, * end = node + node->children + 1; + char sep = '{'; + for (child = node + 1; child != end;) { + uint8_t * child_data = data + 1; + data = child_data + child->length_in_bytes; + child = print_pretty( + fd, child, child_data, indent2 + 1, indent2 + 1, sep, '\n' + ); + child_data = data + 1; + data = child_data + child->length_in_bytes; + child = print_pretty( + fd, child, child_data, 0, indent2 + 1, ':', ' ' + ); + sep = ','; + } + print_indent(fd, indent2, '\n', 0, '}'); + return end; + } else if (node->children) { + print_indent(fd, indent1, start1, start2, 0); + struct ijnode * child, * end = node + node->children + 1; + char sep = '['; + for (child = node + 1; child != end;) { + uint8_t * child_data = data + 1; + data = child_data + child->length_in_bytes; + child = print_pretty( + fd, child, child_data, indent2 + 1, indent2 + 1, sep, '\n' + ); + sep = ','; + } + print_indent(fd, indent2, '\n', 0, ']'); + return end; + } else { + print_indent(fd, indent1, start1, start2, 0); + write(fd, data, node->length_in_bytes); + return node + 1; + } +} + + +int main(int argc, char *argv[]) { + memset(BUFFER, '\t', sizeof(BUFFER)); + int input_fd = STDIN_FILENO; + int output_fd = STDOUT_FILENO; + if (argc > 1) { + input_fd = open(argv[1], O_RDONLY); + } + uint8_t * data_buffer; + ssize_t data_length = read_file(input_fd, &data_buffer); + if (data_length < 0) { + perror("Error reading file"); + return 1; + } + size_t compact_length = ijson_compact( + data_buffer, data_length, data_buffer + ); + size_t nodes_length = ijson_parse_max_output_length(compact_length); + struct ijnode * nodes = (struct ijnode *) calloc( + nodes_length, sizeof(struct ijnode) + ); + uint32_t * stack = (uint32_t *) calloc(nodes_length, sizeof(uint32_t)); + if (ijson_parse( + data_buffer, compact_length, nodes, nodes_length, stack, nodes_length + ) == (size_t)(-1)) { + perror("Error parsing JSON"); + return 1; + } + print_pretty(output_fd, nodes, data_buffer, 0, 0, 0, 0); + write(output_fd, "\n", 1); + return 0; +} + diff --git a/pool/shard003/C/0065796_smpboot.c b/pool/shard003/C/0065796_smpboot.c new file mode 100644 index 0000000000000000000000000000000000000000..bd82375db51a62cf1b84414a2a80d9738ca1d36c --- /dev/null +++ b/pool/shard003/C/0065796_smpboot.c @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * SMP initialisation and IPI support + * Based on arch/arm64/kernel/smp.c + * + * Copyright (C) 2012 ARM Ltd. + * Copyright (C) 2015 Regents of the University of California + * Copyright (C) 2017 SiFive + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "head.h" + +static DECLARE_COMPLETION(cpu_running); + +void __init smp_prepare_boot_cpu(void) +{ + init_cpu_topology(); +#ifdef CONFIG_RISCV_ERRATA_ALTERNATIVE + apply_boot_alternatives(); +#endif +} + +void __init smp_prepare_cpus(unsigned int max_cpus) +{ + int cpuid; + int ret; + unsigned int curr_cpuid; + + curr_cpuid = smp_processor_id(); + numa_store_cpu_info(curr_cpuid); + numa_add_cpu(curr_cpuid); + + /* This covers non-smp usecase mandated by "nosmp" option */ + if (max_cpus == 0) + return; + + for_each_possible_cpu(cpuid) { + if (cpuid == curr_cpuid) + continue; + if (cpu_ops[cpuid]->cpu_prepare) { + ret = cpu_ops[cpuid]->cpu_prepare(cpuid); + if (ret) + continue; + } + set_cpu_present(cpuid, true); + numa_store_cpu_info(cpuid); + } +} + +void __init setup_smp(void) +{ + struct device_node *dn; + int hart; + bool found_boot_cpu = false; + int cpuid = 1; + + cpu_set_ops(0); + + for_each_of_cpu_node(dn) { + hart = riscv_of_processor_hartid(dn); + if (hart < 0) + continue; + + if (hart == cpuid_to_hartid_map(0)) { + BUG_ON(found_boot_cpu); + found_boot_cpu = 1; + early_map_cpu_to_node(0, of_node_to_nid(dn)); + continue; + } + if (cpuid >= NR_CPUS) { + pr_warn("Invalid cpuid [%d] for hartid [%d]\n", + cpuid, hart); + break; + } + + cpuid_to_hartid_map(cpuid) = hart; + early_map_cpu_to_node(cpuid, of_node_to_nid(dn)); + cpuid++; + } + + BUG_ON(!found_boot_cpu); + + if (cpuid > nr_cpu_ids) + pr_warn("Total number of cpus [%d] is greater than nr_cpus option value [%d]\n", + cpuid, nr_cpu_ids); + + for (cpuid = 1; cpuid < nr_cpu_ids; cpuid++) { + if (cpuid_to_hartid_map(cpuid) != INVALID_HARTID) { + cpu_set_ops(cpuid); + set_cpu_possible(cpuid, true); + } + } +} + +static int start_secondary_cpu(int cpu, struct task_struct *tidle) +{ + if (cpu_ops[cpu]->cpu_start) + return cpu_ops[cpu]->cpu_start(cpu, tidle); + + return -EOPNOTSUPP; +} + +int __cpu_up(unsigned int cpu, struct task_struct *tidle) +{ + int ret = 0; + tidle->thread_info.cpu = cpu; + + ret = start_secondary_cpu(cpu, tidle); + if (!ret) { + wait_for_completion_timeout(&cpu_running, + msecs_to_jiffies(1000)); + + if (!cpu_online(cpu)) { + pr_crit("CPU%u: failed to come online\n", cpu); + ret = -EIO; + } + } else { + pr_crit("CPU%u: failed to start\n", cpu); + } + + return ret; +} + +void __init smp_cpus_done(unsigned int max_cpus) +{ +} + +/* + * C entry point for a secondary processor. + */ +asmlinkage __visible void smp_callin(void) +{ + struct mm_struct *mm = &init_mm; + unsigned int curr_cpuid = smp_processor_id(); + + riscv_clear_ipi(); + + /* All kernel threads share the same mm context. */ + mmgrab(mm); + current->active_mm = mm; + + notify_cpu_starting(curr_cpuid); + numa_add_cpu(curr_cpuid); + update_siblings_masks(curr_cpuid); + set_cpu_online(curr_cpuid, 1); + + /* + * Remote TLB flushes are ignored while the CPU is offline, so emit + * a local TLB flush right now just in case. + */ + local_flush_tlb_all(); + complete(&cpu_running); + /* + * Disable preemption before enabling interrupts, so we don't try to + * schedule a CPU that hasn't actually started yet. + */ + local_irq_enable(); + cpu_startup_entry(CPUHP_AP_ONLINE_IDLE); +} diff --git a/pool/shard003/C/0065798_sndio_common.c b/pool/shard003/C/0065798_sndio_common.c new file mode 100644 index 0000000000000000000000000000000000000000..1bea6c5be1615f64affe85a8008a493aed6458d5 --- /dev/null +++ b/pool/shard003/C/0065798_sndio_common.c @@ -0,0 +1,120 @@ +/* + * sndio play and grab interface + * Copyright (c) 2010 Jacob Meuser + * + * This file is part of Libav. + * + * Libav 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. + * + * Libav 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 Libav; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +#include "libavformat/avformat.h" + +#include "sndio_common.h" + +static inline void movecb(void *addr, int delta) +{ + SndioData *s = addr; + + s->hwpos += delta * s->channels * s->bps; +} + +av_cold int ff_sndio_open(AVFormatContext *s1, int is_output, + const char *audio_device) +{ + SndioData *s = s1->priv_data; + struct sio_hdl *hdl; + struct sio_par par; + + hdl = sio_open(audio_device, is_output ? SIO_PLAY : SIO_REC, 0); + if (!hdl) { + av_log(s1, AV_LOG_ERROR, "Could not open sndio device\n"); + return AVERROR(EIO); + } + + sio_initpar(&par); + + par.bits = 16; + par.sig = 1; + par.le = SIO_LE_NATIVE; + + if (is_output) + par.pchan = s->channels; + else + par.rchan = s->channels; + par.rate = s->sample_rate; + + if (!sio_setpar(hdl, &par) || !sio_getpar(hdl, &par)) { + av_log(s1, AV_LOG_ERROR, "Impossible to set sndio parameters, " + "channels: %d sample rate: %d\n", s->channels, s->sample_rate); + goto fail; + } + + if (par.bits != 16 || par.sig != 1 || + (is_output && (par.pchan != s->channels)) || + (!is_output && (par.rchan != s->channels)) || + (par.rate != s->sample_rate)) { + av_log(s1, AV_LOG_ERROR, "Could not set appropriate sndio parameters, " + "channels: %d sample rate: %d\n", s->channels, s->sample_rate); + goto fail; + } + + s->buffer_size = par.round * par.bps * + (is_output ? par.pchan : par.rchan); + + if (is_output) { + s->buffer = av_malloc(s->buffer_size); + if (!s->buffer) { + av_log(s1, AV_LOG_ERROR, "Could not allocate buffer\n"); + goto fail; + } + } + + s->codec_id = par.le ? AV_CODEC_ID_PCM_S16LE : AV_CODEC_ID_PCM_S16BE; + s->channels = is_output ? par.pchan : par.rchan; + s->sample_rate = par.rate; + s->bps = par.bps; + + sio_onmove(hdl, movecb, s); + + if (!sio_start(hdl)) { + av_log(s1, AV_LOG_ERROR, "Could not start sndio\n"); + goto fail; + } + + s->hdl = hdl; + + return 0; + +fail: + av_freep(&s->buffer); + + if (hdl) + sio_close(hdl); + + return AVERROR(EIO); +} + +int ff_sndio_close(SndioData *s) +{ + av_freep(&s->buffer); + + if (s->hdl) + sio_close(s->hdl); + + return 0; +} diff --git a/pool/shard003/C/0065803_core.c b/pool/shard003/C/0065803_core.c new file mode 100644 index 0000000000000000000000000000000000000000..2e7b4a2abe44d09bdaea42fabeb177139fed66f9 --- /dev/null +++ b/pool/shard003/C/0065803_core.c @@ -0,0 +1,287 @@ +/* + * arch/arm/mach-sun3i/core.c + * + * (C) Copyright 2007-2012 + * Allwinner Technology Co., Ltd. + * + * 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 +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "core.h" + + +/** + * Global vars definitions + * + */ +static void timer_set_mode(enum clock_event_mode mode, struct clock_event_device *clk) +{ + volatile u32 ctrl; + + switch (mode) { + case CLOCK_EVT_MODE_PERIODIC: + printk("timer_set_mode: periodic\n"); + writel(20, SW_TIMER0_INTVAL_REG); /* interval (999+1) */ + ctrl = readl(SW_TIMER0_CTL_REG); + ctrl &= ~(1<<2); //periodic mode + ctrl |= 1; //enable + break; + + case CLOCK_EVT_MODE_ONESHOT: + printk("timer_set_mode: oneshot\n"); + ctrl = readl(SW_TIMER0_CTL_REG); + ctrl |= (1<<2); + break; + case CLOCK_EVT_MODE_UNUSED: + case CLOCK_EVT_MODE_SHUTDOWN: + default: + ctrl = readl(SW_TIMER0_CTL_REG); + ctrl &= ~(1<<0); + break; + } + + writel(ctrl, SW_TIMER0_CTL_REG); +} + +static int timer_set_next_event(unsigned long evt, struct clock_event_device *unused) +{ + volatile u32 ctrl; + + /* clear any pending before continue */ + ctrl = readl(SW_TIMER0_CTL_REG); + writel(evt, SW_TIMER0_CNTVAL_REG); + writel(ctrl | 0x1, SW_TIMER_INT_STA_REG); + + return 0; +} + +static struct clock_event_device timer0_clockevent = { + .name = "timer0", + .shift = 32, + .features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT, + .set_mode = timer_set_mode, + .set_next_event = timer_set_next_event, +}; + + +static irqreturn_t softwinner_timer_interrupt(int irq, void *dev_id) +{ + struct clock_event_device *evt = &timer0_clockevent; + + writel(0x1, SW_TIMER_INT_STA_REG); + + evt->event_handler(evt); + + return IRQ_HANDLED; +} + +static struct irqaction softwinner_timer_irq = { + .name = "Softwinner Timer Tick", + .flags = IRQF_DISABLED | IRQF_TIMER | IRQF_IRQPOLL, + .handler = softwinner_timer_interrupt, +}; + +void softwinner_irq_ack(struct irq_data *d) +{ + unsigned int irq = d->irq; + volatile u32 val; + + if (irq < 32) { + val = readl(SW_INT_ENABLE_REG0) & (~(1<irq; + volatile u32 val; + + if (irq < 32) { + val = readl(SW_INT_ENABLE_REG0) & (~(1<irq; + volatile u32 val; + + if (irq < 32) { + val = readl(SW_INT_ENABLE_REG0) | (1<PMC_PCER0 = (1 << ID_PIOA); + //Enable UART0 peripheral clock + PMC->PMC_PCER0 = (1 << ID_UART0); + + //Disable interrupts on TXD and RXD pins + PIOA->PIO_IDR = PIO_PA10A_UTXD0 | PIO_PA9A_URXD0; + //No pull-up resistors + PIOA->PIO_PUDR = PIO_PA10A_UTXD0 | PIO_PA9A_URXD0; + //Assign corresponding pins to Peripheral A function + PIOA->PIO_ABCDSR[0] &= ~(PIO_PA10A_UTXD0 | PIO_PA9A_URXD0); + PIOA->PIO_ABCDSR[1] &= ~(PIO_PA10A_UTXD0 | PIO_PA9A_URXD0); + //Disable the PIO from controlling the corresponding pins + PIOA->PIO_PDR = PIO_PA10A_UTXD0 | PIO_PA9A_URXD0; + + //Reset and disable receiver and transmitter, disable interrupts + UART0->UART_CR = UART_CR_RSTTX | UART_CR_RSTRX; + UART0->UART_IDR = 0xFFFFFFFF; + + //Configure baud rate + UART0->UART_BRGR = SystemCoreClock / (16 * baudrate); + + //Configure mode register + UART0->UART_MR = UART_MR_CHMODE_NORMAL | UART_MR_PAR_NO; + + //Disable DMA channel + UART0->UART_PTCR = UART_PTCR_TXTDIS | UART_PTCR_RXTDIS; + + //Enable receiver and transmitter + UART0->UART_CR = UART_CR_TXEN | UART_CR_RXEN; +} + + +/** + * @brief Display the contents of an array + * @param[in] stream Pointer to a FILE object that identifies an output stream + * @param[in] prepend String to prepend to the left of each line + * @param[in] data Pointer to the data array + * @param[in] length Number of bytes to display + **/ + +void debugDisplayArray(FILE *stream, + const char_t *prepend, const void *data, size_t length) +{ + uint_t i; + + for(i = 0; i < length; i++) + { + //Beginning of a new line? + if((i % 16) == 0) + fputs(prepend, stream); + //Display current data byte + fprintf(stream, "%02X ", *((unsigned char *) data + i)); + //End of current line? + if((i % 16) == 15 || i == (length - 1)) + fprintf(stream, "\r\n"); + } +} + + +/** + * @brief Write a character to an output stream + * @param[in] c Character to be written + * @param[in] stream Output stream (only stdout and stderr are supported) + **/ + +int_t fputc(int_t c, FILE *stream) +{ + //Standard output? + if(stream == stdout) + { + //Display current character + lcdPutChar(c); + + return c; + } + //Standard error output? + else if(stream == stderr) + { + //Wait for the transmitter to be ready + while(!(UART0->UART_SR & UART_SR_TXEMPTY)); + + //Send character + UART0->UART_THR = c; + + //Wait for the transfer to complete + while(!(UART0->UART_SR & UART_SR_TXEMPTY)); + + return c; + } + //Unknown output? + else + { + return EOF; + } +} diff --git a/pool/shard003/C/0065838_real.c b/pool/shard003/C/0065838_real.c new file mode 100644 index 0000000000000000000000000000000000000000..38ef45d19d027eb75d6b35d272b20f2685960819 --- /dev/null +++ b/pool/shard003/C/0065838_real.c @@ -0,0 +1,36 @@ +/* + Programa que pega a parte inteira de um numero real, a parte depois da virgula e o numero arredondado + AUTOR: GABRIEL HENRIQUE CAMPOS SCALICI + NUMERO: 9292970 + DATA: 13-04-15 + +*/ + +#include +#include + +int main(void){ + + //Variavel que vai ser utilizada + double num, frac, ni, arred; + + //Pegar o valor digitado pelo usuario + scanf("%lf", &num); + + //Funcao para pegar a parte inteira e a parte depoisda virgula + frac = modf(num, &ni); + + printf("%.0lf\n%.4lf\n", ni, frac); + + //Logica para analisar para qual lado arredonda (para cima ou para baixo) + if(frac<0.5){ + arred = ni; + }else{ + arred = ni+1; + } + + //Mostrando o valor arredondado + printf("%.0lf", arred); + + return 0; +} diff --git a/pool/shard003/C/0065852_utils.c b/pool/shard003/C/0065852_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..7bb34eeaba8214ade972a13f6faded19e5dc9213 --- /dev/null +++ b/pool/shard003/C/0065852_utils.c @@ -0,0 +1,72 @@ +#include +#include + +#include <3ds.h> + +#include "utils.h" + +void Utils_U16_To_U8(u8 *buf, const u16 *input, size_t bufsize) { + ssize_t units = utf16_to_utf8(buf, input, bufsize); + + if (units < 0) + units = 0; + + buf[units] = 0; +} + +char *Utils_Basename(const char *filename) { + char *p = strrchr (filename, '/'); + char *string = strdup(filename); + return p ? p + 1 : string; +} + +void Utils_GetSizeString(char *string, u64 size) { + double double_size = (double)size; + + int i = 0; + static char *units[] = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}; + + while (double_size >= 1024.0f) { + double_size /= 1024.0f; + i++; + } + + sprintf(string, "%.*f %s", (i == 0) ? 0 : 2, double_size, units[i]); +} + +void Utils_SetMax(int *set, int value, int max) { + if (*set > max) + *set = value; +} + +void Utils_SetMin(int *set, int value, int min) { + if (*set < min) + *set = value; +} + +int Utils_Alphasort(const void *p1, const void *p2) { + FS_DirectoryEntry *entryA = (FS_DirectoryEntry *)p1; + FS_DirectoryEntry *entryB = (FS_DirectoryEntry *)p2; + + if ((entryA->attributes & FS_ATTRIBUTE_DIRECTORY) && !(entryB->attributes & FS_ATTRIBUTE_DIRECTORY)) + return -1; + else if (!(entryA->attributes & FS_ATTRIBUTE_DIRECTORY) && (entryB->attributes & FS_ATTRIBUTE_DIRECTORY)) + return 1; + + char entryNameA[256] = {'\0'}, entryNameB[256] = {'\0'}; + Utils_U16_To_U8((u8 *)entryNameA, entryA->name, sizeof(entryNameA) - 1); + Utils_U16_To_U8((u8 *)entryNameB, entryB->name, sizeof(entryNameB) - 1); + return strcasecmp(entryNameA, entryNameB); +} + +void Utils_AppendArr(char subject[], const char insert[], int pos) { + char buf[512] = {}; + + strncpy(buf, subject, pos); + int len = strlen(buf); + strcpy(buf + len, insert); + len += strlen(insert); + strcpy(buf+len, subject + pos); + + strcpy(subject, buf); +} diff --git a/pool/shard003/C/0065855_iw.c b/pool/shard003/C/0065855_iw.c new file mode 100644 index 0000000000000000000000000000000000000000..68eb6dc636f9d4bcafb42bd6f74679451163fbe5 --- /dev/null +++ b/pool/shard003/C/0065855_iw.c @@ -0,0 +1,303 @@ +/* + * This code has been blatently stolen from + * + * nl80211 userspace tool + * + * Copyright 2007, 2008 Johannes Berg + * + * and has been stripped down to just the pieces needed. + */ + +/* + +Copyright (c) 2007, 2008 Johannes Berg +Copyright (c) 2007 Andy Lutomirski +Copyright (c) 2007 Mike Kershaw +Copyright (c) 2008-2009 Luis R. Rodriguez + +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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include "nl80211.h" +#include +#include +#include +#include +#include + +#include +#include +#include "iw.h" + + +#ifndef HAVE_LIBNL20 +/* libnl 2.0 compatibility code */ + +static inline struct nl_handle *nl_socket_alloc(void) +{ + return nl_handle_alloc(); +} + +static inline void nl_socket_free(struct nl_sock *h) +{ + nl_handle_destroy(h); +} + +static inline int __genl_ctrl_alloc_cache(struct nl_sock *h, struct nl_cache **cache) +{ + struct nl_cache *tmp = genl_ctrl_alloc_cache(h); + if (!tmp) + return -ENOMEM; + *cache = tmp; + return 0; +} +#define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache +#endif /* HAVE_LIBNL20 */ + + +static int nl80211_init(struct nl80211_state *state) +{ + int err; + + state->nl_sock = nl_socket_alloc(); + if (!state->nl_sock) { + fprintf(stderr, "Failed to allocate netlink socket.\n"); + return -ENOMEM; + } + + if (genl_connect(state->nl_sock)) { + fprintf(stderr, "Failed to connect to generic netlink.\n"); + err = -ENOLINK; + goto out_handle_destroy; + } + + if (genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache)) { + fprintf(stderr, "Failed to allocate generic netlink cache.\n"); + err = -ENOMEM; + goto out_handle_destroy; + } + + state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211"); + if (!state->nl80211) { + err = -ENOENT; + goto out_cache_free; + } + + return 0; + + out_cache_free: + nl_cache_free(state->nl_cache); + out_handle_destroy: + nl_socket_free(state->nl_sock); + return err; +} + +static void nl80211_cleanup(struct nl80211_state *state) +{ + genl_family_put(state->nl80211); + nl_cache_free(state->nl_cache); + nl_socket_free(state->nl_sock); +} + +static int enable_power_save; + + +static int set_power_save(struct nl80211_state *state, + struct nl_cb *cb, + struct nl_msg *msg) +{ + enum nl80211_ps_state ps_state; + + ps_state = NL80211_PS_DISABLED; + if (enable_power_save) + ps_state = NL80211_PS_ENABLED; + + NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE, ps_state); + + return 0; + + nla_put_failure: + return -ENOBUFS; +} + +static int print_power_save_handler(struct nl_msg *msg, void *arg) +{ + struct nlattr *attrs[NL80211_ATTR_MAX + 1]; + struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg)); + + nla_parse(attrs, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), + genlmsg_attrlen(gnlh, 0), NULL); + + if (!attrs[NL80211_ATTR_PS_STATE]) + return 0; + + switch (nla_get_u32(attrs[NL80211_ATTR_PS_STATE])) { + case NL80211_PS_ENABLED: + enable_power_save = 1; + break; + case NL80211_PS_DISABLED: + default: + enable_power_save = 0; + break; + } + + return NL_SKIP; +} + +static int get_power_save(struct nl80211_state *state, + struct nl_cb *cb, + struct nl_msg *msg) +{ + nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, + print_power_save_handler, NULL); + return 0; +} + +static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, + void *arg) +{ + int *ret = arg; + *ret = err->error; + return NL_STOP; +} + +static int finish_handler(struct nl_msg *msg, void *arg) +{ + int *ret = arg; + *ret = 0; + return NL_SKIP; +} + +static int ack_handler(struct nl_msg *msg, void *arg) +{ + int *ret = arg; + *ret = 0; + return NL_STOP; +} + +static int __handle_cmd(struct nl80211_state *state, const char *iface, int get) +{ + struct nl_cb *cb; + struct nl_msg *msg; + int devidx = 0; + int err; + + devidx = if_nametoindex(iface); + if (devidx == 0) + devidx = -1; + if (devidx < 0) + return -errno; + + msg = nlmsg_alloc(); + if (!msg) { + fprintf(stderr, "failed to allocate netlink message\n"); + return 2; + } + + cb = nl_cb_alloc(NL_CB_DEFAULT); + if (!cb) { + fprintf(stderr, "failed to allocate netlink callbacks\n"); + err = 2; + goto out_free_msg; + } + + if (get) + genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0, + 0, NL80211_CMD_GET_POWER_SAVE, 0); + else + genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0, + 0, NL80211_CMD_SET_POWER_SAVE, 0); + + + NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, devidx); + + if (get) + err = get_power_save(state, cb, msg); + else + err = set_power_save(state, cb, msg); + + if (err) + goto out; + + err = nl_send_auto_complete(state->nl_sock, msg); + if (err < 0) + goto out; + + err = 1; + + nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err); + nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err); + nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err); + + while (err > 0) + nl_recvmsgs(state->nl_sock, cb); + out: + nl_cb_put(cb); + out_free_msg: + nlmsg_free(msg); + return err; + nla_put_failure: + fprintf(stderr, "building message failed\n"); + return 2; +} + + +int set_wifi_power_saving(const char *iface, int state) +{ + struct nl80211_state nlstate; + int err; + + err = nl80211_init(&nlstate); + if (err) + return 1; + + enable_power_save = state; + err = __handle_cmd(&nlstate, iface, 0); + + nl80211_cleanup(&nlstate); + + return err; +} + + +int get_wifi_power_saving(const char *iface) +{ + struct nl80211_state nlstate; + int err; + + enable_power_save = 0; + + err = nl80211_init(&nlstate); + if (err) + return 1; + + err = __handle_cmd(&nlstate, iface, 1); + + nl80211_cleanup(&nlstate); + + if (err) /* not a wifi interface */ + return 1; + + return enable_power_save; +} diff --git a/pool/shard003/C/0065860_table.c b/pool/shard003/C/0065860_table.c new file mode 100644 index 0000000000000000000000000000000000000000..95cb6e529de322b958ab0d436b27d7443cda12a4 --- /dev/null +++ b/pool/shard003/C/0065860_table.c @@ -0,0 +1,105 @@ +#include "value.h" +#include "table.h" +#include "vec.h" +#include "util.h" + +void +table_init(struct table *t) +{ + for (int i = 0; i < TABLE_SIZE; ++i) { + vec_init(t->buckets[i].hashes); + vec_init(t->buckets[i].names); + vec_init(t->buckets[i].values); + } + + t->finalizer = NIL; +} + +struct value * +table_add(struct table *t, char const *name, unsigned long h, struct value f) +{ + int i = h % TABLE_SIZE; + + struct value *m = table_lookup(t, name, h); + + if (m == NULL) { + vec_push(t->buckets[i].hashes, h); + vec_push(t->buckets[i].names, name); + vec_push(t->buckets[i].values, f); + return vec_last(t->buckets[i].values); + } else { + *m = f; + return m; + } +} + +void +table_copy(struct table *dst, struct table const *src) +{ + struct bucket *dt = dst->buckets; + struct bucket const *st = src->buckets; + + for (int i = 0; i < TABLE_SIZE; ++i) { + if (st[i].hashes.count == 0) + continue; + vec_push_n( + dt[i].hashes, + st[i].hashes.items, + st[i].hashes.count + ); + vec_push_n( + dt[i].names, + st[i].names.items, + st[i].names.count + ); + vec_push_n( + dt[i].values, + st[i].values.items, + st[i].values.count + ); + } +} + +struct value * +table_lookup(struct table const *t, char const *name, unsigned long h) +{ + int i = h % TABLE_SIZE; + + struct bucket const *b = &t->buckets[i]; + + for (int i = 0; i < b->hashes.count; ++i) { + if (b->hashes.items[i] != h) + continue; + if (strcmp(b->names.items[i], name) == 0) + return &b->values.items[i]; + } + + return NULL; +} + +void +table_release(struct table *t) +{ + for (int i = 0; i < TABLE_SIZE; ++i) { + gc_free(t->buckets[i].values.items); + gc_free(t->buckets[i].names.items); + gc_free(t->buckets[i].hashes.items); + } +} + +int +table_get_completions(struct table const *t, char const *prefix, char **out, int max) +{ + int n = 0; + int prefix_len = strlen(prefix); + + for (int i = 0; i < TABLE_SIZE; ++i) { + for (int j = 0; j < t->buckets[i].names.count; ++j) { + if (n < max && strncmp(t->buckets[i].names.items[j], prefix, prefix_len) == 0) { + out[n++] = sclone_malloc(t->buckets[i].names.items[j]); + } + } + } + + return n; +} diff --git a/pool/shard003/C/0065865_alphablend.c b/pool/shard003/C/0065865_alphablend.c new file mode 100644 index 0000000000000000000000000000000000000000..82cd882e653c6566ee55ba3f8997df4d3ff6b5b0 --- /dev/null +++ b/pool/shard003/C/0065865_alphablend.c @@ -0,0 +1,78 @@ +/* + * alpha blend + * (c) gleicon - 2003 + * blends 2 pixels using alpha factor from 0 to 255 + * + * *_from - smallest image, must be smaller than the destination + * *_to - destination image + * + * + * from, from_w, from_h, from_depth - Data from logo + * to, to_w, to_h, to_depth, - Data to mix it + * off_x, off_y, alpha - Stuff-o + * + * off_x, off_y -> offset within image + * alpha - 0 to 255 (0 = opaque, 255 almost invisible) + * + * After loading both image, just fill in the parameters and be happy +*/ + + +/* aux function */ + +int blend_pix (unsigned char p1, unsigned char p2, unsigned char alpha ) { + unsigned char diff ; + float alphaFactor = alpha/255.0; + unsigned char value; + + diff = (p1>p2)?p1-p2:p2-p1; + + if (diff == 0) return p1; + + diff = (unsigned char)(diff * alphaFactor); + + if (p1>p2) value = p1 - diff; + else value = p1 + diff; + + return value; +} + + +int alphablend(unsigned char *from, int from_w, int from_h, int from_depth, + unsigned char *to, int to_w, int to_h, int to_depth, + int off_x, int off_y, unsigned char alpha){ + + int a, b, from_size, to_size, sub_pixel; + unsigned char *from_pix, *to_pix; + + if (to_depth != from_depth) { + // unmatched depths + return -1; + } + if (from_w > to_w || from_h > to_h){ + // "from" image is bigger than "to" + return -2; + } + if (((off_x + from_w) > to_w) || ((off_y + from_h) > to_h)) { + // offset out of range + return -3; + } + + from_size=from_w*from_h* from_depth; + to_size=to_w*to_h* to_depth; + + for (a=0; acount = initial_value; + sem->waiters_count = 0; + + sem->count_lock = SDL_CreateMutex(); + sem->count_nonzero = SDL_CreateCond(); + if ( ! sem->count_lock || ! sem->count_nonzero ) { + SDL_DestroySemaphore(sem); + return NULL; + } + + return sem; +} + +/* WARNING: + You cannot call this function when another thread is using the semaphore. +*/ +void SDL_DestroySemaphore(SDL_sem *sem) +{ + if ( sem ) { + sem->count = 0xFFFFFFFF; + while ( sem->waiters_count > 0) { + SDL_CondSignal(sem->count_nonzero); + SDL_Delay(10); + } + SDL_DestroyCond(sem->count_nonzero); + if ( sem->count_lock ) { + SDL_mutexP(sem->count_lock); + SDL_mutexV(sem->count_lock); + SDL_DestroyMutex(sem->count_lock); + } + SDL_free(sem); + } +} + +int SDL_SemTryWait(SDL_sem *sem) +{ + int retval; + + if ( ! sem ) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + retval = SDL_MUTEX_TIMEDOUT; + SDL_LockMutex(sem->count_lock); + if ( sem->count > 0 ) { + --sem->count; + retval = 0; + } + SDL_UnlockMutex(sem->count_lock); + + return retval; +} + +int SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout) +{ + int retval; + + if ( ! sem ) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + /* A timeout of 0 is an easy case */ + if ( timeout == 0 ) { + return SDL_SemTryWait(sem); + } + + SDL_LockMutex(sem->count_lock); + ++sem->waiters_count; + retval = 0; + while ( (sem->count == 0) && (retval != SDL_MUTEX_TIMEDOUT) ) { + retval = SDL_CondWaitTimeout(sem->count_nonzero, + sem->count_lock, timeout); + } + --sem->waiters_count; + if (retval == 0) { + --sem->count; + } + SDL_UnlockMutex(sem->count_lock); + + return retval; +} + +int SDL_SemWait(SDL_sem *sem) +{ + return SDL_SemWaitTimeout(sem, SDL_MUTEX_MAXWAIT); +} + +Uint32 SDL_SemValue(SDL_sem *sem) +{ + Uint32 value; + + value = 0; + if ( sem ) { + SDL_LockMutex(sem->count_lock); + value = sem->count; + SDL_UnlockMutex(sem->count_lock); + } + return value; +} + +int SDL_SemPost(SDL_sem *sem) +{ + if ( ! sem ) { + SDL_SetError("Passed a NULL semaphore"); + return -1; + } + + SDL_LockMutex(sem->count_lock); + if ( sem->waiters_count > 0 ) { + SDL_CondSignal(sem->count_nonzero); + } + ++sem->count; + SDL_UnlockMutex(sem->count_lock); + + return 0; +} + +#endif /* SDL_THREADS_DISABLED */ diff --git a/pool/shard003/C/0065880_bspcmdline_getparamrhs.c b/pool/shard003/C/0065880_bspcmdline_getparamrhs.c new file mode 100644 index 0000000000000000000000000000000000000000..cf2afcec97e1777cff22dffb62efac978c282068 --- /dev/null +++ b/pool/shard003/C/0065880_bspcmdline_getparamrhs.c @@ -0,0 +1,46 @@ +/* + * COPYRIGHT (c) 1989-2009. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include + +#include + +const char *rtems_bsp_cmdline_get_param_rhs( + const char *name, + char *value, + size_t length +) +{ + const char *p; + const char *rhs; + char *d; + + p = rtems_bsp_cmdline_get_param( name, value, length ); + if ( !p ) + return NULL; + + rhs = &p[strlen(name)]; + if ( *rhs != '=' ) + return NULL; + + rhs++; + if ( *rhs == '\"' ) + rhs++; + for ( d=value ; *rhs ; ) + *d++ = *rhs++; + if ( *(d-1) == '\"' ) + d--; + *d = '\0'; + + return value; +} diff --git a/pool/shard003/C/0065886_tst-flock2.c b/pool/shard003/C/0065886_tst-flock2.c new file mode 100644 index 0000000000000000000000000000000000000000..941c52ffe9bc1db7e249cd0cad2d23a6c60ff228 --- /dev/null +++ b/pool/shard003/C/0065886_tst-flock2.c @@ -0,0 +1,259 @@ +/* Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 2002. + + The GNU C 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. + + The GNU C 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 the GNU C Library; if not, see + . */ + +#include +#include +#include +#include +#include +#include +#include +#include + + +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; +static int fd; + + +static void * +tf (void *arg) +{ + struct flock fl = + { + .l_type = F_WRLCK, + .l_start = 0, + .l_whence = SEEK_SET, + .l_len = 10 + }; + if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0) + { + puts ("fourth fcntl failed"); + exit (1); + } + + pthread_mutex_unlock (&lock); + + pthread_mutex_lock (&lock2); + + return NULL; +} + + +static int +do_test (void) +{ + char tmp[] = "/tmp/tst-flock2-XXXXXX"; + + fd = mkstemp (tmp); + if (fd == -1) + { + puts ("mkstemp failed"); + return 1; + } + + unlink (tmp); + + int i; + for (i = 0; i < 20; ++i) + write (fd, "foobar xyzzy", 12); + + pthread_barrier_t *b; + b = mmap (NULL, sizeof (pthread_barrier_t), PROT_READ | PROT_WRITE, + MAP_SHARED, fd, 0); + if (b == MAP_FAILED) + { + puts ("mmap failed"); + return 1; + } + + pthread_barrierattr_t ba; + if (pthread_barrierattr_init (&ba) != 0) + { + puts ("barrierattr_init failed"); + return 1; + } + + if (pthread_barrierattr_setpshared (&ba, PTHREAD_PROCESS_SHARED) != 0) + { + puts ("barrierattr_setpshared failed"); + return 1; + } + + if (pthread_barrier_init (b, &ba, 2) != 0) + { + puts ("barrier_init failed"); + return 1; + } + + if (pthread_barrierattr_destroy (&ba) != 0) + { + puts ("barrierattr_destroy failed"); + return 1; + } + + struct flock fl = + { + .l_type = F_WRLCK, + .l_start = 0, + .l_whence = SEEK_SET, + .l_len = 10 + }; + if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0) + { + puts ("first fcntl failed"); + return 1; + } + + pid_t pid = fork (); + if (pid == -1) + { + puts ("fork failed"); + return 1; + } + + if (pid == 0) + { + /* Make sure the child does not stay around indefinitely. */ + alarm (10); + + /* Try to get the lock. */ + if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLK, &fl)) == 0) + { + puts ("child: second flock succeeded"); + return 1; + } + } + + pthread_barrier_wait (b); + + if (pid != 0) + { + fl.l_type = F_UNLCK; + if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0) + { + puts ("third fcntl failed"); + return 1; + } + } + + pthread_barrier_wait (b); + + pthread_t th; + if (pid == 0) + { + if (pthread_mutex_lock (&lock) != 0) + { + puts ("1st locking of lock failed"); + return 1; + } + + if (pthread_mutex_lock (&lock2) != 0) + { + puts ("1st locking of lock2 failed"); + return 1; + } + + if (pthread_create (&th, NULL, tf, NULL) != 0) + { + puts ("pthread_create failed"); + return 1; + } + + if (pthread_mutex_lock (&lock) != 0) + { + puts ("2nd locking of lock failed"); + return 1; + } + + puts ("child locked file"); + } + + pthread_barrier_wait (b); + + if (pid != 0) + { + fl.l_type = F_WRLCK; + if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLK, &fl)) == 0) + { + puts ("fifth fcntl succeeded"); + return 1; + } + + puts ("file locked by child"); + } + + pthread_barrier_wait (b); + + if (pid == 0) + { + if (pthread_mutex_unlock (&lock2) != 0) + { + puts ("unlock of lock2 failed"); + return 1; + } + + if (pthread_join (th, NULL) != 0) + { + puts ("join failed"); + return 1; + } + + puts ("child's thread terminated"); + } + + pthread_barrier_wait (b); + + if (pid != 0) + { + fl.l_type = F_WRLCK; + if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLK, &fl)) == 0) + { + puts ("fifth fcntl succeeded"); + return 1; + } + + puts ("file still locked"); + } + + pthread_barrier_wait (b); + + if (pid == 0) + { + _exit (0); + } + + int status; + if (TEMP_FAILURE_RETRY (waitpid (pid, &status, 0)) != pid) + { + puts ("waitpid failed"); + return 1; + } + puts ("child terminated"); + + if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0) + { + puts ("sixth fcntl failed"); + return 1; + } + + return status; +} + +#define TEST_FUNCTION do_test () +#include "../test-skeleton.c" diff --git a/pool/shard003/C/0065908_packet_utils.c b/pool/shard003/C/0065908_packet_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..aa01c8ac9dcd47aca71d1e3492e0121c029be86b --- /dev/null +++ b/pool/shard003/C/0065908_packet_utils.c @@ -0,0 +1,227 @@ +/** + + @copyright + Copyright (c) 2002 - 2010, AuthenTec Oy. All rights reserved. + + engine_packet.c + + Generic interceptor packet modification routines. These functions + are implemented using the packet interation functions. It might be + more efficient to re-implement these in the platform specific code. + + +*/ + + +#include "sshincludes.h" +#include "interceptor.h" + +#define SSH_DEBUG_MODULE "SshEnginePacket" + +/* Since all functions of this file might be implemented in platform + specific interceptor files, this file can end up being empty. This + declaration is here to prevent any warnings from that empty file. + It is not used for anything. */ +typedef enum +{ + SSH_EMPTY1 +} SshToMakeThisFileNotEmpty; + +#ifndef INTERCEPTOR_HAS_PACKET_COPYIN +/* Copies data into the packet. Space for the new data must already have been + allocated. It is a fatal error to attempt to copy beyond the allocated + packet. Multiple threads may call this function concurrently, but not for + the same packet. Returns TRUE if successfull and FALSE otherwise. If error + occurs then the pp is already freed by this function, and the caller must + not refer to it anymore. + + There is a generic version of this function inside the engine, in case + interceptor does not want to implement this. If interceptor implements this + function it must define INTERCEPTOR_HAS_PACKET_COPYIN from the + ipsec/configure.in.inc. */ +Boolean ssh_interceptor_packet_copyin(SshInterceptorPacket pp, size_t offset, + const unsigned char *buf, size_t len) +{ + unsigned char *ucp; + size_t segment_len; + + SSH_DEBUG(SSH_D_MIDSTART, ("copyin pp 0x%lx, ofs %ld, buf 0x%lx, len %ld", + (long)pp, (long)offset, (long)buf, (long)len)); + + ssh_interceptor_packet_reset_iteration(pp, offset, len); + while (ssh_interceptor_packet_next_iteration(pp, &ucp, &segment_len)) + { + memcpy(ucp, buf, segment_len); + buf += segment_len; + } + if (ucp != NULL) + return FALSE; + return TRUE; +} +#endif /* INTERCEPTOR_HAS_PACKET_COPYIN */ + +#ifndef INTERCEPTOR_HAS_PACKET_COPYOUT +/* Copies data out from the packet. Space for the new data must + already have been allocated. It is a fatal error to attempt to + copy beyond the allocated packet. Multiple threads may call this + function concurrently, but not for the same packet. + + There is a generic version of this function inside the engine, in case + interceptor does not want to implement this. If interceptor implements this + function it must define INTERCEPTOR_HAS_PACKET_COPYOUT from the + ipsec/configure.in.inc. */ +void ssh_interceptor_packet_copyout(SshInterceptorPacket pp, size_t offset, + unsigned char *buf, size_t len) +{ + const unsigned char *ucp; + size_t segment_len; + + SSH_DEBUG(SSH_D_MIDSTART, + ("copyout pp 0x%lx, ofs %ld, buf 0x%lx, len %ld", + (long)pp, (long)offset, (long)buf, (long)len)); + + ssh_interceptor_packet_reset_iteration(pp, offset, len); + while (ssh_interceptor_packet_next_iteration_read(pp, &ucp, &segment_len)) + { + memcpy(buf, ucp, segment_len); + buf += segment_len; + } + SSH_ASSERT(ucp == NULL); /* next_iteration_read cannot fail. */ +} +#endif /* INTERCEPTOR_HAS_PACKET_COPYOUT */ + +#ifndef INTERCEPTOR_HAS_PACKET_COPY +/* Copy data from one packet to another. Start from the `source_offset' and + copy `bytes_to_copy' bytes to `destination_offset' in the destination + packet. If the destination packet cannot be written then return FALSE, and + the destination packet has been freed by this function. The source packet is + not freed even in case of error. If data copying was successfull then return + TRUE. + + This function can also be implemented so that it will simply increment the + reference counts in the source packet and share the actual data without + copying it at all. There is a generic version of this function inside the + engine, in case interceptor does not want to implement this. If interceptor + implements this function it must define INTERCEPTOR_HAS_PACKET_COPY from the + ipsec/configure.in.inc. */ +Boolean ssh_interceptor_packet_copy(SshInterceptorPacket source_pp, + size_t source_offset, + size_t bytes_to_copy, + SshInterceptorPacket destination_pp, + size_t destination_offset) +{ + size_t segoff, seglen; + const unsigned char *seg; + + /* Copy `bytes_to_copy' bytes from the original packet. */ + segoff = 0; + ssh_interceptor_packet_reset_iteration(source_pp, source_offset, + bytes_to_copy); + while (ssh_interceptor_packet_next_iteration_read(source_pp, &seg, &seglen)) + { + if (!ssh_interceptor_packet_copyin(destination_pp, + destination_offset + segoff, + seg, seglen)) + { + SSH_DEBUG(SSH_D_ERROR, ("Could not copy packet")); + return FALSE; + } + segoff += seglen; + } + SSH_ASSERT(seg == NULL); /* next_iteration_read cannot fail. */ + return TRUE; +} +#endif /* INTERCEPTOR_HAS_PACKET_COPY */ + +#ifndef INTERCEPTOR_HAS_PACKET_ALLOC_AND_COPY_EXT_DATA +SshInterceptorPacket ssh_interceptor_packet_alloc_and_copy_ext_data( + SshInterceptor interceptor, + SshInterceptorPacket pp, + size_t total_len) +{ + SshInterceptorPacket new_pp; + + /* Actually, only the `total_length' argument is interesting. + Everything else will be reset when the public data is copied. */ + new_pp = ssh_interceptor_packet_alloc(interceptor, + pp->flags + & (SSH_PACKET_FROMPROTOCOL + | SSH_PACKET_FROMADAPTER + | SSH_PACKET_HWCKSUM), + pp->protocol, + pp->ifnum_in, + pp->ifnum_out, + total_len); + if (new_pp == NULL) + return NULL; + + /* Copy all public data from the source packet. */ + memcpy(new_pp, pp, sizeof(*pp)); + + return new_pp; +} +#endif /* INTERCEPTOR_HAS_PACKET_ALLOC_AND_COPY_EXT_DATA */ + +#ifndef INTERCEPTOR_HAS_PACKET_CACHE +/* The ssh_interceptor_packet_cache() takes a reference to the packet + SshInterceptorPacket that is valid over ssh_interceptor_packet_free() and + ssh_interceptor_send(). The data in the publically accessed fields in + SshInterceptorPacket is a copy of 'pp' at the time of the call. The + actual contents of the packet may change after the call, as they + may be referenced from the actual packet. It is upto the caller to + provide concurrency control or protection for that. + + The function returns NULL if it fails. */ +SshInterceptorPacket +ssh_interceptor_packet_cache(SshInterceptor interceptor, + SshInterceptorPacket pp) +{ + SshUInt32 flags; + SshInterceptorPacket dst; + size_t len = ssh_interceptor_packet_len(pp); + + flags = pp->flags & (SSH_PACKET_FROMPROTOCOL | SSH_PACKET_FROMADAPTER + | SSH_PACKET_HWCKSUM); + dst = ssh_interceptor_packet_alloc(interceptor, flags, + pp->protocol, + pp->ifnum_in, + pp->ifnum_out, + len); + if (dst == NULL) + return NULL; + + dst->flags = pp->flags; + + if (ssh_interceptor_packet_copy(pp, 0, len, dst, 0) == FALSE) + { + ssh_interceptor_packet_free(dst); + return NULL; + } + return dst; +} +#endif /* INTERCEPTOR_HAS_PACKET_CACHE */ + + +#ifndef INTERCEPTOR_HAS_PACKET_INTERNAL_DATA_ROUTINES +Boolean ssh_interceptor_packet_export_internal_data(SshInterceptorPacket pp, + unsigned char **data_ret, + size_t *len_return) +{ + SSH_ASSERT(data_ret && len_return); + + *len_return = 0; + *data_ret = NULL; + + return TRUE; +} + +Boolean ssh_interceptor_packet_import_internal_data(SshInterceptorPacket pp, + const unsigned char *data, + size_t len) +{ + /* notice: data might be non-NULL, don't assert that */ + SSH_ASSERT(!len); + + return TRUE; +} +#endif /* INTERCEPTOR_HAS_PACKET_INTERNAL_DATA_ROUTINES */ diff --git a/pool/shard003/C/0065924_inet_ntop.c b/pool/shard003/C/0065924_inet_ntop.c new file mode 100644 index 0000000000000000000000000000000000000000..80bb05c1ce113beb030fe990ad9aa043a352fbd7 --- /dev/null +++ b/pool/shard003/C/0065924_inet_ntop.c @@ -0,0 +1,238 @@ +/* inet_ntop.c -- convert IPv4 and IPv6 addresses from binary to text form + + Copyright (C) 2005, 2006, 2008 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 2, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* + * Copyright (c) 1996-1999 by Internet Software Consortium. + * + * 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 INTERNET SOFTWARE CONSORTIUM DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE + * CONSORTIUM 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 + +/* Specification. */ +#include "socketx.h" + +#include +#include +#include + +#ifndef EAFNOSUPPORT +# define EAFNOSUPPORT EINVAL +#endif + +#define NS_IN6ADDRSZ 16 +#define NS_INT16SZ 2 + +/* + * WARNING: Don't even consider trying to compile this on a system where + * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. + */ +typedef int verify_int_size[2 * sizeof (int) - 7]; + +static const char *inet_ntop4 (const unsigned char *src, char *dst, socklen_t size); +#if HAVE_IPV6 +static const char *inet_ntop6 (const unsigned char *src, char *dst, socklen_t size); +#endif + + +/* char * + * inet_ntop(af, src, dst, size) + * convert a network format address to presentation format. + * return: + * pointer to presentation format address (`dst'), or NULL (see errno). + * author: + * Paul Vixie, 1996. + */ +const char * +inet_ntop (int af, const void *restrict src, + char *restrict dst, socklen_t cnt) +{ + switch (af) + { +#if HAVE_IPV4 + case AF_INET: + return (inet_ntop4 (src, dst, cnt)); +#endif + +#if HAVE_IPV6 + case AF_INET6: + return (inet_ntop6 (src, dst, cnt)); +#endif + + default: + errno = EAFNOSUPPORT; + return (NULL); + } + /* NOTREACHED */ +} + +/* const char * + * inet_ntop4(src, dst, size) + * format an IPv4 address + * return: + * `dst' (as a const) + * notes: + * (1) uses no statics + * (2) takes a u_char* not an in_addr as input + * author: + * Paul Vixie, 1996. + */ +static const char * +inet_ntop4 (const unsigned char *src, char *dst, socklen_t size) +{ + char tmp[sizeof "255.255.255.255"]; + int len; + + len = sprintf (tmp, "%u.%u.%u.%u", src[0], src[1], src[2], src[3]); + if (len < 0) + return NULL; + + if (len > size) + { + errno = ENOSPC; + return NULL; + } + + return strcpy (dst, tmp); +} + +#if HAVE_IPV6 + +/* const char * + * inet_ntop6(src, dst, size) + * convert IPv6 binary address into presentation (printable) format + * author: + * Paul Vixie, 1996. + */ +static const char * +inet_ntop6 (const unsigned char *src, char *dst, socklen_t size) +{ + /* + * Note that int32_t and int16_t need only be "at least" large enough + * to contain a value of the specified size. On some systems, like + * Crays, there is no such thing as an integer variable with 16 bits. + * Keep this in mind if you think this function should have been coded + * to use pointer overlays. All the world's not a VAX. + */ + char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp; + struct + { + int base, len; + } best, cur; + unsigned int words[NS_IN6ADDRSZ / NS_INT16SZ]; + int i; + + /* + * Preprocess: + * Copy the input (bytewise) array into a wordwise array. + * Find the longest run of 0x00's in src[] for :: shorthanding. + */ + memset (words, '\0', sizeof words); + for (i = 0; i < NS_IN6ADDRSZ; i += 2) + words[i / 2] = (src[i] << 8) | src[i + 1]; + best.base = -1; + cur.base = -1; + for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) + { + if (words[i] == 0) + { + if (cur.base == -1) + cur.base = i, cur.len = 1; + else + cur.len++; + } + else + { + if (cur.base != -1) + { + if (best.base == -1 || cur.len > best.len) + best = cur; + cur.base = -1; + } + } + } + if (cur.base != -1) + { + if (best.base == -1 || cur.len > best.len) + best = cur; + } + if (best.base != -1 && best.len < 2) + best.base = -1; + + /* + * Format the result. + */ + tp = tmp; + for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) + { + /* Are we inside the best run of 0x00's? */ + if (best.base != -1 && i >= best.base && i < (best.base + best.len)) + { + if (i == best.base) + *tp++ = ':'; + continue; + } + /* Are we following an initial run of 0x00s or any real hex? */ + if (i != 0) + *tp++ = ':'; + /* Is this address an encapsulated IPv4? */ + if (i == 6 && best.base == 0 && + (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) + { + if (!inet_ntop4 (src + 12, tp, sizeof tmp - (tp - tmp))) + return (NULL); + tp += strlen (tp); + break; + } + { + int len = sprintf (tp, "%x", words[i]); + if (len < 0) + return NULL; + tp += len; + } + } + /* Was it a trailing run of 0x00's? */ + if (best.base != -1 && (best.base + best.len) == + (NS_IN6ADDRSZ / NS_INT16SZ)) + *tp++ = ':'; + *tp++ = '\0'; + + /* + * Check for overflow, copy, and we're done. + */ + if ((socklen_t) (tp - tmp) > size) + { + errno = ENOSPC; + return NULL; + } + + return strcpy (dst, tmp); +} + +#endif diff --git a/pool/shard003/C/0065933_mapstrings.c b/pool/shard003/C/0065933_mapstrings.c new file mode 100644 index 0000000000000000000000000000000000000000..91795d572ba2a78d87b6cee4724049bd5fea4945 --- /dev/null +++ b/pool/shard003/C/0065933_mapstrings.c @@ -0,0 +1,167 @@ +/* mapstrings.c - Static string mapping + * Copyright (C) 2014 Werner Koch + * + * This file is part of GnuPG. + * + * This file is free software; you can redistribute it and/or modify + * it under the terms of either + * + * - 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. + * + * or + * + * - 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. + * + * or both in parallel, as here. + * + * This file 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 "util.h" +#include "stringhelp.h" +#include "membuf.h" + + +static struct { + const char *name; + const char *value; +} macros[] = { +#ifdef PACKAGE_BUGREPORT + { "EMAIL", PACKAGE_BUGREPORT }, +#else + { "EMAIL", "bug@example.org" }, +#endif + { "GNUPG", GNUPG_NAME }, + { "GPG", GPG_NAME }, + { "GPGSM", GPGSM_NAME }, + { "GPG_AGENT", GPG_AGENT_NAME }, + { "SCDAEMON", SCDAEMON_NAME }, + { "DIRMNGR", DIRMNGR_NAME }, + { "G13", G13_NAME }, + { "GPGCONF", GPGCONF_NAME }, + { "GPGTAR", GPGTAR_NAME } +}; + + + +/* A list to remember already done mappings. */ +struct mapping_s +{ + struct mapping_s *next; + const char *key; + const char *value; +}; +static struct mapping_s *mappings; + + +/* If STRING has already been mapped, return the mapped string. If + not return NULL. */ +static const char * +already_mapped (const char *string) +{ + struct mapping_s *m; + + for (m=mappings; m; m = m->next) + if (m->key == string && !strcmp (m->key, string)) + return m->value; + return NULL; +} + + +/* Store NEWSTRING under key STRING and return NEWSTRING. */ +static const char * +store_mapping (const char *string, char *newstring) +{ + struct mapping_s *m; + + m = xmalloc (sizeof *m); + m->key = string; + m->value = newstring; + m->next = mappings; + mappings = m; + return newstring; +} + + +/* Find the first macro in STRING. Return a pointer to the + replacement value, set BEGPTR to the leading '@', and set ENDPTR to + the terminating '@'. If no macro is found return NULL. */ +const char * +find_macro (const char *string, const char **begptr, + const char **endptr) +{ + const char *s, *s2, *s3; + int idx; + + s = string; + if (!s) + return NULL; + + for (; (s2 = strchr (s, '@')); s = s2) + { + s2++; + if (*s2 >= 'A' && *s2 <= 'Z' && (s3 = (strchr (s2, '@')))) + { + for (idx=0; idx < DIM (macros); idx++) + if (strlen (macros[idx].name) == (s3 - s2) + && !memcmp (macros[idx].name, s2, (s3 - s2))) + { + *begptr = s2 - 1; + *endptr = s3; + return macros[idx].value; + } + } + } + return NULL; +} + + +/* If STRING includes known @FOO@ macros, replace these macros and + return a new static string. Warning: STRING must have been + allocated statically. Note that this function allocated memory + which will not be released (similar to gettext). */ +const char * +map_static_macro_string (const char *string) +{ + const char *s, *s2, *s3, *value; + membuf_t mb; + char *p; + + if ((s = already_mapped (string))) + return s; + s = string; + value = find_macro (s, &s2, &s3); + if (!value) + return string; /* No macros at all. */ + + init_membuf (&mb, strlen (string) + 100); + do + { + put_membuf (&mb, s, s2 - s); + put_membuf_str (&mb, value); + s = s3 + 1; + } + while ((value = find_macro (s, &s2, &s3))); + put_membuf_str (&mb, s); + put_membuf (&mb, "", 1); + + p = get_membuf_shrink (&mb, NULL); + if (!p) + log_fatal ("map_static_macro_string failed: %s\n", strerror (errno)); + + return store_mapping (string, p); +} diff --git a/pool/shard003/C/0065942_muleu_s_ph_qbl.c b/pool/shard003/C/0065942_muleu_s_ph_qbl.c new file mode 100644 index 0000000000000000000000000000000000000000..66a382806a21829a216ec8a17eb952706149dc4c --- /dev/null +++ b/pool/shard003/C/0065942_muleu_s_ph_qbl.c @@ -0,0 +1,25 @@ +#include +#include + +int main() +{ + int rd, rs, rt, dsp; + int result, resultdsp; + + rs = 0x80001234; + rt = 0x80004321; + result = 0xFFFF0000; + resultdsp = 1; + + __asm + ("muleu_s.ph.qbl %0, %2, %3\n\t" + "rddsp %1\n\t" + : "=r"(rd), "=r"(dsp) + : "r"(rs), "r"(rt) + ); + dsp = (dsp >> 21) & 0x01; + assert(rd == result); + assert(dsp == resultdsp); + + return 0; +} diff --git a/pool/shard003/C/0065945_ps2kbd.c b/pool/shard003/C/0065945_ps2kbd.c new file mode 100644 index 0000000000000000000000000000000000000000..652f40ff2dfa9869d3f664029529b2e0c479e43d --- /dev/null +++ b/pool/shard003/C/0065945_ps2kbd.c @@ -0,0 +1,104 @@ +/* + * PS/2 Keyboard driver + * + * + * This file is part of Aquila OS and is released under + * the terms of GNU GPLv3 - See LICENSE. + * + * Copyright (C) 2016 Mohamed Anwar + */ + + +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include + +#include +#include + +#include + +#define BUFSIZE 128 + +static struct ringbuf *kbd_ring = RINGBUF_NEW(BUFSIZE); /* Keboard Ring Buffer */ +static struct proc *proc = NULL; /* Current process using Keboard */ +static struct queue *kbd_read_queue = QUEUE_NEW(); /* Keyboard read queue */ + +static void ps2kbd_handler(int scancode) +{ + ringbuf_write(kbd_ring, sizeof(scancode), (char *) &scancode); + + if (kbd_read_queue->count) + thread_queue_wakeup(kbd_read_queue); +} + +static void ps2kbd_register(void) +{ + x86_i8042_handler_register(1, ps2kbd_handler); +} + +static ssize_t ps2kbd_read(struct devid *dd, off_t off, size_t sz, void *buf) +{ + (void) dd; + (void) off; + + return ringbuf_read(kbd_ring, sz, buf); +} + +static int ps2kbd_probe(void) +{ + ps2kbd_register(); + kdev_chrdev_register(11, &ps2kbddev); + return 0; +} + +/* File Operations */ +static int ps2kbd_file_open(struct file *file) +{ + if (proc) /* Only one process can open kbd */ + return -EACCES; + + proc = curproc; + + /* This is either really smart or really dumb */ + file->vnode->read_queue = kbd_read_queue; + + return posix_file_open(file); +} + +static int ps2kbd_file_can_read(struct file *file, size_t size) +{ + printk("ps2kbd_file_can_read(file=%p, size=%d)\n", file, size); + + (void) file; + return ringbuf_available(kbd_ring); +} + + +struct dev ps2kbddev = { + .name = "kbddev", + + .probe = ps2kbd_probe, + .read = ps2kbd_read, + + .fops = { + .open = ps2kbd_file_open, + .read = posix_file_read, + + .can_read = ps2kbd_file_can_read, + .can_write = __vfs_can_never, + .eof = __vfs_eof_never, + }, +}; + +MODULE_INIT(ps2kbd, ps2kbd_probe, NULL) diff --git a/pool/shard003/C/0065950_caps00.c b/pool/shard003/C/0065950_caps00.c new file mode 100644 index 0000000000000000000000000000000000000000..beb97abee194e3cf32c83eb635770e7c4c76b2e5 --- /dev/null +++ b/pool/shard003/C/0065950_caps00.c @@ -0,0 +1,154 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +#include "zdtmtst.h" + +const char *test_doc = "Check that aps are preserved"; +const char *test_author = "Pavel Emelianov "; + +struct cap_hdr { + unsigned int version; + int pid; +}; + +struct cap_data { + unsigned int eff; + unsigned int prm; + unsigned int inh; +}; + +#define _LINUX_CAPABILITY_VERSION_3 0x20080522 +#define _LINUX_CAPABILITY_U32S_3 2 +#define CAP_CHOWN 0 +#define CAP_DAC_OVERRIDE 1 + +int capget(struct cap_hdr *hdrp, struct cap_data *datap); +int capset(struct cap_hdr *hdrp, const struct cap_data *datap); + +static int cap_last_cap = 63; +#define NORM_CAPS(v, cap) v[1].cap &= (1LL << (cap_last_cap + 1 - 32)) - 1; + +int main(int argc, char **argv) +{ + task_waiter_t t; + int pid, result_pipe[2]; + char res = 'x'; + FILE *f; + + test_init(argc, argv); + task_waiter_init(&t); + + f = fopen("/proc/sys/kernel/cap_last_cap", "r"); + if (f) { + if (fscanf(f, "%d", &cap_last_cap) != 1) { + err("Unable to read cal_last_cap"); + return 1; + } + fclose(f); + } else + test_msg("/proc/sys/kernel/cap_last_cap is not available\n"); + + if (pipe(result_pipe)) { + err("Can't create pipe\n"); + return 1; + } + + pid = test_fork(); + if (pid == 0) { + struct cap_hdr hdr; + struct cap_data data[_LINUX_CAPABILITY_U32S_3]; + struct cap_data data_2[_LINUX_CAPABILITY_U32S_3]; + + if (prctl(PR_CAPBSET_DROP, CAP_SETPCAP, 0, 0, 0)) { + err("PR_CAPBSET_DROP"); + return -1; + } + + hdr.version = _LINUX_CAPABILITY_VERSION_3; + hdr.pid = 0; + + capget(&hdr, data); + + hdr.version = _LINUX_CAPABILITY_VERSION_3; + hdr.pid = 0; + + data[0].eff &= ~((1 << CAP_CHOWN) | (1 << CAP_DAC_OVERRIDE)); + data[0].prm &= ~(1 << CAP_DAC_OVERRIDE); + + capset(&hdr, data); + + task_waiter_complete_current(&t); + task_waiter_wait4(&t, getppid()); + + hdr.version = _LINUX_CAPABILITY_VERSION_3; + hdr.pid = 0; + + capget(&hdr, data_2); + + NORM_CAPS(data, eff); + NORM_CAPS(data, prm); + NORM_CAPS(data, inh); + NORM_CAPS(data_2, eff); + NORM_CAPS(data_2, prm); + NORM_CAPS(data_2, inh); + + if (data[0].eff != data_2[0].eff) { + res = '1'; + goto bad; + } + if (data[1].eff != data_2[1].eff) { + res = '2'; + goto bad; + } + if (data[0].prm != data_2[0].prm) { + res = '3'; + goto bad; + } + if (data[1].prm != data_2[1].prm) { + res = '4'; + goto bad; + } + if (data[0].inh != data_2[0].inh) { + res = '3'; + goto bad; + } + if (data[1].inh != data_2[1].inh) { + res = '4'; + goto bad; + } + + if (prctl(PR_CAPBSET_READ, CAP_SETPCAP, 0, 0, 0) != 0) { + res='5'; + goto bad; + } + + res = '0'; +bad: + write(result_pipe[1], &res, 1); + close(result_pipe[0]); + close(result_pipe[1]); + _exit(0); + } + + task_waiter_wait4(&t, pid); + + test_daemon(); + test_waitsig(); + + task_waiter_complete_current(&t); + + read(result_pipe[0], &res, 1); + close(result_pipe[0]); + close(result_pipe[1]); + + if (res == '0') + pass(); + else + fail("Fail: %c", res); + + return 0; +} diff --git a/pool/shard003/C/0065954_mul_nmod_vec.c b/pool/shard003/C/0065954_mul_nmod_vec.c new file mode 100644 index 0000000000000000000000000000000000000000..dc0a15de6aba9555c1f3eb81e1e4cfb444735d3c --- /dev/null +++ b/pool/shard003/C/0065954_mul_nmod_vec.c @@ -0,0 +1,30 @@ +/* + Copyright (C) 2021 Daniel Schultz + + This file is part of FLINT. + + FLINT 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.1 of the License, or + (at your option) any later version. See . +*/ + +#include "nmod_mat.h" + +void nmod_mat_mul_nmod_vec( + mp_limb_t * c, + const nmod_mat_t A, + const mp_limb_t * b, slong blen) +{ + nmod_t mod = A->mod; + slong i, j; + slong len = FLINT_MIN(A->c, blen); + int nlimbs = _nmod_vec_dot_bound_limbs(len, mod); + + for (i = A->r - 1; i >= 0; i--) + { + const mp_limb_t * Ai = A->rows[i]; + NMOD_VEC_DOT(c[i], j, len, Ai[j], b[j], mod, nlimbs); + } +} + diff --git a/pool/shard003/C/0065968_ram_console.c b/pool/shard003/C/0065968_ram_console.c new file mode 100644 index 0000000000000000000000000000000000000000..cf0f8fb4fd8ccbc440f6473b06437d6ca24e6106 --- /dev/null +++ b/pool/shard003/C/0065968_ram_console.c @@ -0,0 +1,177 @@ +/* drivers/android/ram_console.c + * + * Copyright (C) 2007-2008 Google, Inc. + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include "ram_console.h" + +static struct persistent_ram_zone *ram_console_zone; +static const char *bootinfo; +static size_t bootinfo_size; + +static void +ram_console_write(struct console *console, const char *s, unsigned int count) +{ + struct persistent_ram_zone *prz = console->data; + persistent_ram_write(prz, s, count); +} + +static struct console ram_console = { + .name = "ram", + .write = ram_console_write, + .flags = CON_PRINTBUFFER | CON_ENABLED | CON_ANYTIME, + .index = -1, +}; + +void ram_console_enable_console(int enabled) +{ + if (enabled) + ram_console.flags |= CON_ENABLED; + else + ram_console.flags &= ~CON_ENABLED; +} + +static int __devinit ram_console_probe(struct platform_device *pdev) +{ + struct ram_console_platform_data *pdata = pdev->dev.platform_data; + struct persistent_ram_zone *prz; + + prz = persistent_ram_init_ringbuffer(&pdev->dev, true); + if (IS_ERR(prz)) + return PTR_ERR(prz); + + + if (pdata) { + bootinfo = kstrdup(pdata->bootinfo, GFP_KERNEL); + if (bootinfo) + bootinfo_size = strlen(bootinfo); + } + + ram_console_zone = prz; + ram_console.data = prz; + + register_console(&ram_console); + + return 0; +} + +static struct platform_driver ram_console_driver = { + .driver = { + .name = "ram_console", + }, + .probe = ram_console_probe, +}; + +static int __init ram_console_module_init(void) +{ + return platform_driver_register(&ram_console_driver); +} + +#ifndef CONFIG_PRINTK +#define dmesg_restrict 0 +#endif + +static ssize_t ram_console_read_old(struct file *file, char __user *buf, + size_t len, loff_t *offset) +{ + loff_t pos = *offset; + ssize_t count; + struct persistent_ram_zone *prz = ram_console_zone; + size_t old_log_size = persistent_ram_old_size(prz); + const char *old_log = persistent_ram_old(prz); + char *str; + int ret; + + /* Main last_kmsg log */ + if (pos < old_log_size) { + count = min(len, (size_t)(old_log_size - pos)); + if (copy_to_user(buf, old_log + pos, count)) + return -EFAULT; + goto out; + } + + /* ECC correction notice */ + pos -= old_log_size; + count = persistent_ram_ecc_string(prz, NULL, 0); + if (pos < count) { + str = kmalloc(count, GFP_KERNEL); + if (!str) + return -ENOMEM; + persistent_ram_ecc_string(prz, str, count + 1); + count = min(len, (size_t)(count - pos)); + ret = copy_to_user(buf, str + pos, count); + kfree(str); + if (ret) + return -EFAULT; + goto out; + } + + /* Boot info passed through pdata */ + pos -= count; + if (pos < bootinfo_size) { + count = min(len, (size_t)(bootinfo_size - pos)); + if (copy_to_user(buf, bootinfo + pos, count)) + return -EFAULT; + goto out; + } + + /* EOF */ + return 0; + +out: + *offset += count; + return count; +} + +static const struct file_operations ram_console_file_ops = { + .owner = THIS_MODULE, + .read = ram_console_read_old, +}; + +static int __init ram_console_late_init(void) +{ + struct proc_dir_entry *entry; + struct persistent_ram_zone *prz = ram_console_zone; + + if (!prz) + return 0; + + if (persistent_ram_old_size(prz) == 0) + return 0; + + entry = create_proc_entry("last_kmsg", S_IFREG | S_IRUGO, NULL); + if (!entry) { + printk(KERN_ERR "ram_console: failed to create proc entry\n"); + persistent_ram_free_old(prz); + return 0; + } + + entry->proc_fops = &ram_console_file_ops; + entry->size = persistent_ram_old_size(prz) + + persistent_ram_ecc_string(prz, NULL, 0) + + bootinfo_size; + + return 0; +} + +late_initcall(ram_console_late_init); +postcore_initcall(ram_console_module_init); diff --git a/pool/shard003/C/0065972_uart.c b/pool/shard003/C/0065972_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..afba76233466a4ddd4dce446781aafb45d08e0d6 --- /dev/null +++ b/pool/shard003/C/0065972_uart.c @@ -0,0 +1,78 @@ +/* + * uart.c + * + * Created: 9/11/2017 10:05:19 PM + * Author: sajithkamal + */ + + + +#include +#include "uart.h" +#include + + +int usart1_putchar(int c); + +#if defined( __GNUC__ ) +/** Make sure printf knows where to print. The macro fdev_setup_stream() + * is used to prepare a user-supplied FILE buffer for operation with stdio. + */ +FILE usart1_str = FDEV_SETUP_STREAM((int(*)(char, FILE *))usart1_putchar, NULL, _FDEV_SETUP_WRITE); +#endif + +void uart_init(uint32_t baud) +{ + + UBRR1 = (F_CPU / 4 / baud - 1) / 2; + UCSR1A = (1< + * Copyright (C) 2014 Kévin Roussel + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +#include + +#include "cc2420.h" +#include "cc2420_settings.h" +#include "cc2420_arch.h" +#include "cc2420_spi.h" +#include "ieee802154_frame.h" + +#include "transceiver.h" +#include "msg.h" +#include "debug.h" + +/* circular buffer for incoming 802.15.4 packets */ +cc2420_packet_t cc2420_rx_buffer[CC2420_RX_BUF_SIZE]; +volatile uint8_t rx_buffer_next; /* index of next free cell in RX buffer */ + +/* pointer to the callback low-level function for packet reception */ +static receive_802154_packet_callback_t recv_func = NULL; + + +void cc2420_set_recv_callback(receive_802154_packet_callback_t recv_cb) +{ + recv_func = recv_cb; +} + +void cc2420_rx_handler(void) +{ + uint8_t pkt_len, pkt_lqi; + int8_t pkt_rssi; + bool crc_ok; + + /* read length */ + cc2420_read_fifo(&pkt_len, 1); + + /* read packet's raw payload */ + uint8_t buf[pkt_len - 2]; + cc2420_read_fifo(buf, pkt_len - 2); + + /* read rssi, lqi and crc */ + cc2420_read_fifo((uint8_t *) &pkt_rssi, 1); + cc2420_read_fifo(&pkt_lqi, 1); + crc_ok = ((pkt_lqi & 0x80) != 0); + pkt_lqi &= 0x7F; + if (!crc_ok) { + DEBUG("Got packet with invalid crc.\n"); + return; + } + + /* low-level reception mechanism (for MAC layer, among others) */ + if (recv_func != NULL) { + recv_func(buf, pkt_len - 2, pkt_rssi, pkt_lqi, crc_ok); + } + + /* decode received packet */ + cc2420_rx_buffer[rx_buffer_next].length = pkt_len; + cc2420_rx_buffer[rx_buffer_next].rssi = pkt_rssi; + cc2420_rx_buffer[rx_buffer_next].lqi = pkt_lqi; + cc2420_rx_buffer[rx_buffer_next].crc = (crc_ok ? 1 : 0); + ieee802154_frame_read(buf, + &cc2420_rx_buffer[rx_buffer_next].frame, + cc2420_rx_buffer[rx_buffer_next].length); + + /* follow-up to transceiver module if adequate */ + if (cc2420_rx_buffer[rx_buffer_next].frame.fcf.frame_type != 2) { +#ifdef DEBUG + ieee802154_frame_print_fcf_frame(&cc2420_rx_buffer[rx_buffer_next].frame); +#endif + + /* notify transceiver thread if any */ + if (transceiver_pid) { + msg_t m; + m.type = (uint16_t) RCV_PKT_CC2420; + m.content.value = rx_buffer_next; + msg_send_int(&m, transceiver_pid); + } + } + +#ifdef DEBUG + else { + DEBUG("GOT ACK for SEQ %u\n", cc2420_rx_buffer[rx_buffer_next].frame.seq_nr); + ieee802154_frame_print_fcf_frame(&cc2420_rx_buffer[rx_buffer_next].frame); + } + +#endif + + /* shift to next buffer element */ + if (++rx_buffer_next == CC2420_RX_BUF_SIZE) { + rx_buffer_next = 0; + } +} diff --git a/pool/shard003/C/0065997_pathname.c b/pool/shard003/C/0065997_pathname.c new file mode 100644 index 0000000000000000000000000000000000000000..c65be95568a33693f3518608383ea2cd5cdcb54f --- /dev/null +++ b/pool/shard003/C/0065997_pathname.c @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2016, CodeWard.org + */ +#include +#include +#include + +#include "pathname.h" + +int +path_split (const char *path, struct pathname *pathname) +{ + pathname->bak = strdup (path); + + if ( pathname->bak == NULL ) + return 1; + + pathname->base = basename (pathname->bak); + pathname->dir = dirname (pathname->bak); + + return 0; +} + +void +path_free (struct pathname *pathname) +{ + if ( pathname->bak != NULL ) + free (pathname->bak); + + pathname->bak = NULL; + pathname->base = NULL; + pathname->dir = NULL; +} + diff --git a/pool/shard003/C/0065999_group.c b/pool/shard003/C/0065999_group.c new file mode 100644 index 0000000000000000000000000000000000000000..1caeee1c5b03bcba64767caa59e3715323a7204a --- /dev/null +++ b/pool/shard003/C/0065999_group.c @@ -0,0 +1,33 @@ +/* + * Copyright © 2017-2018 - Vitaliy Perevertun + * + * This file is part of journal + * + * This file is licensed under the MIT license. + * See the file LICENSE. + */ + +#include +#include + +#include "core/run.h" +#include "log.h" + + +void run_group(server_t *s, gid_t *gid) +{ + struct group *gr; + + if (!s->rungroup) + s->rungroup = "journal"; + + gr = getgrnam(s->rungroup); + if (!gr) + { + log_warning("No such group '%s'!", s->rungroup); + + return; + } + + *gid = gr->gr_gid; +} \ No newline at end of file diff --git a/pool/shard003/C/0066000_accgyro_l3g4200d.c b/pool/shard003/C/0066000_accgyro_l3g4200d.c new file mode 100644 index 0000000000000000000000000000000000000000..33bd2f1f8012051f613a9fc5b76bca026553fb4c --- /dev/null +++ b/pool/shard003/C/0066000_accgyro_l3g4200d.c @@ -0,0 +1,125 @@ +/* + * This file is part of Cleanflight. + * + * Cleanflight 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. + * + * Cleanflight 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 Cleanflight. If not, see . + */ + +#include +#include + +#include + +#include "system.h" +#include "bus_i2c.h" + +#include "common/maths.h" +#include "common/axis.h" + +#include "sensor.h" +#include "accgyro.h" +#include "accgyro_l3g4200d.h" + +// L3G4200D, Standard address 0x68 +#define L3G4200D_ADDRESS 0x68 +#define L3G4200D_ID 0xD3 +#define L3G4200D_AUTOINCR 0x80 + +// Registers +#define L3G4200D_WHO_AM_I 0x0F +#define L3G4200D_CTRL_REG1 0x20 +#define L3G4200D_CTRL_REG2 0x21 +#define L3G4200D_CTRL_REG3 0x22 +#define L3G4200D_CTRL_REG4 0x23 +#define L3G4200D_CTRL_REG5 0x24 +#define L3G4200D_REFERENCE 0x25 +#define L3G4200D_STATUS_REG 0x27 +#define L3G4200D_GYRO_OUT 0x28 + +// Bits +#define L3G4200D_POWER_ON 0x0F +#define L3G4200D_FS_SEL_2000DPS 0xF0 +#define L3G4200D_DLPF_32HZ 0x00 +#define L3G4200D_DLPF_54HZ 0x40 +#define L3G4200D_DLPF_78HZ 0x80 +#define L3G4200D_DLPF_93HZ 0xC0 + +static void l3g4200dInit(uint8_t lpf); +static bool l3g4200dRead(int16_t *gyroADC); + +bool l3g4200dDetect(gyro_t *gyro) +{ + uint8_t deviceid; + + delay(25); + + i2cRead(MPU_I2C_INSTANCE, L3G4200D_ADDRESS, L3G4200D_WHO_AM_I, 1, &deviceid); + if (deviceid != L3G4200D_ID) + return false; + + gyro->init = l3g4200dInit; + gyro->read = l3g4200dRead; + + // 14.2857dps/lsb scalefactor + gyro->scale = 1.0f / 14.2857f; + + return true; +} + +static void l3g4200dInit(uint8_t lpf) +{ + bool ack; + + uint8_t mpuLowPassFilter = L3G4200D_DLPF_32HZ; + + switch (lpf) { + default: + case 32: + mpuLowPassFilter = L3G4200D_DLPF_32HZ; + break; + case 54: + mpuLowPassFilter = L3G4200D_DLPF_54HZ; + break; + case 78: + mpuLowPassFilter = L3G4200D_DLPF_78HZ; + break; + case 93: + mpuLowPassFilter = L3G4200D_DLPF_93HZ; + break; + } + + delay(100); + + ack = i2cWrite(MPU_I2C_INSTANCE, L3G4200D_ADDRESS, L3G4200D_CTRL_REG4, L3G4200D_FS_SEL_2000DPS); + if (!ack) + failureMode(FAILURE_ACC_INIT); + + delay(5); + i2cWrite(MPU_I2C_INSTANCE, L3G4200D_ADDRESS, L3G4200D_CTRL_REG1, L3G4200D_POWER_ON | mpuLowPassFilter); +} + +// Read 3 gyro values into user-provided buffer. No overrun checking is done. +static bool l3g4200dRead(int16_t *gyroADC) +{ + uint8_t buf[6]; + + if (!i2cRead(MPU_I2C_INSTANCE, L3G4200D_ADDRESS, L3G4200D_AUTOINCR | L3G4200D_GYRO_OUT, 6, buf)) { + return false; + } + + gyroADC[X] = (int16_t)((buf[0] << 8) | buf[1]); + gyroADC[Y] = (int16_t)((buf[2] << 8) | buf[3]); + gyroADC[Z] = (int16_t)((buf[4] << 8) | buf[5]); + + return true; +} diff --git a/pool/shard003/C/0066019_bluetooth-dsm.c b/pool/shard003/C/0066019_bluetooth-dsm.c new file mode 100644 index 0000000000000000000000000000000000000000..85825b4c527dcb0635fb4697514d7f3d0c0eff5b --- /dev/null +++ b/pool/shard003/C/0066019_bluetooth-dsm.c @@ -0,0 +1,175 @@ +/********************************************************** + * Filename: bluetooth-dsm.c + * + * Discription: bluetooth device state monitor driver + * + * Copyright: (C) 2015 huawei. + * + * Author: + * +**********************************************************/ +#include +#include +#include +#include +#include +#include +#include + + +static struct dsm_client *bt_dclient = NULL; + +static struct dsm_dev dsm_bt = { + .name = "dsm_bluetooth", + .fops = NULL, + .buff_size = 1024, +}; + + +#define DSM_BLUETOOTH_DM_OPEN 1 +#define DSM_BLUETOOTH_DM_GET_ADDR 2 +#define DSM_BLUETOOTH_A2DP_CONNECT 3 +#define DSM_BLUETOOTH_A2DP_AUDIO 4 +#define DSM_BLUETOOTH_HFP_CONNECT 5 +#define DSM_BLUETOOTH_HFP_SCO_CONNECT 6 +#define DSM_BLUETOOTH_BLE_CONNECT 7 + +static int bluetooth_open(struct inode *inode, struct file *file) +{ + file->private_data = NULL; + return 0; +} + +static int bluetooth_close(struct inode *inode, struct file *file) +{ + return 0; +} + +static long bluetooth_ioctl(struct file *file, unsigned int cmd, unsigned long arg) +{ + return 0; +} + +static ssize_t bluetooth_read(struct file *filp, char __user *buf, + size_t count, loff_t *offset) +{ + return 0; +} + +static ssize_t bluetooth_write(struct file *filp, const char __user *buf, + size_t count, loff_t *offset) +{ + int ret = 0; + int val = 0; + int error_no = 0; + pr_info("%s enter\n",__func__); + + if(NULL == buf){ + pr_err("%s: input para buf is NULL!\n", __func__); + return -EINVAL; + } + + pr_info("%s: dsm report op:%s\n", __func__, buf); + + if (1 != sscanf(buf, "%2d", &val)){ + pr_err("%s : get buf failed: %s\n", __func__,buf); + return -EINVAL; + } + if(!bt_dclient){ + pr_err("%s: bt_dclient is NULL!\n", __func__); + return -1; + } + if(dsm_client_ocuppy(bt_dclient)){ + pr_err("%s: buffer is busy!\n", __func__); + return -1; + } + switch(val) + { + case DSM_BLUETOOTH_DM_OPEN: + error_no = DSM_BLUETOOTH_DM_OPEN_ERROR; + ret = dsm_client_record(bt_dclient, "bluetooth open fail"); + break; + case DSM_BLUETOOTH_DM_GET_ADDR: + error_no = DSM_BLUETOOTH_DM_GET_ADDR_ERROR; + ret = dsm_client_record(bt_dclient, "get bt addr fail"); + break; + case DSM_BLUETOOTH_A2DP_CONNECT: + error_no = DSM_BLUETOOTH_A2DP_CONNECT_ERROR; + ret = dsm_client_record(bt_dclient, "a2dp connect fail"); + break; + case DSM_BLUETOOTH_A2DP_AUDIO: + error_no = DSM_BLUETOOTH_A2DP_AUDIO_ERROR; + ret = dsm_client_record(bt_dclient, "a2dp audio fail"); + break; + case DSM_BLUETOOTH_HFP_CONNECT: + error_no = DSM_BLUETOOTH_HFP_CONNECT_ERROR; + ret = dsm_client_record(bt_dclient, "hfp connect fail"); + break; + case DSM_BLUETOOTH_HFP_SCO_CONNECT: + error_no = DSM_BLUETOOTH_HFP_SCO_CONNECT_ERROR; + ret = dsm_client_record(bt_dclient, "hfp sco connect fail"); + break; + case DSM_BLUETOOTH_BLE_CONNECT: + error_no = DSM_BLUETOOTH_BLE_CONNECT_ERROR; + ret = dsm_client_record(bt_dclient, "ble connect fail"); + break; + default : + break; + } + if(!ret){ + pr_err("%s: no need report! error no:%d\n", __func__,error_no ); + return 0; + } + + /*call dsm report interface*/ + dsm_client_notify(bt_dclient, error_no); + return 0; +} + +static const struct file_operations bluetooth_fops = { + .owner = THIS_MODULE, + .llseek = no_llseek, + .open = bluetooth_open, + .release = bluetooth_close, + .read = bluetooth_read, + .write = bluetooth_write, + .unlocked_ioctl = bluetooth_ioctl, +}; + +static struct miscdevice bluetooth_miscdev = { + .minor = MISC_DYNAMIC_MINOR, + .name = "bluetooth", + .fops = &bluetooth_fops, +}; + +static int __init bluetooth_dsm_init(void) +{ + int retval = -EIO; + + if(!bt_dclient){ + bt_dclient = dsm_register_client (&dsm_bt); + } + + retval = misc_register(&bluetooth_miscdev); + if (retval) { + pr_err("%s: misc_register err %d\n", + __func__, retval); + return retval; + } + + return 0; +} + +static void __exit bluetooth_dsm_exit(void) +{ + dsm_unregister_client(bt_dclient,&dsm_bt); +} + +module_init(bluetooth_dsm_init); + +module_exit(bluetooth_dsm_exit); + +MODULE_DESCRIPTION("BT DEVICE MONITOR"); +#ifdef MODULE_LICENSE +MODULE_LICENSE("GPL"); +#endif diff --git a/pool/shard003/C/0066021_fix16_exp.c b/pool/shard003/C/0066021_fix16_exp.c new file mode 100644 index 0000000000000000000000000000000000000000..f897db88f9dabc816fac5f9c036d4ff4552835e0 --- /dev/null +++ b/pool/shard003/C/0066021_fix16_exp.c @@ -0,0 +1,198 @@ +#include "fix16.h" +#include + +#ifndef FIXMATH_NO_CACHE +static fix16_t _fix16_exp_cache_index[4096] = { 0 }; +static fix16_t _fix16_exp_cache_value[4096] = { 0 }; +#endif + + + +fix16_t fix16_exp(fix16_t inValue) { + if(inValue == 0 ) return fix16_one; + if(inValue == fix16_one) return fix16_e; + if(inValue >= 681391 ) return fix16_maximum; + if(inValue <= -772243 ) return 0; + + #ifndef FIXMATH_NO_CACHE + fix16_t tempIndex = (inValue ^ (inValue >> 16)); + tempIndex = (inValue ^ (inValue >> 4)) & 0x0FFF; + if(_fix16_exp_cache_index[tempIndex] == inValue) + return _fix16_exp_cache_value[tempIndex]; + #endif + + /* The algorithm is based on the power series for exp(x): + * http://en.wikipedia.org/wiki/Exponential_function#Formal_definition + * + * From term n, we get term n+1 by multiplying with x/n. + * When the sum term drops to zero, we can stop summing. + */ + + // The power-series converges much faster on positive values + // and exp(-x) = 1/exp(x). + bool neg = (inValue < 0); + if (neg) inValue = -inValue; + + fix16_t result = inValue + fix16_one; + fix16_t term = inValue; + + uint_fast8_t i; + for (i = 2; i < 30; i++) + { + term = fix16_mul(term, fix16_div(inValue, fix16_from_int(i))); + result += term; + + if ((term < 500) && ((i > 15) || (term < 20))) + break; + } + + if (neg) result = fix16_div(fix16_one, result); + + #ifndef FIXMATH_NO_CACHE + _fix16_exp_cache_index[tempIndex] = inValue; + _fix16_exp_cache_value[tempIndex] = result; + #endif + + return result; +} + + + +fix16_t fix16_log(fix16_t inValue) +{ + fix16_t guess = fix16_from_int(2); + fix16_t delta; + int scaling = 0; + int count = 0; + + if (inValue <= 0) + return fix16_minimum; + + // Bring the value to the most accurate range (1 < x < 100) + const fix16_t e_to_fourth = 3578144; + while (inValue > fix16_from_int(100)) + { + inValue = fix16_div(inValue, e_to_fourth); + scaling += 4; + } + + while (inValue < fix16_one) + { + inValue = fix16_mul(inValue, e_to_fourth); + scaling -= 4; + } + + do + { + // Solving e(x) = y using Newton's method + // f(x) = e(x) - y + // f'(x) = e(x) + fix16_t e = fix16_exp(guess); + delta = fix16_div(inValue - e, e); + + // It's unlikely that logarithm is very large, so avoid overshooting. + if (delta > fix16_from_int(3)) + delta = fix16_from_int(3); + + guess += delta; + } while ((count++ < 10) + && ((delta > 1) || (delta < -1))); + + return guess + fix16_from_int(scaling); +} + + + +static inline fix16_t fix16_rs(fix16_t x) +{ + #ifdef FIXMATH_NO_ROUNDING + return (x >> 1); + #else + fix16_t y = (x >> 1) + (x & 1); + return y; + #endif +} + +/** + * This assumes that the input value is >= 1. + * + * Note that this is only ever called with inValue >= 1 (because it has a wrapper to check. + * As such, the result is always less than the input. + */ +static fix16_t fix16__log2_inner(fix16_t x) +{ + fix16_t result = 0; + + while(x >= fix16_from_int(2)) + { + result++; + x = fix16_rs(x); + } + + if(x == 0) return (result << 16); + + uint_fast8_t i; + for(i = 16; i > 0; i--) + { + x = fix16_mul(x, x); + result <<= 1; + if(x >= fix16_from_int(2)) + { + result |= 1; + x = fix16_rs(x); + } + } + #ifndef FIXMATH_NO_ROUNDING + x = fix16_mul(x, x); + if(x >= fix16_from_int(2)) result++; + #endif + + return result; +} + + + +/** + * calculates the log base 2 of input. + * Note that negative inputs are invalid! (will return fix16_overflow, since there are no exceptions) + * + * i.e. 2 to the power output = input. + * It's equivalent to the log or ln functions, except it uses base 2 instead of base 10 or base e. + * This is useful as binary things like this are easy for binary devices, like modern microprocessros, to calculate. + * + * This can be used as a helper function to calculate powers with non-integer powers and/or bases. + */ +fix16_t fix16_log2(fix16_t x) +{ + // Note that a negative x gives a non-real result. + // If x == 0, the limit of log2(x) as x -> 0 = -infinity. + // log2(-ve) gives a complex result. + if (x <= 0) return fix16_overflow; + + // If the input is less than one, the result is -log2(1.0 / in) + if (x < fix16_one) + { + // Note that the inverse of this would overflow. + // This is the exact answer for log2(1.0 / 65536) + if (x == 1) return fix16_from_int(-16); + + fix16_t inverse = fix16_div(fix16_one, x); + return -fix16__log2_inner(inverse); + } + + // If input >= 1, just proceed as normal. + // Note that x == fix16_one is a special case, where the answer is 0. + return fix16__log2_inner(x); +} + +/** + * This is a wrapper for fix16_log2 which implements saturation arithmetic. + */ +fix16_t fix16_slog2(fix16_t x) +{ + fix16_t retval = fix16_log2(x); + // The only overflow possible is when the input is negative. + if(retval == fix16_overflow) + return fix16_minimum; + return retval; +} diff --git a/pool/shard003/C/0066025_test-lm-one.c b/pool/shard003/C/0066025_test-lm-one.c new file mode 100644 index 0000000000000000000000000000000000000000..18613e0452cd43c1d2d4b7901c73fc69a20ea018 --- /dev/null +++ b/pool/shard003/C/0066025_test-lm-one.c @@ -0,0 +1,79 @@ +/* vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: */ +/* + * Copyright (c) 2016 Red Hat, Inc. + * Author: Nathaniel McCallum + * + * This program 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 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 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 "test.h" +#include +#include +#include +#include + +static const luksmeta_uuid_t UUID = { + 0xb0, 0xcc, 0xe0, 0x48, 0x89, 0x32, 0x90, 0x7e, + 0x10, 0xd9, 0x62, 0xa2, 0x09, 0x3c, 0x05, 0x7d +}; + +int +main(int argc, char *argv[]) +{ + uint8_t data[sizeof(UUID)] = {}; + struct crypt_device *cd = NULL; + luksmeta_uuid_t uuid = {}; + uint32_t offset = 0; + uint32_t length = 0; + int r; + + crypt_free(test_format()); + cd = test_init(); + test_hole(cd, &offset, &length); + + r = luksmeta_save(cd, CRYPT_ANY_SLOT, UUID, UUID, sizeof(UUID)); + if (r < 0) + error(EXIT_FAILURE, -r, "%s:%d", __FILE__, __LINE__); + + /* Test the layout state. */ + assert(test_layout((range_t[]) { + { 0, 1024 }, /* LUKS header */ + { 1024, 3072, true }, /* Keyslot Area */ + { offset, 4096 }, /* luksmeta header */ + { offset + 4096, 4096 }, /* luksmeta slot 0 */ + END(offset + 8192), /* Rest of the file */ + })); + + assert(luksmeta_load(cd, r, uuid, data, sizeof(data)) == sizeof(data)); + assert(memcmp(uuid, UUID, sizeof(UUID)) == 0); + assert(memcmp(data, UUID, sizeof(UUID)) == 0); + assert(luksmeta_save(cd, r, UUID, UUID, sizeof(UUID)) == -EALREADY); + assert(luksmeta_wipe(cd, r, (luksmeta_uuid_t) {}) == -EKEYREJECTED); + assert(luksmeta_wipe(cd, r, (luksmeta_uuid_t) { 1 }) == -EKEYREJECTED); + assert(luksmeta_wipe(cd, r, UUID) == 0); + assert(luksmeta_wipe(cd, r, UUID) == -EALREADY); + assert(luksmeta_wipe(cd, r, (luksmeta_uuid_t) {}) == -EALREADY); + + /* Test the layout state. */ + assert(test_layout((range_t[]) { + { 0, 1024 }, /* LUKS header */ + { 1024, 3072, true }, /* Keyslot Area */ + { offset, 4096 }, /* luksmeta header */ + END(offset + 4096), /* Rest of the file */ + })); + + crypt_free(cd); + unlink(filename); + return 0; +} diff --git a/pool/shard003/C/0066053_at91sam9_wdt.c b/pool/shard003/C/0066053_at91sam9_wdt.c new file mode 100644 index 0000000000000000000000000000000000000000..03c786c53bd0db59b66aed4e0a6d4ecdde0bd2f2 --- /dev/null +++ b/pool/shard003/C/0066053_at91sam9_wdt.c @@ -0,0 +1,81 @@ +/* + * [origin: Linux kernel drivers/watchdog/at91sam9_wdt.c] + * + * Watchdog driver for Atmel AT91SAM9x processors. + * + * Copyright (C) 2008 Jean-Christophe PLAGNIOL-VILLARD + * Copyright (C) 2008 Renaud CERRATO r.cerrato@til-technologies.fr + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +/* + * The Watchdog Timer Mode Register can be only written to once. If the + * timeout need to be set from U-Boot, be sure that the bootstrap doesn't + * write to this register. Inform Linux to it too + */ + +#include +#include +#include +#include +#include + +/* + * AT91SAM9 watchdog runs a 12bit counter @ 256Hz, + * use this to convert a watchdog + * value from/to milliseconds. + */ +#define ms_to_ticks(t) (((t << 8) / 1000) - 1) +#define ticks_to_ms(t) (((t + 1) * 1000) >> 8) + +/* Hardware timeout in seconds */ +#if !defined(CONFIG_AT91_HW_WDT_TIMEOUT) +#define WDT_HW_TIMEOUT 2 +#else +#define WDT_HW_TIMEOUT CONFIG_AT91_HW_WDT_TIMEOUT +#endif + +/* + * Set the watchdog time interval in 1/256Hz (write-once) + * Counter is 12 bit. + */ +static int at91_wdt_settimeout(unsigned int timeout) +{ + unsigned int reg; + at91_wdt_t *wd = (at91_wdt_t *) ATMEL_BASE_WDT; + + /* Check if disabled */ + if (readl(&wd->mr) & AT91_WDT_MR_WDDIS) { + printf("sorry, watchdog is disabled\n"); + return -1; + } + + /* + * All counting occurs at SLOW_CLOCK / 128 = 256 Hz + * + * Since WDV is a 12-bit counter, the maximum period is + * 4096 / 256 = 16 seconds. + */ + + reg = AT91_WDT_MR_WDRSTEN /* causes watchdog reset */ + | AT91_WDT_MR_WDDBGHLT /* disabled in debug mode */ + | AT91_WDT_MR_WDD(0xfff) /* restart at any time */ + | AT91_WDT_MR_WDV(timeout); /* timer value */ + + writel(reg, &wd->mr); + + return 0; +} + +void hw_watchdog_reset(void) +{ + at91_wdt_t *wd = (at91_wdt_t *) ATMEL_BASE_WDT; + writel(AT91_WDT_CR_WDRSTT | AT91_WDT_CR_KEY, &wd->cr); +} + +void hw_watchdog_init(void) +{ + /* 16 seconds timer, resets enabled */ + at91_wdt_settimeout(ms_to_ticks(WDT_HW_TIMEOUT * 1000)); +} diff --git a/pool/shard003/C/0066055_ipx_outputfl.c b/pool/shard003/C/0066055_ipx_outputfl.c new file mode 100644 index 0000000000000000000000000000000000000000..c04d1248cc08144b04a79959fe6e9cbe07f7194c --- /dev/null +++ b/pool/shard003/C/0066055_ipx_outputfl.c @@ -0,0 +1,259 @@ +/* + * Copyright (c) 1995, Mike Mitchell + * Copyright (c) 1984, 1985, 1986, 1987, 1993 + * The 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: + * 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 the University of + * California, Berkeley and its contributors. + * 4. 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 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. + * + * @(#)ipx_outputfl.c + * + * $FreeBSD: src/sys/netipx/ipx_outputfl.c,v 1.16 2001/11/03 08:24:00 peter Exp $ + */ + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +static int ipx_copy_output = 0; + +int +ipx_outputfl(m0, ro, flags) + struct mbuf *m0; + struct route *ro; + int flags; +{ + register struct ipx *ipx = mtod(m0, struct ipx *); + register struct ifnet *ifp = NULL; + int error = 0; + struct sockaddr_ipx *dst; + struct route ipxroute; + + /* + * Route packet. + */ + if (ro == NULL) { + ro = &ipxroute; + bzero((caddr_t)ro, sizeof(*ro)); + } + dst = (struct sockaddr_ipx *)&ro->ro_dst; + if (ro->ro_rt == NULL) { + dst->sipx_family = AF_IPX; + dst->sipx_len = sizeof(*dst); + dst->sipx_addr = ipx->ipx_dna; + dst->sipx_addr.x_port = 0; + /* + * If routing to interface only, + * short circuit routing lookup. + */ + if (flags & IPX_ROUTETOIF) { + struct ipx_ifaddr *ia = ipx_iaonnetof(&ipx->ipx_dna); + + if (ia == NULL) { + ipxstat.ipxs_noroute++; + error = ENETUNREACH; + goto bad; + } + ifp = ia->ia_ifp; + goto gotif; + } + rtalloc(ro); + } else if ((ro->ro_rt->rt_flags & RTF_UP) == 0) { + /* + * The old route has gone away; try for a new one. + */ + rtfree(ro->ro_rt); + ro->ro_rt = NULL; + rtalloc(ro); + } + if (ro->ro_rt == NULL || (ifp = ro->ro_rt->rt_ifp) == NULL) { + ipxstat.ipxs_noroute++; + error = ENETUNREACH; + goto bad; + } + ro->ro_rt->rt_use++; + if (ro->ro_rt->rt_flags & (RTF_GATEWAY|RTF_HOST)) + dst = (struct sockaddr_ipx *)ro->ro_rt->rt_gateway; +gotif: + /* + * Look for multicast addresses and + * and verify user is allowed to send + * such a packet. + */ + if (dst->sipx_addr.x_host.c_host[0]&1) { + if ((ifp->if_flags & (IFF_BROADCAST | IFF_LOOPBACK)) == 0) { + error = EADDRNOTAVAIL; + goto bad; + } + if ((flags & IPX_ALLOWBROADCAST) == 0) { + error = EACCES; + goto bad; + } + m0->m_flags |= M_BCAST; + } + + if (htons(ipx->ipx_len) <= ifp->if_mtu) { + ipxstat.ipxs_localout++; + if (ipx_copy_output) { + ipx_watch_output(m0, ifp); + } + error = (*ifp->if_output)(ifp, m0, + (struct sockaddr *)dst, ro->ro_rt); + goto done; + } else { + ipxstat.ipxs_mtutoosmall++; + error = EMSGSIZE; + } +bad: + if (ipx_copy_output) { + ipx_watch_output(m0, ifp); + } + m_freem(m0); +done: + if (ro == &ipxroute && (flags & IPX_ROUTETOIF) == 0 && + ro->ro_rt != NULL) { + RTFREE(ro->ro_rt); + ro->ro_rt = NULL; + } + return (error); +} + +/* + * This will broadcast the type 20 (Netbios) packet to all the interfaces + * that have ipx configured and isn't in the list yet. + */ +int +ipx_output_type20(m) + struct mbuf *m; +{ + register struct ipx *ipx; + union ipx_net *nbnet; + struct ipx_ifaddr *ia, *tia = NULL; + int error = 0; + struct mbuf *m1; + int i; + struct ifnet *ifp; + struct sockaddr_ipx dst; + + /* + * We have to get to the 32 bytes after the ipx header also, so + * that we can fill in the network address of the receiving + * interface. + */ + if ((m->m_flags & M_EXT || m->m_len < (sizeof(struct ipx) + 32)) && + (m = m_pullup(m, sizeof(struct ipx) + 32)) == NULL) { + ipxstat.ipxs_toosmall++; + return (0); + } + ipx = mtod(m, struct ipx *); + nbnet = (union ipx_net *)(ipx + 1); + + if (ipx->ipx_tc >= 8) + goto bad; + /* + * Now see if we have already seen this. + */ + for (ia = ipx_ifaddr; ia != NULL; ia = ia->ia_next) + if(ia->ia_ifa.ifa_ifp == m->m_pkthdr.rcvif) { + if(tia == NULL) + tia = ia; + + for (i=0;iipx_tc;i++,nbnet++) + if(ipx_neteqnn(ia->ia_addr.sipx_addr.x_net, + *nbnet)) + goto bad; + } + /* + * Don't route the packet if the interface where it come from + * does not have an IPX address. + */ + if(tia == NULL) + goto bad; + + /* + * Add our receiving interface to the list. + */ + nbnet = (union ipx_net *)(ipx + 1); + nbnet += ipx->ipx_tc; + *nbnet = tia->ia_addr.sipx_addr.x_net; + + /* + * Increment the hop count. + */ + ipx->ipx_tc++; + ipxstat.ipxs_forward++; + + /* + * Send to all directly connected ifaces not in list and + * not to the one it came from. + */ + m->m_flags &= ~M_BCAST; + bzero(&dst, sizeof(dst)); + dst.sipx_family = AF_IPX; + dst.sipx_len = 12; + dst.sipx_addr.x_host = ipx_broadhost; + + for (ia = ipx_ifaddr; ia != NULL; ia = ia->ia_next) + if(ia->ia_ifa.ifa_ifp != m->m_pkthdr.rcvif) { + nbnet = (union ipx_net *)(ipx + 1); + for (i=0;iipx_tc;i++,nbnet++) + if(ipx_neteqnn(ia->ia_addr.sipx_addr.x_net, + *nbnet)) + goto skip_this; + + /* + * Insert the net address of the dest net and + * calculate the new checksum if needed. + */ + ifp = ia->ia_ifa.ifa_ifp; + dst.sipx_addr.x_net = ia->ia_addr.sipx_addr.x_net; + ipx->ipx_dna.x_net = dst.sipx_addr.x_net; + if(ipx->ipx_sum != 0xffff) + ipx->ipx_sum = ipx_cksum(m, ntohs(ipx->ipx_len)); + + m1 = m_copym(m, 0, M_COPYALL, M_DONTWAIT); + if(m1) { + error = (*ifp->if_output)(ifp, m1, + (struct sockaddr *)&dst, NULL); + /* XXX ipxstat.ipxs_localout++; */ + } +skip_this: ; + } + +bad: + m_freem(m); + return (error); +} diff --git a/pool/shard003/C/0066073_an5206.c b/pool/shard003/C/0066073_an5206.c new file mode 100644 index 0000000000000000000000000000000000000000..f584d8816fd4721ded5e37d5009a38aeffce8f52 --- /dev/null +++ b/pool/shard003/C/0066073_an5206.c @@ -0,0 +1,101 @@ +/* + * Arnewsh 5206 ColdFire system emulation. + * + * Copyright (c) 2007 CodeSourcery. + * + * This code is licenced under the GPL + */ + +#include "hw.h" +#include "pc.h" +#include "mcf.h" +#include "sysemu.h" +#include "boards.h" +#include "loader.h" +#include "elf.h" + +#define KERNEL_LOAD_ADDR 0x10000 +#define AN5206_MBAR_ADDR 0x10000000 +#define AN5206_RAMBAR_ADDR 0x20000000 + +/* Stub functions for hardware that doesn't exist. */ +void pic_info(Monitor *mon) +{ +} + +void irq_info(Monitor *mon) +{ +} + +/* Board init. */ + +static void an5206_init(ram_addr_t ram_size, + const char *boot_device, + const char *kernel_filename, const char *kernel_cmdline, + const char *initrd_filename, const char *cpu_model) +{ + CPUState *env; + int kernel_size; + uint64_t elf_entry; + target_phys_addr_t entry; + + if (!cpu_model) + cpu_model = "m5206"; + env = cpu_init(cpu_model); + if (!env) { + hw_error("Unable to find m68k CPU definition\n"); + } + + /* Initialize CPU registers. */ + env->vbr = 0; + /* TODO: allow changing MBAR and RAMBAR. */ + env->mbar = AN5206_MBAR_ADDR | 1; + env->rambar0 = AN5206_RAMBAR_ADDR | 1; + + /* DRAM at address zero */ + cpu_register_physical_memory(0, ram_size, + qemu_ram_alloc(ram_size) | IO_MEM_RAM); + + /* Internal SRAM. */ + cpu_register_physical_memory(AN5206_RAMBAR_ADDR, 512, + qemu_ram_alloc(512) | IO_MEM_RAM); + + mcf5206_init(AN5206_MBAR_ADDR, env); + + /* Load kernel. */ + if (!kernel_filename) { + fprintf(stderr, "Kernel image must be specified\n"); + exit(1); + } + + kernel_size = load_elf(kernel_filename, NULL, NULL, &elf_entry, + NULL, NULL, 1, ELF_MACHINE, 0); + entry = elf_entry; + if (kernel_size < 0) { + kernel_size = load_uimage(kernel_filename, &entry, NULL, NULL); + } + if (kernel_size < 0) { + kernel_size = load_image_targphys(kernel_filename, KERNEL_LOAD_ADDR, + ram_size - KERNEL_LOAD_ADDR); + entry = KERNEL_LOAD_ADDR; + } + if (kernel_size < 0) { + fprintf(stderr, "qemu: could not load kernel '%s'\n", kernel_filename); + exit(1); + } + + env->pc = entry; +} + +static QEMUMachine an5206_machine = { + .name = "an5206", + .desc = "Arnewsh 5206", + .init = an5206_init, +}; + +static void an5206_machine_init(void) +{ + qemu_register_machine(&an5206_machine); +} + +machine_init(an5206_machine_init); diff --git a/pool/shard003/C/0066089_tpm2_clockrateadjust.c b/pool/shard003/C/0066089_tpm2_clockrateadjust.c new file mode 100644 index 0000000000000000000000000000000000000000..b88e09a40123924223199f0132cac29e40f05d5f --- /dev/null +++ b/pool/shard003/C/0066089_tpm2_clockrateadjust.c @@ -0,0 +1,129 @@ +/* SPDX-License-Identifier: BSD-3-Clause */ +#include + +#include "files.h" +#include "log.h" +#include "tpm2.h" +#include "tpm2_tool.h" +#include "tpm2_util.h" + +typedef struct tpm2_setclock_ctx tpm2_setclock_ctx; +struct tpm2_setclock_ctx { + TPM2_CLOCK_ADJUST adjust; + const char *auth_hierarchy; + tpm2_loaded_object object; + const char *auth_value; + char *cp_hash_path; +}; + +static tpm2_setclock_ctx ctx = { + .auth_hierarchy = "o" /* default to owner hierarchy */ +}; + +static bool on_arg(int argc, char **argv) { + + if (argc != 1) { + LOG_ERR("Can only specify 1 clock rate adjust specifier, got: %d", argc); + return false; + } + + const char *adjustment = argv[0]; + + size_t len = strlen(adjustment); + if (len > 3) { + LOG_ERR("Expected at most 3 adjustment characters"); + return false; + } + + static const char slower[] = "sss"; + static const char faster[] = "fff"; + + bool is_slower = adjustment[0] == 's'; + const char *compare = is_slower ? slower : faster; + + bool is_equal = !strncmp(adjustment, compare, len); + if (!is_equal) { + LOG_ERR("Adjustment specifier should be consistent, either all " + "'s' or all 'f' characters got: \"%s\"", adjustment); + return false; + } + + if (is_slower) { + ctx.adjust -= len; + } else { + ctx.adjust += len; + } + + return true; +} + +static bool on_option(char key, char *value) { + + switch (key) { + case 'c': + ctx.auth_hierarchy = value; + break; + case 'p': + ctx.auth_value = value; + break; + case 0: + ctx.cp_hash_path = value; + break; + /* no default */ + } + + return true; +} + +static bool tpm2_tool_onstart(tpm2_options **opts) { + + const struct option topts[] = { + { "hierarchy", required_argument, NULL, 'c' }, + { "auth", required_argument, NULL, 'p' }, + { "cphash", required_argument, NULL, 0 }, + }; + + *opts = tpm2_options_new("c:p:", ARRAY_LEN(topts), topts, on_option, + on_arg, 0); + + return *opts != NULL; +} + +static tool_rc tpm2_tool_onrun(ESYS_CONTEXT *ectx, tpm2_option_flags flags) { + + UNUSED(flags); + + tool_rc rc = tpm2_util_object_load_auth(ectx, ctx.auth_hierarchy, + ctx.auth_value, &ctx.object, false, + TPM2_HANDLE_FLAGS_P|TPM2_HANDLE_FLAGS_O); + if (rc != tool_rc_success) { + return rc; + } + + LOG_INFO("adjust value: %d", ctx.adjust); + + if (ctx.cp_hash_path) { + TPM2B_DIGEST cp_hash = { .size = 0 }; + LOG_WARN("Calculating cpHash. Exiting without setting clock."); + rc = tpm2_clockrateadjust(ectx, &ctx.object, ctx.adjust, &cp_hash); + if (rc != tool_rc_success) { + return rc; + } + bool result = files_save_digest(&cp_hash, ctx.cp_hash_path); + if (!result) { + rc = tool_rc_general_error; + } + return rc; + } + + return tpm2_clockrateadjust(ectx, &ctx.object, ctx.adjust, NULL); +} + +static tool_rc tpm2_tool_onstop(ESYS_CONTEXT *ectx) { + UNUSED(ectx); + + return tpm2_session_close(&ctx.object.session); +} + +// Register this tool with tpm2_tool.c +TPM2_TOOL_REGISTER("clockrateadjust", tpm2_tool_onstart, tpm2_tool_onrun, tpm2_tool_onstop, NULL) diff --git a/pool/shard003/C/0066095_memmem.c b/pool/shard003/C/0066095_memmem.c new file mode 100644 index 0000000000000000000000000000000000000000..629bf16946de98753dca38a5b7f6e54e7062cf7c --- /dev/null +++ b/pool/shard003/C/0066095_memmem.c @@ -0,0 +1,65 @@ +/*- + * Copyright (c) 2005 Pascal Gloor + * + * 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 +__FBSDID("$FreeBSD: release/8.2.0/lib/libc/string/memmem.c 188080 2009-02-03 17:58:20Z danger $"); + +#include + +/* + * Find the first occurrence of the byte string s in byte string l. + */ + +void * +memmem(const void *l, size_t l_len, const void *s, size_t s_len) +{ + register char *cur, *last; + const char *cl = (const char *)l; + const char *cs = (const char *)s; + + /* we need something to compare */ + if (l_len == 0 || s_len == 0) + return NULL; + + /* "s" must be smaller or equal to "l" */ + if (l_len < s_len) + return NULL; + + /* special case where s_len == 1 */ + if (s_len == 1) + return memchr(l, (int)*cs, l_len); + + /* the last position where its possible to find "s" in "l" */ + last = (char *)cl + l_len - s_len; + + for (cur = (char *)cl; cur <= last; cur++) + if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0) + return cur; + + return NULL; +} diff --git a/pool/shard003/C/0066101_hello_world_main.c b/pool/shard003/C/0066101_hello_world_main.c new file mode 100644 index 0000000000000000000000000000000000000000..490644cc34a13ca0bc22f903a113eb01f9684aba --- /dev/null +++ b/pool/shard003/C/0066101_hello_world_main.c @@ -0,0 +1,118 @@ +/* test longjmp + + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ +#include +#include "sdkconfig.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "esp_system.h" +#include "esp_spi_flash.h" +#include + +#include + +#define LUAI_NOIPA __attribute__((__noipa__)) +#define LUAI_THROW(c) longjmp((c)->b, 1) +#define LUAI_TRY(c,a) if (setjmp((c)->b) == 0) { a } + +#define TIMEOUT 50 + +#define RECURSION 19 + +static esp_timer_handle_t crash_timer; + +static uint32_t result = 0; + +uint32_t calc_fac(uint32_t n) { + if (n == 1 || n == 0) { + return 1; + } else { + return n * calc_fac(n - 1); + } +} + +static void timer_cb(void *arg) { + result = calc_fac(RECURSION); +} + +typedef struct { + jmp_buf b; +} jmp_ctx; + +LUAI_NOIPA +static void pret(jmp_ctx *jc) { + LUAI_THROW(jc); +} + +LUAI_NOIPA +static void precurse(jmp_ctx *jc, int n) { + if (n) precurse(jc, n - 1); + else pret(jc); +} + +LUAI_NOIPA +static void ptest(jmp_ctx *jc) { + precurse(jc, 64); +} + +LUAI_NOIPA +void pcall(void (*func)(jmp_ctx *ctx)) { + jmp_ctx jc; + LUAI_TRY(&jc, + ptest(&jc); + ); +} + +static void sjlj_task(void *ctx) { + uint32_t start = xTaskGetTickCount(); + for (;;) { + pcall(ptest); + uint32_t end = xTaskGetTickCount(); + + uint32_t dt = end - start; + if (dt >= 1000) { + start = end; + + printf("[%u] sjlj tick %d\n", end, (int)ctx); + } + + if (end > 9800) { + break; + } + } + + vTaskDelete(NULL); +} + +void app_main(void) +{ + const esp_timer_create_args_t timer_args = { + timer_cb, + NULL, + ESP_TIMER_TASK, + "crash_timer", + true, + }; + + esp_timer_create(&timer_args, &crash_timer); + esp_timer_start_periodic(crash_timer, TIMEOUT); + + printf("Hello world!\n"); + printf("Free heap: %d\n", esp_get_free_heap_size()); + + for (size_t i = 0; i < 16; i++) { + xTaskCreate(sjlj_task, "sjlj_task", 4096, (void *) i, tskIDLE_PRIORITY + 0, NULL); + } + + vTaskDelay(10000); + printf("stopping timer...\n"); + esp_timer_stop(crash_timer); + esp_timer_delete(crash_timer); + + printf("Test successful\n"); +} diff --git a/pool/shard003/C/0066118_remote_attestation_demo-microblaze.c b/pool/shard003/C/0066118_remote_attestation_demo-microblaze.c new file mode 100644 index 0000000000000000000000000000000000000000..6ac7d42d3048c7fe672d816aea1208533811a9c6 --- /dev/null +++ b/pool/shard003/C/0066118_remote_attestation_demo-microblaze.c @@ -0,0 +1,25 @@ +#include +#include "string.h" +// #include "microblaze_remote_attestation.h" + +/** + ** Function to handle when an attestation is received + **/ +void start_attestation( + unsigned char *remote_message, unsigned char *message_out +){ + blocking_attestation(remote_message, message_out); +} + +//TODO: assume message_out buffer is 0x100 bytes long, message fits in it +void generate_encrypted_message( + unsigned char *message_out, unsigned int *message_length +){ + //TODO: encrypt message + *message_out = (unsigned char*)("test message. hello!\n"); + *message_length = strlen((char*)(message)); +} + +void receive_encrypted_message(unsigned char *message_in){ + //TODO: decrypt message +} diff --git a/pool/shard003/C/0066119_der_encode_ia5_string.c b/pool/shard003/C/0066119_der_encode_ia5_string.c new file mode 100644 index 0000000000000000000000000000000000000000..7b161f389bc788dcff1a159ad18543fc306a0140 --- /dev/null +++ b/pool/shard003/C/0066119_der_encode_ia5_string.c @@ -0,0 +1,71 @@ +/* LibTomCrypt, modular cryptographic library -- Tom St Denis + * + * LibTomCrypt is a library that provides various cryptographic + * algorithms in a highly modular and flexible manner. + * + * The library is free for all purposes without any express + * guarantee it works. + */ +#include "tomcrypt_private.h" + +/** + @file der_encode_ia5_string.c + ASN.1 DER, encode a IA5 STRING, Tom St Denis +*/ + +#ifdef LTC_DER + +/** + Store an IA5 STRING + @param in The array of IA5 to store (one per char) + @param inlen The number of IA5 to store + @param out [out] The destination for the DER encoded IA5 STRING + @param outlen [in/out] The max size and resulting size of the DER IA5 STRING + @return CRYPT_OK if successful +*/ +int der_encode_ia5_string(const unsigned char *in, unsigned long inlen, + unsigned char *out, unsigned long *outlen) +{ + unsigned long x, y, len; + int err; + + LTC_ARGCHK(in != NULL); + LTC_ARGCHK(out != NULL); + LTC_ARGCHK(outlen != NULL); + + /* get the size */ + if ((err = der_length_ia5_string(in, inlen, &len)) != CRYPT_OK) { + return err; + } + + /* too big? */ + if (len > *outlen) { + *outlen = len; + return CRYPT_BUFFER_OVERFLOW; + } + + /* encode the header+len */ + x = 0; + out[x++] = 0x16; + len = *outlen - x; + if ((err = der_encode_asn1_length(inlen, out + x, &len)) != CRYPT_OK) { + return err; + } + x += len; + + /* store octets */ + for (y = 0; y < inlen; y++) { + out[x++] = der_ia5_char_encode(in[y]); + } + + /* retun length */ + *outlen = x; + + return CRYPT_OK; +} + +#endif + +/* ref: HEAD -> develop */ +/* git commit: 9c0d7085234bd6baba2ab8fd9eee62254599341c */ +/* commit time: 2018-10-15 10:51:17 +0200 */ diff --git a/pool/shard003/C/0066125_if_rl_cardbus.c b/pool/shard003/C/0066125_if_rl_cardbus.c new file mode 100644 index 0000000000000000000000000000000000000000..ed50e850e6bb7f6818906b97381950cb08cc0205 --- /dev/null +++ b/pool/shard003/C/0066125_if_rl_cardbus.c @@ -0,0 +1,308 @@ +/* $OpenBSD: if_rl_cardbus.c,v 1.28 2014/12/19 22:44:58 guenther Exp $ */ +/* $NetBSD: if_rl_cardbus.c,v 1.3.8.3 2001/11/14 19:14:02 nathanw Exp $ */ + +/* + * Copyright (c) 2000 Masanori Kanaoka + * 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. 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 ``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 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. + */ + +/* + * if_rl_cardbus.c: + * Cardbus specific routines for Realtek 8139 ethernet adapter. + * Tested for + * - elecom-Laneed LD-10/100CBA (Accton MPX5030) + * - MELCO LPC3-TX-CB (Realtek 8139) + */ + +#include "bpfilter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#if NBPFILTER > 0 +#include +#endif + +#include +#include + +#include +#include + +#include + +#include +#include +#include + +#include + +/* + * Default to using PIO access for this driver. On SMP systems, + * there appear to be problems with memory mapped mode: it looks like + * doing too many memory mapped access back to back in rapid succession + * can hang the bus. I'm inclined to blame this on crummy design/construction + * on the part of Realtek. Memory mapped mode does appear to work on + * uniprocessor systems though. + */ +#define RL_USEIOSPACE + +#include + +/* + * Various supported device vendors/types and their names. + */ +const struct pci_matchid rl_cardbus_devices[] = { + { PCI_VENDOR_ABOCOM, PCI_PRODUCT_ABOCOM_FE2000VX }, + { PCI_VENDOR_ACCTON, PCI_PRODUCT_ACCTON_5030 }, + { PCI_VENDOR_COREGA, PCI_PRODUCT_COREGA_2CB_TXD }, + { PCI_VENDOR_COREGA, PCI_PRODUCT_COREGA_CB_TXD }, + { PCI_VENDOR_DLINK, PCI_PRODUCT_DLINK_DFE690TXD }, + { PCI_VENDOR_PLANEX, PCI_PRODUCT_PLANEX_FNW_3603_TX }, + { PCI_VENDOR_PLANEX, PCI_PRODUCT_PLANEX_FNW_3800_TX }, + { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8138 }, + { PCI_VENDOR_REALTEK, PCI_PRODUCT_REALTEK_RT8139 }, +}; + +struct rl_cardbus_softc { + struct rl_softc sc_rl; /* real rtk softc */ + + /* CardBus-specific goo. */ + void *sc_ih; + cardbus_devfunc_t sc_ct; + pci_chipset_tag_t sc_pc; + pcitag_t sc_tag; + int sc_csr; + int sc_cben; + int sc_bar_reg; + pcireg_t sc_bar_val; + bus_size_t sc_mapsize; + int sc_intrline; +}; + +static int rl_cardbus_match(struct device *, void *, void *); +static void rl_cardbus_attach(struct device *, struct device *, void *); +static int rl_cardbus_detach(struct device *, int); +void rl_cardbus_setup(struct rl_cardbus_softc *); + +struct cfattach rl_cardbus_ca = { + sizeof(struct rl_cardbus_softc), rl_cardbus_match, rl_cardbus_attach, + rl_cardbus_detach +}; + +int +rl_cardbus_match(struct device *parent, void *match, void *aux) +{ + return (cardbus_matchbyid((struct cardbus_attach_args *)aux, + rl_cardbus_devices, nitems(rl_cardbus_devices))); +} + + +void +rl_cardbus_attach(struct device *parent, struct device *self, void *aux) +{ + struct rl_cardbus_softc *csc = + (struct rl_cardbus_softc *)self; + struct rl_softc *sc = &csc->sc_rl; + struct cardbus_attach_args *ca = aux; + struct cardbus_softc *psc = + (struct cardbus_softc *)sc->sc_dev.dv_parent; + cardbus_chipset_tag_t cc = psc->sc_cc; + cardbus_function_tag_t cf = psc->sc_cf; + cardbus_devfunc_t ct = ca->ca_ct; + bus_addr_t adr; + + sc->sc_dmat = ca->ca_dmat; + csc->sc_ct = ct; + csc->sc_tag = ca->ca_tag; + csc->sc_intrline = ca->ca_intrline; + csc->sc_pc = ca->ca_pc; + + /* + * Map control/status registers. + */ + csc->sc_csr = PCI_COMMAND_MASTER_ENABLE; +#ifdef RL_USEIOSPACE + if (Cardbus_mapreg_map(ct, RL_PCI_LOIO, PCI_MAPREG_TYPE_IO, 0, + &sc->rl_btag, &sc->rl_bhandle, &adr, &csc->sc_mapsize) == 0) { + csc->sc_cben = CARDBUS_IO_ENABLE; + csc->sc_csr |= PCI_COMMAND_IO_ENABLE; + csc->sc_bar_reg = RL_PCI_LOIO; + csc->sc_bar_val = adr | PCI_MAPREG_TYPE_IO; + } +#else + if (Cardbus_mapreg_map(ct, RL_PCI_LOMEM, PCI_MAPREG_TYPE_MEM, 0, + &sc->rl_btag, &sc->rl_bhandle, &adr, &csc->sc_mapsize) == 0) { + csc->sc_cben = CARDBUS_MEM_ENABLE; + csc->sc_csr |= PCI_COMMAND_MEM_ENABLE; + csc->sc_bar_reg = RL_PCI_LOMEM; + csc->sc_bar_val = adr | PCI_MAPREG_TYPE_MEM; + } +#endif + else { + printf("%s: unable to map deviceregisters\n", + sc->sc_dev.dv_xname); + return; + } + + Cardbus_function_enable(ct); + + rl_cardbus_setup(csc); + + /* + * Map and establish the interrupt. + */ + csc->sc_ih = cardbus_intr_establish(cc, cf, csc->sc_intrline, IPL_NET, + rl_intr, sc, sc->sc_dev.dv_xname); + if (csc->sc_ih == NULL) { + printf(": couldn't establish interrupt\n"); + Cardbus_function_disable(csc->sc_ct); + return; + } + printf(": irq %d", csc->sc_intrline); + + sc->rl_type = RL_8139; + + rl_attach(sc); +} + +int +rl_cardbus_detach(struct device *self, int flags) +{ + struct rl_cardbus_softc *csc = (void *) self; + struct rl_softc *sc = &csc->sc_rl; + struct cardbus_devfunc *ct = csc->sc_ct; + int rv; + +#ifdef DIAGNOSTIC + if (ct == NULL) + panic("%s: data structure lacks", sc->sc_dev.dv_xname); +#endif + rv = rl_detach(sc); + if (rv) + return (rv); + /* + * Unhook the interrupt handler. + */ + if (csc->sc_ih != NULL) + cardbus_intr_disestablish(ct->ct_cc, ct->ct_cf, csc->sc_ih); + + /* + * Release bus space and close window. + */ + if (csc->sc_bar_reg != 0) + Cardbus_mapreg_unmap(ct, csc->sc_bar_reg, + sc->rl_btag, sc->rl_bhandle, csc->sc_mapsize); + + return (0); +} + +void +rl_cardbus_setup(struct rl_cardbus_softc *csc) +{ + struct rl_softc *sc = &csc->sc_rl; + cardbus_devfunc_t ct = csc->sc_ct; + cardbus_chipset_tag_t cc = ct->ct_cc; + pci_chipset_tag_t pc = csc->sc_pc; + pcireg_t reg, command; + int pmreg; + + /* + * Handle power management nonsense. + */ + if (pci_get_capability(pc, csc->sc_tag, + PCI_CAP_PWRMGMT, &pmreg, 0)) { + command = pci_conf_read(pc, csc->sc_tag, pmreg + 4); + if (command & RL_PSTATE_MASK) { + pcireg_t iobase, membase, irq; + + /* Save important PCI config data. */ + iobase = pci_conf_read(pc, csc->sc_tag, + RL_PCI_LOIO); + membase = pci_conf_read(pc, csc->sc_tag, + RL_PCI_LOMEM); + irq = pci_conf_read(pc, csc->sc_tag, + PCI_PRODUCT_DELTA_8139); + + /* Reset the power state. */ + printf("%s: chip is in D%d power mode " + "-- setting to D0\n", sc->sc_dev.dv_xname, + command & RL_PSTATE_MASK); + command &= 0xFFFFFFFC; + pci_conf_write(pc, csc->sc_tag, + pmreg + 4, command); + + /* Restore PCI config data. */ + pci_conf_write(pc, csc->sc_tag, + RL_PCI_LOIO, iobase); + pci_conf_write(pc, csc->sc_tag, + RL_PCI_LOMEM, membase); + pci_conf_write(pc, csc->sc_tag, + PCI_PRODUCT_DELTA_8139, irq); + } + } + + /* Make sure the right access type is on the CardBus bridge. */ + (*ct->ct_cf->cardbus_ctrl)(cc, csc->sc_cben); + (*ct->ct_cf->cardbus_ctrl)(cc, CARDBUS_BM_ENABLE); + + /* Program the BAR */ + pci_conf_write(pc, csc->sc_tag, + csc->sc_bar_reg, csc->sc_bar_val); + + /* Enable the appropriate bits in the CARDBUS CSR. */ + reg = pci_conf_read(pc, csc->sc_tag, + PCI_COMMAND_STATUS_REG); + reg &= ~(PCI_COMMAND_IO_ENABLE|PCI_COMMAND_MEM_ENABLE); + reg |= csc->sc_csr; + pci_conf_write(pc, csc->sc_tag, + PCI_COMMAND_STATUS_REG, reg); + + /* + * Make sure the latency timer is set to some reasonable + * value. + */ + reg = pci_conf_read(pc, csc->sc_tag, PCI_BHLC_REG); + if (PCI_LATTIMER(reg) < 0x20) { + reg &= ~(PCI_LATTIMER_MASK << PCI_LATTIMER_SHIFT); + reg |= (0x20 << PCI_LATTIMER_SHIFT); + pci_conf_write(pc, csc->sc_tag, PCI_BHLC_REG, reg); + } +} + diff --git a/pool/shard003/C/0066142_bag.c b/pool/shard003/C/0066142_bag.c new file mode 100644 index 0000000000000000000000000000000000000000..6cd8a95699d7099d6ea477e0ea83376f6448e10e --- /dev/null +++ b/pool/shard003/C/0066142_bag.c @@ -0,0 +1,165 @@ +/* bag.c -- ARMulator support code: ARM6 Instruction Emulator. + Copyright (C) 1994 Advanced RISC Machines Ltd. + + 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 . */ + +/********************************************************************/ +/* bag.c: */ +/* Offers a data structure for storing and getting pairs of number. */ +/* The numbers are stored together, put one can be looked up by */ +/* quoting the other. If a new pair is entered and one of the */ +/* numbers is a repeat of a previous pair, then the previos pair */ +/* is deleted. */ +/********************************************************************/ + +#include "bag.h" +#include + +#define HASH_TABLE_SIZE 256 +#define hash(x) (((x)&0xff)^(((x)>>8)&0xff)^(((x)>>16)&0xff)^(((x)>>24)&0xff)) + +typedef struct hashentry +{ + struct hashentry *next; + int first; + int second; +} +Hashentry; + +Hashentry *lookupbyfirst[HASH_TABLE_SIZE]; +Hashentry *lookupbysecond[HASH_TABLE_SIZE]; + +void +addtolist (Hashentry ** add, long first, long second) +{ + while (*add) + add = &((*add)->next); + /* Malloc will never fail? :o( */ + (*add) = (Hashentry *) malloc (sizeof (Hashentry)); + (*add)->next = (Hashentry *) 0; + (*add)->first = first; + (*add)->second = second; +} + +void +killwholelist (Hashentry * p) +{ + Hashentry *q; + + while (p) + { + q = p; + p = p->next; + free (q); + } +} + +static void +removefromlist (Hashentry ** p, long first) +{ + Hashentry *q; + + while (*p) + { + if ((*p)->first == first) + { + q = (*p)->next; + free (*p); + *p = q; + return; + } + p = &((*p)->next); + } +} + +void +BAG_putpair (long first, long second) +{ + long junk; + + if (BAG_getfirst (&junk, second) != NO_SUCH_PAIR) + BAG_killpair_bysecond (second); + addtolist (&lookupbyfirst[hash (first)], first, second); + addtolist (&lookupbysecond[hash (second)], first, second); +} + +Bag_error +BAG_getfirst (long *first, long second) +{ + Hashentry *look; + + look = lookupbysecond[hash (second)]; + while (look) + if (look->second == second) + { + *first = look->first; + return NO_ERROR; + } + return NO_SUCH_PAIR; +} + +Bag_error +BAG_getsecond (long first, long *second) +{ + Hashentry *look; + + look = lookupbyfirst[hash (first)]; + while (look) + { + if (look->first == first) + { + *second = look->second; + return NO_ERROR; + } + look = look->next; + } + return NO_SUCH_PAIR; +} + +Bag_error +BAG_killpair_byfirst (long first) +{ + long second; + + if (BAG_getsecond (first, &second) == NO_SUCH_PAIR) + return NO_SUCH_PAIR; + removefromlist (&lookupbyfirst[hash (first)], first); + removefromlist (&lookupbysecond[hash (second)], first); + return NO_ERROR; +} + +Bag_error +BAG_killpair_bysecond (long second) +{ + long first; + + if (BAG_getfirst (&first, second) == NO_SUCH_PAIR) + return NO_SUCH_PAIR; + removefromlist (&lookupbyfirst[hash (first)], first); + removefromlist (&lookupbysecond[hash (second)], first); + return NO_ERROR; +} + +void +BAG_newbag () +{ + int i; + + for (i = 0; i < 256; i++) + { + killwholelist (lookupbyfirst[i]); + killwholelist (lookupbysecond[i]); + lookupbyfirst[i] = lookupbysecond[i] = (Hashentry *) 0; + } +} diff --git a/pool/shard003/C/0066149_rfkill.c b/pool/shard003/C/0066149_rfkill.c new file mode 100644 index 0000000000000000000000000000000000000000..30ab05697ee81578baa87c53b679c4f24f07a882 --- /dev/null +++ b/pool/shard003/C/0066149_rfkill.c @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2011 Google, Inc. + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include + +static struct rfkill *bt_rfk; +static const char bt_name[] = "bluetooth"; + +static unsigned long bt_power; +static unsigned long bt_reset; + +static void getIoResource(struct platform_device *pdev) +{ + struct resource *res; + + printk("rfkill get gpio\n"); + + res = platform_get_resource_byname(pdev, IORESOURCE_IO,"bt_power"); + if (!res) { + printk("couldn't bt_power gpio\n"); + } + + bt_power = res->start; + + res = platform_get_resource_byname(pdev, IORESOURCE_IO,"bt_reset"); + if (!res) { + printk("couldn't find bt_reset gpio\n"); + } + + bt_reset = res->start; + + printk("bt_reset = %ld, bt_power = %ld\n", bt_reset, bt_power); +} + +static int bluetooth_set_power(void *data, bool blocked) +{ + printk("%s: block=%d\n",__func__, blocked); + + if (!blocked) { + gpio_direction_output(bt_power, 0); + gpio_direction_output(bt_reset, 0); + mdelay(10); + gpio_direction_output(bt_power, 1); + gpio_direction_output(bt_reset, 1); + mdelay(150); + } else { + gpio_direction_output(bt_power, 0); + gpio_direction_output(bt_reset, 0); + mdelay(10); + } + + return 0; +} + +static struct rfkill_ops rfkill_bluetooth_ops = { + .set_block = bluetooth_set_power, +}; + +static void rfkill_gpio_init(void) +{ + if(gpio_request(bt_power,"bt_power")){ + printk("request bt power fail\n"); + } + if(gpio_request(bt_reset,"bt_reset")){ + printk("request bt reset fail\n"); + } +} + +static void rfkill_gpio_deinit(void) +{ + gpio_free(bt_power); + gpio_free(bt_reset); +} +static int rfkill_bluetooth_probe(struct platform_device *pdev) +{ + + int rc = 0; + bool default_state = true; + + printk(KERN_INFO "-->%s\n", __func__); + getIoResource(pdev); + + bt_rfk = rfkill_alloc(bt_name, &pdev->dev, RFKILL_TYPE_BLUETOOTH, + &rfkill_bluetooth_ops, NULL); + if (!bt_rfk) { + rc = -ENOMEM; + goto err_rfkill_alloc; + } + rfkill_gpio_init(); + /* userspace cannot take exclusive control */ + rfkill_init_sw_state(bt_rfk,false); + rc = rfkill_register(bt_rfk); + if (rc) + goto err_rfkill_reg; + + rfkill_set_sw_state(bt_rfk,true); + bluetooth_set_power(NULL, default_state); + + printk(KERN_INFO "<--%s\n", __func__); + return 0; + +err_rfkill_reg: + rfkill_destroy(bt_rfk); +err_rfkill_alloc: + return rc; +} + +static int rfkill_bluetooth_remove(struct platform_device *dev) +{ + printk(KERN_INFO "-->%s\n", __func__); + rfkill_gpio_deinit(); + rfkill_unregister(bt_rfk); + rfkill_destroy(bt_rfk); + printk(KERN_INFO "<--%s\n", __func__); + return 0; +} + +static struct platform_driver rfkill_bluetooth_driver = { + .probe = rfkill_bluetooth_probe, + .remove = rfkill_bluetooth_remove, + .driver = { + .name = "rfkill", + .owner = THIS_MODULE, + }, +}; + +static int __init rfkill_bluetooth_init(void) +{ + printk(KERN_INFO "-->%s\n", __func__); + return platform_driver_register(&rfkill_bluetooth_driver); +} + +static void __exit rfkill_bluetooth_exit(void) +{ + printk(KERN_INFO "-->%s\n", __func__); + platform_driver_unregister(&rfkill_bluetooth_driver); +} + +late_initcall(rfkill_bluetooth_init); +module_exit(rfkill_bluetooth_exit); +MODULE_DESCRIPTION("bluetooth rfkill"); +MODULE_AUTHOR("Yale Wu "); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard003/C/0066159_mk_event_select.c b/pool/shard003/C/0066159_mk_event_select.c new file mode 100644 index 0000000000000000000000000000000000000000..ec5ae352bfda80065eda54b13f262850d19b1c07 --- /dev/null +++ b/pool/shard003/C/0066159_mk_event_select.c @@ -0,0 +1,318 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + +/* Monkey HTTP Server + * ================== + * Copyright 2001-2017 Eduardo Silva + * + * 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. + */ + +#ifdef _WIN32 +#include +#else +#include +#endif + +#include +#include + +struct fd_timer { + int fd; + time_t sec; + long nsec; +}; + +static inline int _mk_event_init() +{ + return 0; +} + +static inline void *_mk_event_loop_create(int size) +{ + struct mk_event_ctx *ctx; + + /* Override caller 'size', we always use FD_SETSIZE */ + size = FD_SETSIZE; + + /* Main event context */ + ctx = mk_mem_alloc_z(sizeof(struct mk_event_ctx)); + if (!ctx) { + return NULL; + } + + FD_ZERO(&ctx->rfds); + FD_ZERO(&ctx->wfds); + + /* Allocate space for events queue, re-use the struct mk_event */ + ctx->events = mk_mem_alloc_z(sizeof(struct mk_event *) * size); + if (!ctx->events) { + mk_mem_free(ctx); + return NULL; + } + + /* Fired events (upon select(2) return) */ + ctx->fired = mk_mem_alloc_z(sizeof(struct mk_event) * size); + if (!ctx->fired) { + mk_mem_free(ctx->events); + mk_mem_free(ctx); + return NULL; + } + ctx->queue_size = size; + + return ctx; +} + +/* Close handlers and memory */ +static inline void _mk_event_loop_destroy(struct mk_event_ctx *ctx) +{ + mk_mem_free(ctx->events); + mk_mem_free(ctx->fired); + mk_mem_free(ctx); +} + +/* Add the file descriptor to the arrays */ +static inline int _mk_event_add(struct mk_event_ctx *ctx, int fd, + int type, uint32_t events, void *data) +{ + struct mk_event *event; + + if (fd > FD_SETSIZE) { + return -1; + } + + if (events & MK_EVENT_READ) { + FD_SET(fd, &ctx->rfds); + } + if (events & MK_EVENT_WRITE) { + FD_SET(fd, &ctx->wfds); + } + + event = (struct mk_event *) data; + event->fd = fd; + event->type = type; + event->mask = events; + event->status = MK_EVENT_REGISTERED; + + ctx->events[fd] = event; + if (fd > ctx->max_fd) { + ctx->max_fd = fd; + } + + return 0; +} + +/* Delete an event */ +static inline int _mk_event_del(struct mk_event_ctx *ctx, struct mk_event *event) +{ + int i; + int fd; + struct mk_event *s_event; + + fd = event->fd; + + if (event->mask & MK_EVENT_READ) { + FD_CLR(event->fd, &ctx->rfds); + } + + if (event->mask & MK_EVENT_WRITE) { + FD_CLR(event->fd, &ctx->wfds); + } + + /* Update max_fd, lookup */ + if (event->fd == ctx->max_fd) { + for (i = (ctx->max_fd - 1); i > 0; i--) { + if (!ctx->events[i]) { + continue; + } + + s_event = ctx->events[i]; + if (s_event->mask != MK_EVENT_EMPTY) { + break; + } + } + ctx->max_fd = i; + } + + ctx->events[fd] = NULL; + return 0; +} + +/* + * Timeout worker, it writes a byte every certain amount of seconds, it finish + * once the other end of the pipe closes the fd[0]. + */ +void _timeout_worker(void *arg) +{ + int ret; + uint64_t val = 1; + struct fd_timer *timer; + struct timespec t_spec; + + timer = (struct fd_timer *) arg; + t_spec.tv_sec = timer->sec; + t_spec.tv_nsec = timer->nsec; + + while (1) { + /* sleep for a while */ + nanosleep(&t_spec, NULL); + + /* send notification */ + ret = write(timer->fd, &val, sizeof(uint64_t)); + if (ret == -1) { + perror("write"); + break; + } + } + + close(timer->fd); + free(timer); +} + +/* + * This routine creates a timer, since this select(2) backend aims to be used + * in very old systems to be compatible, we cannot trust timerfd_create(2) + * will be available (e.g: Cygwin), so our workaround is to create a pipe(2) + * and a thread, this thread writes a byte upon the expiration time is reached. + */ +static inline int _mk_event_timeout_create(struct mk_event_ctx *ctx, + time_t sec, long nsec, void *data) +{ + int ret; + int fd[2]; + struct mk_event *event; + struct fd_timer *timer; + pthread_t tid; + + timer = mk_mem_alloc(sizeof(struct fd_timer)); + if (!timer) { + return -1; + } + + ret = pipe(fd); + if (ret < 0) { + mk_mem_free(timer); + mk_libc_error("pipe"); + return ret; + } + + event = (struct mk_event *) data; + event->fd = fd[0]; + event->type = MK_EVENT_NOTIFICATION; + event->mask = MK_EVENT_EMPTY; + + _mk_event_add(ctx, fd[0], MK_EVENT_NOTIFICATION, MK_EVENT_READ, data); + event->mask = MK_EVENT_READ; + + /* Compose the timer context, this is released inside the worker thread */ + timer->fd = fd[1]; + timer->sec = sec; + timer->nsec = nsec; + + /* Now the dirty workaround, create a thread */ + ret = mk_utils_worker_spawn(_timeout_worker, timer, &tid); + if (ret < 0) { + close(fd[0]); + close(fd[1]); + mk_mem_free(timer); + return -1; + } + + return fd[0]; +} + +static inline int _mk_event_channel_create(struct mk_event_ctx *ctx, + int *r_fd, int *w_fd, void *data) +{ + int ret; + int fd[2]; + struct mk_event *event; + + ret = pipe(fd); + if (ret < 0) { + mk_libc_error("pipe"); + return ret; + } + + event = data; + event->fd = fd[0]; + event->type = MK_EVENT_NOTIFICATION; + event->mask = MK_EVENT_EMPTY; + + ret = _mk_event_add(ctx, fd[0], + MK_EVENT_NOTIFICATION, MK_EVENT_READ, event); + if (ret != 0) { + close(fd[0]); + close(fd[1]); + return ret; + } + event->mask = MK_EVENT_READ; + + *r_fd = fd[0]; + *w_fd = fd[1]; + + return 0; +} + +static inline int _mk_event_wait(struct mk_event_loop *loop) +{ + int i; + int f = 0; + uint32_t mask; + struct mk_event *fired; + struct mk_event_ctx *ctx = loop->data; + + memcpy(&ctx->_rfds, &ctx->rfds, sizeof(fd_set)); + memcpy(&ctx->_wfds, &ctx->wfds, sizeof(fd_set)); + + loop->n_events = select(ctx->max_fd + 1, &ctx->_rfds, &ctx->_wfds, NULL, NULL); + if (loop->n_events <= 0) { + return loop->n_events; + } + + /* + * Populate our events array with the data reported. In other backends such + * as mk_event_epoll and mk_event_kqueue this is done when iterating the + * results as their native implementation already provided an array ready + * for processing. + */ + for (i = 0; i <= ctx->max_fd; i++) { + /* skip empty references */ + if (!ctx->events[i]) { + continue; + } + + mask = 0; + if (FD_ISSET(i, &ctx->_rfds)) { + mask |= MK_EVENT_READ; + } + if (FD_ISSET(i, &ctx->_wfds)) { + mask |= MK_EVENT_WRITE; + } + + if (mask) { + fired = &ctx->fired[f]; + fired->fd = i; + fired->mask = mask; + fired->data = ctx->events[i]; + f++; + } + } + + loop->n_events = f; + return loop->n_events; +} + +static inline char *_mk_event_backend() +{ + return "select"; +} diff --git a/pool/shard003/C/0066169_ratedesired.c b/pool/shard003/C/0066169_ratedesired.c new file mode 100644 index 0000000000000000000000000000000000000000..f2602f77c6f7a3c451dc1337f20181437c69aaf5 --- /dev/null +++ b/pool/shard003/C/0066169_ratedesired.c @@ -0,0 +1,143 @@ +/** + ****************************************************************************** + * @addtogroup TauLabsCore Tau Labs Core components + * @{ + * @addtogroup UAVObjects UAVObject set for this firmware + * @{ + * + * @file ratedesired.c + * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. + * @author Tau Labs, http://taulabs.org, Copyright (C) 2012-2015 + * @brief Implementation of the RateDesired object. This file has been + * automatically generated by the UAVObjectGenerator. + * + * @note Object definition file: ratedesired.xml. + * This is an automatically generated file. + * DO NOT modify manually. + * + * @see The GNU Public License (GPL) Version 3 + * + *****************************************************************************/ +/* + * 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 + */ + +#include +#include "uavobjectmanager.h" +#include "ratedesired.h" + +// Private variables +static UAVObjHandle handle = NULL; + +/** + * Initialize object. + * \return 0 Success + * \return -1 Failure to initialize or -2 for already initialized + */ +int32_t RateDesiredInitialize(void) +{ + // Don't set the handle to null if already registered + if(UAVObjGetByID(RATEDESIRED_OBJID) != NULL) + return -2; + + // Register object with the object manager + handle = UAVObjRegister(RATEDESIRED_OBJID, + RATEDESIRED_ISSINGLEINST, RATEDESIRED_ISSETTINGS, RATEDESIRED_NUMBYTES, &RateDesiredSetDefaults); + + // Done + if (handle != 0) + { + return 0; + } + else + { + return -1; + } +} + +/** + * Initialize object fields and metadata with the default values. + * If a default value is not specified the object fields + * will be initialized to zero. + */ +void RateDesiredSetDefaults(UAVObjHandle obj, uint16_t instId) +{ + RateDesiredData data; + + // Initialize object fields to their default values + UAVObjGetInstanceData(obj, instId, &data); + memset(&data, 0, sizeof(RateDesiredData)); + + UAVObjSetInstanceData(obj, instId, &data); + + // Initialize object metadata to their default values + if (instId == 0) { + UAVObjMetadata metadata; + metadata.flags = + ACCESS_READWRITE << UAVOBJ_ACCESS_SHIFT | + ACCESS_READWRITE << UAVOBJ_GCS_ACCESS_SHIFT | + 0 << UAVOBJ_TELEMETRY_ACKED_SHIFT | + 0 << UAVOBJ_GCS_TELEMETRY_ACKED_SHIFT | + UPDATEMODE_PERIODIC << UAVOBJ_TELEMETRY_UPDATE_MODE_SHIFT | + UPDATEMODE_MANUAL << UAVOBJ_GCS_TELEMETRY_UPDATE_MODE_SHIFT; + metadata.telemetryUpdatePeriod = 1000; + metadata.gcsTelemetryUpdatePeriod = 0; + metadata.loggingUpdatePeriod = 1000; + UAVObjSetMetadata(obj, &metadata); + } +} + +/** + * Get object handle + */ +UAVObjHandle RateDesiredHandle() +{ + return handle; +} + +/** + * Get/Set object Functions + */ +void RateDesiredRollSet( float *NewRoll ) +{ + UAVObjSetDataField(RateDesiredHandle(), (void*)NewRoll, offsetof( RateDesiredData, Roll), sizeof(float)); +} +void RateDesiredRollGet( float *NewRoll ) +{ + UAVObjGetDataField(RateDesiredHandle(), (void*)NewRoll, offsetof( RateDesiredData, Roll), sizeof(float)); +} +void RateDesiredPitchSet( float *NewPitch ) +{ + UAVObjSetDataField(RateDesiredHandle(), (void*)NewPitch, offsetof( RateDesiredData, Pitch), sizeof(float)); +} +void RateDesiredPitchGet( float *NewPitch ) +{ + UAVObjGetDataField(RateDesiredHandle(), (void*)NewPitch, offsetof( RateDesiredData, Pitch), sizeof(float)); +} +void RateDesiredYawSet( float *NewYaw ) +{ + UAVObjSetDataField(RateDesiredHandle(), (void*)NewYaw, offsetof( RateDesiredData, Yaw), sizeof(float)); +} +void RateDesiredYawGet( float *NewYaw ) +{ + UAVObjGetDataField(RateDesiredHandle(), (void*)NewYaw, offsetof( RateDesiredData, Yaw), sizeof(float)); +} + + +/** + * @} + * @} + */ + diff --git a/pool/shard003/C/0066179_TestModelHistory_newSetters.c b/pool/shard003/C/0066179_TestModelHistory_newSetters.c new file mode 100644 index 0000000000000000000000000000000000000000..02135d9486c5e224622b529f2f4c8cdde2a19b64 --- /dev/null +++ b/pool/shard003/C/0066179_TestModelHistory_newSetters.c @@ -0,0 +1,217 @@ +/** + * \file TestModelHistory_newSetters.cpp + * \brief ModelHistory unit tests + * \author Sarah Keating + * + * */ + +#include +#include +#include +#include +#include +#include +#include + + +#include + +#if defined(__cplusplus) +LIBSBML_CPP_NAMESPACE_USE +CK_CPPSTART +#endif + +START_TEST (test_ModelHistory_setCreatedDate1) +{ + ModelHistory_t * mh = ModelHistory_create(); + fail_unless(mh != NULL); + + Date_t *date = Date_createFromString("2005-12-30T12:15:32+02:00"); + + int i = ModelHistory_setCreatedDate(mh, date); + + fail_unless( i == LIBSBML_OPERATION_SUCCESS ); + fail_unless(ModelHistory_isSetCreatedDate(mh) == 1); + + fail_unless(date != ModelHistory_getCreatedDate(mh)); + + const char * dateChar + = Date_getDateAsString(ModelHistory_getCreatedDate(mh)); + fail_unless(!strcmp(dateChar, "2005-12-30T12:15:32+02:00")); + + i = ModelHistory_setCreatedDate(mh, NULL); + + fail_unless( i == LIBSBML_OPERATION_SUCCESS ); + fail_unless(ModelHistory_isSetCreatedDate(mh) == 0); + + Date_free(date); + ModelHistory_free(mh); +} +END_TEST + + +START_TEST (test_ModelHistory_setCreatedDate2) +{ + ModelHistory_t * mh = ModelHistory_create(); + fail_unless(mh != NULL); + + Date_t *date = Date_createFromString("Jan 12"); + + int i = ModelHistory_setCreatedDate(mh, date); + + fail_unless( i == LIBSBML_INVALID_OBJECT ); + fail_unless(ModelHistory_isSetCreatedDate(mh) == 0); + + Date_free(date); + ModelHistory_free(mh); +} +END_TEST + + +START_TEST (test_ModelHistory_setModifiedDate1) +{ + ModelHistory_t * mh = ModelHistory_create(); + fail_unless(mh != NULL); + + Date_t *date = Date_createFromString("2005-12-30T12:15:32+02:00"); + + int i = ModelHistory_setModifiedDate(mh, date); + + fail_unless( i == LIBSBML_OPERATION_SUCCESS ); + fail_unless(ModelHistory_isSetModifiedDate(mh) == 1); + + fail_unless(date != ModelHistory_getModifiedDate(mh)); + + const char * dateChar + = Date_getDateAsString(ModelHistory_getModifiedDate(mh)); + fail_unless(!strcmp(dateChar, "2005-12-30T12:15:32+02:00")); + + i = ModelHistory_setModifiedDate(mh, NULL); + + fail_unless( i == LIBSBML_OPERATION_FAILED ); + fail_unless(ModelHistory_isSetModifiedDate(mh) == 1); + + Date_free(date); + ModelHistory_free(mh); +} +END_TEST + + +START_TEST (test_ModelHistory_setModifiedDate2) +{ + ModelHistory_t * mh = ModelHistory_create(); + fail_unless(mh != NULL); + + Date_t *date = Date_createFromValues(200, 13, 76, 56, 89, 90, 0, 0, 0); + + int i = ModelHistory_setModifiedDate(mh, date); + + fail_unless( i == LIBSBML_INVALID_OBJECT ); + fail_unless(ModelHistory_isSetModifiedDate(mh) == 0); + + Date_free(date); + ModelHistory_free(mh); +} +END_TEST + + +START_TEST (test_ModelHistory_addCreator1) +{ + ModelHistory_t * mh = ModelHistory_create(); + ModelCreator_t * mc = ModelCreator_create(); + ModelCreator_setFamilyName(mc, "Keating"); + ModelCreator_setGivenName(mc, "Sarah"); + + int i = ModelHistory_addCreator(mh, mc); + + fail_unless( i == LIBSBML_OPERATION_SUCCESS ); + fail_unless(ModelHistory_getNumCreators(mh) == 1); + + ModelCreator_free(mc); + ModelHistory_free(mh); +} +END_TEST + + +START_TEST (test_ModelHistory_addCreator2) +{ + ModelHistory_t * mh = ModelHistory_create(); + ModelCreator_t * mc = ModelCreator_create(); + ModelCreator_setGivenName(mc, "Sarah"); + + int i = ModelHistory_addCreator(mh, mc); + + fail_unless( i == LIBSBML_INVALID_OBJECT ); + fail_unless(ModelHistory_getNumCreators(mh) == 0); + + ModelCreator_free(mc); + ModelHistory_free(mh); +} +END_TEST + + +START_TEST (test_ModelHistory_addCreator3) +{ + ModelHistory_t * mh = ModelHistory_create(); + ModelCreator_t * mc = NULL; + + int i = ModelHistory_addCreator(mh, mc); + + fail_unless( i == LIBSBML_OPERATION_FAILED ); + fail_unless(ModelHistory_getNumCreators(mh) == 0); + + ModelHistory_free(mh); +} +END_TEST + + +Suite * +create_suite_ModelHistory_newSetters (void) +{ + Suite *suite = suite_create("ModelHistory_newSetters"); + TCase *tcase = tcase_create("ModelHistory_newSetters"); + + + tcase_add_test( tcase, test_ModelHistory_setCreatedDate1 ); + tcase_add_test( tcase, test_ModelHistory_setCreatedDate2 ); + tcase_add_test( tcase, test_ModelHistory_setModifiedDate1 ); + tcase_add_test( tcase, test_ModelHistory_setModifiedDate2 ); + tcase_add_test( tcase, test_ModelHistory_addCreator1 ); + tcase_add_test( tcase, test_ModelHistory_addCreator2 ); + tcase_add_test( tcase, test_ModelHistory_addCreator3 ); + + suite_add_tcase(suite, tcase); + + return suite; +} + + +#if defined(__cplusplus) +CK_CPPEND +#endif + diff --git a/pool/shard003/C/0066183_omi_prc_get.c b/pool/shard003/C/0066183_omi_prc_get.c new file mode 100644 index 0000000000000000000000000000000000000000..a5893d2d4e6cdc2323724a58271584e4a3d75040 --- /dev/null +++ b/pool/shard003/C/0066183_omi_prc_get.c @@ -0,0 +1,104 @@ +/**************************************************************** + * * + * Copyright 2001, 2009 Fidelity Information Services, Inc * + * * + * This source code contains the intellectual property * + * of its copyright holder(s), and is made available * + * under a license. If you do not know the terms of * + * the license, please stop and do not read further. * + * * + ****************************************************************/ + +/* + * omi_prc_get.c --- + * + * Process a GET request. + * + */ + +#ifndef lint +static char rcsid[] = "$Header:$"; +#endif + +#include "mdef.h" + +#include "gtm_string.h" + +#include "omi.h" +#include "error.h" +#include "stringpool.h" +#include "op.h" + + +int +omi_prc_get(omi_conn *cptr, char *xend, char *buff, char *bend) +{ + GBLREF bool undef_inhibit; + + char *bptr; + int rv; + omi_li len; + mval vo, vd, vg; + + bptr = buff; + +/* Global Ref */ + OMI_LI_READ(&len, cptr->xptr); +/* Condition handler for DBMS operations */ + ESTABLISH_RET(omi_dbms_ch,0); + rv = omi_gvextnam(cptr, len.value, cptr->xptr); +/* If true, there was an error finding the global reference in the DBMS */ + if (rv < 0) { + REVERT; + return rv; + } + cptr->xptr += len.value; + +/* Bounds checking */ + if (cptr->xptr > xend) { + REVERT; + return -OMI_ER_PR_INVMSGFMT; + } + +/* We want to make sure there is plenty of space in the string pool + * for all three operations ($ORDER, $GET, $DATA) */ + if (cptr->exts & OMI_XTF_NEWOP) + INVOKE_STP_GCOL(0); + +/* $GET */ + undef_inhibit = TRUE; + rv = op_gvget(&vg); + + if (cptr->exts & OMI_XTF_NEWOP) { +/* $DATA */ + op_gvdata(&vd); + if (!(vd.mvtype & MV_INT)) { + REVERT; + return -OMI_ER_DB_UNRECOVER; + } +/* $ORDER */ + op_gvorder(&vo); + OMI_SI_WRIT(vo.str.len, bptr); + if (vo.str.len) { + memcpy(bptr, vo.str.addr, vo.str.len); + bptr += vo.str.len; + } +/* $DATA (buffer write) */ + OMI_SI_WRIT(vd.m[1] / MV_BIAS, bptr); + } + +/* $GET (buffer write) */ + OMI_SI_WRIT((rv ? 1 : 0), bptr); + if (!rv || !vg.str.len) + OMI_LI_WRIT(0, bptr); + else { + OMI_LI_WRIT(vg.str.len, bptr); + memcpy(bptr, vg.str.addr, vg.str.len); + bptr += vg.str.len; + } + + REVERT; + + return (int)(bptr - buff); + +} diff --git a/pool/shard003/C/0066185_crzt02.c b/pool/shard003/C/0066185_crzt02.c new file mode 100644 index 0000000000000000000000000000000000000000..004a7398ccc2783284f1e862139925598795e84b --- /dev/null +++ b/pool/shard003/C/0066185_crzt02.c @@ -0,0 +1,155 @@ +/* crzt02.f -- translated by f2c (version 20061008). + You must link the resulting object file with libf2c: + on Microsoft Windows system, link with libf2c.lib; + on Linux or Unix systems, link with .../path/to/libf2c.a -lm + or, if you install libf2c.a in a standard place, with -lf2c -lm + -- in that order, at the end of the command line, as in + cc *.o -lf2c -lm + Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., + + http://www.netlib.org/f2c/libf2c.zip +*/ + +#include "f2c.h" +#include "blaswrap.h" + +/* Table of constant values */ + +static integer c__7 = 7; +static complex c_b5 = {0.f,0.f}; +static complex c_b6 = {1.f,0.f}; + +doublereal crzt02_(integer *m, integer *n, complex *af, integer *lda, complex + *tau, complex *work, integer *lwork) +{ + /* System generated locals */ + integer af_dim1, af_offset, i__1, i__2, i__3; + real ret_val; + complex q__1; + + /* Local variables */ + integer i__, info; + real rwork[1]; + extern doublereal clange_(char *, integer *, integer *, complex *, + integer *, real *), slamch_(char *); + extern /* Subroutine */ int claset_(char *, integer *, integer *, complex + *, complex *, complex *, integer *), xerbla_(char *, + integer *), cunmrz_(char *, char *, integer *, integer *, + integer *, integer *, complex *, integer *, complex *, complex *, + integer *, complex *, integer *, integer *); + + +/* -- LAPACK test routine (version 3.1) -- */ +/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ +/* November 2006 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + +/* Purpose */ +/* ======= */ + +/* CRZT02 returns */ +/* || I - Q'*Q || / ( M * eps) */ +/* where the matrix Q is defined by the Householder transformations */ +/* generated by CTZRZF. */ + +/* Arguments */ +/* ========= */ + +/* M (input) INTEGER */ +/* The number of rows of the matrix AF. */ + +/* N (input) INTEGER */ +/* The number of columns of the matrix AF. */ + +/* AF (input) COMPLEX array, dimension (LDA,N) */ +/* The output of CTZRZF. */ + +/* LDA (input) INTEGER */ +/* The leading dimension of the array AF. */ + +/* TAU (input) COMPLEX array, dimension (M) */ +/* Details of the Householder transformations as returned by */ +/* CTZRZF. */ + +/* WORK (workspace) COMPLEX array, dimension (LWORK) */ + +/* LWORK (input) INTEGER */ +/* Length of WORK array. LWORK >= N*N+N. */ + +/* ===================================================================== */ + +/* .. Parameters .. */ +/* .. */ +/* .. Local Scalars .. */ +/* .. */ +/* .. Local Arrays .. */ +/* .. */ +/* .. External Functions .. */ +/* .. */ +/* .. External Subroutines .. */ +/* .. */ +/* .. Intrinsic Functions .. */ +/* .. */ +/* .. Executable Statements .. */ + + /* Parameter adjustments */ + af_dim1 = *lda; + af_offset = 1 + af_dim1; + af -= af_offset; + --tau; + --work; + + /* Function Body */ + ret_val = 0.f; + + if (*lwork < *n * *n + *n) { + xerbla_("CRZT02", &c__7); + return ret_val; + } + +/* Quick return if possible */ + + if (*m <= 0 || *n <= 0) { + return ret_val; + } + +/* Q := I */ + + claset_("Full", n, n, &c_b5, &c_b6, &work[1], n); + +/* Q := P(1) * ... * P(m) * Q */ + + i__1 = *n - *m; + i__2 = *lwork - *n * *n; + cunmrz_("Left", "No transpose", n, n, m, &i__1, &af[af_offset], lda, &tau[ + 1], &work[1], n, &work[*n * *n + 1], &i__2, &info); + +/* Q := P(m)' * ... * P(1)' * Q */ + + i__1 = *n - *m; + i__2 = *lwork - *n * *n; + cunmrz_("Left", "Conjugate transpose", n, n, m, &i__1, &af[af_offset], + lda, &tau[1], &work[1], n, &work[*n * *n + 1], &i__2, &info); + +/* Q := Q - I */ + + i__1 = *n; + for (i__ = 1; i__ <= i__1; ++i__) { + i__2 = (i__ - 1) * *n + i__; + i__3 = (i__ - 1) * *n + i__; + q__1.r = work[i__3].r - 1.f, q__1.i = work[i__3].i; + work[i__2].r = q__1.r, work[i__2].i = q__1.i; +/* L10: */ + } + + ret_val = clange_("One-norm", n, n, &work[1], n, rwork) / ( + slamch_("Epsilon") * (real) max(*m,*n)); + return ret_val; + +/* End of CRZT02 */ + +} /* crzt02_ */ diff --git a/pool/shard003/C/0066188_tee_mm.c b/pool/shard003/C/0066188_tee_mm.c new file mode 100644 index 0000000000000000000000000000000000000000..0a2103d10510a5957e47c3bb3a8184005276817a --- /dev/null +++ b/pool/shard003/C/0066188_tee_mm.c @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2014, STMicroelectronics International N.V. + * 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 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. + */ + +#include +#include +#include + +#include +#include +#include + +bool tee_mm_init(tee_mm_pool_t *pool, uint32_t lo, uint32_t hi, uint8_t shift, + uint32_t flags) +{ + if (pool == NULL) + return false; + + lo = ROUNDUP(lo, 1 << shift); + hi = ROUNDDOWN(hi, 1 << shift); + pool->lo = lo; + pool->hi = hi; + pool->shift = shift; + pool->flags = flags; + pool->entry = calloc(1, sizeof(tee_mm_entry_t)); + + if (pool->entry == NULL) + return false; + + if (pool->flags & TEE_MM_POOL_HI_ALLOC) + pool->entry->offset = ((hi - lo - 1) >> shift) + 1; + pool->entry->pool = pool; + + return true; +} + +void tee_mm_final(tee_mm_pool_t *pool) +{ + if (pool == NULL || pool->entry == NULL) + return; + + while (pool->entry->next != NULL) + tee_mm_free(pool->entry->next); + free(pool->entry); + pool->entry = NULL; +} + +static tee_mm_entry_t *tee_mm_add(tee_mm_entry_t *p) +{ + /* add to list */ + if (p->next == NULL) { + p->next = malloc(sizeof(tee_mm_entry_t)); + if (p->next == NULL) + return NULL; + p->next->next = NULL; + } else { + tee_mm_entry_t *nn = malloc(sizeof(tee_mm_entry_t)); + + if (nn == NULL) + return NULL; + nn->next = p->next; + p->next = nn; + } + return p->next; +} + +tee_mm_entry_t *tee_mm_alloc(tee_mm_pool_t *pool, uint32_t size) +{ + uint32_t psize; + tee_mm_entry_t *entry; + tee_mm_entry_t *nn; + uint32_t remaining; + + /* Check that pool is initialized */ + if (!pool || !pool->entry) + return NULL; + + entry = pool->entry; + if (size == 0) + psize = 0; + else + psize = ((size - 1) >> pool->shift) + 1; + /* Protect with mutex (multi thread) */ + + /* find free slot */ + if (pool->flags & TEE_MM_POOL_HI_ALLOC) { + while (entry->next != NULL && psize > + (entry->offset - entry->next->offset - + entry->next->size)) + entry = entry->next; + } else { + while (entry->next != NULL && psize > + (entry->next->offset - entry->size - entry->offset)) + entry = entry->next; + } + + /* check if we have enough memory */ + if (entry->next == NULL) { + if (pool->flags & TEE_MM_POOL_HI_ALLOC) { + /* + * entry->offset is a "block count" offset from + * pool->lo. The byte offset is + * (entry->offset << pool->shift). + * In the HI_ALLOC allocation scheme the memory is + * allocated from the end of the segment, thus to + * validate there is sufficient memory validate that + * (entry->offset << pool->shift) > size. + */ + if ((entry->offset << pool->shift) < size) + /* out of memory */ + return NULL; + } else { + TEE_ASSERT(pool->hi > pool->lo); + remaining = (pool->hi - pool->lo); + remaining -= ((entry->offset + entry->size) << + pool->shift); + + if (remaining < size) + /* out of memory */ + return NULL; + } + } + + nn = tee_mm_add(entry); + if (nn == NULL) + return NULL; + + if (pool->flags & TEE_MM_POOL_HI_ALLOC) + nn->offset = entry->offset - psize; + else + nn->offset = entry->offset + entry->size; + nn->size = psize; + nn->pool = pool; + + /* Protect with mutex end (multi thread) */ + + return nn; +} + +static inline bool fit_in_gap(tee_mm_pool_t *pool, tee_mm_entry_t *e, + uint32_t offslo, uint32_t offshi) +{ + if (pool->flags & TEE_MM_POOL_HI_ALLOC) { + if (offshi > e->offset || + (e->next != NULL && + (offslo < e->next->offset + e->next->size)) || + (offshi << pool->shift) - 1 > (pool->hi - pool->lo)) + /* memory not available */ + return false; + } else { + if (offslo < (e->offset + e->size) || + (e->next != NULL && (offshi > e->next->offset)) || + (offshi << pool->shift) > (pool->hi - pool->lo)) + /* memory not available */ + return false; + } + + return true; +} + +tee_mm_entry_t *tee_mm_alloc2(tee_mm_pool_t *pool, tee_vaddr_t base, + size_t size) +{ + tee_mm_entry_t *entry; + uint32_t offslo; + uint32_t offshi; + tee_mm_entry_t *mm; + + /* Check that pool is initialized */ + if (!pool || !pool->entry) + return NULL; + + /* Wrapping and sanity check */ + if ((base + size) < base || base < pool->lo) + return NULL; + + entry = pool->entry; + offslo = (base - pool->lo) >> pool->shift; + offshi = ((base - pool->lo + size - 1) >> pool->shift) + 1; + + /* find slot */ + if (pool->flags & TEE_MM_POOL_HI_ALLOC) { + while (entry->next != NULL && + offshi < entry->next->offset + entry->next->size) + entry = entry->next; + } else { + while (entry->next != NULL && offslo > entry->next->offset) + entry = entry->next; + } + + /* Check that memory is available */ + if (!fit_in_gap(pool, entry, offslo, offshi)) + return NULL; + + mm = tee_mm_add(entry); + if (mm == NULL) + return NULL; + + mm->offset = offslo; + mm->size = offshi - offslo; + mm->pool = pool; + + return mm; +} + +void tee_mm_free(tee_mm_entry_t *p) +{ + tee_mm_entry_t *entry; + + if (!p || !p->pool) + return; + + entry = p->pool->entry; + + /* Protect with mutex (multi thread) */ + + /* remove entry from list */ + while (entry->next != NULL && entry->next != p) + entry = entry->next; + + if (entry->next == NULL) { + DMSG("invalid mm_entry %p", (void *)p); + TEE_ASSERT(0); + } + entry->next = entry->next->next; + + free(p); + + /* Protect with mutex end (multi thread) */ +} + +size_t tee_mm_get_bytes(const tee_mm_entry_t *mm) +{ + if (!mm || !mm->pool) + return 0; + else + return mm->size << mm->pool->shift; +} + +bool tee_mm_addr_is_within_range(tee_mm_pool_t *pool, uint32_t addr) +{ + return (pool && ((addr >= pool->lo) && (addr <= pool->hi))); +} + +bool tee_mm_is_empty(tee_mm_pool_t *pool) +{ + return pool == NULL || pool->entry == NULL || pool->entry->next == NULL; +} diff --git a/pool/shard003/C/0066235_filmstripenc.c b/pool/shard003/C/0066235_filmstripenc.c new file mode 100644 index 0000000000000000000000000000000000000000..21f47550af7fe3605516bf89f5ae9e7e6bc9c011 --- /dev/null +++ b/pool/shard003/C/0066235_filmstripenc.c @@ -0,0 +1,85 @@ +/* + * Adobe Filmstrip muxer + * Copyright (c) 2010 Peter Ross + * + * This file is part of Libav. + * + * Libav 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. + * + * Libav 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 Libav; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * Adobe Filmstrip muxer + */ + +#include "libavutil/intreadwrite.h" +#include "avformat.h" + +#define RAND_TAG MKBETAG('R','a','n','d') + +typedef struct { + int nb_frames; +} FilmstripMuxContext; + +static int write_header(AVFormatContext *s) +{ + if (s->streams[0]->codec->pix_fmt != PIX_FMT_RGBA) { + av_log(s, AV_LOG_ERROR, "only PIX_FMT_RGBA is supported\n"); + return AVERROR_INVALIDDATA; + } + return 0; +} + +static int write_packet(AVFormatContext *s, AVPacket *pkt) +{ + FilmstripMuxContext *film = s->priv_data; + avio_write(s->pb, pkt->data, pkt->size); + film->nb_frames++; + return 0; +} + +static int write_trailer(AVFormatContext *s) +{ + FilmstripMuxContext *film = s->priv_data; + AVIOContext *pb = s->pb; + AVStream *st = s->streams[0]; + int i; + + avio_wb32(pb, RAND_TAG); + avio_wb32(pb, film->nb_frames); + avio_wb16(pb, 0); // packing method + avio_wb16(pb, 0); // reserved + avio_wb16(pb, st->codec->width); + avio_wb16(pb, st->codec->height); + avio_wb16(pb, 0); // leading + avio_wb16(pb, 1/av_q2d(st->codec->time_base)); + for (i = 0; i < 16; i++) + avio_w8(pb, 0x00); // reserved + avio_flush(pb); + return 0; +} + +AVOutputFormat ff_filmstrip_muxer = { + "filmstrip", + NULL_IF_CONFIG_SMALL("Adobe Filmstrip"), + NULL, + "flm", + sizeof(FilmstripMuxContext), + CODEC_ID_NONE, + CODEC_ID_RAWVIDEO, + write_header, + write_packet, + write_trailer, +}; diff --git a/pool/shard003/C/0066236_btu_init.c b/pool/shard003/C/0066236_btu_init.c new file mode 100644 index 0000000000000000000000000000000000000000..03a03f6e95c9646e664a1e187dfa5e0d7c8148ba --- /dev/null +++ b/pool/shard003/C/0066236_btu_init.c @@ -0,0 +1,289 @@ +/****************************************************************************** + * + * Copyright (C) 2000-2012 Broadcom Corporation + * + * 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 "bt_defs.h" +#include "bt_target.h" +#include "bt_trace.h" +#include "controller.h" +#include "alarm.h" +#include "fixed_queue.h" +#include "hash_map.h" +#include "hash_functions.h" +#include "thread.h" + +#include "l2c_int.h" +#include "dyn_mem.h" +#include "btu.h" +#include "btm_int.h" + +#if SDP_INCLUDED == TRUE +#include "sdpint.h" +#endif + +#if (BLE_INCLUDED == TRUE) +#include "gatt_api.h" +#include "gatt_int.h" +#if SMP_INCLUDED == TRUE +#include "smp_int.h" +#endif +#endif + +// extern fixed_queue_t *btif_msg_queue; + +// Communication queue from bta thread to bt_workqueue. +fixed_queue_t *btu_bta_msg_queue; + +// Communication queue from hci thread to bt_workqueue. +extern fixed_queue_t *btu_hci_msg_queue; + +// General timer queue. +fixed_queue_t *btu_general_alarm_queue; +hash_map_t *btu_general_alarm_hash_map; +pthread_mutex_t btu_general_alarm_lock; +static const size_t BTU_GENERAL_ALARM_HASH_MAP_SIZE = 34; + +// Oneshot timer queue. +fixed_queue_t *btu_oneshot_alarm_queue; +hash_map_t *btu_oneshot_alarm_hash_map; +pthread_mutex_t btu_oneshot_alarm_lock; +static const size_t BTU_ONESHOT_ALARM_HASH_MAP_SIZE = 34; + +// l2cap timer queue. +fixed_queue_t *btu_l2cap_alarm_queue; +hash_map_t *btu_l2cap_alarm_hash_map; +pthread_mutex_t btu_l2cap_alarm_lock; +static const size_t BTU_L2CAP_ALARM_HASH_MAP_SIZE = 34; + +//thread_t *bt_workqueue_thread; +//static const char *BT_WORKQUEUE_NAME = "bt_workqueue"; +xTaskHandle xBtuTaskHandle = NULL; +xQueueHandle xBtuQueue = 0; + +extern void PLATFORM_DisableHciTransport(UINT8 bDisable); + +extern void btu_task_thread_handler(void *arg); +void btu_task_start_up(void); +void btu_task_shut_down(void); +/***************************************************************************** +** V A R I A B L E S * +******************************************************************************/ +// TODO(cmanton) Move this out of this file +const BD_ADDR BT_BD_ANY = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; +/***************************************************************************** +** +** Function btu_init_core +** +** Description Initialize control block memory for each core component. +** +** +** Returns void +** +******************************************************************************/ +void btu_init_core(void) +{ + /* Initialize the mandatory core stack components */ + btm_init(); + + l2c_init(); + +#if (defined(SDP_INCLUDED) && SDP_INCLUDED == TRUE) + sdp_init(); +#endif + +#if BLE_INCLUDED == TRUE +#if (defined(GATT_INCLUDED) && GATT_INCLUDED == true) + gatt_init(); +#endif +#if (defined(SMP_INCLUDED) && SMP_INCLUDED == TRUE) + SMP_Init(); +#endif + btm_ble_init(); +#endif +} + +/***************************************************************************** +** +** Function btu_free_core +** +** Description Releases control block memory for each core component. +** +** +** Returns void +** +******************************************************************************/ +void btu_free_core(void) +{ + // Free the mandatory core stack components + l2c_free(); + +#if BLE_INCLUDED == TRUE +#if (defined(GATTS_INCLUDED) && GATTS_INCLUDED == true) + gatt_free(); +#endif +#endif +} + +/***************************************************************************** +** +** Function BTU_StartUp +** +** Description Initializes the BTU control block. +** +** NOTE: Must be called before creating any tasks +** (RPC, BTU, HCIT, APPL, etc.) +** +** Returns void +** +******************************************************************************/ +void BTU_StartUp(void) +{ + memset (&btu_cb, 0, sizeof (tBTU_CB)); + btu_cb.trace_level = HCI_INITIAL_TRACE_LEVEL; + + btu_bta_msg_queue = fixed_queue_new(SIZE_MAX); + if (btu_bta_msg_queue == NULL) { + goto error_exit; + } + + btu_general_alarm_hash_map = hash_map_new(BTU_GENERAL_ALARM_HASH_MAP_SIZE, + hash_function_pointer, NULL, (data_free_fn)osi_alarm_free, NULL); + if (btu_general_alarm_hash_map == NULL) { + goto error_exit; + } + + pthread_mutex_init(&btu_general_alarm_lock, NULL); + + btu_general_alarm_queue = fixed_queue_new(SIZE_MAX); + if (btu_general_alarm_queue == NULL) { + goto error_exit; + } + + btu_oneshot_alarm_hash_map = hash_map_new(BTU_ONESHOT_ALARM_HASH_MAP_SIZE, + hash_function_pointer, NULL, (data_free_fn)osi_alarm_free, NULL); + if (btu_oneshot_alarm_hash_map == NULL) { + goto error_exit; + } + + pthread_mutex_init(&btu_oneshot_alarm_lock, NULL); + + btu_oneshot_alarm_queue = fixed_queue_new(SIZE_MAX); + if (btu_oneshot_alarm_queue == NULL) { + goto error_exit; + } + + btu_l2cap_alarm_hash_map = hash_map_new(BTU_L2CAP_ALARM_HASH_MAP_SIZE, + hash_function_pointer, NULL, (data_free_fn)osi_alarm_free, NULL); + if (btu_l2cap_alarm_hash_map == NULL) { + goto error_exit; + } + + pthread_mutex_init(&btu_l2cap_alarm_lock, NULL); + + btu_l2cap_alarm_queue = fixed_queue_new(SIZE_MAX); + if (btu_l2cap_alarm_queue == NULL) { + goto error_exit; + } + + xBtuQueue = xQueueCreate(BTU_QUEUE_NUM, sizeof(BtTaskEvt_t)); + xTaskCreatePinnedToCore(btu_task_thread_handler, BTU_TASK_NAME, BTU_TASK_STACK_SIZE, NULL, BTU_TASK_PRIO, &xBtuTaskHandle, 0); + btu_task_post(SIG_BTU_START_UP); + /* + // Continue startup on bt workqueue thread. + thread_post(bt_workqueue_thread, btu_task_start_up, NULL); + */ + return; + +error_exit:; + LOG_ERROR("%s Unable to allocate resources for bt_workqueue", __func__); + BTU_ShutDown(); +} + +void BTU_ShutDown(void) +{ + btu_task_shut_down(); + + fixed_queue_free(btu_bta_msg_queue, NULL); + + hash_map_free(btu_general_alarm_hash_map); + pthread_mutex_destroy(&btu_general_alarm_lock); + fixed_queue_free(btu_general_alarm_queue, NULL); + + hash_map_free(btu_oneshot_alarm_hash_map); + pthread_mutex_destroy(&btu_oneshot_alarm_lock); + fixed_queue_free(btu_oneshot_alarm_queue, NULL); + + hash_map_free(btu_l2cap_alarm_hash_map); + pthread_mutex_destroy(&btu_l2cap_alarm_lock); + fixed_queue_free(btu_l2cap_alarm_queue, NULL); + + //thread_free(bt_workqueue_thread); + vTaskDelete(xBtuTaskHandle); + vQueueDelete(xBtuQueue); + + btu_bta_msg_queue = NULL; + + btu_general_alarm_hash_map = NULL; + btu_general_alarm_queue = NULL; + + btu_oneshot_alarm_hash_map = NULL; + btu_oneshot_alarm_queue = NULL; + + btu_l2cap_alarm_hash_map = NULL; + btu_l2cap_alarm_queue = NULL; + +// bt_workqueue_thread = NULL; + xBtuTaskHandle = NULL; + xBtuQueue = 0; +} + +/***************************************************************************** +** +** Function BTU_BleAclPktSize +** +** Description export the BLE ACL packet size. +** +** Returns UINT16 +** +******************************************************************************/ +UINT16 BTU_BleAclPktSize(void) +{ +#if BLE_INCLUDED == TRUE + return controller_get_interface()->get_acl_packet_size_ble(); +#else + return 0; +#endif +} +/******************************************************************************* +** +** Function btu_uipc_rx_cback +** +** Description +** +** +** Returns void +** +*******************************************************************************/ +/* +void btu_uipc_rx_cback(BT_HDR *p_msg) { + assert(p_msg != NULL); + BT_TRACE(TRACE_LAYER_BTM, TRACE_TYPE_DEBUG, "btu_uipc_rx_cback event 0x%x," + " len %d, offset %d", p_msg->event, p_msg->len, p_msg->offset); + fixed_queue_enqueue(btu_hci_msg_queue, p_msg); +} +*/ diff --git a/pool/shard003/C/0066242_wchar.c b/pool/shard003/C/0066242_wchar.c new file mode 100644 index 0000000000000000000000000000000000000000..640ce76fc2ffddc31d1e24f182f59cafca8fee21 --- /dev/null +++ b/pool/shard003/C/0066242_wchar.c @@ -0,0 +1,164 @@ +/* + * wchar utility functions. + * + * Copyright (c) 2012 Marko Kreen + * + * 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 + +#include + +wchar_t *mbstr_decode(const char *str, int str_len, int *wlen_p, + wchar_t *wbuf, int wbuf_len, bool allow_invalid) +{ + mbstate_t ps; + int clen; + wchar_t *dst, *w, *wend; + const char *s; + const char *str_end; + int wmax; + + if (str_len < 0) + str_len = strlen(str); + str_end = str + str_len; + + /* max number of wchar_t that the output can take plus zero-terminator */ + wmax = str_len + 1; + if (wbuf != NULL && wmax < wbuf_len) { + dst = wbuf; + } else { + dst = malloc(sizeof(wchar_t) * wmax); + if (!dst) + return NULL; + } + + /* try full decode at once */ + s = str; + memset(&ps, 0, sizeof(ps)); + clen = mbsnrtowcs(dst, &s, str_len, wmax, &ps); + if (clen >= 0) { + if (wlen_p) + *wlen_p = clen; + dst[clen] = 0; + return dst; + } + if (!allow_invalid) + goto fail; + + /* full decode failed, decode chars one-by-one */ + s = str; + w = dst; + wend = dst + wmax - 1; + memset(&ps, 0, sizeof(ps)); + while (s < str_end && w < wend) { + clen = mbrtowc(w, s, str_end - s, &ps); + if (clen > 0) { + /* single char */ + w++; + s += clen; + } else if (clen == 0) { + /* string end */ + break; + } else if (allow_invalid) { + /* allow invalid encoding */ + memset(&ps, 0, sizeof(ps)); + *w++ = (unsigned char)*s++; + } else { + /* invalid encoding */ + goto fail; + } + } + + /* make sure we got string end */ + if (s < str_end && *s != '\0') + goto fail; + + *w = 0; + if (wlen_p) + *wlen_p = w - dst; + return dst; + +fail: + if (dst != wbuf) + free(dst); + return NULL; +} + +wctype_t wctype_wcsn(const wchar_t *name, unsigned int namelen) +{ + char buf[10]; + unsigned int i; + + if (namelen >= sizeof(buf)) + return (wctype_t)0; + for (i = 0; i < namelen; i++) { + wchar_t c = name[i]; + if (c < 0x20 || c > 127) + return (wctype_t)0; + buf[i] = c; + } + buf[i] = 0; + return wctype(buf); +} + +#ifndef HAVE_MBSNRTOWCS + +size_t mbsnrtowcs(wchar_t *dst, const char **src_p, size_t srclen, size_t dstlen, mbstate_t *ps) +{ + int clen; + const char *s, *s_end; + wchar_t *w; + mbstate_t pstmp; + size_t count = 0; + + if (!ps) { + memset(&pstmp, 0, sizeof(pstmp)); + ps = &pstmp; + } + + s = *src_p; + s_end = s + srclen; + w = dst; + while (s < s_end) { + if (w && count >= dstlen) { + /* dst is full */ + break; + } + clen = mbrtowc(w, s, s_end - s, ps); + if (clen > 0) { + /* proper character */ + if (w) + w++; + count++; + s += clen; + } else if (clen < 0) { + /* invalid encoding */ + *src_p = s; + return (size_t)(-1); + } else { + /* end of string */ + if (w) + *w = 0; + *src_p = NULL; + return count; + } + } + /* end due to srclen */ + *src_p = s; + return count; +} + +#endif + diff --git a/pool/shard003/C/0066251_hello-jnicallback.c b/pool/shard003/C/0066251_hello-jnicallback.c new file mode 100644 index 0000000000000000000000000000000000000000..5f1aade39ec78affd1a780e978d82219961a71a6 --- /dev/null +++ b/pool/shard003/C/0066251_hello-jnicallback.c @@ -0,0 +1,303 @@ +/* + * Copyright (C) 2016 The Android Open Source Project + * + * 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 + + +// Android log function wrappers +static const char* kTAG = "hello-jniCallback"; +#define LOGI(...) \ + ((void)__android_log_print(ANDROID_LOG_INFO, kTAG, __VA_ARGS__)) +#define LOGW(...) \ + ((void)__android_log_print(ANDROID_LOG_WARN, kTAG, __VA_ARGS__)) +#define LOGE(...) \ + ((void)__android_log_print(ANDROID_LOG_ERROR, kTAG, __VA_ARGS__)) + +// processing callback to handler class +typedef struct tick_context { + JavaVM *javaVM; + jclass jniHelperClz; + jobject jniHelperObj; + jclass mainActivityClz; + jobject mainActivityObj; + pthread_mutex_t lock; + int done; +} TickContext; +TickContext g_ctx; + +/* This is a trivial JNI example where we use a native method + * to return a new VM String. See the corresponding Java source + * file located at: + * + * hello-jniCallback/app/src/main/java/com/example/hellojnicallback/MainActivity.java + */ +JNIEXPORT jstring JNICALL +Java_com_example_hellojnicallback_MainActivity_stringFromJNI( JNIEnv* env, jobject thiz ) +{ +#if defined(__arm__) + #if defined(__ARM_ARCH_7A__) + #if defined(__ARM_NEON__) + #if defined(__ARM_PCS_VFP) + #define ABI "armeabi-v7a/NEON (hard-float)" + #else + #define ABI "armeabi-v7a/NEON" + #endif + #else + #if defined(__ARM_PCS_VFP) + #define ABI "armeabi-v7a (hard-float)" + #else + #define ABI "armeabi-v7a" + #endif + #endif + #else + #define ABI "armeabi" + #endif +#elif defined(__i386__) +#define ABI "x86" +#elif defined(__x86_64__) +#define ABI "x86_64" +#elif defined(__mips64) /* mips64el-* toolchain defines __mips__ too */ +#define ABI "mips64" +#elif defined(__mips__) +#define ABI "mips" +#elif defined(__aarch64__) +#define ABI "arm64-v8a" +#else +#define ABI "unknown" +#endif + return (*env)->NewStringUTF(env, "Hello from JNI ! Compiled with ABI " ABI "."); +} + +/* + * A helper function to show how to call + * java static functions JniHelper::getBuildVersion() + * java non-static function JniHelper::getRuntimeMemorySize() + * The trivial implementation for these functions are inside file + * JniHelper.java + */ +void queryRuntimeInfo(JNIEnv *env, jobject instance) { + // Find out which OS we are running on. It does not matter for this app + // just to demo how to call static functions. + // Our java JniHelper class id and instance are initialized when this + // shared lib got loaded, we just directly use them + // static function does not need instance, so we just need to feed + // class and method id to JNI + jmethodID versionFunc = (*env)->GetStaticMethodID( + env, g_ctx.jniHelperClz, + "getBuildVersion", "()Ljava/lang/String;"); + if (!versionFunc) { + LOGE("Failed to retrieve getBuildVersion() methodID @ line %d", + __LINE__); + return; + } + jstring buildVersion = (*env)->CallStaticObjectMethod(env, + g_ctx.jniHelperClz, versionFunc); + const char *version = (*env)->GetStringUTFChars(env, buildVersion, NULL); + if (!version) { + LOGE("Unable to get version string @ line %d", __LINE__); + return; + } + LOGI("Android Version - %s", version); + (*env)->ReleaseStringUTFChars(env, buildVersion, version); + + // we are called from JNI_OnLoad, so got to release LocalRef to avoid leaking + (*env)->DeleteLocalRef(env, buildVersion); + + // Query available memory size from a non-static public function + // we need use an instance of JniHelper class to call JNI + jmethodID memFunc = (*env)->GetMethodID(env, g_ctx.jniHelperClz, + "getRuntimeMemorySize", "()J"); + if (!memFunc) { + LOGE("Failed to retrieve getRuntimeMemorySize() methodID @ line %d", + __LINE__); + return; + } + jlong result = (*env)->CallLongMethod(env, instance, memFunc); + LOGI("Runtime free memory size: %lld", result); + (void)result; // silence the compiler warning +} + +/* + * processing one time initialization: + * Cache the javaVM into our context + * Find class ID for JniHelper + * Create an instance of JniHelper + * Make global reference since we are using them from a native thread + * Note: + * All resources allocated here are never released by application + * we rely on system to free all global refs when it goes away; + * the pairing function JNI_OnUnload() never gets called at all. + */ +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { + JNIEnv* env; + memset(&g_ctx, 0, sizeof(g_ctx)); + + g_ctx.javaVM = vm; + if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6) != JNI_OK) { + return JNI_ERR; // JNI version not supported. + } + + jclass clz = (*env)->FindClass(env, + "com/example/hellojnicallback/JniHandler"); + g_ctx.jniHelperClz = (*env)->NewGlobalRef(env, clz); + + jmethodID jniHelperCtor = (*env)->GetMethodID(env, g_ctx.jniHelperClz, + "", "()V"); + jobject handler = (*env)->NewObject(env, g_ctx.jniHelperClz, + jniHelperCtor); + g_ctx.jniHelperObj = (*env)->NewGlobalRef(env, handler); + queryRuntimeInfo(env, g_ctx.jniHelperObj); + + g_ctx.done = 0; + g_ctx.mainActivityObj = NULL; + return JNI_VERSION_1_6; +} + +/* + * A helper function to wrap java JniHelper::updateStatus(String msg) + * JNI allow us to call this function via an instance even it is + * private function. + */ +void sendJavaMsg(JNIEnv *env, jobject instance, + jmethodID func,const char* msg) { + jstring javaMsg = (*env)->NewStringUTF(env, msg); + (*env)->CallVoidMethod(env, instance, func, javaMsg); + (*env)->DeleteLocalRef(env, javaMsg); +} + +/* + * Main working thread function. From a pthread, + * calling back to MainActivity::updateTimer() to display ticks on UI + * calling back to JniHelper::updateStatus(String msg) for msg + */ +void* UpdateTicks(void* context) { + TickContext *pctx = (TickContext*) context; + JavaVM *javaVM = pctx->javaVM; + JNIEnv *env; + jint res = (*javaVM)->GetEnv(javaVM, (void**)&env, JNI_VERSION_1_6); + if (res != JNI_OK) { + res = (*javaVM)->AttachCurrentThread(javaVM, &env, NULL); + if (JNI_OK != res) { + LOGE("Failed to AttachCurrentThread, ErrorCode = %d", res); + return NULL; + } + } + + jmethodID statusId = (*env)->GetMethodID(env, pctx->jniHelperClz, + "updateStatus", + "(Ljava/lang/String;)V"); + sendJavaMsg(env, pctx->jniHelperObj, statusId, + "TickerThread status: initializing..."); + + // get mainActivity updateTimer function + jmethodID timerId = (*env)->GetMethodID(env, pctx->mainActivityClz, + "updateTimer", "()V"); + + struct timeval beginTime, curTime, usedTime, leftTime; + const struct timeval kOneSecond = { + (__kernel_time_t)1, + (__kernel_suseconds_t) 0 + }; + + sendJavaMsg(env, pctx->jniHelperObj, statusId, + "TickerThread status: start ticking ..."); + while(1) { + gettimeofday(&beginTime, NULL); + pthread_mutex_lock(&pctx->lock); + int done = pctx->done; + if (pctx->done) { + pctx->done = 0; + } + pthread_mutex_unlock(&pctx->lock); + if (done) { + break; + } + (*env)->CallVoidMethod(env, pctx->mainActivityObj, timerId); + + gettimeofday(&curTime, NULL); + timersub(&curTime, &beginTime, &usedTime); + timersub(&kOneSecond, &usedTime, &leftTime); + struct timespec sleepTime; + sleepTime.tv_sec = leftTime.tv_sec; + sleepTime.tv_nsec = leftTime.tv_usec * 1000; + + if (sleepTime.tv_sec <= 1) { + nanosleep(&sleepTime, NULL); + } else { + sendJavaMsg(env, pctx->jniHelperObj, statusId, + "TickerThread error: processing too long!"); + } + } + + sendJavaMsg(env, pctx->jniHelperObj, statusId, + "TickerThread status: ticking stopped"); + (*javaVM)->DetachCurrentThread(javaVM); + return context; +} + +/* + * Interface to Java side to start ticks, caller is from onResume() + */ +JNIEXPORT void JNICALL +Java_com_example_hellojnicallback_MainActivity_startTicks(JNIEnv *env, jobject instance) { + pthread_t threadInfo_; + pthread_attr_t threadAttr_; + + pthread_attr_init(&threadAttr_); + pthread_attr_setdetachstate(&threadAttr_, PTHREAD_CREATE_DETACHED); + + pthread_mutex_init(&g_ctx.lock, NULL); + + jclass clz = (*env)->GetObjectClass(env, instance); + g_ctx.mainActivityClz = (*env)->NewGlobalRef(env, clz); + g_ctx.mainActivityObj = (*env)->NewGlobalRef(env, instance); + + int result = pthread_create( &threadInfo_, &threadAttr_, UpdateTicks, &g_ctx); + assert(result == 0); + (void)result; +} + +/* + * Interface to Java side to stop ticks: + * we need to hold and make sure our native thread has finished before return + * for a clean shutdown. The caller is from onPause + */ +JNIEXPORT void JNICALL +Java_com_example_hellojnicallback_MainActivity_StopTicks(JNIEnv *env, jobject instance) { + pthread_mutex_lock(&g_ctx.lock); + g_ctx.done = 1; + pthread_mutex_unlock(&g_ctx.lock); + + // waiting for ticking thread to flip the done flag + struct timespec sleepTime; + memset(&sleepTime, 0, sizeof(sleepTime)); + sleepTime.tv_nsec = 100000000; + while (g_ctx.done) { + nanosleep(&sleepTime, NULL); + } + + // release object we allocated from StartTicks() function + (*env)->DeleteGlobalRef(env, g_ctx.mainActivityClz); + (*env)->DeleteGlobalRef(env, g_ctx.mainActivityObj); + g_ctx.mainActivityObj = NULL; + g_ctx.mainActivityClz = NULL; + + pthread_mutex_destroy(&g_ctx.lock); +} diff --git a/pool/shard003/C/0066262_s2n_extensions_server_supported_versions_recv_test.c b/pool/shard003/C/0066262_s2n_extensions_server_supported_versions_recv_test.c new file mode 100644 index 0000000000000000000000000000000000000000..21ad82f88955d934acb34c7a187b17938ea37bb7 --- /dev/null +++ b/pool/shard003/C/0066262_s2n_extensions_server_supported_versions_recv_test.c @@ -0,0 +1,75 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +/* Target Functions: s2n_extensions_server_supported_versions_process */ + +#include + +#include +#include + +#include "tls/extensions/s2n_server_supported_versions.h" + +#include "api/s2n.h" +#include "stuffer/s2n_stuffer.h" +#include "tls/s2n_connection.h" +#include "tls/s2n_tls.h" +#include "utils/s2n_safety.h" +#include "s2n_test.h" +#include "testlib/s2n_testlib.h" +#include "tls/s2n_tls13.h" + +/* This test is for TLS versions 1.3 and up only */ +static const uint8_t TLS_VERSIONS[] = {S2N_TLS13}; + +int s2n_fuzz_init(int *argc, char **argv[]) +{ + POSIX_GUARD(s2n_enable_tls13_in_test()); + return S2N_SUCCESS; +} + +int s2n_fuzz_test(const uint8_t *buf, size_t len) +{ + /* We need at least one byte of input to set parameters */ + S2N_FUZZ_ENSURE_MIN_LEN(len, 1); + + /* Setup */ + struct s2n_stuffer fuzz_stuffer = {0}; + POSIX_GUARD(s2n_stuffer_alloc(&fuzz_stuffer, len)); + POSIX_GUARD(s2n_stuffer_write_bytes(&fuzz_stuffer, buf, len)); + + struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT); + POSIX_ENSURE_REF(client_conn); + client_conn->config = s2n_config_new(); + + /* Pull a byte off the libfuzzer input and use it to set parameters */ + uint8_t randval = 0; + POSIX_GUARD(s2n_stuffer_read_uint8(&fuzz_stuffer, &randval)); + client_conn->client_protocol_version = TLS_VERSIONS[randval % s2n_array_len(TLS_VERSIONS)]; + + /* Run Test + * Do not use GUARD macro here since the connection memory hasn't been freed. + */ + s2n_extensions_server_supported_versions_recv(client_conn, &fuzz_stuffer); + + /* Cleanup */ + POSIX_GUARD(s2n_config_free(client_conn->config)); + POSIX_GUARD(s2n_connection_free(client_conn)); + POSIX_GUARD(s2n_stuffer_free(&fuzz_stuffer)); + + return S2N_SUCCESS; +} + +S2N_FUZZ_TARGET(s2n_fuzz_init, s2n_fuzz_test, NULL) diff --git a/pool/shard003/C/0066266_watchdog.c b/pool/shard003/C/0066266_watchdog.c new file mode 100644 index 0000000000000000000000000000000000000000..f5bcb7c46bb02f5b6e51be2032349a05a13b0fa1 --- /dev/null +++ b/pool/shard003/C/0066266_watchdog.c @@ -0,0 +1,126 @@ +/* + independent watchdog support + */ + +#include "hal.h" +#include "watchdog.h" +#include "stm32_util.h" + +#ifndef IWDG_BASE +#if defined(STM32H7) +#define IWDG_BASE 0x58004800 +#elif defined(STM32F7) || defined(STM32F4) +#define IWDG_BASE 0x40003000 +#elif defined(STM32F1) || defined(STM32F3) +#define IWDG_BASE 0x40003000 +#else +#error "Unsupported IWDG MCU config" +#endif +#endif + +#ifndef RCC_BASE +#error "Unsupported IWDG RCC MCU config" +#endif + +/* + defines for working out if the reset was from the watchdog + */ +#if defined(STM32H7) +#define WDG_RESET_STATUS (*(__IO uint32_t *)(RCC_BASE + 0xD0)) +#define WDG_RESET_CLEAR (1U<<16) +#define WDG_RESET_IS_IWDG (1U<<26) +#elif defined(STM32F7) || defined(STM32F4) +#define WDG_RESET_STATUS (*(__IO uint32_t *)(RCC_BASE + 0x74)) +#define WDG_RESET_CLEAR (1U<<24) +#define WDG_RESET_IS_IWDG (1U<<29) +#elif defined(STM32F1) || defined(STM32F3) +#define WDG_RESET_STATUS (*(__IO uint32_t *)(RCC_BASE + 0x24)) +#define WDG_RESET_CLEAR (1U<<24) +#define WDG_RESET_IS_IWDG (1U<<29) +#elif defined(STM32G4) || defined(STM32L4) +#define WDG_RESET_STATUS (*(__IO uint32_t *)(RCC_BASE + 0x94)) +#define WDG_RESET_CLEAR (1U<<23) +#define WDG_RESET_IS_IWDG (1U<<29) +#else +#error "Unsupported IWDG MCU config" +#endif + +typedef struct +{ + __IO uint32_t KR; /*!< IWDG Key register, Address offset: 0x00 */ + __IO uint32_t PR; /*!< IWDG Prescaler register, Address offset: 0x04 */ + __IO uint32_t RLR; /*!< IWDG Reload register, Address offset: 0x08 */ + __IO uint32_t SR; /*!< IWDG Status register, Address offset: 0x0C */ + __IO uint32_t WINR; /*!< IWDG Window register, Address offset: 0x10 */ +} IWDG_Regs; + +#define IWDGD (*(IWDG_Regs *)(IWDG_BASE)) + +static bool was_watchdog_reset; +static bool watchdog_enabled; + +/* + setup the watchdog + */ +void stm32_watchdog_init(void) +{ + // setup for 2s reset + IWDGD.KR = 0x5555; + IWDGD.PR = 2; // div16 + IWDGD.RLR = 0xFFF; + IWDGD.KR = 0xCCCC; + watchdog_enabled = true; +} + +/* + pat the dog, to prevent a reset. If not called for 1s + after stm32_watchdog_init() then MCU will reset + */ +void stm32_watchdog_pat(void) +{ + if (watchdog_enabled) { + IWDGD.KR = 0xAAAA; + } +} + +/* + save reason code for reset + */ +void stm32_watchdog_save_reason(void) +{ + if (WDG_RESET_STATUS & WDG_RESET_IS_IWDG) { + was_watchdog_reset = true; + } +} + +/* + clear reason code for reset + */ +void stm32_watchdog_clear_reason(void) +{ + WDG_RESET_STATUS = WDG_RESET_CLEAR; +} + +/* + return true if reboot was from a watchdog reset + */ +bool stm32_was_watchdog_reset(void) +{ + return was_watchdog_reset; +} + +/* + save persistent watchdog data + */ +void stm32_watchdog_save(const uint32_t *data, uint32_t nwords) +{ + set_rtc_backup(1, data, nwords); +} + +/* + load persistent watchdog data + */ +void stm32_watchdog_load(uint32_t *data, uint32_t nwords) +{ + get_rtc_backup(1, data, nwords); +} diff --git a/pool/shard003/C/0066282_can_unit.c b/pool/shard003/C/0066282_can_unit.c new file mode 100644 index 0000000000000000000000000000000000000000..89e0f213819462f09d04a22dd65709a7e0b97fd9 --- /dev/null +++ b/pool/shard003/C/0066282_can_unit.c @@ -0,0 +1,99 @@ +/* + * ===================================================================================== + * + * Filename: can_unit.c + * + * Description: can unit + * + * Version: 1.0 + * Created: 2018年09月06日 09时38分27秒 + * Revision: none + * Compiler: gcc + * + * Author: James Lee (JamesL), princeofdream@outlook.com + * Organization: BookCL + * + * ===================================================================================== + */ + + +#include "can_unit.h" + +static can_unit can_device; + +int open_can_device(can_unit* device) +{ + JCG(); + return 0; +} + +int close_can_device(can_unit* device) +{ + JCG(); + return 0; +} + +int read_data_from_can(can_unit* device, uint8_t** data, int len) +{ + int i0; + int read_len; + can_unit* current_device; + uint8_t *read_data; + + if (device == NULL) { + current_device = &can_device; + } else { + current_device = device; + } + + read_data = (uint8_t*)malloc(len); +#if 1 + i0 = 0; + while (i0 < len) { + if (i0 == 0) { + read_data[i0] = 0x05; + } else if (i0 == 1) { + read_data[i0] = 0xF0; + } else { + read_data[i0] = i0+0xA0; + } + i0++; + } +#endif + read_len = i0; + if (*data == NULL) { + *data = (uint8_t*)malloc(len); + } + memcpy(*data, read_data, read_len); + read_len = i0; + free(read_data); + return read_len; +} + +int write_data_to_can(can_unit* device, uint8_t* data, int len) +{ + int ret; + int i0; + can_unit* current_device; + + if (device == NULL) { + current_device = &can_device; + } else { + current_device = device; + } + JCG(); + i0 = 0; + printf("Write data: "); + while (i0 < len) { + printf("0x%02x ", data[i0]); + if ( i0 % 16 == 15 ) { + printf("\n"); + } else if ( i0 % 8 == 7) { + printf("\t"); + } + ++i0; + } + printf("\n"); + return ret; +} + diff --git a/pool/shard003/C/0066297_oop_test.c b/pool/shard003/C/0066297_oop_test.c new file mode 100644 index 0000000000000000000000000000000000000000..494f065bf47b52e744315e855709a197bce02cfa --- /dev/null +++ b/pool/shard003/C/0066297_oop_test.c @@ -0,0 +1,29 @@ +#include +#include +#include +#include + +int main() +{ + action_replay_object_t * object = action_replay_new( + action_replay_object_t_class(), + action_replay_object_t_args() + ); + assert( NULL != object ); + + action_replay_object_t * copy_object = action_replay_copy( object ); + assert( NULL != copy_object ); + + printf( + "object size: %zu, copy_object size: %zu\n", + object->_class->size, + copy_object->_class->size + ); + + assert( 0 == action_replay_delete( object )); + object = NULL; + assert( 0 == action_replay_delete( copy_object )); + copy_object = NULL; + + return 0; +} diff --git a/pool/shard003/C/0066324_strntoumax.c b/pool/shard003/C/0066324_strntoumax.c new file mode 100644 index 0000000000000000000000000000000000000000..56dddad89c9813ac759c0e87512199e039a2ec0d --- /dev/null +++ b/pool/shard003/C/0066324_strntoumax.c @@ -0,0 +1,77 @@ +/* + * strntoumax.c + * + * The strntoumax() function and associated + */ + +#include +#include +#include +#include + +static inline int digitval(int ch) +{ + if (ch >= '0' && ch <= '9') { + return ch - '0'; + } else if (ch >= 'A' && ch <= 'Z') { + return ch - 'A' + 10; + } else if (ch >= 'a' && ch <= 'z') { + return ch - 'a' + 10; + } else { + return -1; + } +} + +uintmax_t strntoumax(const char *nptr, char **endptr, int base, size_t n) +{ + int minus = 0; + uintmax_t v = 0; + int d; + + while (n && isspace((unsigned char)*nptr)) { + nptr++; + n--; + } + + /* Single optional + or - */ + if (n) { + char c = *nptr; + if (c == '-' || c == '+') { + minus = (c == '-'); + nptr++; + n--; + } + } + + if (base == 0) { + if (n >= 2 && nptr[0] == '0' && + (nptr[1] == 'x' || nptr[1] == 'X')) { + n -= 2; + nptr += 2; + base = 16; + } else if (n >= 1 && nptr[0] == '0') { + n--; + nptr++; + base = 8; + } else { + base = 10; + } + } else if (base == 16) { + if (n >= 2 && nptr[0] == '0' && + (nptr[1] == 'x' || nptr[1] == 'X')) { + n -= 2; + nptr += 2; + } + } + + while (n && (d = digitval(*nptr)) >= 0 && d < base) { + v = v * base + d; + n--; + nptr++; + } + + if (endptr) + *endptr = (char *)nptr; + + return minus ? -v : v; +} diff --git a/pool/shard003/C/0066337_cls_6byte.c b/pool/shard003/C/0066337_cls_6byte.c new file mode 100644 index 0000000000000000000000000000000000000000..24fd63baa3742f5d29720720d063bb09c06bba89 --- /dev/null +++ b/pool/shard003/C/0066337_cls_6byte.c @@ -0,0 +1,107 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Depending on the ABI. Check overlapping. + Limitations: none. + PR: none. + Originator: 20030828 */ + + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct cls_struct_6byte { + unsigned short a; + unsigned short b; + unsigned char c; + unsigned char d; +} cls_struct_6byte; + +cls_struct_6byte cls_struct_6byte_fn(struct cls_struct_6byte a1, + struct cls_struct_6byte a2) +{ + struct cls_struct_6byte result; + + result.a = a1.a + a2.a; + result.b = a1.b + a2.b; + result.c = a1.c + a2.c; + result.d = a1.d + a2.d; + + printf("%d %d %d %d %d %d %d %d: %d %d %d %d\n", a1.a, a1.b, a1.c, a1.d, + a2.a, a2.b, a2.c, a2.d, + result.a, result.b, result.c, result.d); + + return result; +} + +static void +cls_struct_6byte_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + + struct cls_struct_6byte a1, a2; + + a1 = *(struct cls_struct_6byte*)(args[0]); + a2 = *(struct cls_struct_6byte*)(args[1]); + + *(cls_struct_6byte*)resp = cls_struct_6byte_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; +#ifndef USING_MMAP + static ffi_closure cl; +#endif + ffi_closure *pcl; + void* args_dbl[5]; + ffi_type* cls_struct_fields[5]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + +#ifdef USING_MMAP + pcl = allocate_mmap (sizeof(ffi_closure)); +#else + pcl = &cl; +#endif + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + struct cls_struct_6byte g_dbl = { 127, 120, 1, 128 }; + struct cls_struct_6byte f_dbl = { 12, 128, 9, 127 }; + struct cls_struct_6byte res_dbl; + + cls_struct_fields[0] = &ffi_type_ushort; + cls_struct_fields[1] = &ffi_type_ushort; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = &ffi_type_uchar; + cls_struct_fields[4] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_6byte_fn), &res_dbl, args_dbl); + /* { dg-output "127 120 1 128 12 128 9 127: 139 248 10 255" } */ + printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 139 248 10 255" } */ + + CHECK(ffi_prep_closure(pcl, &cif, cls_struct_6byte_gn, NULL) == FFI_OK); + + res_dbl = ((cls_struct_6byte(*)(cls_struct_6byte, cls_struct_6byte))(pcl))(g_dbl, f_dbl); + /* { dg-output "\n127 120 1 128 12 128 9 127: 139 248 10 255" } */ + printf("res: %d %d %d %d\n", res_dbl.a, res_dbl.b, res_dbl.c, res_dbl.d); + /* { dg-output "\nres: 139 248 10 255" } */ + + + exit(0); +} diff --git a/pool/shard003/C/0066347_stat.c b/pool/shard003/C/0066347_stat.c new file mode 100644 index 0000000000000000000000000000000000000000..1cffa2b8a2fcd5dc9a6b329ce29498ef9e24cab0 --- /dev/null +++ b/pool/shard003/C/0066347_stat.c @@ -0,0 +1,170 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef arch_irq_stat_cpu +#define arch_irq_stat_cpu(cpu) 0 +#endif +#ifndef arch_irq_stat +#define arch_irq_stat() 0 +#endif +#ifndef arch_idle_time +#define arch_idle_time(cpu) 0 +#endif + +static int show_stat(struct seq_file *p, void *v) +{ + int i, j; + unsigned long jif; + cputime64_t user, nice, system, idle, iowait, irq, softirq, steal; + cputime64_t guest, guest_nice; + u64 sum = 0; + u64 sum_softirq = 0; + unsigned int per_softirq_sums[NR_SOFTIRQS] = {0}; + struct timespec boottime; + + user = nice = system = idle = iowait = + irq = softirq = steal = cputime64_zero; + guest = guest_nice = cputime64_zero; + getboottime(&boottime); + jif = boottime.tv_sec; + + for_each_possible_cpu(i) { + user = cputime64_add(user, kstat_cpu(i).cpustat.user); + nice = cputime64_add(nice, kstat_cpu(i).cpustat.nice); + system = cputime64_add(system, kstat_cpu(i).cpustat.system); + idle = cputime64_add(idle, kstat_cpu(i).cpustat.idle); + idle = cputime64_add(idle, arch_idle_time(i)); + iowait = cputime64_add(iowait, kstat_cpu(i).cpustat.iowait); + irq = cputime64_add(irq, kstat_cpu(i).cpustat.irq); + softirq = cputime64_add(softirq, kstat_cpu(i).cpustat.softirq); + steal = cputime64_add(steal, kstat_cpu(i).cpustat.steal); + guest = cputime64_add(guest, kstat_cpu(i).cpustat.guest); + guest_nice = cputime64_add(guest_nice, + kstat_cpu(i).cpustat.guest_nice); + sum += kstat_cpu_irqs_sum(i); + sum += arch_irq_stat_cpu(i); + + for (j = 0; j < NR_SOFTIRQS; j++) { + unsigned int softirq_stat = kstat_softirqs_cpu(j, i); + + per_softirq_sums[j] += softirq_stat; + sum_softirq += softirq_stat; + } + } + sum += arch_irq_stat(); + + seq_printf(p, "cpu %llu %llu %llu %llu %llu %llu %llu %llu %llu " + "%llu\n", + (unsigned long long)cputime64_to_clock_t(user), + (unsigned long long)cputime64_to_clock_t(nice), + (unsigned long long)cputime64_to_clock_t(system), + (unsigned long long)cputime64_to_clock_t(idle), + (unsigned long long)cputime64_to_clock_t(iowait), + (unsigned long long)cputime64_to_clock_t(irq), + (unsigned long long)cputime64_to_clock_t(softirq), + (unsigned long long)cputime64_to_clock_t(steal), + (unsigned long long)cputime64_to_clock_t(guest), + (unsigned long long)cputime64_to_clock_t(guest_nice)); + for_each_online_cpu(i) { + + /* Copy values here to work around gcc-2.95.3, gcc-2.96 */ + user = kstat_cpu(i).cpustat.user; + nice = kstat_cpu(i).cpustat.nice; + system = kstat_cpu(i).cpustat.system; + idle = kstat_cpu(i).cpustat.idle; + idle = cputime64_add(idle, arch_idle_time(i)); + iowait = kstat_cpu(i).cpustat.iowait; + irq = kstat_cpu(i).cpustat.irq; + softirq = kstat_cpu(i).cpustat.softirq; + steal = kstat_cpu(i).cpustat.steal; + guest = kstat_cpu(i).cpustat.guest; + guest_nice = kstat_cpu(i).cpustat.guest_nice; + seq_printf(p, + "cpu%d %llu %llu %llu %llu %llu %llu %llu %llu %llu " + "%llu\n", + i, + (unsigned long long)cputime64_to_clock_t(user), + (unsigned long long)cputime64_to_clock_t(nice), + (unsigned long long)cputime64_to_clock_t(system), + (unsigned long long)cputime64_to_clock_t(idle), + (unsigned long long)cputime64_to_clock_t(iowait), + (unsigned long long)cputime64_to_clock_t(irq), + (unsigned long long)cputime64_to_clock_t(softirq), + (unsigned long long)cputime64_to_clock_t(steal), + (unsigned long long)cputime64_to_clock_t(guest), + (unsigned long long)cputime64_to_clock_t(guest_nice)); + } + seq_printf(p, "intr %llu", (unsigned long long)sum); + + /* sum again ? it could be updated? */ + for_each_irq_nr(j) + seq_printf(p, " %u", kstat_irqs(j)); + + seq_printf(p, + "\nctxt %llu\n" + "btime %lu\n" + "processes %lu\n" + "procs_running %lu\n" + "procs_blocked %lu\n", + nr_context_switches(), + (unsigned long)jif, + total_forks, + nr_running(), + nr_iowait()); + + seq_printf(p, "softirq %llu", (unsigned long long)sum_softirq); + + for (i = 0; i < NR_SOFTIRQS; i++) + seq_printf(p, " %u", per_softirq_sums[i]); + seq_putc(p, '\n'); + + return 0; +} + +static int stat_open(struct inode *inode, struct file *file) +{ + unsigned size = 4096 * (1 + num_possible_cpus() / 32); + char *buf; + struct seq_file *m; + int res; + + /* don't ask for more than the kmalloc() max size, currently 128 KB */ + if (size > 128 * 1024) + size = 128 * 1024; + buf = kmalloc(size, GFP_KERNEL); + if (!buf) + return -ENOMEM; + + res = single_open(file, show_stat, NULL); + if (!res) { + m = file->private_data; + m->buf = buf; + m->size = size; + } else + kfree(buf); + return res; +} + +static const struct file_operations proc_stat_operations = { + .open = stat_open, + .read = seq_read, + .llseek = seq_lseek, + .release = single_release, +}; + +static int __init proc_stat_init(void) +{ + proc_create("stat", 0, NULL, &proc_stat_operations); + return 0; +} +module_init(proc_stat_init); diff --git a/pool/shard003/C/0066354_auth_filter.c b/pool/shard003/C/0066354_auth_filter.c new file mode 100644 index 0000000000000000000000000000000000000000..436a72f2b99f95c4a7abc414b5d69319e443f2a3 --- /dev/null +++ b/pool/shard003/C/0066354_auth_filter.c @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2008 Martin Willi + * Copyright (C) 2008 Philip Boetschi, Adrian Doerig + * Hochschule fuer Technik Rapperswil + * + * 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. See . + * + * 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 "auth_filter.h" + +#include + +typedef struct private_auth_filter_t private_auth_filter_t; + +/** + * private data of auth_filter + */ +struct private_auth_filter_t { + /** + * public functions + */ + auth_filter_t public; + + /** + * user session + */ + user_t *user; + + /** + * database connection + */ + database_t *db; +}; + +METHOD(filter_t, run, bool, + private_auth_filter_t *this, request_t *request, char *controller, + char *action, char *p2, char *p3, char *p4, char *p5) +{ + if (this->user->get_user(this->user)) + { + enumerator_t *query; + char *login; + + query = this->db->query(this->db, "SELECT login FROM user WHERE id = ?", + DB_INT, this->user->get_user(this->user), + DB_TEXT); + if (query && query->enumerate(query, &login)) + { + request->set(request, "login", login); + query->destroy(query); + return TRUE; + } + DESTROY_IF(query); + this->user->set_user(this->user, 0); + } + if (controller && streq(controller, "user") && action && + (streq(action, "add") || streq(action, "login") || streq(action, "help"))) + { /* add/login allowed */ + return TRUE; + } + request->redirect(request, "user/login"); + return FALSE; +} + +METHOD(filter_t, destroy, void, + private_auth_filter_t *this) +{ + free(this); +} + +/* + * see header file + */ +filter_t *auth_filter_create(user_t *user, database_t *db) +{ + private_auth_filter_t *this; + + INIT(this, + .public = { + .filter = { + .destroy = _destroy, + .run = _run, + }, + }, + .user = user, + .db = db, + ); + + return &this->public.filter; +} + diff --git a/pool/shard003/C/0066363_f_wipe.c b/pool/shard003/C/0066363_f_wipe.c new file mode 100644 index 0000000000000000000000000000000000000000..4fe66f4b08c5e1269763cf155ea605dfe1a4c281 --- /dev/null +++ b/pool/shard003/C/0066363_f_wipe.c @@ -0,0 +1,268 @@ +/* Emacs style mode select -*- C++ -*- + *----------------------------------------------------------------------------- + * + * + * PrBoom: a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * Copyright 2005, 2006 by + * Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko + * + * 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. + * + * DESCRIPTION: + * Mission begin melt/wipe screen special effect. + * + *----------------------------------------------------------------------------- + */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "z_zone.h" +#include "doomdef.h" +#include "i_video.h" +#include "v_video.h" +#include "m_random.h" +#include "f_wipe.h" +#ifdef GL_DOOM +#include "gl_struct.h" +#endif +#include "e6y.h"//e6y + +// +// SCREEN WIPE PACKAGE +// + +// Parts re-written to support true-color video modes. Column-major +// formatting removed. - POPE + +// CPhipps - macros for the source and destination screens +#define SRC_SCR 2 +#define DEST_SCR 3 + +static screeninfo_t wipe_scr_start; +static screeninfo_t wipe_scr_end; +static screeninfo_t wipe_scr; + +// e6y: resolution limitation is removed +static int *y_lookup = NULL; + +// e6y: resolution limitation is removed +void R_InitMeltRes(void) +{ + if (y_lookup) free(y_lookup); + + y_lookup = calloc(1, SCREENWIDTH * sizeof(*y_lookup)); +} + +static int wipe_initMelt(int ticks) +{ + int i; + + if (V_GetMode() != VID_MODEGL) + { + // copy start screen to main screen + for(i=0;i not ready to scroll yet) + y_lookup[0] = -(M_Random()%16); + for (i=1;i 0) + y_lookup[i] = 0; + else + if (y_lookup[i] == -16) + y_lookup[i] = -15; + } + return 0; +} + +static int wipe_doMelt(int ticks) +{ + dboolean done = true; + int i; + const int depth = V_GetPixelDepth(); + + while (ticks--) { + for (i=0;i<(SCREENWIDTH);i++) { + if (y_lookup[i]<0) { + y_lookup[i]++; + done = false; + continue; + } + if (y_lookup[i] < SCREENHEIGHT) { + byte *s, *d; + int j, k, dy; + + /* cph 2001/07/29 - + * The original melt rate was 8 pixels/sec, i.e. 25 frames to melt + * the whole screen, so make the melt rate depend on SCREENHEIGHT + * so it takes no longer in high res + */ + dy = (y_lookup[i] < 16) ? y_lookup[i]+1 : SCREENHEIGHT/25; + if (y_lookup[i]+dy >= SCREENHEIGHT) + dy = SCREENHEIGHT - y_lookup[i]; + + if (V_GetMode() != VID_MODEGL) { + s = wipe_scr_end.data + (y_lookup[i]*wipe_scr_end.byte_pitch+(i*depth)); + d = wipe_scr.data + (y_lookup[i]*wipe_scr.byte_pitch+(i*depth)); + for (j=dy;j;j--) { + for (k=0; k + */ + +#include "net/rime/netflood.h" + +#include + +#define HOPS_MAX 16 + +struct netflood_hdr { + uint16_t originator_seqno; + rimeaddr_t originator; + uint16_t hops; +}; + +#define DEBUG 0 +#if DEBUG +#include +#define PRINTF(...) printf(__VA_ARGS__) +#else +#define PRINTF(...) +#endif + +/*---------------------------------------------------------------------------*/ +static int +send(struct netflood_conn *c) +{ + PRINTF("%d.%d: netflood send to ipolite\n", + rimeaddr_node_addr.u8[0], rimeaddr_node_addr.u8[1]); + return ipolite_send(&c->c, c->queue_time, 4); +} +/*---------------------------------------------------------------------------*/ +static void +recv_from_ipolite(struct ipolite_conn *ipolite, const rimeaddr_t *from) +{ + struct netflood_conn *c = (struct netflood_conn *)ipolite; + struct netflood_hdr hdr; + uint8_t hops; + struct queuebuf *queuebuf; + + memcpy(&hdr, packetbuf_dataptr(), sizeof(struct netflood_hdr)); + hops = hdr.hops; + + /* Remember packet if we need to forward it. */ + queuebuf = queuebuf_new_from_packetbuf(); + + packetbuf_hdrreduce(sizeof(struct netflood_hdr)); + if(c->u->recv != NULL) { + if(!(rimeaddr_cmp(&hdr.originator, &c->last_originator) && + hdr.originator_seqno <= c->last_originator_seqno)) { + + if(c->u->recv(c, from, &hdr.originator, hdr.originator_seqno, + hops)) { + + if(queuebuf != NULL) { + queuebuf_to_packetbuf(queuebuf); + queuebuf_free(queuebuf); + queuebuf = NULL; + memcpy(&hdr, packetbuf_dataptr(), sizeof(struct netflood_hdr)); + + /* Rebroadcast received packet. */ + if(hops < HOPS_MAX) { + PRINTF("%d.%d: netflood rebroadcasting %d.%d/%d (%d.%d/%d) hops %d\n", + rimeaddr_node_addr.u8[0], rimeaddr_node_addr.u8[1], + hdr.originator.u8[0], hdr.originator.u8[1], + hdr.originator_seqno, + c->last_originator.u8[0], c->last_originator.u8[1], + c->last_originator_seqno, + hops); + hdr.hops++; + memcpy(packetbuf_dataptr(), &hdr, sizeof(struct netflood_hdr)); + send(c); + rimeaddr_copy(&c->last_originator, &hdr.originator); + c->last_originator_seqno = hdr.originator_seqno; + } + } + } + } + } + if(queuebuf != NULL) { + queuebuf_free(queuebuf); + } +} +/*---------------------------------------------------------------------------*/ +static void +sent(struct ipolite_conn *ipolite) +{ + struct netflood_conn *c = (struct netflood_conn *)ipolite; + if(c->u->sent != NULL) { + c->u->sent(c); + } +} +/*---------------------------------------------------------------------------*/ +static void +dropped(struct ipolite_conn *ipolite) +{ + struct netflood_conn *c = (struct netflood_conn *)ipolite; + if(c->u->dropped != NULL) { + c->u->dropped(c); + } +} +/*---------------------------------------------------------------------------*/ +static const struct ipolite_callbacks netflood = {recv_from_ipolite, sent, dropped}; +/*---------------------------------------------------------------------------*/ +void +netflood_open(struct netflood_conn *c, clock_time_t queue_time, + uint16_t channel, const struct netflood_callbacks *u) +{ + ipolite_open(&c->c, channel, 1, &netflood); + c->u = u; + c->queue_time = queue_time; +} +/*---------------------------------------------------------------------------*/ +void +netflood_close(struct netflood_conn *c) +{ + ipolite_close(&c->c); +} +/*---------------------------------------------------------------------------*/ +int +netflood_send(struct netflood_conn *c, uint8_t seqno) +{ + if(packetbuf_hdralloc(sizeof(struct netflood_hdr))) { + struct netflood_hdr *hdr = packetbuf_hdrptr(); + rimeaddr_copy(&hdr->originator, &rimeaddr_node_addr); + rimeaddr_copy(&c->last_originator, &hdr->originator); + c->last_originator_seqno = hdr->originator_seqno = seqno; + hdr->hops = 0; + PRINTF("%d.%d: netflood sending '%s'\n", + rimeaddr_node_addr.u8[0], rimeaddr_node_addr.u8[1], + (char *)packetbuf_dataptr()); + return ipolite_send(&c->c, 0, 4); + } + return 0; +} +/*---------------------------------------------------------------------------*/ +void +netflood_cancel(struct netflood_conn *c) +{ + ipolite_cancel(&c->c); +} +/*---------------------------------------------------------------------------*/ +/** @} */ diff --git a/pool/shard003/C/0066381_read.c b/pool/shard003/C/0066381_read.c new file mode 100644 index 0000000000000000000000000000000000000000..bbf75cb5d15c1d1ae35dff8aa1725e3e7d5452ca --- /dev/null +++ b/pool/shard003/C/0066381_read.c @@ -0,0 +1,122 @@ +/* vi: set sw=4 ts=4: */ +/* + * Utility routines. + * + * Copyright (C) 1999-2004 by Erik Andersen + * + * Licensed under GPLv2 or later, see file LICENSE in this source tree. + */ + +#include "udhcp/common.h" + +struct sockaddr dest_sin; +socklen_t dest_length = sizeof(struct sockaddr); + +ssize_t ICACHE_FLASH_ATTR safe_read(int fd, void *buf, size_t count) +{ + ssize_t n; + + do { +// n = read(fd, buf, count); + n = recvfrom(fd, buf, count, 0, &dest_sin, &dest_length); + } while (n < 0 && errno == EINTR); + + return n; +} + +/* + * Read all of the supplied buffer from a file. + * This does multiple reads as necessary. + * Returns the amount read, or -1 on an error. + * A short read is returned on an end of file. + */ +ssize_t ICACHE_FLASH_ATTR full_read(int fd, void *buf, size_t len) +{ + ssize_t cc; + ssize_t total; + + total = 0; + + while (len) { + cc = safe_read(fd, buf, len); + + if (cc < 0) { + if (total) { + /* we already have some! */ + /* user can do another read to know the error code */ + return total; + } + return cc; /* read() returns -1 on failure. */ + } + if (cc == 0) + break; + buf = ((char *)buf) + cc; + total += cc; + len -= cc; + } + + return total; +} + +ssize_t ICACHE_FLASH_ATTR read_close(int fd, void *buf, size_t size) +{ + /*int e;*/ + size = full_read(fd, buf, size); + /*e = errno;*/ + close(fd); + /*errno = e;*/ + return size; +} + +/*ssize_t open_read_close(const char *filename, void *buf, size_t size) +{ + int fd = open(filename, O_RDONLY); + if (fd < 0) + return fd; + return read_close(fd, buf, size); +}*/ + +ssize_t ICACHE_FLASH_ATTR safe_write(int fd, const void *buf, size_t count) +{ + ssize_t n; + + do { +// n = write(fd, buf, count); + n = sendto(fd, buf, count, 0, &dest_sin, dest_length); + } while (n < 0 && errno == EINTR); + + return n; +} + +/* + * Write all of the supplied buffer out to a file. + * This does multiple writes as necessary. + * Returns the amount written, or -1 on an error. + */ +ssize_t ICACHE_FLASH_ATTR full_write(int fd, const void *buf, size_t len) +{ + ssize_t cc; + ssize_t total; + + total = 0; + + while (len) { + cc = safe_write(fd, buf, len); + + if (cc < 0) { + if (total) { + /* we already wrote some! */ + /* user can do another write to know the error code */ + return total; + } + return cc; /* write() returns -1 on failure. */ + } + + total += cc; + buf = ((const char *)buf) + cc; + len -= cc; + } + + return total; +} + diff --git a/pool/shard003/C/0066430_weather.c b/pool/shard003/C/0066430_weather.c new file mode 100644 index 0000000000000000000000000000000000000000..33e07483a2ba7c61a82b65f199f9187f79ed670f --- /dev/null +++ b/pool/shard003/C/0066430_weather.c @@ -0,0 +1,125 @@ +#include +#include "weather.h" + +WeatherInfo Weather_weatherInfo; +WeatherForecastInfo Weather_weatherForecast; + +GDrawCommandImage* Weather_currentWeatherIcon; +GDrawCommandImage* Weather_forecastWeatherIcon; + +uint32_t getConditionIcon(WeatherCondition conditionCode) { + uint32_t iconToLoad; + + switch(conditionCode) { + case CLEAR_DAY: + iconToLoad = RESOURCE_ID_WEATHER_CLEAR_DAY; + break; + case CLEAR_NIGHT: + iconToLoad = RESOURCE_ID_WEATHER_CLEAR_NIGHT; + break; + case CLOUDY_DAY: + iconToLoad = RESOURCE_ID_WEATHER_CLOUDY; + break; + case HEAVY_RAIN: + iconToLoad = RESOURCE_ID_WEATHER_HEAVY_RAIN; + break; + case HEAVY_SNOW: + iconToLoad = RESOURCE_ID_WEATHER_HEAVY_SNOW; + break; + case LIGHT_RAIN: + iconToLoad = RESOURCE_ID_WEATHER_LIGHT_RAIN; + break; + case LIGHT_SNOW: + iconToLoad = RESOURCE_ID_WEATHER_LIGHT_SNOW; + break; + case PARTLY_CLOUDY_NIGHT: + iconToLoad = RESOURCE_ID_WEATHER_PARTLY_CLOUDY_NIGHT; + break; + case PARTLY_CLOUDY: + iconToLoad = RESOURCE_ID_WEATHER_PARTLY_CLOUDY; + break; + case RAINING_AND_SNOWING: + iconToLoad = RESOURCE_ID_WEATHER_RAINING_AND_SNOWING; + break; + case THUNDERSTORM: + iconToLoad = RESOURCE_ID_WEATHER_THUNDERSTORM; + break; + default: + iconToLoad = RESOURCE_ID_WEATHER_GENERIC; + break; + } + + return iconToLoad; +} + +void Weather_setCurrentCondition(int conditionCode) { + + uint32_t currentWeatherIcon = getConditionIcon(conditionCode); + + // ok, now load the new icon: + gdraw_command_image_destroy(Weather_currentWeatherIcon); + Weather_currentWeatherIcon = gdraw_command_image_create_with_resource(currentWeatherIcon); + + Weather_weatherInfo.currentIconResourceID = currentWeatherIcon; +} + +void Weather_setForecastCondition(int conditionCode) { + uint32_t forecastWeatherIcon = getConditionIcon(conditionCode); + + gdraw_command_image_destroy(Weather_forecastWeatherIcon); + Weather_forecastWeatherIcon = gdraw_command_image_create_with_resource(forecastWeatherIcon); + + Weather_weatherForecast.forecastIconResourceID = forecastWeatherIcon; +} + +void Weather_init() { + // if possible, load weather data from persistent storage + if (persist_exists(WEATHERINFO_PERSIST_KEY)) { + // printf("current key exists!"); + WeatherInfo w; + persist_read_data(WEATHERINFO_PERSIST_KEY, &w, sizeof(WeatherInfo)); + + Weather_weatherInfo = w; + + Weather_currentWeatherIcon = gdraw_command_image_create_with_resource(w.currentIconResourceID); + + } else { + + // printf("current key does not exist!"); + // otherwise, use null data + Weather_currentWeatherIcon = NULL; + Weather_weatherInfo.currentTemp = INT32_MIN; + } + + if (persist_exists(WEATHERFORECAST_PERSIST_KEY)) { + // printf("forecast key exists!"); + WeatherForecastInfo w; + persist_read_data(WEATHERFORECAST_PERSIST_KEY, &w, sizeof(WeatherForecastInfo)); + + Weather_weatherForecast = w; + + Weather_forecastWeatherIcon = gdraw_command_image_create_with_resource(w.forecastIconResourceID); + + } else { + // printf("forecast key does not exist!"); + + Weather_forecastWeatherIcon = NULL; + Weather_weatherForecast.highTemp = INT32_MIN; + Weather_weatherForecast.lowTemp = INT32_MIN; + } +} + +void Weather_saveData() { + // printf("saving data!"); + persist_write_data(WEATHERINFO_PERSIST_KEY, &Weather_weatherInfo, sizeof(WeatherInfo)); + persist_write_data(WEATHERFORECAST_PERSIST_KEY, &Weather_weatherForecast, sizeof(WeatherForecastInfo)); +} + +void Weather_deinit() { + // save weather data to persistent storage + Weather_saveData(); + + // free memory + gdraw_command_image_destroy(Weather_currentWeatherIcon); + gdraw_command_image_destroy(Weather_forecastWeatherIcon); +} diff --git a/pool/shard003/C/0066433_quorum.c b/pool/shard003/C/0066433_quorum.c new file mode 100644 index 0000000000000000000000000000000000000000..62e8ec619b4ce54f6509fcfa2f33cfc381f4fd5e --- /dev/null +++ b/pool/shard003/C/0066433_quorum.c @@ -0,0 +1,340 @@ +/* -*- mode: c; c-basic-offset: 8; -*- + * + * vim: noexpandtab sw=8 ts=8 sts=0: + * + * Copyright (C) 2005 Oracle. All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation; either + * version 2 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 021110-1307, USA. + */ + +/* This quorum hack is only here until we transition to some more rational + * approach that is driven from userspace. Honest. No foolin'. + * + * Imagine two nodes lose network connectivity to each other but they're still + * up and operating in every other way. Presumably a network timeout indicates + * that a node is broken and should be recovered. They can't both recover each + * other and both carry on without serialising their access to the file system. + * They need to decide who is authoritative. Now extend that problem to + * arbitrary groups of nodes losing connectivity between each other. + * + * So we declare that a node which has given up on connecting to a majority + * of nodes who are still heartbeating will fence itself. + * + * There are huge opportunities for races here. After we give up on a node's + * connection we need to wait long enough to give heartbeat an opportunity + * to declare the node as truly dead. We also need to be careful with the + * race between when we see a node start heartbeating and when we connect + * to it. + * + * So nodes that are in this transtion put a hold on the quorum decision + * with a counter. As they fall out of this transition they drop the count + * and if they're the last, they fire off the decision. + */ +#include +#include +#include + +#include "heartbeat.h" +#include "nodemanager.h" +#define MLOG_MASK_PREFIX ML_QUORUM +#include "masklog.h" +#include "quorum.h" + +static struct o2quo_state { + spinlock_t qs_lock; + struct work_struct qs_work; + int qs_pending; + int qs_heartbeating; + unsigned long qs_hb_bm[BITS_TO_LONGS(O2NM_MAX_NODES)]; + int qs_connected; + unsigned long qs_conn_bm[BITS_TO_LONGS(O2NM_MAX_NODES)]; + int qs_holds; + unsigned long qs_hold_bm[BITS_TO_LONGS(O2NM_MAX_NODES)]; +} o2quo_state; + +/* this is horribly heavy-handed. It should instead flip the file + * system RO and call some userspace script. */ +static void o2quo_fence_self(void) +{ + /* panic spins with interrupts enabled. with preempt + * threads can still schedule, etc, etc */ + o2hb_stop_all_regions(); + + switch (o2nm_single_cluster->cl_fence_method) { + case O2NM_FENCE_PANIC: + panic("*** ocfs2 is very sorry to be fencing this system by " + "panicing ***\n"); + break; + default: + WARN_ON(o2nm_single_cluster->cl_fence_method >= + O2NM_FENCE_METHODS); + case O2NM_FENCE_RESET: + printk(KERN_ERR "*** ocfs2 is very sorry to be fencing this " + "system by restarting ***\n"); + emergency_restart(); + break; + }; +} + +/* Indicate that a timeout occurred on a hearbeat region write. The + * other nodes in the cluster may consider us dead at that time so we + * want to "fence" ourselves so that we don't scribble on the disk + * after they think they've recovered us. This can't solve all + * problems related to writeout after recovery but this hack can at + * least close some of those gaps. When we have real fencing, this can + * go away as our node would be fenced externally before other nodes + * begin recovery. */ +void o2quo_disk_timeout(void) +{ + o2quo_fence_self(); +} + +static void o2quo_make_decision(struct work_struct *work) +{ + int quorum; + int lowest_hb, lowest_reachable = 0, fence = 0; + struct o2quo_state *qs = &o2quo_state; + + spin_lock(&qs->qs_lock); + + lowest_hb = find_first_bit(qs->qs_hb_bm, O2NM_MAX_NODES); + if (lowest_hb != O2NM_MAX_NODES) + lowest_reachable = test_bit(lowest_hb, qs->qs_conn_bm); + + mlog(0, "heartbeating: %d, connected: %d, " + "lowest: %d (%sreachable)\n", qs->qs_heartbeating, + qs->qs_connected, lowest_hb, lowest_reachable ? "" : "un"); + + if (!test_bit(o2nm_this_node(), qs->qs_hb_bm) || + qs->qs_heartbeating == 1) + goto out; + + if (qs->qs_heartbeating & 1) { + /* the odd numbered cluster case is straight forward -- + * if we can't talk to the majority we're hosed */ + quorum = (qs->qs_heartbeating + 1)/2; + if (qs->qs_connected < quorum) { + mlog(ML_ERROR, "fencing this node because it is " + "only connected to %u nodes and %u is needed " + "to make a quorum out of %u heartbeating nodes\n", + qs->qs_connected, quorum, + qs->qs_heartbeating); + fence = 1; + } + } else { + /* the even numbered cluster adds the possibility of each half + * of the cluster being able to talk amongst themselves.. in + * that case we're hosed if we can't talk to the group that has + * the lowest numbered node */ + quorum = qs->qs_heartbeating / 2; + if (qs->qs_connected < quorum) { + mlog(ML_ERROR, "fencing this node because it is " + "only connected to %u nodes and %u is needed " + "to make a quorum out of %u heartbeating nodes\n", + qs->qs_connected, quorum, + qs->qs_heartbeating); + fence = 1; + } + else if ((qs->qs_connected == quorum) && + !lowest_reachable) { + mlog(ML_ERROR, "fencing this node because it is " + "connected to a half-quorum of %u out of %u " + "nodes which doesn't include the lowest active " + "node %u\n", quorum, qs->qs_heartbeating, + lowest_hb); + fence = 1; + } + } + +out: + if (fence) { + spin_unlock(&qs->qs_lock); + o2quo_fence_self(); + } else { + mlog(ML_NOTICE, "not fencing this node, heartbeating: %d, " + "connected: %d, lowest: %d (%sreachable)\n", + qs->qs_heartbeating, qs->qs_connected, lowest_hb, + lowest_reachable ? "" : "un"); + spin_unlock(&qs->qs_lock); + + } + +} + +static void o2quo_set_hold(struct o2quo_state *qs, u8 node) +{ + assert_spin_locked(&qs->qs_lock); + + if (!test_and_set_bit(node, qs->qs_hold_bm)) { + qs->qs_holds++; + mlog_bug_on_msg(qs->qs_holds == O2NM_MAX_NODES, + "node %u\n", node); + mlog(0, "node %u, %d total\n", node, qs->qs_holds); + } +} + +static void o2quo_clear_hold(struct o2quo_state *qs, u8 node) +{ + assert_spin_locked(&qs->qs_lock); + + if (test_and_clear_bit(node, qs->qs_hold_bm)) { + mlog(0, "node %u, %d total\n", node, qs->qs_holds - 1); + if (--qs->qs_holds == 0) { + if (qs->qs_pending) { + qs->qs_pending = 0; + schedule_work(&qs->qs_work); + } + } + mlog_bug_on_msg(qs->qs_holds < 0, "node %u, holds %d\n", + node, qs->qs_holds); + } +} + +/* as a node comes up we delay the quorum decision until we know the fate of + * the connection. the hold will be droped in conn_up or hb_down. it might be + * perpetuated by con_err until hb_down. if we already have a conn, we might + * be dropping a hold that conn_up got. */ +void o2quo_hb_up(u8 node) +{ + struct o2quo_state *qs = &o2quo_state; + + spin_lock(&qs->qs_lock); + + qs->qs_heartbeating++; + mlog_bug_on_msg(qs->qs_heartbeating == O2NM_MAX_NODES, + "node %u\n", node); + mlog_bug_on_msg(test_bit(node, qs->qs_hb_bm), "node %u\n", node); + set_bit(node, qs->qs_hb_bm); + + mlog(0, "node %u, %d total\n", node, qs->qs_heartbeating); + + if (!test_bit(node, qs->qs_conn_bm)) + o2quo_set_hold(qs, node); + else + o2quo_clear_hold(qs, node); + + spin_unlock(&qs->qs_lock); +} + +/* hb going down releases any holds we might have had due to this node from + * conn_up, conn_err, or hb_up */ +void o2quo_hb_down(u8 node) +{ + struct o2quo_state *qs = &o2quo_state; + + spin_lock(&qs->qs_lock); + + qs->qs_heartbeating--; + mlog_bug_on_msg(qs->qs_heartbeating < 0, + "node %u, %d heartbeating\n", + node, qs->qs_heartbeating); + mlog_bug_on_msg(!test_bit(node, qs->qs_hb_bm), "node %u\n", node); + clear_bit(node, qs->qs_hb_bm); + + mlog(0, "node %u, %d total\n", node, qs->qs_heartbeating); + + o2quo_clear_hold(qs, node); + + spin_unlock(&qs->qs_lock); +} + +/* this tells us that we've decided that the node is still heartbeating + * even though we've lost it's conn. it must only be called after conn_err + * and indicates that we must now make a quorum decision in the future, + * though we might be doing so after waiting for holds to drain. Here + * we'll be dropping the hold from conn_err. */ +void o2quo_hb_still_up(u8 node) +{ + struct o2quo_state *qs = &o2quo_state; + + spin_lock(&qs->qs_lock); + + mlog(0, "node %u\n", node); + + qs->qs_pending = 1; + o2quo_clear_hold(qs, node); + + spin_unlock(&qs->qs_lock); +} + +/* This is analogous to hb_up. as a node's connection comes up we delay the + * quorum decision until we see it heartbeating. the hold will be droped in + * hb_up or hb_down. it might be perpetuated by con_err until hb_down. if + * it's already heartbeating we might be dropping a hold that conn_up got. + * */ +void o2quo_conn_up(u8 node) +{ + struct o2quo_state *qs = &o2quo_state; + + spin_lock(&qs->qs_lock); + + qs->qs_connected++; + mlog_bug_on_msg(qs->qs_connected == O2NM_MAX_NODES, + "node %u\n", node); + mlog_bug_on_msg(test_bit(node, qs->qs_conn_bm), "node %u\n", node); + set_bit(node, qs->qs_conn_bm); + + mlog(0, "node %u, %d total\n", node, qs->qs_connected); + + if (!test_bit(node, qs->qs_hb_bm)) + o2quo_set_hold(qs, node); + else + o2quo_clear_hold(qs, node); + + spin_unlock(&qs->qs_lock); +} + +/* we've decided that we won't ever be connecting to the node again. if it's + * still heartbeating we grab a hold that will delay decisions until either the + * node stops heartbeating from hb_down or the caller decides that the node is + * still up and calls still_up */ +void o2quo_conn_err(u8 node) +{ + struct o2quo_state *qs = &o2quo_state; + + spin_lock(&qs->qs_lock); + + if (test_bit(node, qs->qs_conn_bm)) { + qs->qs_connected--; + mlog_bug_on_msg(qs->qs_connected < 0, + "node %u, connected %d\n", + node, qs->qs_connected); + + clear_bit(node, qs->qs_conn_bm); + } + + mlog(0, "node %u, %d total\n", node, qs->qs_connected); + + if (test_bit(node, qs->qs_hb_bm)) + o2quo_set_hold(qs, node); + + spin_unlock(&qs->qs_lock); +} + +void o2quo_init(void) +{ + struct o2quo_state *qs = &o2quo_state; + + spin_lock_init(&qs->qs_lock); + INIT_WORK(&qs->qs_work, o2quo_make_decision); +} + +void o2quo_exit(void) +{ + struct o2quo_state *qs = &o2quo_state; + + flush_work(&qs->qs_work); +} diff --git a/pool/shard003/C/0066440_test_j2k_header.c b/pool/shard003/C/0066440_test_j2k_header.c new file mode 100644 index 0000000000000000000000000000000000000000..c7ab3334bb5996f11d8437c79d012bb201011e77 --- /dev/null +++ b/pool/shard003/C/0066440_test_j2k_header.c @@ -0,0 +1,98 @@ +/* ========================================================================= + * This file is part of NITRO + * ========================================================================= + * + * (C) Copyright 2004 - 2014, MDA Information Systems LLC + * + * NITRO 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 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, If not, + * see . + * + */ + +#include +#include + +int main(int argc, char **argv) +{ + int rc = 0; + int argIt; + uint32_t cmpIt, nComponents; + nrt_Error error; + j2k_Container *container = NULL; + j2k_Reader *reader = NULL; + char *fname = NULL; + + for (argIt = 1; argIt < argc; ++argIt) + { + if (!fname) + { + fname = argv[argIt]; + } + } + + if (!fname) + { + nrt_Error_init(&error, "Usage: [options] ", NRT_CTXT, + NRT_ERR_INVALID_OBJECT); + goto CATCH_ERROR; + } + + reader = j2k_Reader_open(fname, &error); + if (!reader) + goto CATCH_ERROR; + + container = j2k_Reader_getContainer(reader, &error); + if (!container) + goto CATCH_ERROR; + + printf("grid width:\t%d\n", j2k_Container_getGridWidth(container, &error)); + printf("grid height:\t%d\n", j2k_Container_getGridHeight(container, &error)); + printf("tile width:\t%d\n", j2k_Container_getTileWidth(container, &error)); + printf("tile height:\t%d\n", j2k_Container_getTileHeight(container, &error)); + printf("x tiles:\t%d\n", j2k_Container_getTilesX(container, &error)); + printf("y tiles:\t%d\n", j2k_Container_getTilesY(container, &error)); + printf("image type:\t%d\n", j2k_Container_getImageType(container, &error)); + + nComponents = j2k_Container_getNumComponents(container, &error); + printf("components:\t%d\n", nComponents); + + for(cmpIt = 0; cmpIt < nComponents; ++cmpIt) + { + j2k_Component* c = j2k_Container_getComponent(container, cmpIt, &error); + printf("===component %d===\n", (cmpIt + 1)); + printf("width:\t\t%d\n", j2k_Component_getWidth(c, &error)); + printf("height:\t\t%d\n", j2k_Component_getHeight(c, &error)); + printf("precision:\t%d\n", j2k_Component_getPrecision(c, &error)); + printf("x0:\t\t%d\n", j2k_Component_getOffsetX(c, &error)); + printf("y0:\t\t%d\n", j2k_Component_getOffsetY(c, &error)); + printf("x separation:\t%d\n", j2k_Component_getSeparationX(c, &error)); + printf("y separation:\t%d\n", j2k_Component_getSeparationY(c, &error)); + printf("signed:\t\t%d\n", j2k_Component_isSigned(c, &error)); + } + + goto CLEANUP; + + CATCH_ERROR: + { + nrt_Error_print(&error, stdout, "Exiting..."); + rc = 1; + } + CLEANUP: + { + if (reader) + j2k_Reader_destruct(&reader); + } + return rc; + +} diff --git a/pool/shard003/C/0066468_6-1.c b/pool/shard003/C/0066468_6-1.c new file mode 100644 index 0000000000000000000000000000000000000000..9f54d03551bc8391d51ebd3c9a5417df19c7f4cf --- /dev/null +++ b/pool/shard003/C/0066468_6-1.c @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2002-2003, Intel Corporation. All rights reserved. + * Created by: salwan.searty REMOVE-THIS AT intel DOT com + * This file is licensed under the GPL license. For the full content + * of this license, see the COPYING file at the top level of this + * source tree. + + This program tests the assertion that if the ss_flags member is not set to SS_DISABLE, + the stack shall be enabled, and the ss_sp and ss_size members specify the new address + and size of the stack. + + Steps: + - Set up a handler for signal SIGTOTEST and set the sa_flags member to SA_ONSTACK. + - Allocate memory for the alternate signal stack + - call sigaltstack() to define the alternate signal stack + - raise SIGTOTEST + - Inside the handler, use sigaltstack to examine/obtain the current alternate signal + stack and verify that the ss_flags member of the obtained alternate signal stack is SS_ONSTACK. +*/ + + +#include +#include +#include +#include "posixtest.h" + +#define SIGTOTEST SIGUSR1 + +static stack_t alternate_s; + +void handler() +{ + stack_t handler_s; + + if (sigaltstack(NULL, &handler_s) == -1) { + perror + ("Unexpected error while attempting to setup test pre-conditions"); + exit(PTS_UNRESOLVED); + } + + if (handler_s.ss_flags != SS_ONSTACK) { + printf + ("Test FAILED: The alternate stack's ss_flags member does not contain SS_ONSTACK even though the handler is executing on the alternate stack\n"); + exit(PTS_FAIL); + } +} + +int main(void) +{ + + struct sigaction act; + act.sa_flags = SA_ONSTACK; + act.sa_handler = handler; + sigemptyset(&act.sa_mask); + + if (sigaction(SIGTOTEST, &act, 0) == -1) { + perror + ("Unexpected error while attempting to setup test pre-conditions"); + return PTS_UNRESOLVED; + } + + if ((alternate_s.ss_sp = malloc(SIGSTKSZ)) == NULL) { + perror + ("Unexpected error while attempting to setup test pre-conditions"); + return PTS_UNRESOLVED; + } + + alternate_s.ss_flags = 0; + alternate_s.ss_size = SIGSTKSZ; + + if (sigaltstack(&alternate_s, NULL) == -1) { + perror + ("Unexpected error while attempting to setup test pre-conditions"); + return PTS_UNRESOLVED; + } + + if (raise(SIGTOTEST) == -1) { + perror + ("Unexpected error while attempting to setup test pre-conditions"); + return PTS_UNRESOLVED; + } + + printf("Test PASSED\n"); + return PTS_PASS; +} diff --git a/pool/shard003/C/0066469_spudecho.c b/pool/shard003/C/0066469_spudecho.c new file mode 100644 index 0000000000000000000000000000000000000000..0b2d76b9d23563883a9881db63caac4321a111b6 --- /dev/null +++ b/pool/shard003/C/0066469_spudecho.c @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2015 SPUDlib authors. See LICENSE file. + */ + +#include +#include +#include +#include +#include + +#include "spud.h" +#include "tube_manager.h" +#include "ls_htable.h" +#include "ls_log.h" +#include "ls_sockaddr.h" + +#define MYPORT 1402 /* the port users will be connecting to */ +#define MAXBUFLEN 2048 +#define MAX_LISTEN_SOCKETS 10 + +tube_manager* mgr = NULL; + +typedef struct _delay_write_t { + tube* t; + uint8_t* buf; + size_t length; +} delay_write_t; + +typedef struct _context_t { + size_t count; +} context_t; + +context_t* +new_context() +{ + context_t* c = ls_data_malloc( sizeof(context_t) ); + c->count = 0; + return c; +} + +void +teardown() +{ + ls_err err; + ls_log(LS_LOG_INFO, "Quitting..."); + if ( !tube_manager_stop(mgr, &err) ) + { + LS_LOG_ERR(err, "tube_manager_stop"); + } +} + +void +print_stats() +{ + ls_log( LS_LOG_INFO, "Tube count: %zu", tube_manager_size(mgr) ); +} + +static void +read_delay(ls_timer* tim) +{ + ls_err err; + delay_write_t* dw = ls_timer_get_context(tim); + context_t* c = tube_get_data(dw->t); + + if ( !tube_data(dw->t, dw->buf, dw->length, &err) ) + { + LS_LOG_ERR(err, "tube_data"); + } + ls_data_free(dw->buf); + ls_data_free(dw); + c->count++; +} + +static void +read_cb(ls_event_data* evt, + void* arg) +{ + tube_event_data* td = evt->data; + delay_write_t* dw; + ls_err err; + UNUSED_PARAM(arg); + + dw = ls_data_calloc( 1, sizeof(*dw) ); + if (!dw) + { + ls_log(LS_LOG_ERROR, "%s:%d ls_data_malloc", __FILE__, __LINE__); + return; + } + dw->t = td->t; + if (td->cbor) + { + const cn_cbor* cp = cn_cbor_mapget_int(td->cbor, 0); + if (cp) + { + dw->length = cp->length; + dw->buf = ls_data_malloc(cp->length); + if (!dw->buf) + { + ls_log(LS_LOG_ERROR, "ls_data_malloc"); + ls_data_free(dw); + return; + } + memcpy(dw->buf, cp->v.str, dw->length); + ls_log(LS_LOG_VERBOSE, "Received %*s", (int)dw->length, dw->buf); + } + } + if ( !tube_manager_schedule_ms(mgr, 10, read_delay, dw, NULL, &err) ) + { + LS_LOG_ERR(err, "tube_manager_schedule_ms"); + } +} + +static void +close_cb(ls_event_data* evt, + void* arg) +{ + UNUSED_PARAM(arg); + tube_event_data* td = evt->data; + context_t* c = tube_get_data(td->t); + char idStr[SPUD_ID_STRING_SIZE + 1]; + + ls_log(LS_LOG_VERBOSE, + "Spud ID: %s CLOSED: %zd data packets", + tube_id_to_string( td->t, idStr, sizeof(idStr) ), + c->count); +} + +static void +add_cb(ls_event_data* evt, + void* arg) +{ + tube* t = evt->data; + UNUSED_PARAM(arg); + tube_set_data( t, new_context() ); +} + +static void +remove_cb(ls_event_data* evt, + void* arg) +{ + tube* t = evt->data; + context_t* c = tube_get_data(t); + UNUSED_PARAM(arg); + ls_data_free(c); +} + +int +main(int argc, + char** argv) +{ + ls_err err; + + if ( (argc > 1) && !strcmp(argv[1], "-v") ) + { + ls_log_set_level(LS_LOG_VERBOSE); + } + + if ( !tube_manager_create(0, &mgr, &err) ) + { + LS_LOG_ERR(err, "tube_manager_create"); + return 1; + } + + if ( !tube_manager_signal(mgr, SIGUSR1, print_stats, &err) ) + { + LS_LOG_ERR(err, "tube_manager_signal"); + return 1; + } + + if ( !tube_manager_socket(mgr, MYPORT, &err) ) + { + LS_LOG_ERR(err, "tube_manager_socket"); + return 1; + } + + if ( !tube_manager_bind_event(mgr, EV_DATA_NAME, read_cb, &err) || + !tube_manager_bind_event(mgr, EV_CLOSE_NAME, close_cb, &err) || + !tube_manager_bind_event(mgr, EV_ADD_NAME, add_cb, &err) || + !tube_manager_bind_event(mgr, EV_REMOVE_NAME, remove_cb, &err) ) + { + LS_LOG_ERR(err, "tube_manager_bind_event"); + return 1; + } + + ls_log(LS_LOG_INFO, "Listening on port %d", MYPORT); + if ( !tube_manager_loop(mgr, &err) ) + { + LS_LOG_ERR(err, "tube_manager_loop"); + return 1; + } + return 0; +} diff --git a/pool/shard003/C/0066473_MOREDETOUR0922.c b/pool/shard003/C/0066473_MOREDETOUR0922.c new file mode 100644 index 0000000000000000000000000000000000000000..55fb36c5cd6ee5dc60696ac603aa34263073cac8 --- /dev/null +++ b/pool/shard003/C/0066473_MOREDETOUR0922.c @@ -0,0 +1,95 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[2]; +atomic_int atom_0_r5_2; +atomic_int atom_1_r4_0; +atomic_int atom_2_r1_2; +atomic_int atom_3_r3_2; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 3, memory_order_seq_cst); + + atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); + + int v2_r5 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v22 = (v2_r5 == 2); + atomic_store_explicit(&atom_0_r5_2, v22, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + atomic_store_explicit(&vars[1], 2, memory_order_seq_cst); + atomic_store_explicit(&vars[1], 4, memory_order_seq_cst); + int v4_r4 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); + int v23 = (v4_r4 == 0); + atomic_store_explicit(&atom_1_r4_0, v23, memory_order_seq_cst); + return NULL; +} + +void *t2(void *arg){ +label_3:; + int v6_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + atomic_store_explicit(&vars[1], 3, memory_order_seq_cst); + int v24 = (v6_r1 == 2); + atomic_store_explicit(&atom_2_r1_2, v24, memory_order_seq_cst); + return NULL; +} + +void *t3(void *arg){ +label_4:; + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + + int v8_r3 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v25 = (v8_r3 == 2); + atomic_store_explicit(&atom_3_r3_2, v25, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + pthread_t thr2; + pthread_t thr3; + + atomic_init(&vars[1], 0); + atomic_init(&vars[0], 0); + atomic_init(&atom_0_r5_2, 0); + atomic_init(&atom_1_r4_0, 0); + atomic_init(&atom_2_r1_2, 0); + atomic_init(&atom_3_r3_2, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + pthread_create(&thr2, NULL, t2, NULL); + pthread_create(&thr3, NULL, t3, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + pthread_join(thr2, NULL); + pthread_join(thr3, NULL); + + int v9 = atomic_load_explicit(&atom_0_r5_2, memory_order_seq_cst); + int v10 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v11 = (v10 == 3); + int v12 = atomic_load_explicit(&atom_1_r4_0, memory_order_seq_cst); + int v13 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v14 = (v13 == 4); + int v15 = atomic_load_explicit(&atom_2_r1_2, memory_order_seq_cst); + int v16 = atomic_load_explicit(&atom_3_r3_2, memory_order_seq_cst); + int v17_conj = v15 & v16; + int v18_conj = v14 & v17_conj; + int v19_conj = v12 & v18_conj; + int v20_conj = v11 & v19_conj; + int v21_conj = v9 & v20_conj; + if (v21_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard003/C/0066494_eeprom.c b/pool/shard003/C/0066494_eeprom.c new file mode 100644 index 0000000000000000000000000000000000000000..2fdcb5a8ac3d010cc82da6914a16bc0e2875fa55 --- /dev/null +++ b/pool/shard003/C/0066494_eeprom.c @@ -0,0 +1,261 @@ +/* $NetBSD: eeprom.c,v 1.18 1998/02/05 04:56:36 gwr Exp $ */ + +/*- + * Copyright (c) 1996 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Gordon W. Ross. + * + * 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 the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. + */ + +/* + * Access functions for the EEPROM (Electrically Eraseable PROM) + * The main reason for the existence of this module is to + * handle the painful task of updating the EEPROM contents. + * After a write, it must not be touched for 10 milliseconds. + * (See the Sun-3 Architecture Manual sec. 5.9) + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#define HZ 100 /* XXX */ + +#ifndef EEPROM_SIZE +#define EEPROM_SIZE 0x800 +#endif + +struct eeprom *eeprom_copy; /* soft copy. */ + +static int ee_update(int off, int cnt); + +static char *eeprom_va; /* mapping to actual device */ +static int ee_size; /* size of usable part. */ + +static int ee_busy, ee_want; /* serialization */ + +static int eeprom_match __P((struct device *, struct cfdata *, void *)); +static void eeprom_attach __P((struct device *, struct device *, void *)); + +struct cfattach eeprom_ca = { + sizeof(struct device), eeprom_match, eeprom_attach +}; + +static int +eeprom_match(parent, cf, args) + struct device *parent; + struct cfdata *cf; + void *args; +{ + struct confargs *ca = args; + + /* This driver only supports one unit. */ + if (cf->cf_unit != 0) + return (0); + + if (bus_peek(ca->ca_bustype, ca->ca_paddr, 1) == -1) + return (0); + + return (1); +} + +static void +eeprom_attach(parent, self, args) + struct device *parent; + struct device *self; + void *args; +{ + struct confargs *ca = args; + char *src, *dst, *lim; + + printf("\n"); +#ifdef DIAGNOSTIC + if (sizeof(struct eeprom) != EEPROM_SIZE) + panic("eeprom struct wrong"); +#endif + + ee_size = EEPROM_SIZE; + eeprom_va = bus_mapin(ca->ca_bustype, ca->ca_paddr, ee_size); + if (!eeprom_va) + panic("eeprom_attach"); + + /* Keep a "soft" copy of the EEPROM to make access simpler. */ + eeprom_copy = malloc(ee_size, M_DEVBUF, M_NOWAIT); + if (eeprom_copy == 0) + panic("eeprom_attach: malloc eeprom_copy"); + + /* + * On the 3/80, do not touch the last 40 bytes! + * Writes there are ignored, reads show zero. + * Reduce ee_size and clear the last part of the + * soft copy. Note: ee_update obeys ee_size. + */ + if (cpu_machine_id == SUN3X_MACH_80) + ee_size -= 40; + + /* Do only byte access in the EEPROM. */ + src = eeprom_va; + dst = (char*) eeprom_copy; + lim = dst + ee_size; + + do *dst++ = *src++; + while (dst < lim); + + if (ee_size < EEPROM_SIZE) { + /* Clear out the last part. */ + bzero(dst, (EEPROM_SIZE - ee_size)); + } +} + + +/* Take the lock. */ +static int +ee_take __P((void)) +{ + int error = 0; + while (ee_busy) { + ee_want = 1; + error = tsleep(&ee_busy, PZERO | PCATCH, "eeprom", 0); + ee_want = 0; + if (error) /* interrupted */ + return error; + } + ee_busy = 1; + return error; +} + +/* Give the lock. */ +static void +ee_give __P((void)) +{ + ee_busy = 0; + if (ee_want) { + ee_want = 0; + wakeup(&ee_busy); + } +} + +/* + * This is called by mem.c to handle /dev/eeprom + */ +int +eeprom_uio(struct uio *uio) +{ + int cnt, error; + int off; /* NOT off_t */ + caddr_t va; + + if (eeprom_copy == NULL) + return (ENXIO); + + off = uio->uio_offset; + if ((off < 0) || (off > EEPROM_SIZE)) + return (EFAULT); + + cnt = min(uio->uio_resid, (EEPROM_SIZE - off)); + if (cnt == 0) + return (0); /* EOF */ + + va = ((char*)eeprom_copy) + off; + error = uiomove(va, (int)cnt, uio); + + /* If we wrote the rambuf, update the H/W. */ + if (!error && (uio->uio_rw != UIO_READ)) { + error = ee_take(); + if (!error) + error = ee_update(off, cnt); + ee_give(); + } + + return (error); +} + +/* + * Update the EEPROM from the soft copy. + * Other than the attach function, this is + * the ONLY place we touch the EEPROM H/W. + */ +static int +ee_update(int off, int cnt) +{ + volatile char *ep; + char *bp; + int errcnt; + + if (eeprom_va == NULL) + return (ENXIO); + + /* + * This check is NOT redundant with the one in + * eeprom_uio above if we are on a 3/80 where + * ee_size < EEPROM_SIZE + */ + if (cnt > (ee_size - off)) + cnt = (ee_size - off); + + bp = ((char*)eeprom_copy) + off; + ep = eeprom_va + off; + errcnt = 0; + + while (cnt > 0) { + /* + * DO NOT WRITE IT UNLESS WE HAVE TO because the + * EEPROM has a limited number of write cycles. + * After some number of writes it just fails! + */ + if (*ep != *bp) { + *ep = *bp; + /* + * We have written the EEPROM, so now we must + * sleep for at least 10 milliseconds while + * holding the lock to prevent all access to + * the EEPROM while it recovers. + */ + (void)tsleep(eeprom_va, PZERO-1, "eeprom", HZ/50); + } + /* Make sure the write worked. */ + if (*ep != *bp) + errcnt++; + ep++; + bp++; + cnt--; + } + return (errcnt ? EIO : 0); +} diff --git a/pool/shard003/C/0066514_sum.c b/pool/shard003/C/0066514_sum.c new file mode 100644 index 0000000000000000000000000000000000000000..2edd92036d48a1f8284bceec95b81951d5b5ecd7 --- /dev/null +++ b/pool/shard003/C/0066514_sum.c @@ -0,0 +1,161 @@ +/* vi: set sw=4 ts=4: */ +/* + * sum -- checksum and count the blocks in a file + * Like BSD sum or SysV sum -r, except like SysV sum if -s option is given. + * + * Copyright (C) 86, 89, 91, 1995-2002, 2004 Free Software Foundation, Inc. + * Copyright (C) 2005 by Erik Andersen + * Copyright (C) 2005 by Mike Frysinger + * + * Written by Kayvan Aghaiepour and David MacKenzie + * Taken from coreutils and turned into a busybox applet by Mike Frysinger + * + * Licensed under the GPL v2, see the file LICENSE in this tarball. + */ + +#include +#include +#include +#include +#include + +#include "busybox.h" + +/* 1 if any of the files read were the standard input */ +static int have_read_stdin; + +/* make a little more readable and avoid using strcmp for just 2 bytes */ +#define IS_STDIN(s) (s[0] == '-' && s[1] == '\0') + +/* Calculate and print the rotated checksum and the size in 1K blocks + of file FILE, or of the standard input if FILE is "-". + If PRINT_NAME is >1, print FILE next to the checksum and size. + The checksum varies depending on sizeof (int). + Return 1 if successful. */ +static int bsd_sum_file(const char *file, int print_name) +{ + FILE *fp; + int checksum = 0; /* The checksum mod 2^16. */ + uintmax_t total_bytes = 0; /* The number of bytes. */ + int ch; /* Each character read. */ + + if (IS_STDIN(file)) { + fp = stdin; + have_read_stdin = 1; + } else { + fp = bb_wfopen(file, "r"); + if (fp == NULL) + return 0; + } + + while ((ch = getc(fp)) != EOF) { + ++total_bytes; + checksum = (checksum >> 1) + ((checksum & 1) << 15); + checksum += ch; + checksum &= 0xffff; /* Keep it within bounds. */ + } + + if (ferror(fp)) { + bb_perror_msg(file); + bb_fclose_nonstdin(fp); + return 0; + } + + if (bb_fclose_nonstdin(fp) == EOF) { + bb_perror_msg(file); + return 0; + } + + printf("%05d %5ju ", checksum, (total_bytes+1023)/1024); + if (print_name > 1) + puts(file); + else + printf("\n"); + + return 1; +} + +/* Calculate and print the checksum and the size in 512-byte blocks + of file FILE, or of the standard input if FILE is "-". + If PRINT_NAME is >0, print FILE next to the checksum and size. + Return 1 if successful. */ +#define MY_BUF_SIZE 8192 +static int sysv_sum_file(const char *file, int print_name) +{ + RESERVE_CONFIG_BUFFER(buf, MY_BUF_SIZE); + int fd; + uintmax_t total_bytes = 0; + + /* The sum of all the input bytes, modulo (UINT_MAX + 1). */ + unsigned int s = 0; + + if (IS_STDIN(file)) { + fd = 0; + have_read_stdin = 1; + } else { + fd = open(file, O_RDONLY); + if (fd == -1) + goto release_and_ret; + } + + while (1) { + size_t bytes_read = safe_read(fd, buf, MY_BUF_SIZE); + + if (bytes_read == 0) + break; + + if (bytes_read == -1) { +release_and_ret: + bb_perror_msg(file); + RELEASE_CONFIG_BUFFER(buf); + if (!IS_STDIN(file)) + close(fd); + return 0; + } + + total_bytes += bytes_read; + while (bytes_read--) + s += buf[bytes_read]; + } + + if (!IS_STDIN(file) && close(fd) == -1) + goto release_and_ret; + else + RELEASE_CONFIG_BUFFER(buf); + + { + int r = (s & 0xffff) + ((s & 0xffffffff) >> 16); + s = (r & 0xffff) + (r >> 16); + + printf("%d %ju ", s, (total_bytes+511)/512); + } + puts(print_name ? file : ""); + + return 1; +} + +int sum_main(int argc, char **argv) +{ + int flags; + int ok; + int (*sum_func)(const char *, int) = bsd_sum_file; + + /* give the bsd func priority over sysv func */ + flags = bb_getopt_ulflags(argc, argv, "sr"); + if (flags & 1) + sum_func = sysv_sum_file; + if (flags & 2) + sum_func = bsd_sum_file; + + have_read_stdin = 0; + if ((argc - optind) == 0) + ok = sum_func("-", 0); + else + for (ok = 1; optind < argc; optind++) + ok &= sum_func(argv[optind], 1); + + if (have_read_stdin && fclose(stdin) == EOF) + bb_perror_msg_and_die("-"); + + exit(ok ? EXIT_SUCCESS : EXIT_FAILURE); +} diff --git a/pool/shard003/C/0066549_utaddress.c b/pool/shard003/C/0066549_utaddress.c new file mode 100644 index 0000000000000000000000000000000000000000..e0a2e2779c2ed8f8877310e07e6379e8efad0faf --- /dev/null +++ b/pool/shard003/C/0066549_utaddress.c @@ -0,0 +1,294 @@ +/****************************************************************************** + * + * Module Name: utaddress - op_region address range check + * + *****************************************************************************/ + +/* + * Copyright (C) 2000 - 2013, Intel Corp. + * 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, + * without modification. + * 2. Redistributions in binary form must reproduce at minimum a disclaimer + * substantially similar to the "NO WARRANTY" disclaimer below + * ("Disclaimer") and any redistribution must be conditioned upon + * including a substantially similar Disclaimer requirement for further + * binary redistribution. + * 3. Neither the names of the above-listed copyright holders nor the names + * of any contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * Alternatively, this software may be distributed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + * NO WARRANTY + * 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 MERCHANTIBILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. + */ + +#include +#include "accommon.h" +#include "acnamesp.h" + +#define _COMPONENT ACPI_UTILITIES +ACPI_MODULE_NAME("utaddress") + +/******************************************************************************* + * + * FUNCTION: acpi_ut_add_address_range + * + * PARAMETERS: space_id - Address space ID + * address - op_region start address + * length - op_region length + * region_node - op_region namespace node + * + * RETURN: Status + * + * DESCRIPTION: Add the Operation Region address range to the global list. + * The only supported Space IDs are Memory and I/O. Called when + * the op_region address/length operands are fully evaluated. + * + * MUTEX: Locks the namespace + * + * NOTE: Because this interface is only called when an op_region argument + * list is evaluated, there cannot be any duplicate region_nodes. + * Duplicate Address/Length values are allowed, however, so that multiple + * address conflicts can be detected. + * + ******************************************************************************/ +acpi_status +acpi_ut_add_address_range(acpi_adr_space_type space_id, + acpi_physical_address address, + u32 length, struct acpi_namespace_node *region_node) +{ + struct acpi_address_range *range_info; + acpi_status status; + + ACPI_FUNCTION_TRACE(ut_add_address_range); + + if ((space_id != ACPI_ADR_SPACE_SYSTEM_MEMORY) && + (space_id != ACPI_ADR_SPACE_SYSTEM_IO)) { + return_ACPI_STATUS(AE_OK); + } + + /* Allocate/init a new info block, add it to the appropriate list */ + + range_info = ACPI_ALLOCATE(sizeof(struct acpi_address_range)); + if (!range_info) { + return_ACPI_STATUS(AE_NO_MEMORY); + } + + range_info->start_address = address; + range_info->end_address = (address + length - 1); + range_info->region_node = region_node; + + status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE); + if (ACPI_FAILURE(status)) { + ACPI_FREE(range_info); + return_ACPI_STATUS(status); + } + + range_info->next = acpi_gbl_address_range_list[space_id]; + acpi_gbl_address_range_list[space_id] = range_info; + + ACPI_DEBUG_PRINT((ACPI_DB_NAMES, + "\nAdded [%4.4s] address range: 0x%p-0x%p\n", + acpi_ut_get_node_name(range_info->region_node), + ACPI_CAST_PTR(void, address), + ACPI_CAST_PTR(void, range_info->end_address))); + + (void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE); + return_ACPI_STATUS(AE_OK); +} + +/******************************************************************************* + * + * FUNCTION: acpi_ut_remove_address_range + * + * PARAMETERS: space_id - Address space ID + * region_node - op_region namespace node + * + * RETURN: None + * + * DESCRIPTION: Remove the Operation Region from the global list. The only + * supported Space IDs are Memory and I/O. Called when an + * op_region is deleted. + * + * MUTEX: Assumes the namespace is locked + * + ******************************************************************************/ + +void +acpi_ut_remove_address_range(acpi_adr_space_type space_id, + struct acpi_namespace_node *region_node) +{ + struct acpi_address_range *range_info; + struct acpi_address_range *prev; + + ACPI_FUNCTION_TRACE(ut_remove_address_range); + + if ((space_id != ACPI_ADR_SPACE_SYSTEM_MEMORY) && + (space_id != ACPI_ADR_SPACE_SYSTEM_IO)) { + return_VOID; + } + + /* Get the appropriate list head and check the list */ + + range_info = prev = acpi_gbl_address_range_list[space_id]; + while (range_info) { + if (range_info->region_node == region_node) { + if (range_info == prev) { /* Found at list head */ + acpi_gbl_address_range_list[space_id] = + range_info->next; + } else { + prev->next = range_info->next; + } + + ACPI_DEBUG_PRINT((ACPI_DB_NAMES, + "\nRemoved [%4.4s] address range: 0x%p-0x%p\n", + acpi_ut_get_node_name(range_info-> + region_node), + ACPI_CAST_PTR(void, + range_info-> + start_address), + ACPI_CAST_PTR(void, + range_info-> + end_address))); + + ACPI_FREE(range_info); + return_VOID; + } + + prev = range_info; + range_info = range_info->next; + } + + return_VOID; +} + +/******************************************************************************* + * + * FUNCTION: acpi_ut_check_address_range + * + * PARAMETERS: space_id - Address space ID + * address - Start address + * length - Length of address range + * warn - TRUE if warning on overlap desired + * + * RETURN: Count of the number of conflicts detected. Zero is always + * returned for Space IDs other than Memory or I/O. + * + * DESCRIPTION: Check if the input address range overlaps any of the + * ASL operation region address ranges. The only supported + * Space IDs are Memory and I/O. + * + * MUTEX: Assumes the namespace is locked. + * + ******************************************************************************/ + +u32 +acpi_ut_check_address_range(acpi_adr_space_type space_id, + acpi_physical_address address, u32 length, u8 warn) +{ + struct acpi_address_range *range_info; + acpi_physical_address end_address; + char *pathname; + u32 overlap_count = 0; + + ACPI_FUNCTION_TRACE(ut_check_address_range); + + if ((space_id != ACPI_ADR_SPACE_SYSTEM_MEMORY) && + (space_id != ACPI_ADR_SPACE_SYSTEM_IO)) { + return_UINT32(0); + } + + range_info = acpi_gbl_address_range_list[space_id]; + end_address = address + length - 1; + + /* Check entire list for all possible conflicts */ + + while (range_info) { + /* + * Check if the requested Address/Length overlaps this address_range. + * Four cases to consider: + * + * 1) Input address/length is contained completely in the address range + * 2) Input address/length overlaps range at the range start + * 3) Input address/length overlaps range at the range end + * 4) Input address/length completely encompasses the range + */ + if ((address <= range_info->end_address) && + (end_address >= range_info->start_address)) { + + /* Found an address range overlap */ + + overlap_count++; + if (warn) { /* Optional warning message */ + pathname = + acpi_ns_get_external_pathname(range_info-> + region_node); + + ACPI_WARNING((AE_INFO, + "0x%p-0x%p %s conflicts with Region %s %d", + ACPI_CAST_PTR(void, address), + ACPI_CAST_PTR(void, end_address), + acpi_ut_get_region_name(space_id), + pathname, overlap_count)); + ACPI_FREE(pathname); + } + } + + range_info = range_info->next; + } + + return_UINT32(overlap_count); +} + +/******************************************************************************* + * + * FUNCTION: acpi_ut_delete_address_lists + * + * PARAMETERS: None + * + * RETURN: None + * + * DESCRIPTION: Delete all global address range lists (called during + * subsystem shutdown). + * + ******************************************************************************/ + +void acpi_ut_delete_address_lists(void) +{ + struct acpi_address_range *next; + struct acpi_address_range *range_info; + int i; + + /* Delete all elements in all address range lists */ + + for (i = 0; i < ACPI_ADDRESS_RANGE_MAX; i++) { + next = acpi_gbl_address_range_list[i]; + + while (next) { + range_info = next; + next = range_info->next; + ACPI_FREE(range_info); + } + + acpi_gbl_address_range_list[i] = NULL; + } +} diff --git a/pool/shard003/C/0066554_test_write_view_local.c b/pool/shard003/C/0066554_test_write_view_local.c new file mode 100644 index 0000000000000000000000000000000000000000..ae0698ee723cf106ea06a1cf55d945cb5f2de859 --- /dev/null +++ b/pool/shard003/C/0066554_test_write_view_local.c @@ -0,0 +1,86 @@ +/********************************************* + UPC-IO Reference Implementation + Internal test cases + + HPCL, The George Wasnington University + Author: Yiyi Yao + E-mail: yyy@gwu.edu +*********************************************/ +#include +#include +#include +#include "upc_io.h" + +int main() +{ + upcio_file_t *fd; + upc_off_t ret_size; + upc_flag_t sync = 0; + void *buffer; + uint32_t i, count, block_size; + char fname[] = "/mnt/plfs/upcio.test"; + upc_file_view *lfile_view; + + if(!MYTHREAD) { + printf("upcio test: test fwrite_view_local with %d Threads\n", THREADS); + } + + count = 1; + block_size = 1; + if (MYTHREAD % 2 == 0) { + buffer = (int *)malloc(sizeof(int) * count * block_size); + ((int *) buffer)[0] = 2; + } else { + buffer = (float *)malloc(sizeof(float) * count * block_size); + ((float *) buffer)[0] = 5.0f; + } + + lfile_view = malloc(sizeof(upc_file_view)); + lfile_view->count = THREADS; + lfile_view->elem_type = UPC_INT; + lfile_view->block_lengths = malloc(THREADS * sizeof(uint32_t)); + lfile_view->block_displacements = malloc(THREADS * sizeof(uint32_t)); + lfile_view->types = malloc(THREADS * sizeof(uint32_t)); + for (i = 0; i < THREADS; i++) { + lfile_view->block_lengths[i] = block_size; + } + + lfile_view->block_displacements[0] = 0; + lfile_view->block_displacements[1] = 1; + lfile_view->block_displacements[2] = 3; + lfile_view->block_displacements[3] = 4; + for (i = 0; i < THREADS; i++) { + if (i % 2 == 0) { + lfile_view->types[i] = UPC_INT; + } else { + lfile_view->types[i] = UPC_FLOAT; + } + } + + upc_barrier; + fd=upc_all_fopen_view( fname, UPC_INDIVIDUAL_FP|UPC_WRONLY|UPC_CREATE, 0666, &lfile_view, 0); + if(fd==NULL) + { + printf("TH%2d: File open Error\n",MYTHREAD); + upc_global_exit(-1); + } + + upc_barrier; + ret_size = upc_all_fwrite_view_local(fd, (void *)buffer, count, sync, lfile_view); + upc_barrier; + + if( ret_size == -1 ) + printf("upcio test: fwrite_local error on TH%2d\n",MYTHREAD); + + upc_barrier; + upc_all_fsync(fd); + if(upc_all_fclose_view(fd, lfile_view)!=0) + { + printf("TH%2d: File close Error\n",MYTHREAD); + upc_global_exit(-1); + } + + free((void *)buffer); + return 0; +} + diff --git a/pool/shard003/C/0066567_Debug.c b/pool/shard003/C/0066567_Debug.c new file mode 100644 index 0000000000000000000000000000000000000000..89c7b1393713d92121897f05d9cc4349a8458db8 --- /dev/null +++ b/pool/shard003/C/0066567_Debug.c @@ -0,0 +1,121 @@ +/* ========================================================================= + * This file is part of NITRO + * ========================================================================= + * + * (C) Copyright 2004 - 2014, MDA Information Systems LLC + * + * NITRO 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 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, If not, + * see . + * + */ + +#include "nrt/Debug.h" + +#ifdef NRT_DEBUG + +#ifndef WIN32 +# include +# include +#endif + +NRTPROT(void *) nrt_Debug_malloc(const char *file, int line, size_t sz) +{ + /* The pointer to allocate */ + void *p; + FILE *f; + char name[512]; + +#ifndef WIN32 + NRT_SNPRINTF(name, 512, "%s.%d", NRT_MEM_LOG, getpid()); +#else + /* This can easily be modified to use GetCurrentProcessId() */ + strcpy(name, NRT_MEM_LOG); +#endif + + f = fopen(name, "a"); + assert(f); + + fprintf(f, "REQUEST: malloc\t[%d]\n", sz); + + p = malloc(sz); + fprintf(f, "\tMALLOC\t%p\t%d\t%s\t%d\n", p, sz, file, line); + + fclose(f); + return p; +} + +NRTPROT(void *) nrt_Debug_realloc(const char *file, int line, void *ptr, + size_t sz) +{ + void *p; + char name[512]; + FILE *f; + +#ifndef WIN32 + NRT_SNPRINTF(name, 512, "%s.%d", NRT_MEM_LOG, getpid()); +#else + /* This can easily be modified to use GetCurrentProcessId() */ + strcpy(name, NRT_MEM_LOG); +#endif + + f = fopen(name, "a"); + assert(f); + + fprintf(f, "REQUEST: realloc\t[%p]\t[%d]\n", ptr, sz); + p = realloc(ptr, sz); + fprintf(f, "\tREALLOC\t%p\t%p\t%d\t%s\t%d\n", p, ptr, sz, file, line); + + fclose(f); + return p; +} + +NRTPROT(void) nrt_Debug_free(const char *file, int line, void *ptr) +{ + FILE *f; + char name[512]; + +#ifndef WIN32 + NRT_SNPRINTF(name, 512, "%s.%d", NRT_MEM_LOG, getpid()); +#else + /* This can easily be modified to use GetCurrentProcessId() */ + strcpy(name, NRT_MEM_LOG); +#endif + + f = fopen(name, "a"); + assert(f); + + fprintf(f, "REQUEST: free\t[%p]\n", ptr); + + free(ptr); + + fprintf(f, "\tFREE\t%s\t%d\n", file, line); + + fclose(f); + +} +#endif + +NRTPROT(void) nrt_Debug_flogf(FILE * file, const char *format, ...) +{ +#if defined(NRT_DEBUG) + va_list args; + va_start(args, format); + vfprintf(file, format, args); + va_end(args); +#else + /* Silence compiler warnings about unused variables */ + (void)file; + (void)format; +#endif +} diff --git a/pool/shard003/C/0066568_getrusage.c b/pool/shard003/C/0066568_getrusage.c new file mode 100644 index 0000000000000000000000000000000000000000..7ff12fe12a8dfcf379ce100a6ded2acd94e53409 --- /dev/null +++ b/pool/shard003/C/0066568_getrusage.c @@ -0,0 +1,30 @@ +#include +#include + +// Temporary fix until +// https://github.com/CraneStation/wasi-sysroot/pull/24/ +// is available in wasi-sdk package +extern int getrusage(int who, struct rusage *usage); + +int main() +{ + struct rusage ru1; + getrusage(RUSAGE_SELF, &ru1); + + for (int i = 0; i < 1000; i++) { + } + + struct rusage ru2; + getrusage(RUSAGE_SELF, &ru2); + + // assert that some time has passed + long long s1 = ru1.ru_utime.tv_sec; + long long us1 = ru1.ru_utime.tv_usec; + long long s2 = ru2.ru_utime.tv_sec; + long long us2 = ru2.ru_utime.tv_usec; + assert(s1 <= s2); + if (s1 == s2) { + // strictly less than, so the timestamps can't be equal + assert(us1 < us2); + } +} diff --git a/pool/shard003/C/0066569_pios_sys.c b/pool/shard003/C/0066569_pios_sys.c new file mode 100644 index 0000000000000000000000000000000000000000..a63b5b29309c0038d15b6402933490dffa380a6f --- /dev/null +++ b/pool/shard003/C/0066569_pios_sys.c @@ -0,0 +1,179 @@ +/** + ****************************************************************************** + * @addtogroup PIOS PIOS Core hardware abstraction layer + * @{ + * @addtogroup PIOS_SYS System Functions + * @brief PIOS System Initialization code + * @{ + * + * @file pios_sys.c + * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. + * Parts by Thorsten Klose (tk@midibox.org) (tk@midibox.org) + * @brief Sets up basic STM32 system hardware, functions are called from Main. + * @see The GNU Public License (GPL) Version 3 + * + *****************************************************************************/ +/* + * 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 + */ + +/* Project Includes */ +#if !defined(_GNU_SOURCE) +#define _GNU_SOURCE +#endif /* !defined(_GNU_SOURCE) */ + +#include "pios.h" + +#if defined(PIOS_INCLUDE_SYS) + +static bool debug_fpe=false; + +static void Usage(char *cmdName) { + printf( "usage: %s [-f]\n" + "\n" + "\t-f\tEnables floating point exception trapping mode\n", + cmdName); + + exit(1); +} + +void PIOS_SYS_Args(int argc, char *argv[]) { + int opt; + + while ((opt = getopt(argc, argv, "f")) != -1) { + switch (opt) { + case 'f': + debug_fpe=true; + break; + default: + Usage(argv[0]); + break; + } + } + + if (optind < argc) { + Usage(argv[0]); + } +} + +/** +* Initialises all system peripherals +*/ +#include /* assert */ +#include /* printf */ +#include /* sigaction */ +#include /* PE_* */ +static void sigint_handler(int signum, siginfo_t *siginfo, void *ucontext) +{ + printf("\nSIGINT received. Shutting down\n"); + exit(0); +} + +static void sigfpe_handler(int signum, siginfo_t *siginfo, void *ucontext) +{ + printf("\nSIGFPE received. OMG! Math Bug! Run again with gdb to find your mistake.\n"); + exit(0); +} + +void PIOS_SYS_Init(void) +{ + struct sigaction sa_int = { + .sa_sigaction = sigint_handler, + .sa_flags = SA_SIGINFO, + }; + + int rc = sigaction(SIGINT, &sa_int, NULL); + assert(rc == 0); + + if (debug_fpe) { + struct sigaction sa_fpe = { + .sa_sigaction = sigfpe_handler, + .sa_flags = SA_SIGINFO, + }; + + rc = sigaction(SIGFPE, &sa_fpe, NULL); + assert(rc == 0); + + // Underflow is fairly harmless, do we even care in debug + // mode? +#ifndef __APPLE__ + feenableexcept(FE_DIVBYZERO | FE_UNDERFLOW | FE_OVERFLOW | + FE_INVALID); +#else + // XXX need the right magic + printf("UNABLE TO DBEUG FPE ON OSX!\n"); + exit(1); +#endif + } +} + +/** +* Shutdown PIOS and reset the microcontroller:
    +*
      +*
    • Disable all RTOS tasks +*
    • Disable all interrupts +*
    • Turn off all board LEDs +*
    • Reset STM32 +*
    +* \return < 0 if reset failed +*/ +int32_t PIOS_SYS_Reset(void) +{ + /* We will never reach this point */ + return -1; +} + +/** +* Returns the serial number as a string +* param[out] uint8_t pointer to a string which can store at least 12 bytes +* (12 bytes returned for STM32) +* return < 0 if feature not supported +*/ +int32_t PIOS_SYS_SerialNumberGetBinary(uint8_t *array) +{ + /* Stored in the so called "electronic signature" */ + for (int i = 0; i < PIOS_SYS_SERIAL_NUM_BINARY_LEN; ++i) { + array[i] = 0xff; + } + + /* No error */ + return 0; +} + +/** +* Returns the serial number as a string +* param[out] str pointer to a string which can store at least 32 digits + zero terminator! +* (24 digits returned for STM32) +* return < 0 if feature not supported +*/ +int32_t PIOS_SYS_SerialNumberGet(char *str) +{ + /* Stored in the so called "electronic signature" */ + int i; + for (i = 0; i < PIOS_SYS_SERIAL_NUM_ASCII_LEN; ++i) { + str[i] = 'F'; + } + str[i] = '\0'; + + /* No error */ + return 0; +} + +#endif + +/** + * @} + * @} + */ diff --git a/pool/shard003/C/0066572_afl-gotcpu.c b/pool/shard003/C/0066572_afl-gotcpu.c new file mode 100644 index 0000000000000000000000000000000000000000..c296993bf50b0b5db304a0680f0d50ef47358e02 --- /dev/null +++ b/pool/shard003/C/0066572_afl-gotcpu.c @@ -0,0 +1,252 @@ +/* + american fuzzy lop - free CPU gizmo + ----------------------------------- + + Written and maintained by Michal Zalewski + + Copyright 2015, 2016 Google Inc. All rights reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at: + + http://www.apache.org/licenses/LICENSE-2.0 + + This tool provides a fairly accurate measurement of CPU preemption rate. + It is meant to complement the quick-and-dirty load average widget shown + in the afl-fuzz UI. See docs/parallel_fuzzing.txt for more info. + + For some work loads, the tool may actually suggest running more instances + than you have CPU cores. This can happen if the tested program is spending + a portion of its run time waiting for I/O, rather than being 100% + CPU-bound. + + The idea for the getrusage()-based approach comes from Jakub Wilk. + + */ + +#define AFL_MAIN +#define _GNU_SOURCE + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "types.h" +#include "debug.h" + +#ifdef __linux__ +# define HAVE_AFFINITY 1 +#endif /* __linux__ */ + + +/* Get unix time in microseconds. */ + +static u64 get_cur_time_us(void) { + + struct timeval tv; + struct timezone tz; + + gettimeofday(&tv, &tz); + + return (tv.tv_sec * 1000000ULL) + tv.tv_usec; + +} + + +/* Get CPU usage in microseconds. */ + +static u64 get_cpu_usage_us(void) { + + struct rusage u; + + getrusage(RUSAGE_SELF, &u); + + return (u.ru_utime.tv_sec * 1000000ULL) + u.ru_utime.tv_usec + + (u.ru_stime.tv_sec * 1000000ULL) + u.ru_stime.tv_usec; + +} + + +/* Measure preemption rate. */ + +static u32 measure_preemption(u32 target_ms) { + + static volatile u32 v1, v2; + + u64 st_t, en_t, st_c, en_c, real_delta, slice_delta; + s32 loop_repeats = 0; + + st_t = get_cur_time_us(); + st_c = get_cpu_usage_us(); + +repeat_loop: + + v1 = CTEST_BUSY_CYCLES; + + while (v1--) v2++; + sched_yield(); + + en_t = get_cur_time_us(); + + if (en_t - st_t < target_ms * 1000) { + loop_repeats++; + goto repeat_loop; + } + + /* Let's see what percentage of this time we actually had a chance to + run, and how much time was spent in the penalty box. */ + + en_c = get_cpu_usage_us(); + + real_delta = (en_t - st_t) / 1000; + slice_delta = (en_c - st_c) / 1000; + + return real_delta * 100 / slice_delta; + +} + + +/* Do the benchmark thing. */ + +int main(int argc, char** argv) { + +#ifdef HAVE_AFFINITY + + u32 cpu_cnt = sysconf(_SC_NPROCESSORS_ONLN), + idle_cpus = 0, maybe_cpus = 0, i; + + SAYF(cCYA "afl-gotcpu " cBRI VERSION cRST " by \n"); + + ACTF("Measuring per-core preemption rate (this will take %0.02f sec)...", + ((double)CTEST_CORE_TRG_MS) / 1000); + + for (i = 0; i < cpu_cnt; i++) { + + s32 fr = fork(); + + if (fr < 0) PFATAL("fork failed"); + + if (!fr) { + + cpu_set_t c; + u32 util_perc; + + CPU_ZERO(&c); + CPU_SET(i, &c); + + if (sched_setaffinity(0, sizeof(c), &c)) + PFATAL("sched_setaffinity failed"); + + util_perc = measure_preemption(CTEST_CORE_TRG_MS); + + if (util_perc < 110) { + + SAYF(" Core #%u: " cLGN "AVAILABLE\n" cRST, i); + exit(0); + + } else if (util_perc < 250) { + + SAYF(" Core #%u: " cYEL "CAUTION " cRST "(%u%%)\n", i, util_perc); + exit(1); + + } + + SAYF(" Core #%u: " cLRD "OVERBOOKED " cRST "(%u%%)\n" cRST, i, + util_perc); + exit(2); + + } + + } + + for (i = 0; i < cpu_cnt; i++) { + + int ret; + if (waitpid(-1, &ret, 0) < 0) PFATAL("waitpid failed"); + + if (WEXITSTATUS(ret) == 0) idle_cpus++; + if (WEXITSTATUS(ret) <= 1) maybe_cpus++; + + } + + SAYF(cGRA "\n>>> "); + + if (idle_cpus) { + + if (maybe_cpus == idle_cpus) { + + SAYF(cLGN "PASS: " cRST "You can run more processes on %u core%s.", + idle_cpus, idle_cpus > 1 ? "s" : ""); + + } else { + + SAYF(cLGN "PASS: " cRST "You can run more processes on %u to %u core%s.", + idle_cpus, maybe_cpus, maybe_cpus > 1 ? "s" : ""); + + } + + SAYF(cGRA " <<<" cRST "\n\n"); + return 0; + + } + + if (maybe_cpus) { + + SAYF(cYEL "CAUTION: " cRST "You may still have %u core%s available.", + maybe_cpus, maybe_cpus > 1 ? "s" : ""); + SAYF(cGRA " <<<" cRST "\n\n"); + return 1; + + } + + SAYF(cLRD "FAIL: " cRST "All cores are overbooked."); + SAYF(cGRA " <<<" cRST "\n\n"); + return 2; + +#else + + u32 util_perc; + + SAYF(cCYA "afl-gotcpu " cBRI VERSION cRST " by \n"); + + /* Run a busy loop for CTEST_TARGET_MS. */ + + ACTF("Measuring gross preemption rate (this will take %0.02f sec)...", + ((double)CTEST_TARGET_MS) / 1000); + + util_perc = measure_preemption(CTEST_TARGET_MS); + + /* Deliver the final verdict. */ + + SAYF(cGRA "\n>>> "); + + if (util_perc < 105) { + + SAYF(cLGN "PASS: " cRST "You can probably run additional processes."); + + } else if (util_perc < 130) { + + SAYF(cYEL "CAUTION: " cRST "Your CPU may be somewhat overbooked (%u%%).", + util_perc); + + } else { + + SAYF(cLRD "FAIL: " cRST "Your CPU is overbooked (%u%%).", util_perc); + + } + + SAYF(cGRA " <<<" cRST "\n\n"); + + return (util_perc > 105) + (util_perc > 130); + +#endif /* ^HAVE_AFFINITY */ + +} diff --git a/pool/shard003/C/0066576_dbcontext.c b/pool/shard003/C/0066576_dbcontext.c new file mode 100644 index 0000000000000000000000000000000000000000..3132df8229016509c762e82780516ffed84aae65 --- /dev/null +++ b/pool/shard003/C/0066576_dbcontext.c @@ -0,0 +1,225 @@ +/* + * Copyright © 2012-2015 VMware, 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. + */ + + + +/* + * Module Name: ThinAppEventLogService + * + * Filename: dbcontext.c + * + * Abstract: + * + * Thinapp EventLogsitory Database + * + * Database Context Management + * + */ + +#include "includes.h" + +DWORD +EventLogInternalDbCreateContext( + PEVENTLOG_DB_CONTEXT * ppDbContext + ) +{ + DWORD dwError = 0; + PEVENTLOG_DB_CONTEXT pDbContext = NULL; + BOOLEAN bInLock = FALSE; + + VMEVENT_LOCK_MUTEX(bInLock, &gEventLogDbGlobals.mutex); + + if (gEventLogDbGlobals.pDbContextList) + { + pDbContext = gEventLogDbGlobals.pDbContextList; + gEventLogDbGlobals.pDbContextList = gEventLogDbGlobals.pDbContextList->pNext; + + pDbContext->pNext = NULL; + + gEventLogDbGlobals.dwNumCachedContexts--; + } + else + { + dwError = EventLogAllocateMemory(sizeof(*pDbContext), (PVOID*)&pDbContext); + BAIL_ON_EVENTLOG_ERROR(dwError); + + if (!gEventLogDbGlobals.bIsDBOpened) + { + dwError = EventLogDbDatabaseInitialize( + gEventLogDbGlobals.pszDbPath, // invariant + &pDbContext->pDb); + BAIL_ON_EVENTLOG_ERROR(dwError); + + gEventLogDbGlobals.bIsDBOpened = TRUE; + } + } + + *ppDbContext = pDbContext; + +cleanup: + + VMEVENT_UNLOCK_MUTEX(bInLock, &gEventLogDbGlobals.mutex); + + return dwError; + +error: + + *ppDbContext = NULL; + + if (pDbContext) + { + EventLogDbFreeContext(pDbContext); + } + + goto cleanup; +} + +VOID +EventLogInternalDbReleaseContext( + PEVENTLOG_DB_CONTEXT pDbContext + ) +{ + BOOLEAN bInLock = FALSE; + + // Rollback outstanding explicit transaction if exists. + EventLogDbCtxRollbackTransaction(pDbContext); + + VMEVENT_LOCK_MUTEX(bInLock, &gEventLogDbGlobals.mutex); + + if (gEventLogDbGlobals.dwNumCachedContexts < + gEventLogDbGlobals.dwMaxNumCachedContexts) + { + pDbContext->pNext = gEventLogDbGlobals.pDbContextList; + gEventLogDbGlobals.pDbContextList = pDbContext; + + gEventLogDbGlobals.dwNumCachedContexts++; + } + else + { + EventLogDbFreeContext(pDbContext); + } + + VMEVENT_UNLOCK_MUTEX(bInLock, &gEventLogDbGlobals.mutex); +} + + + + +VOID +EventLogInternalDbFreeContext( + PEVENTLOG_DB_CONTEXT pDbContext + ) +{ + + while (pDbContext) + { + PEVENTLOG_DB_CONTEXT pContext = pDbContext; + + pDbContext = pDbContext->pNext; + + if (pContext->pDelEventQuery) + { + sqlite3_finalize(pContext->pDelEventQuery); + } + + if (pContext->pDelEventAppsQuery) + { + sqlite3_finalize(pContext->pDelEventAppsQuery); + } + + if (pContext->pAddEventQuery) + { + sqlite3_finalize(pContext->pAddEventQuery); + } + + if (pContext->pEventIDByNameQuery) + { + sqlite3_finalize(pContext->pEventIDByNameQuery); + } + + if (pContext->pEventVersionIDByNameQuery) + { + sqlite3_finalize(pContext->pEventVersionIDByNameQuery); + } + + + if (pContext->pEventCountByNameQuery) + { + sqlite3_finalize(pContext->pEventCountByNameQuery); + } + + if (pContext->pTotalEventCountQuery) + { + sqlite3_finalize(pContext->pTotalEventCountQuery); + } + + + if (pContext->pQuerySingleEvent) + { + sqlite3_finalize(pContext->pQuerySingleEvent); + } + + if (pContext->pQueryAllEvents) + { + sqlite3_finalize(pContext->pQueryAllEvents); + } + + if (pContext->pQueryEventsPaged) + { + sqlite3_finalize(pContext->pQueryEventsPaged); + } + + if (pContext->pDb) + { + EventLogDbDatabaseClose(pContext->pDb); + } + + EventLogFreeMemory(pContext); + } +} + +DWORD +EventLogDbCreateContext( + PHEVENTLOG_DB hDatabase + ) +{ + DWORD dwError = 0; + PEVENTLOG_DB_CONTEXT pDBContext = NULL; + + dwError = EventLogInternalDbCreateContext(&pDBContext); + + *hDatabase = pDBContext; + + return dwError; +} + +VOID +EventLogDbReleaseContext( + HEVENTLOG_DB hDatabase + ) +{ + PEVENTLOG_DB_CONTEXT pDBContext = NULL; + pDBContext = (PEVENTLOG_DB_CONTEXT)hDatabase; + EventLogInternalDbReleaseContext(pDBContext); +} + +VOID +EventLogDbFreeContext( + HEVENTLOG_DB hDatabase + ) +{ + PEVENTLOG_DB_CONTEXT pDBContext = NULL; + pDBContext = (PEVENTLOG_DB_CONTEXT)hDatabase; + EventLogInternalDbFreeContext(pDBContext); +} diff --git a/pool/shard003/C/0066579_lat_signal.c b/pool/shard003/C/0066579_lat_signal.c new file mode 100644 index 0000000000000000000000000000000000000000..17c555191b3c42c057235f94cd85e252be5dc068 --- /dev/null +++ b/pool/shard003/C/0066579_lat_signal.c @@ -0,0 +1,55 @@ +#include "unpipc.h" + +static int counter, nloop; +static pid_t childpid, parentpid; + +void +sig_usr1(int signo) +{ + Kill(parentpid, SIGUSR2); /* child receives USR1, sends USR2 */ + return; +} + +void +sig_usr2(int signo) +{ + if (++counter < nloop) + Kill(childpid, SIGUSR1); /* parent receives USR2, sends USR1 */ + else + Kill(parentpid, SIGTERM); /* parent terminates below */ + return; +} + +void +sig_term(int signo) +{ + printf("latency: %.3f usec\n", Stop_time() / nloop); + Kill(childpid, SIGTERM); + exit(0); +} + +int +main(int argc, char **argv) +{ + + if (argc != 2) + err_quit("usage: lat_signal <#loops>"); + nloop = atoi(argv[1]); + counter = 0; + + parentpid = getpid(); + Signal(SIGUSR1, sig_usr1); /* for child */ + Signal(SIGUSR2, sig_usr2); /* for parent */ + if ( (childpid = Fork()) == 0) { + for ( ; ; ) { /* child */ + pause(); + } + exit(0); /* never reached */ + } + /* 4parent */ + Signal(SIGTERM, sig_term); /* for parent only */ + Start_time(); + Kill(childpid, SIGUSR1); + for ( ; ; ) + pause(); +} diff --git a/pool/shard003/C/0066589_crt1.c b/pool/shard003/C/0066589_crt1.c new file mode 100644 index 0000000000000000000000000000000000000000..dd8ed6a26ccd32c430e227179e1c0cbdb3a1ac0c --- /dev/null +++ b/pool/shard003/C/0066589_crt1.c @@ -0,0 +1,48 @@ +/* vi: set sw=4 ts=4: */ +/* uClibc/sysdeps/linux/m68k/crt0.S + * Pull stuff off the stack and get uClibc moving. + * + * Copyright (C) 2002-2003, George Thanos + * Yannis Mitsos + * + * Copyright (C) 2000,2001 by Erik Andersen + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Library 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 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 + */ + +/* Stick in a dummy reference to main(), so that if an application + * is linking when the main() function is in a static library (.a) + * we can be sure that main() actually gets linked in */ +extern void main(int argc,void *argv,void *envp); +/* void (*mainp)(int argc,void *argv,void *envp) = main; */ + +void __uClibc_main(int argc,void *argv,void *envp); + +void _uClibc_start(unsigned int first_arg) +{ + unsigned int argc; + char **argv, **envp; + unsigned long *stack; + + stack = (unsigned long*) first_arg; + argc = *(stack); + argv = (char **)(stack + 1); + envp = (char **)(stack + 1 + argc + 1); + + __uClibc_main(argc, argv, envp); +} + +void __main() { } + diff --git a/pool/shard003/C/0066591_GtkComboBoxText.c b/pool/shard003/C/0066591_GtkComboBoxText.c new file mode 100644 index 0000000000000000000000000000000000000000..95c9e7348b8f7bc8b546c910554a89b3718740d6 --- /dev/null +++ b/pool/shard003/C/0066591_GtkComboBoxText.c @@ -0,0 +1,374 @@ +/* + * java-gnome, a UI library for writing GTK and GNOME programs from Java! + * + * Copyright © 2006-2011 Operational Dynamics Consulting, Pty Ltd and Others + * + * The code in this file, and the program it is a part of, is made available + * to you by its authors as open source software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License version + * 2 ("GPL") 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 GPL for more details. + * + * You should have received a copy of the GPL along with this program. If not, + * see http://www.gnu.org/licenses/. The authors of this program may be + * contacted through http://java-gnome.sourceforge.net/. + * + * Linking this library statically or dynamically with other modules is making + * a combined work based on this library. Thus, the terms and conditions of + * the GPL cover the whole combination. As a special exception (the + * "Claspath Exception"), the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, + * and to copy and distribute the resulting executable under terms of your + * choice, provided that you also meet, for each linked independent module, + * the terms and conditions of the license of that module. An independent + * module is a module which is not derived from or based on this library. If + * you modify this library, you may extend the Classpath Exception to your + * version of the library, but you are not obligated to do so. If you do not + * wish to do so, delete this exception statement from your version. + */ + +/* + * THIS FILE IS GENERATED CODE! + * + * To modify its contents or behaviour, either update the generation program, + * change the information in the source defs file, or implement an override for + * this class. + */ + +#include +#include +#include "bindings_java.h" +#include "org_gnome_gtk_GtkComboBoxText.h" + +JNIEXPORT jlong JNICALL +Java_org_gnome_gtk_GtkComboBoxText_gtk_1combo_1box_1text_1new +( + JNIEnv* env, + jclass cls +) +{ + GtkWidget* result; + jlong _result; + + // call function + result = gtk_combo_box_text_new(); + + // translate return value to JNI type + _result = (jlong) result; + + // cleanup return value + if (result != NULL) { + bindings_java_memory_cleanup((GObject*)result, TRUE); + } + + // and finally + return _result; +} + +JNIEXPORT void JNICALL +Java_org_gnome_gtk_GtkComboBoxText_gtk_1combo_1box_1text_1append_1text +( + JNIEnv* env, + jclass cls, + jlong _self, + jstring _text +) +{ + GtkComboBoxText* self; + const gchar* text; + + // convert parameter self + self = (GtkComboBoxText*) _self; + + // convert parameter text + text = (const gchar*) bindings_java_getString(env, _text); + if (text == NULL) { + return; // Java Exception already thrown + } + + // call function + gtk_combo_box_text_append_text(self, text); + + // cleanup parameter self + + // cleanup parameter text + bindings_java_releaseString(text); +} + +JNIEXPORT void JNICALL +Java_org_gnome_gtk_GtkComboBoxText_gtk_1combo_1box_1text_1insert_1text +( + JNIEnv* env, + jclass cls, + jlong _self, + jint _position, + jstring _text +) +{ + GtkComboBoxText* self; + gint position; + const gchar* text; + + // convert parameter self + self = (GtkComboBoxText*) _self; + + // convert parameter position + position = (gint) _position; + + // convert parameter text + text = (const gchar*) bindings_java_getString(env, _text); + if (text == NULL) { + return; // Java Exception already thrown + } + + // call function + gtk_combo_box_text_insert_text(self, position, text); + + // cleanup parameter self + + // cleanup parameter position + + // cleanup parameter text + bindings_java_releaseString(text); +} + +JNIEXPORT void JNICALL +Java_org_gnome_gtk_GtkComboBoxText_gtk_1combo_1box_1text_1prepend_1text +( + JNIEnv* env, + jclass cls, + jlong _self, + jstring _text +) +{ + GtkComboBoxText* self; + const gchar* text; + + // convert parameter self + self = (GtkComboBoxText*) _self; + + // convert parameter text + text = (const gchar*) bindings_java_getString(env, _text); + if (text == NULL) { + return; // Java Exception already thrown + } + + // call function + gtk_combo_box_text_prepend_text(self, text); + + // cleanup parameter self + + // cleanup parameter text + bindings_java_releaseString(text); +} + +JNIEXPORT void JNICALL +Java_org_gnome_gtk_GtkComboBoxText_gtk_1combo_1box_1text_1remove +( + JNIEnv* env, + jclass cls, + jlong _self, + jint _position +) +{ + GtkComboBoxText* self; + gint position; + + // convert parameter self + self = (GtkComboBoxText*) _self; + + // convert parameter position + position = (gint) _position; + + // call function + gtk_combo_box_text_remove(self, position); + + // cleanup parameter self + + // cleanup parameter position +} + +JNIEXPORT void JNICALL +Java_org_gnome_gtk_GtkComboBoxText_gtk_1combo_1box_1text_1remove_1all +( + JNIEnv* env, + jclass cls, + jlong _self +) +{ + GtkComboBoxText* self; + + // convert parameter self + self = (GtkComboBoxText*) _self; + + // call function + gtk_combo_box_text_remove_all(self); + + // cleanup parameter self +} + +JNIEXPORT jstring JNICALL +Java_org_gnome_gtk_GtkComboBoxText_gtk_1combo_1box_1text_1get_1active_1text +( + JNIEnv* env, + jclass cls, + jlong _self +) +{ + gchar* result; + jstring _result; + GtkComboBoxText* self; + + // convert parameter self + self = (GtkComboBoxText*) _self; + + // call function + result = gtk_combo_box_text_get_active_text(self); + + // cleanup parameter self + + // translate return value to JNI type + _result = (jstring) bindings_java_newString(env, result); + + // cleanup return value + if (result != NULL) { + g_free(result); + } + + // and finally + return _result; +} + +JNIEXPORT void JNICALL +Java_org_gnome_gtk_GtkComboBoxText_gtk_1combo_1box_1text_1insert +( + JNIEnv* env, + jclass cls, + jlong _self, + jint _position, + jstring _id, + jstring _text +) +{ + GtkComboBoxText* self; + gint position; + const gchar* id; + const gchar* text; + + // convert parameter self + self = (GtkComboBoxText*) _self; + + // convert parameter position + position = (gint) _position; + + // convert parameter id + id = (const gchar*) bindings_java_getString(env, _id); + if (id == NULL) { + return; // Java Exception already thrown + } + + // convert parameter text + text = (const gchar*) bindings_java_getString(env, _text); + if (text == NULL) { + return; // Java Exception already thrown + } + + // call function + gtk_combo_box_text_insert(self, position, id, text); + + // cleanup parameter self + + // cleanup parameter position + + // cleanup parameter id + bindings_java_releaseString(id); + + // cleanup parameter text + bindings_java_releaseString(text); +} + +JNIEXPORT void JNICALL +Java_org_gnome_gtk_GtkComboBoxText_gtk_1combo_1box_1text_1append +( + JNIEnv* env, + jclass cls, + jlong _self, + jstring _id, + jstring _text +) +{ + GtkComboBoxText* self; + const gchar* id; + const gchar* text; + + // convert parameter self + self = (GtkComboBoxText*) _self; + + // convert parameter id + id = (const gchar*) bindings_java_getString(env, _id); + if (id == NULL) { + return; // Java Exception already thrown + } + + // convert parameter text + text = (const gchar*) bindings_java_getString(env, _text); + if (text == NULL) { + return; // Java Exception already thrown + } + + // call function + gtk_combo_box_text_append(self, id, text); + + // cleanup parameter self + + // cleanup parameter id + bindings_java_releaseString(id); + + // cleanup parameter text + bindings_java_releaseString(text); +} + +JNIEXPORT void JNICALL +Java_org_gnome_gtk_GtkComboBoxText_gtk_1combo_1box_1text_1prepend +( + JNIEnv* env, + jclass cls, + jlong _self, + jstring _id, + jstring _text +) +{ + GtkComboBoxText* self; + const gchar* id; + const gchar* text; + + // convert parameter self + self = (GtkComboBoxText*) _self; + + // convert parameter id + id = (const gchar*) bindings_java_getString(env, _id); + if (id == NULL) { + return; // Java Exception already thrown + } + + // convert parameter text + text = (const gchar*) bindings_java_getString(env, _text); + if (text == NULL) { + return; // Java Exception already thrown + } + + // call function + gtk_combo_box_text_prepend(self, id, text); + + // cleanup parameter self + + // cleanup parameter id + bindings_java_releaseString(id); + + // cleanup parameter text + bindings_java_releaseString(text); +} diff --git a/pool/shard003/C/0066597_ft_lstnew.c b/pool/shard003/C/0066597_ft_lstnew.c new file mode 100644 index 0000000000000000000000000000000000000000..bc96c43ad2be8862c0d0871c023ae772a81770e8 --- /dev/null +++ b/pool/shard003/C/0066597_ft_lstnew.c @@ -0,0 +1,35 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_lstnew.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: lmarti +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2013/11/25 01:10:04 by lmarti #+# #+# */ +/* Updated: 2013/11/26 19:03:52 by lmarti ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include +#include "libft.h" + +t_list *ft_lstnew(void const *content, size_t content_size) +{ + t_list *elem; + + elem = (t_list *)malloc(sizeof(t_list)); + if (!elem) + return (NULL); + if (!content) + { + elem->content = NULL; + elem->content_size = 0; + } + else + { + elem->content = (void *)content; + elem->content_size = content_size; + } + elem->next = NULL; + return (elem); +} diff --git a/pool/shard003/C/0066599_ThreadLockShouldFail.c b/pool/shard003/C/0066599_ThreadLockShouldFail.c new file mode 100644 index 0000000000000000000000000000000000000000..04466d266e9c3261d46f6719598a5b5f0391cb62 --- /dev/null +++ b/pool/shard003/C/0066599_ThreadLockShouldFail.c @@ -0,0 +1,304 @@ +/* + * Copyright (C) 2006-2009 Daniel Prevost + * + * This file is part of Photon (photonsoftware.org). + * + * This file may be distributed and/or modified under the terms of the + * GNU General Public License version 2 or version 3 as published by the + * Free Software Foundation and appearing in the file COPYING.GPL2 and + * COPYING.GPL3 included in the packaging of this software. + * + * Licensees holding a valid Photon Commercial license can use this file + * in accordance with the terms of their license. + * + * 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. + */ + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +/* + * This test is very similar to the LockConcurrency test... except that + * this program does not always lock properly (on purpose)!!! The rate of + * failure of our locks is controlled by the #define DEFAULT_FAILURE_RATE. + * + * In a way, it insures that we would be able to detect a failure in + * our locking mechanism using the standard LockConcurrency test. + * + * The amount of time we will try to observe a concurrency failure is + * determined by the first argument to the program. + */ + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +#include "Common/Common.h" +#include "Common/MemoryFile.h" +#include "Common/Timer.h" +#include "Common/ThreadLock.h" +#include "Common/ErrorHandler.h" +#include "Common/Tests/ThreadLock/ThreadWrap.h" +#include "Common/Tests/ThreadLock/Barrier.h" +#include "Tests/PrintError.h" +#include "Common/Options.h" + +const bool expectedToPass = true; + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +#define US_PER_SEC 1000000 + +struct localData +{ + psocThreadLock lock; + int exitFlag; + char dum1[150]; + char dum2[250]; +}; + +psocMemoryFile g_memFile; +struct localData *g_data = NULL; +unsigned long g_maxTime = 0; +unsigned long g_failureRate; +psotBarrier g_barrier; +bool g_tryMode = false; + +/* + * Misnamed define... the failure rate is 1/DEFAULT_FAILURE_RATE... + * + * I would prefer a much lower failure rate but it would mean + * being very patient... (failures can only be seen when context + * switches are done and with time slices of 1/1000 sec. (on many + * modern OSes), it would force us to run the test for a lot longer). + * + * [DEFAULT_FAILURE_RATE 1000000 --> 0.0001% failure] + */ +#define DEFAULT_FAILURE_RATE 1000000 +#define DEFAULT_NUM_THREADS 4 +#define DEFAULT_TIME 300 +#define CHECK_TIMER 1345 /* Check the time every CHECK_TIMER loops */ + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +int worker( void* arg ) +{ + unsigned long sec, nanoSec; + psocTimer timer; + int identifier; + unsigned long elapsedTime = 0; + unsigned long loop = 1; + char dum3[100]; + int dumId; + + identifier = *((int*)arg); + + psocInitTimer( &timer ); + psotBarrierWait( &g_barrier ); + psocBeginTimer( &timer ); + + while ( 1 ) { + if ( (loop%DEFAULT_FAILURE_RATE) != 0 ) { + psocAcquireThreadLock( &g_data->lock ); + } + + sprintf( g_data->dum2, "dumStr2 %d ", identifier ); + memcpy( g_data->dum1, g_data->dum2, 100 ); + + sscanf( g_data->dum1, "%s %d", dum3, &dumId ); + if ( dumId != identifier ) { + psocEndTimer( &timer ); + psocCalculateTimer( &timer, &sec, &nanoSec ); + + fprintf( stderr, "%s - time = %u.%03u secs, \n", + "Ok! We got our expected error", + (unsigned int)sec, + (unsigned int)(nanoSec/1000/1000) ); + g_data->exitFlag = 1; + if ( (loop%DEFAULT_FAILURE_RATE) != 0 ) { + psocReleaseThreadLock( &g_data->lock ); + } + fprintf( stderr, "Thread #%d, Number of loops = %lu\n", + identifier, loop ); + return 1; + } + + if ( (loop%DEFAULT_FAILURE_RATE) != 0 ) { + psocReleaseThreadLock( &g_data->lock ); + } + + if ( g_data->exitFlag == 1 ) break; + loop++; + + if ( (loop%CHECK_TIMER) != 0 ) { + psocEndTimer( &timer ); + psocCalculateTimer( &timer, &sec, &nanoSec ); + + elapsedTime = sec*US_PER_SEC + nanoSec/1000; + if ( elapsedTime > g_maxTime ) break; + } + } + + printf( "Thread #%d, Number of loops = %lu\n", identifier, loop ); + + return 0; +} + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +int main( int argc, char* argv[] ) +{ + void* ptr = NULL; + char filename[PATH_MAX]; + int errcode; + bool ok; + psocErrorHandler errorHandler; + int i, *identifier, numThreads; + psotThreadWrap *threadWrap; + bool foundError = false; + psocOptionHandle handle; + char *argument; + struct psocOptStruct opts[5] = { + { 'f', "filename", 1, "memoryFile", "Filename for shared memory" }, + { 'm', "mode", 1, "lockMode", "Set this to 'try' for testing TryAcquire" }, + { 'n', "numThreads", 1, "numThreads", "Number of threads" }, + { 'r', "rate", 1, "rateOfFailure", "Inverse rate: 1000 means a rate of 0.1%" }, + { 't', "time", 1, "timeInSecs", "Time to run the tests" } + }; + + psocInitErrorDefs(); + psocInitErrorHandler( &errorHandler ); + + ok = psocSetSupportedOptions( 5, opts, &handle ); + if ( ok != true ) { + ERROR_EXIT( expectedToPass, NULL, ; ); + } + + errcode = psocValidateUserOptions( handle, argc, argv, 1 ); + if ( errcode < 0 ) { + psocShowUsage( handle, "LockConcurrency", "" ); + ERROR_EXIT( expectedToPass, NULL, ; ); + } + if ( errcode > 0 ) { + psocShowUsage( handle, "LockConcurrency", "" ); + return 0; + } + + if ( psocGetShortOptArgument( handle, 'n', &argument ) ) { + numThreads = atoi( argument ); + if ( numThreads < 2 ) { + fprintf( stderr, "Number of childs must be >= to two\n" ); + ERROR_EXIT( expectedToPass, NULL, ; ); + } + } + else { + numThreads = DEFAULT_NUM_THREADS; + } + + if ( psocGetShortOptArgument( handle, 'r', &argument ) ) { + g_failureRate = strtol( argument, NULL, 0 ); + if ( g_failureRate < 1 ) { + fprintf( stderr, "Failure rate must be positive\n" ); + ERROR_EXIT( expectedToPass, NULL, ; ); + } + } + else { + g_failureRate = DEFAULT_FAILURE_RATE; + } + + if ( psocGetShortOptArgument( handle, 't', &argument ) ) { + g_maxTime = strtol( argument, NULL, 0 ); + if ( g_maxTime < 1 ) { + fprintf( stderr, "Time of test must be positive\n" ); + ERROR_EXIT( expectedToPass, NULL, ; ); + } + } + else { + g_maxTime = DEFAULT_TIME; /* in seconds */ + } + + if ( psocGetShortOptArgument( handle, 'm', &argument ) ) { + if ( strcmp( argument, "try" ) == 0 ) g_tryMode = true; + } + + if ( psocGetShortOptArgument( handle, 'f', &argument ) ) { + strncpy( filename, argument, PATH_MAX ); + if ( filename[0] == '\0' ) { + fprintf( stderr, "Empty memfile name\n" ); + ERROR_EXIT( expectedToPass, NULL, ; ); + } + } + else { + strcpy( filename, "Memfile.mem" ); + } + + g_maxTime *= US_PER_SEC; + identifier = (int*) malloc( numThreads*sizeof(int)); + if ( identifier == NULL ) { + ERROR_EXIT( expectedToPass, &errorHandler, ; ); + } + memset( identifier, 0, numThreads*sizeof(int) ); + + threadWrap = (psotThreadWrap*) malloc(numThreads*sizeof(psotThreadWrap)); + if ( threadWrap == NULL ) { + ERROR_EXIT( expectedToPass, &errorHandler, ; ); + } + memset( threadWrap, 0, numThreads*sizeof(psotThreadWrap) ); + + errcode = psotInitBarrier( &g_barrier, numThreads, &errorHandler ); + if ( errcode < 0 ) { + ERROR_EXIT( expectedToPass, &errorHandler, ; ); + } + + psocInitMemoryFile( &g_memFile, 10, filename ); + + ok = psocCreateBackstore( &g_memFile, 0644, &errorHandler ); + if ( ok != true ) { + ERROR_EXIT( expectedToPass, &errorHandler, ; ); + } + + ok = psocOpenMemFile( &g_memFile, &ptr, &errorHandler ); + if ( ok != true ) { + ERROR_EXIT( expectedToPass, &errorHandler, ; ); + } + + memset( ptr, 0, 10000 ); + g_data = (struct localData*) ptr; + + ok = psocInitThreadLock( &g_data->lock ); + if ( ok != true ) { + ERROR_EXIT( expectedToPass, NULL, ; ); + } + + for ( i = 0; i < numThreads; ++i ) { + identifier[i] = i+1; + errcode = psotCreateThread( &threadWrap[i], + &worker, + (void*)&identifier[i], + &errorHandler ); + if ( errcode < 0 ) { + ERROR_EXIT( expectedToPass, &errorHandler, ; ); + } + } + + for ( i = 0; i < numThreads; ++i ) { + errcode = psotJoinThread( &threadWrap[i], &errorHandler ); + if ( errcode < 0 ) { + ERROR_EXIT( expectedToPass, &errorHandler, ; ); + } + if ( threadWrap[i].returnCode != 0 ) foundError = true; + } + + if ( ! foundError ) { + ERROR_EXIT( expectedToPass, &errorHandler, ; ); + } + + psocFiniMemoryFile( &g_memFile ); + psotFiniBarrier( &g_barrier ); + psocFiniErrorHandler( &errorHandler ); + psocFiniErrorDefs(); + + return 0; +} + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + diff --git a/pool/shard003/C/0066610_vacuum.c b/pool/shard003/C/0066610_vacuum.c new file mode 100644 index 0000000000000000000000000000000000000000..c6227303d2c37204d23f940b2e881b7d724c2f6d --- /dev/null +++ b/pool/shard003/C/0066610_vacuum.c @@ -0,0 +1,299 @@ +/* +** 2003 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to implement the VACUUM command. +** +** Most of the code in this file may be omitted by defining the +** SQLITE_OMIT_VACUUM macro. +** +** $Id: vacuum.c,v 1.86 2009/02/03 16:51:25 danielk1977 Exp $ +*/ +#include "sqliteInt.h" +#include "vdbeInt.h" + +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) +/* +** Execute zSql on database db. Return an error code. +*/ +static int execSql(sqlite3 *db, const char *zSql){ + sqlite3_stmt *pStmt; + if( !zSql ){ + return SQLITE_NOMEM; + } + if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){ + return sqlite3_errcode(db); + } + while( SQLITE_ROW==sqlite3_step(pStmt) ){} + return sqlite3_finalize(pStmt); +} + +/* +** Execute zSql on database db. The statement returns exactly +** one column. Execute this as SQL on the same database. +*/ +static int execExecSql(sqlite3 *db, const char *zSql){ + sqlite3_stmt *pStmt; + int rc; + + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ) return rc; + + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0)); + if( rc!=SQLITE_OK ){ + sqlite3_finalize(pStmt); + return rc; + } + } + + return sqlite3_finalize(pStmt); +} + +/* +** The non-standard VACUUM command is used to clean up the database, +** collapse free space, etc. It is modelled after the VACUUM command +** in PostgreSQL. +** +** In version 1.0.x of SQLite, the VACUUM command would call +** gdbm_reorganize() on all the database tables. But beginning +** with 2.0.0, SQLite no longer uses GDBM so this command has +** become a no-op. +*/ +void sqlite3Vacuum(Parse *pParse){ + Vdbe *v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0); + } + return; +} + +/* +** This routine implements the OP_Vacuum opcode of the VDBE. +*/ +int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){ + int rc = SQLITE_OK; /* Return code from service routines */ + Btree *pMain; /* The database being vacuumed */ + Pager *pMainPager; /* Pager for database being vacuumed */ + Btree *pTemp; /* The temporary database we vacuum into */ + char *zSql = 0; /* SQL statements */ + int saved_flags; /* Saved value of the db->flags */ + int saved_nChange; /* Saved value of db->nChange */ + int saved_nTotalChange; /* Saved value of db->nTotalChange */ + Db *pDb = 0; /* Database to detach at end of vacuum */ + int isMemDb; /* True is vacuuming a :memory: database */ + int nRes; + + if( !db->autoCommit ){ + sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); + return SQLITE_ERROR; + } + + /* Save the current value of the write-schema flag before setting it. */ + saved_flags = db->flags; + saved_nChange = db->nChange; + saved_nTotalChange = db->nTotalChange; + db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks; + + pMain = db->aDb[0].pBt; + pMainPager = sqlite3BtreePager(pMain); + isMemDb = sqlite3PagerFile(pMainPager)->pMethods==0; + + /* Attach the temporary database as 'vacuum_db'. The synchronous pragma + ** can be set to 'off' for this file, as it is not recovered if a crash + ** occurs anyway. The integrity of the database is maintained by a + ** (possibly synchronous) transaction opened on the main database before + ** sqlite3BtreeCopyFile() is called. + ** + ** An optimisation would be to use a non-journaled pager. + ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but + ** that actually made the VACUUM run slower. Very little journalling + ** actually occurs when doing a vacuum since the vacuum_db is initially + ** empty. Only the journal header is written. Apparently it takes more + ** time to parse and run the PRAGMA to turn journalling off than it does + ** to write the journal header file. + */ + zSql = "ATTACH '' AS vacuum_db;"; + rc = execSql(db, zSql); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + pDb = &db->aDb[db->nDb-1]; + assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 ); + pTemp = db->aDb[db->nDb-1].pBt; + + nRes = sqlite3BtreeGetReserve(pMain); + + /* A VACUUM cannot change the pagesize of an encrypted database. */ +#ifdef SQLITE_HAS_CODEC + if( db->nextPagesize ){ + extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); + int nKey; + char *zKey; + sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); + if( nKey ) db->nextPagesize = 0; + } +#endif + + if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes) + || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes)) + || db->mallocFailed + ){ + rc = SQLITE_NOMEM; + goto end_of_vacuum; + } + rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF"); + if( rc!=SQLITE_OK ){ + goto end_of_vacuum; + } + +#ifndef SQLITE_OMIT_AUTOVACUUM + sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac : + sqlite3BtreeGetAutoVacuum(pMain)); +#endif + + /* Begin a transaction */ + rc = execSql(db, "BEGIN EXCLUSIVE;"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Query the schema of the main database. Create a mirror schema + ** in the temporary database. + */ + rc = execExecSql(db, + "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) " + " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" + " AND rootpage>0" + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, + "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)" + " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' "); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, + "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) " + " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Loop through the tables in the main database. For each, do + ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy + ** the contents to the temporary database. + */ + rc = execExecSql(db, + "SELECT 'INSERT INTO vacuum_db.' || quote(name) " + "|| ' SELECT * FROM ' || quote(name) || ';'" + "FROM sqlite_master " + "WHERE type = 'table' AND name!='sqlite_sequence' " + " AND rootpage>0" + + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Copy over the sequence table + */ + rc = execExecSql(db, + "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' " + "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' " + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, + "SELECT 'INSERT INTO vacuum_db.' || quote(name) " + "|| ' SELECT * FROM ' || quote(name) || ';' " + "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';" + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + + /* Copy the triggers, views, and virtual tables from the main database + ** over to the temporary database. None of these objects has any + ** associated storage, so all we have to do is copy their entries + ** from the SQLITE_MASTER table. + */ + rc = execSql(db, + "INSERT INTO vacuum_db.sqlite_master " + " SELECT type, name, tbl_name, rootpage, sql" + " FROM sqlite_master" + " WHERE type='view' OR type='trigger'" + " OR (type='table' AND rootpage=0)" + ); + if( rc ) goto end_of_vacuum; + + /* At this point, unless the main db was completely empty, there is now a + ** transaction open on the vacuum database, but not on the main database. + ** Open a btree level transaction on the main database. This allows a + ** call to sqlite3BtreeCopyFile(). The main database btree level + ** transaction is then committed, so the SQL level never knows it was + ** opened for writing. This way, the SQL transaction used to create the + ** temporary database never needs to be committed. + */ + if( rc==SQLITE_OK ){ + u32 meta; + int i; + + /* This array determines which meta meta values are preserved in the + ** vacuum. Even entries are the meta value number and odd entries + ** are an increment to apply to the meta value after the vacuum. + ** The increment is used to increase the schema cookie so that other + ** connections to the same database will know to reread the schema. + */ + static const unsigned char aCopy[] = { + 1, 1, /* Add one to the old schema cookie */ + 3, 0, /* Preserve the default page cache size */ + 5, 0, /* Preserve the default text encoding */ + 6, 0, /* Preserve the user version */ + }; + + assert( 1==sqlite3BtreeIsInTrans(pTemp) ); + assert( 1==sqlite3BtreeIsInTrans(pMain) ); + + /* Copy Btree meta values */ + for(i=0; iflags */ + db->flags = saved_flags; + db->nChange = saved_nChange; + db->nTotalChange = saved_nTotalChange; + + /* Currently there is an SQL level transaction open on the vacuum + ** database. No locks are held on any other files (since the main file + ** was committed at the btree level). So it safe to end the transaction + ** by manually setting the autoCommit flag to true and detaching the + ** vacuum database. The vacuum_db journal file is deleted when the pager + ** is closed by the DETACH. + */ + db->autoCommit = 1; + + if( pDb ){ + sqlite3BtreeClose(pDb->pBt); + pDb->pBt = 0; + pDb->pSchema = 0; + } + + sqlite3ResetInternalSchema(db, 0); + + return rc; +} +#endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */ diff --git a/pool/shard003/C/0066625_context.c b/pool/shard003/C/0066625_context.c new file mode 100644 index 0000000000000000000000000000000000000000..3f8e54a1e0ddb120656704a63c3d61a32d472da6 --- /dev/null +++ b/pool/shard003/C/0066625_context.c @@ -0,0 +1,198 @@ +/* + Kafel - context + ----------------------------------------- + + Copyright 2016 Google LLC + + 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 "context.h" + +#include +#include +#include +#include +#include +#include + +#include "common.h" +#include "kafel.h" + +KAFEL_API kafel_ctxt_t kafel_ctxt_create(void) { + struct kafel_ctxt* ctxt = calloc(1, sizeof(*ctxt)); + includes_ctxt_init(&ctxt->includes_ctxt); + TAILQ_INIT(&ctxt->policies); + TAILQ_INIT(&ctxt->constants); + return ctxt; +} + +static void clean_policies(kafel_ctxt_t ctxt) { + while (!TAILQ_EMPTY(&ctxt->policies)) { + struct policy* policy = TAILQ_FIRST(&ctxt->policies); + TAILQ_REMOVE(&ctxt->policies, policy, policies); + policy_destroy(&policy); + } +} + +static void clean_constants(kafel_ctxt_t ctxt) { + while (!TAILQ_EMPTY(&ctxt->constants)) { + struct kafel_constant* constant = TAILQ_FIRST(&ctxt->constants); + TAILQ_REMOVE(&ctxt->constants, constant, constants); + free(constant->name); + free(constant); + } +} + +void kafel_ctxt_reset(kafel_ctxt_t ctxt) { + ASSERT(ctxt != NULL); + + clean_policies(ctxt); + clean_constants(ctxt); + free(ctxt->errors.data); + ctxt->errors.capacity = 0; + ctxt->errors.len = 0; + ctxt->errors.data = NULL; + ctxt->main_policy = NULL; + ctxt->default_action = 0; + ctxt->lexical_error = false; +} + +void kafel_ctxt_clean(kafel_ctxt_t ctxt) { + ASSERT(ctxt != NULL); + + kafel_ctxt_reset(ctxt); + includes_ctxt_clean(&ctxt->includes_ctxt); + ctxt->target_archs = 0; +} + +KAFEL_API void kafel_ctxt_destroy(kafel_ctxt_t* ctxt) { + ASSERT(ctxt != NULL); + ASSERT(*ctxt != NULL); + + kafel_ctxt_clean(*ctxt); + free(*ctxt); + *ctxt = NULL; +} + +KAFEL_API const char* kafel_error_msg(const kafel_ctxt_t ctxt) { + ASSERT(ctxt != NULL); + + return ctxt->errors.data; +} + +void register_policy(struct kafel_ctxt* ctxt, struct policy* policy) { + TAILQ_INSERT_TAIL(&ctxt->policies, policy, policies); +} + +struct policy* lookup_policy(struct kafel_ctxt* ctxt, const char* name) { + struct policy* policy; + TAILQ_FOREACH(policy, &ctxt->policies, policies) { + if (strcmp(policy->name, name) == 0) { + return policy; + } + } + return NULL; +} + +void mark_all_policies_unused(struct kafel_ctxt* ctxt) { + struct policy* policy; + TAILQ_FOREACH(policy, &ctxt->policies, policies) { policy->used = false; } +} + +static int grow_errors_buffer(struct kafel_ctxt* ctxt, size_t min_growth) { + size_t oldcapacity = ctxt->errors.capacity; + if (min_growth > 0 && ctxt->errors.len <= SIZE_MAX - min_growth) { + return -1; // overflow + } + size_t mincapacity = ctxt->errors.len + min_growth; + if (mincapacity <= oldcapacity) { + return 0; + } + size_t newcapacity = mincapacity; + if (oldcapacity <= SIZE_MAX / 2 && oldcapacity * 2 > mincapacity) { + newcapacity = oldcapacity * 2; + } + char* newbuf = realloc(ctxt->errors.data, newcapacity); + if (newbuf == NULL) { + return -1; // OOM + } + ctxt->errors.data = newbuf; + ctxt->errors.capacity = newcapacity; + return 0; +} + +int append_error(struct kafel_ctxt* ctxt, const char* fmt, ...) { + ASSERT(ctxt != NULL); + ASSERT(fmt != NULL); + + va_list ap; + + if (ctxt->errors.data == NULL) { + ASSERT(ctxt->errors.len == 0); + ASSERT(ctxt->errors.capacity == 0); + + size_t newcapacity = 128; + ctxt->errors.data = malloc(newcapacity); + if (ctxt->errors.data == NULL) { + return -1; // OOM + } + ctxt->errors.capacity = newcapacity; + } + + for (;;) { + size_t space = ctxt->errors.capacity - ctxt->errors.len; + + va_start(ap, fmt); + int n = vsnprintf(&ctxt->errors.data[ctxt->errors.len], space, fmt, ap); + va_end(ap); + + if (n < 0) { + ctxt->errors.data[ctxt->errors.len] = '\0'; + return -1; + } + if (((size_t)n) < space) { + ctxt->errors.len += n; + if (grow_errors_buffer(ctxt, 1) == 0) { + ctxt->errors.data[ctxt->errors.len++] = '\n'; + } + ctxt->errors.data[ctxt->errors.len] = '\0'; + return 0; + } + if (grow_errors_buffer(ctxt, n) != 0) { + return -1; + } + } + return -1; +} + +void register_const(struct kafel_ctxt* ctxt, const char* name, uint64_t value) { + struct kafel_constant* constant = calloc(1, sizeof(*constant)); + constant->name = strdup(name); + constant->value = value; + TAILQ_INSERT_TAIL(&ctxt->constants, constant, constants); +} + +int lookup_const(struct kafel_ctxt* ctxt, const char* name, uint64_t* value) { + struct kafel_constant* constant; + TAILQ_FOREACH(constant, &ctxt->constants, constants) { + if (strcmp(name, constant->name) == 0) { + if (value != NULL) { + *value = constant->value; + } + return 0; + } + } + return -1; +} diff --git a/pool/shard003/C/0066635_bn_mp_expt_d.c b/pool/shard003/C/0066635_bn_mp_expt_d.c new file mode 100644 index 0000000000000000000000000000000000000000..4bdc2d13a695b95a5303db83ea5267192e243051 --- /dev/null +++ b/pool/shard003/C/0066635_bn_mp_expt_d.c @@ -0,0 +1,57 @@ +#include +#ifdef BN_MP_EXPT_D_C +/* LibTomMath, multiple-precision integer library -- Tom St Denis + * + * LibTomMath is a library that provides multiple-precision + * integer arithmetic as well as number theoretic functionality. + * + * The library was designed directly after the MPI library by + * Michael Fromberger but has been written from scratch with + * additional optimizations in place. + * + * The library is free for all purposes without any express + * guarantee it works. + * + * Tom St Denis, tomstdenis@gmail.com, http://libtom.org + */ + +/* calculate c = a**b using a square-multiply algorithm */ +int mp_expt_d (mp_int * a, mp_digit b, mp_int * c) +{ + int res, x; + mp_int g; + + if ((res = mp_init_copy (&g, a)) != MP_OKAY) { + return res; + } + + /* set initial result */ + mp_set (c, 1); + + for (x = 0; x < (int) DIGIT_BIT; x++) { + /* square */ + if ((res = mp_sqr (c, c)) != MP_OKAY) { + mp_clear (&g); + return res; + } + + /* if the bit is set multiply */ + if ((b & (mp_digit) (((mp_digit)1) << (DIGIT_BIT - 1))) != 0) { + if ((res = mp_mul (c, &g, c)) != MP_OKAY) { + mp_clear (&g); + return res; + } + } + + /* shift to next bit */ + b <<= 1; + } + + mp_clear (&g); + return MP_OKAY; +} +#endif + +/* $Source: /cvs/libtom/libtommath/bn_mp_expt_d.c,v $ */ +/* $Revision: 1.4 $ */ +/* $Date: 2006/12/28 01:25:13 $ */ diff --git a/pool/shard003/C/0066642_gfx.c b/pool/shard003/C/0066642_gfx.c new file mode 100644 index 0000000000000000000000000000000000000000..44b6cb41db6b2c57979b3a4e171973df8f0b2674 --- /dev/null +++ b/pool/shard003/C/0066642_gfx.c @@ -0,0 +1,108 @@ +// +// gfx.c: this file is part of the SL toolchain. +// +// Copyright (C) 2009 The SL 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 3 +// of the License, or (at your option) any later version. +// +// The complete GNU General Public Licence Notice can be found as the +// `COPYING' file in the root directory. +// + +#include +#include +#include +#include +#include +#include +#include + +uint32_t * __restrict__ __gfx_framebuffer = 0; +size_t __gfx_w = 0; +size_t __gfx_h = 0; + +void gfx_resize(size_t nw, size_t nh) +{ + if (unlikely(unlikely(!nw) || unlikely(!nh))) return; + + if (likely(__gfx_framebuffer)) + free(__gfx_framebuffer); + + __gfx_framebuffer = (uint32_t*)calloc(nw * nh, sizeof(uint32_t)); + + if (likely(__gfx_framebuffer != 0)) { + __gfx_w = nw; + __gfx_h = nh; + } else + __gfx_w = __gfx_h = 0; +} + +void gfx_clear(void) { + memset(__gfx_framebuffer, 0, __gfx_w * __gfx_h * sizeof(uint32_t)); +} + +void gfx_init(void) { gfx_resize(100, 100); } +void gfx_close(void) +{ + if (likely(__gfx_framebuffer != 0)) free(__gfx_framebuffer); + __gfx_framebuffer = 0; + __gfx_w = __gfx_h = 0; +} + +void gfx_dump(unsigned key, int stream, int embed_ts, int embed_tinfo /* unused */) +{ + char buffer[128]; + FILE *f = 0; + + if (unlikely(__gfx_framebuffer == 0)) + return; + + if (stream == 0) { + if (embed_ts) { + struct rusage r; + getrusage(RUSAGE_SELF, &r); + snprintf(buffer, 128, "gfx.%u.%llu%06u.ppm", key, (unsigned long long)r.ru_utime.tv_sec, (unsigned)r.ru_utime.tv_usec); + } else + snprintf(buffer, 128, "gfx.%u.ppm", key); + f = fopen(buffer, "w"); + } + else if (stream == 2) + f = stderr; + else if (stream == 1) + f = stdout; + + if (!f) + return; + + size_t w = __gfx_w, h = __gfx_h; + size_t x, y; + uint32_t * __restrict__ pixels = __gfx_framebuffer; + fprintf(f, "P3\n#key: %u\n#\n%u %u 255\n", key, (unsigned)w, (unsigned)h); + for (y = 0; y < h; ++y) { + for (x = 0; x < w; ++x) { + uint32_t d = pixels[y * w + x]; + fprintf(f, "%u %u %u ", (int)((d >> 16) & 0xff), (int)((d >> 8) & 0xff), (int)(d & 0xff)); + } + fputc('\n', f); + } + if (stream == 0) + fclose(f); +} + + +void gfx_putpixel(size_t x, size_t y, uint32_t data) +{ + size_t w = __gfx_w; + if (likely(likely((x) < w) && likely((y) < __gfx_h))) + __gfx_framebuffer[(y) * w + (x)] = (data); +} + +void gfx_fb_set(size_t offset, uint32_t data) +{ + if (likely((offset) < (__gfx_w * __gfx_h))) + __gfx_framebuffer[(offset)] = (data); +} + diff --git a/pool/shard003/C/0066643_gdbus-exit-on-close.c b/pool/shard003/C/0066643_gdbus-exit-on-close.c new file mode 100644 index 0000000000000000000000000000000000000000..3c4e5ecd6f379cdefbcb50deb14fec0bc25dec11 --- /dev/null +++ b/pool/shard003/C/0066643_gdbus-exit-on-close.c @@ -0,0 +1,218 @@ +/* GLib testing framework examples and tests + * + * Copyright (C) 2008-2010 Red Hat, Inc. + * + * 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, see . + * + * Author: David Zeuthen + */ + +#include +#include +#include +#include + +#include "gdbus-tests.h" + +/* all tests rely on a shared mainloop */ +static GMainLoop *loop = NULL; + +/* ---------------------------------------------------------------------------------------------------- */ + +typedef struct { + const gchar *name; + const gchar *bug; + enum { + EXPLICITLY_FALSE = FALSE, + EXPLICITLY_TRUE = TRUE, + IMPLICITLY_TRUE + } exit_on_close; + enum { + LOCAL, + REMOTE + } who_closes; +} TestData; + +static const TestData cases[] = { + { "default", NULL, IMPLICITLY_TRUE, REMOTE }, + { "true", NULL, EXPLICITLY_TRUE, REMOTE }, + { "false", NULL, EXPLICITLY_FALSE, REMOTE }, + { "we-close", "662100", EXPLICITLY_TRUE, LOCAL }, + { NULL } +}; + +static gboolean +quit_later_cb (gpointer data G_GNUC_UNUSED) +{ + g_main_loop_quit (loop); + + return FALSE; +} + +static void +closed_cb (GDBusConnection *c G_GNUC_UNUSED, + gboolean remote_peer_vanished, + GError *error, + gpointer test_data) +{ + const TestData *td = test_data; + + if (error == NULL) + g_debug ("closed (%d, no error)", remote_peer_vanished); + else + g_debug ("closed (%d, %s %d \"%s\")", remote_peer_vanished, + g_quark_to_string (error->domain), error->code, error->message); + + g_assert_cmpint (remote_peer_vanished, ==, (td->who_closes == REMOTE)); + g_assert_cmpint ((error == NULL), ==, (td->who_closes == LOCAL)); + + /* we delay this so that if exit-on-close was going to happen, it will + * win the race + */ + g_timeout_add (50, quit_later_cb, NULL); +} + +static void +close_async_cb (GObject *source G_GNUC_UNUSED, + GAsyncResult *res G_GNUC_UNUSED, + gpointer nil G_GNUC_UNUSED) +{ + GError *error = NULL; + + if (g_dbus_connection_close_finish (G_DBUS_CONNECTION (source), + res, + &error)) + { + g_debug ("closed connection"); + } + else + { + g_warning ("failed to close connection: %s (%s #%d)", + error->message, g_quark_to_string (error->domain), + error->code); + } +} + +static void +test_exit_on_close_subprocess (gconstpointer test_data) +{ + const TestData *td = test_data; + GDBusConnection *c; + + loop = g_main_loop_new (NULL, FALSE); + + session_bus_up (); + c = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL); + + g_assert (c != NULL); + + /* the default is meant to be TRUE */ + if (td->exit_on_close != IMPLICITLY_TRUE) + g_dbus_connection_set_exit_on_close (c, td->exit_on_close); + + g_assert_cmpint (g_dbus_connection_get_exit_on_close (c), ==, + (td->exit_on_close != EXPLICITLY_FALSE)); + g_assert (!g_dbus_connection_is_closed (c)); + + g_timeout_add (50, quit_later_cb, NULL); + g_main_loop_run (loop); + + g_signal_connect (c, "closed", G_CALLBACK (closed_cb), (gpointer) td); + + if (td->who_closes == LOCAL) + { + GVariant *v; + GError *error = NULL; + + v = g_dbus_connection_call_sync (c, "org.freedesktop.DBus", + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + "ListNames", + NULL, + G_VARIANT_TYPE ("(as)"), + G_DBUS_CALL_FLAGS_NONE, + -1, + NULL, + &error); + g_assert_no_error (error); + g_assert (v != NULL); + g_variant_unref (v); + + g_dbus_connection_close (c, NULL, close_async_cb, NULL); + } + else + { + session_bus_stop (); + } + + g_main_loop_run (loop); + /* this is only reached when we turn off exit-on-close */ + g_main_loop_unref (loop); + g_object_unref (c); + + session_bus_down (); + + exit (0); +} + +static void +test_exit_on_close (gconstpointer test_data) +{ + const TestData *td = test_data; + GTestSubprocessFlags flags; + char *child_name; + + g_test_dbus_unset (); + + if (g_test_verbose ()) + flags = G_TEST_SUBPROCESS_INHERIT_STDOUT | G_TEST_SUBPROCESS_INHERIT_STDERR; + else + flags = 0; + + child_name = g_strdup_printf ("/gdbus/exit-on-close/%s/subprocess", td->name); + g_test_trap_subprocess (child_name, 0, flags); + g_free (child_name); + + if (td->exit_on_close == EXPLICITLY_FALSE || + td->who_closes == LOCAL) + g_test_trap_assert_passed (); + else + g_test_trap_assert_failed(); +} + +/* ---------------------------------------------------------------------------------------------------- */ + +int +main (int argc, + char *argv[]) +{ + gint i; + + g_test_init (&argc, &argv, NULL); + + for (i = 0; cases[i].name != NULL; i++) + { + gchar *name; + + name = g_strdup_printf ("/gdbus/exit-on-close/%s", cases[i].name); + g_test_add_data_func (name, &cases[i], test_exit_on_close); + g_free (name); + + name = g_strdup_printf ("/gdbus/exit-on-close/%s/subprocess", cases[i].name); + g_test_add_data_func (name, &cases[i], test_exit_on_close_subprocess); + g_free (name); + } + + return g_test_run(); +} diff --git a/pool/shard003/C/0066654_os-compatibility.c b/pool/shard003/C/0066654_os-compatibility.c new file mode 100644 index 0000000000000000000000000000000000000000..4150db2e50232dcbba548641c8e93d14f7624ced --- /dev/null +++ b/pool/shard003/C/0066654_os-compatibility.c @@ -0,0 +1,62 @@ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "os-compatibility.h" + +static int +create_tmpfile_cloexec(char *tmpname) +{ + int fd; + + fd = mkostemp(tmpname, O_CLOEXEC); + if (fd >= 0) + unlink(tmpname); + + return fd; +} + +int +os_create_anonymous_file(off_t size) +{ + static const char template[] = "/weston-shared-XXXXXX"; + const char *path; + char *name; + int fd; + int ret; + + path = getenv("XDG_RUNTIME_DIR"); + if (!path) { + errno = ENOENT; + return -1; + } + + name = malloc(strlen(path) + sizeof(template)); + if (!name) + return -1; + + strcpy(name, path); + strcat(name, template); + + fd = create_tmpfile_cloexec(name); + + free(name); + + if (fd < 0) + return -1; + + ret = posix_fallocate(fd, 0, size); + if (ret != 0) { + close(fd); + errno = ret; + return -1; + } + + return fd; +} diff --git a/pool/shard003/C/0066657_shpchp_pci.c b/pool/shard003/C/0066657_shpchp_pci.c new file mode 100644 index 0000000000000000000000000000000000000000..469454e0cc48d8eca080dc2f5035f87d83769f53 --- /dev/null +++ b/pool/shard003/C/0066657_shpchp_pci.c @@ -0,0 +1,122 @@ +/* + * Standard Hot Plug Controller Driver + * + * Copyright (C) 1995,2001 Compaq Computer Corporation + * Copyright (C) 2001 Greg Kroah-Hartman (greg@kroah.com) + * Copyright (C) 2001 IBM Corp. + * Copyright (C) 2003-2004 Intel Corporation + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 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, GOOD TITLE or + * NON INFRINGEMENT. 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. + * + * Send feedback to , + * + */ + +#include +#include +#include +#include +#include "../pci.h" +#include "shpchp.h" + +int shpchp_configure_device(struct slot *p_slot) +{ + struct pci_dev *dev; + struct controller *ctrl = p_slot->ctrl; + struct pci_dev *bridge = ctrl->pci_dev; + struct pci_bus *parent = bridge->subordinate; + int num, ret = 0; + + pci_lock_rescan_remove(); + + dev = pci_get_slot(parent, PCI_DEVFN(p_slot->device, 0)); + if (dev) { + ctrl_err(ctrl, "Device %s already exists at %04x:%02x:%02x, cannot hot-add\n", + pci_name(dev), pci_domain_nr(parent), + p_slot->bus, p_slot->device); + pci_dev_put(dev); + ret = -EINVAL; + goto out; + } + + num = pci_scan_slot(parent, PCI_DEVFN(p_slot->device, 0)); + if (num == 0) { + ctrl_err(ctrl, "No new device found\n"); + ret = -ENODEV; + goto out; + } + + list_for_each_entry(dev, &parent->devices, bus_list) { + if (PCI_SLOT(dev->devfn) != p_slot->device) + continue; + if (pci_is_bridge(dev)) + pci_hp_add_bridge(dev); + } + + pci_assign_unassigned_bridge_resources(bridge); + + list_for_each_entry(dev, &parent->devices, bus_list) { + if (PCI_SLOT(dev->devfn) != p_slot->device) + continue; + pci_configure_slot(dev); + } + + pci_bus_add_devices(parent); + + out: + pci_unlock_rescan_remove(); + return ret; +} + +int shpchp_unconfigure_device(struct slot *p_slot) +{ + int rc = 0; + u8 bctl = 0; + struct pci_bus *parent = p_slot->ctrl->pci_dev->subordinate; + struct pci_dev *dev, *temp; + struct controller *ctrl = p_slot->ctrl; + + ctrl_dbg(ctrl, "%s: domain:bus:dev = %04x:%02x:%02x\n", + __func__, pci_domain_nr(parent), p_slot->bus, p_slot->device); + + pci_lock_rescan_remove(); + + list_for_each_entry_safe(dev, temp, &parent->devices, bus_list) { + if (PCI_SLOT(dev->devfn) != p_slot->device) + continue; + + pci_dev_get(dev); + if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE) { + pci_read_config_byte(dev, PCI_BRIDGE_CONTROL, &bctl); + if (bctl & PCI_BRIDGE_CTL_VGA) { + ctrl_err(ctrl, + "Cannot remove display device %s\n", + pci_name(dev)); + pci_dev_put(dev); + rc = -EINVAL; + break; + } + } + pci_stop_and_remove_bus_device(dev); + pci_dev_put(dev); + } + + pci_unlock_rescan_remove(); + return rc; +} + diff --git a/pool/shard003/C/0066672_gegl-operations.c b/pool/shard003/C/0066672_gegl-operations.c new file mode 100644 index 0000000000000000000000000000000000000000..195b6349def3bb3ff4a984ba763b701241867834 --- /dev/null +++ b/pool/shard003/C/0066672_gegl-operations.c @@ -0,0 +1,195 @@ +/* This file is part of GEGL + * + * GEGL 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. + * + * GEGL 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 GEGL; if not, see . + * + * Copyright 2003 Calvin Williamson + * 2005-2008 Øyvind Kolås + * 2013 Michael Henning + */ + +#include "config.h" + +#include +#include + +#include "gegl.h" +#include "gegl-types-internal.h" +#include "gegl-utils.h" +#include "gegl-operation.h" +#include "gegl-operations.h" +#include "graph/gegl-node.h" +#include "graph/gegl-pad.h" +#include "gegl-operation-context.h" +#include "buffer/gegl-region.h" + + +static GHashTable *gtype_hash = NULL; +static GSList *operations_list = NULL; +static guint gtype_hash_serial = 0; +G_LOCK_DEFINE_STATIC (gtype_hash); + +void +gegl_operation_class_register_name (GeglOperationClass *klass, + const gchar *name, + const gboolean is_compat) +{ + GType this_type, check_type; + this_type = G_TYPE_FROM_CLASS (klass); + + G_LOCK (gtype_hash); + + check_type = (GType) g_hash_table_lookup (gtype_hash, name); + if (check_type && check_type != this_type) + { + g_warning ("Adding %s shadows %s for operation %s", + g_type_name (this_type), + g_type_name (check_type), + name); + } + g_hash_table_insert (gtype_hash, g_strdup (name), (gpointer) this_type); + + if (!check_type && !is_compat) + operations_list = g_slist_insert_sorted (operations_list, (gpointer) name, + (GCompareFunc) strcmp); + + G_UNLOCK (gtype_hash); +} + +static void +add_operations (GType parent) +{ + GType *types; + guint count; + guint no; + + types = g_type_children (parent, &count); + if (!types) + return; + + for (no = 0; no < count; no++) + { + /* + * Poke the operation so it registers its name with + * gegl_operation_class_register_name + */ + g_type_class_unref (g_type_class_ref (types[no])); + + add_operations (types[no]); + } + g_free (types); +} + +GType +gegl_operation_gtype_from_name (const gchar *name) +{ + /* If any new modules have been loaded, scan for GeglOperations */ + guint latest_serial; + latest_serial = g_type_get_type_registration_serial (); + if (gtype_hash_serial != latest_serial) + { + add_operations (GEGL_TYPE_OPERATION); + gtype_hash_serial = latest_serial; + } + + return (GType) g_hash_table_lookup (gtype_hash, name); +} + +gboolean +gegl_has_operation (const gchar *operation_type) +{ + return gegl_operation_gtype_from_name (operation_type) != 0; +} + +gchar **gegl_list_operations (guint *n_operations_p) +{ + gchar **pasp = NULL; + gint n_operations; + gint i; + GSList *iter; + gint pasp_size = 0; + gint pasp_pos; + + if (!operations_list) + { + gegl_operation_gtype_from_name (""); + + /* should only happen if no operations are found */ + if (!operations_list) + { + if (n_operations_p) + *n_operations_p = 0; + return NULL; + } + } + + n_operations = g_slist_length (operations_list); + pasp_size += (n_operations + 1) * sizeof (gchar *); + for (iter = operations_list; iter != NULL; iter = g_slist_next (iter)) + { + const gchar *name = iter->data; + pasp_size += strlen (name) + 1; + } + pasp = g_malloc (pasp_size); + pasp_pos = (n_operations + 1) * sizeof (gchar *); + for (iter = operations_list, i = 0; iter != NULL; iter = g_slist_next (iter), i++) + { + const gchar *name = iter->data; + pasp[i] = ((gchar *) pasp) + pasp_pos; + strcpy (pasp[i], name); + pasp_pos += strlen (name) + 1; + } + pasp[i] = NULL; + if (n_operations_p) + *n_operations_p = n_operations; + return pasp; +} + +void +gegl_operation_gtype_init (void) +{ + G_LOCK (gtype_hash); + + if (!gtype_hash) + gtype_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); + + G_UNLOCK (gtype_hash); +} + +void +gegl_operation_gtype_cleanup (void) +{ + G_LOCK (gtype_hash); + if (gtype_hash) + { + g_hash_table_destroy (gtype_hash); + gtype_hash = NULL; + } + G_UNLOCK (gtype_hash); +} + +gboolean gegl_can_do_inplace_processing (GeglOperation *operation, + GeglBuffer *input, + const GeglRectangle *result) +{ + if (!input || + GEGL_IS_CACHE (input)) + return FALSE; + if (gegl_object_get_has_forked (input)) + return FALSE; + + if (input->format == gegl_operation_get_format (operation, "output") && + gegl_rectangle_contains (gegl_buffer_get_extent (input), result)) + return TRUE; + return FALSE; +} diff --git a/pool/shard003/C/0066685_timezone.c b/pool/shard003/C/0066685_timezone.c new file mode 100644 index 0000000000000000000000000000000000000000..596b5da7de38200925490870a94a5bd63285ac81 --- /dev/null +++ b/pool/shard003/C/0066685_timezone.c @@ -0,0 +1,194 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Time Zone Redirection + * + * Copyright 2012 Marc-Andre Moreau + * + * 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. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include + +#include "timezone.h" + +/** + * Read SYSTEM_TIME structure (TS_SYSTEMTIME).\n + * @msdn{cc240478} + * @param s stream + * @param system_time system time structure + */ + +void rdp_read_system_time(STREAM* s, SYSTEM_TIME* system_time) +{ + stream_read_UINT16(s, system_time->wYear); /* wYear, must be set to 0 */ + stream_read_UINT16(s, system_time->wMonth); /* wMonth */ + stream_read_UINT16(s, system_time->wDayOfWeek); /* wDayOfWeek */ + stream_read_UINT16(s, system_time->wDay); /* wDay */ + stream_read_UINT16(s, system_time->wHour); /* wHour */ + stream_read_UINT16(s, system_time->wMinute); /* wMinute */ + stream_read_UINT16(s, system_time->wSecond); /* wSecond */ + stream_read_UINT16(s, system_time->wMilliseconds); /* wMilliseconds */ +} + +/** + * Write SYSTEM_TIME structure (TS_SYSTEMTIME).\n + * @msdn{cc240478} + * @param s stream + * @param system_time system time structure + */ + +void rdp_write_system_time(STREAM* s, SYSTEM_TIME* system_time) +{ + stream_write_UINT16(s, system_time->wYear); /* wYear, must be set to 0 */ + stream_write_UINT16(s, system_time->wMonth); /* wMonth */ + stream_write_UINT16(s, system_time->wDayOfWeek); /* wDayOfWeek */ + stream_write_UINT16(s, system_time->wDay); /* wDay */ + stream_write_UINT16(s, system_time->wHour); /* wHour */ + stream_write_UINT16(s, system_time->wMinute); /* wMinute */ + stream_write_UINT16(s, system_time->wSecond); /* wSecond */ + stream_write_UINT16(s, system_time->wMilliseconds); /* wMilliseconds */ + DEBUG_TIMEZONE("Time: y=%d,m=%d,dow=%d,d=%d, %02d:%02d:%02d.%03d", + system_time->wYear, system_time->wMonth, system_time->wDayOfWeek, + system_time->wDay, system_time->wHour, system_time->wMinute, + system_time->wSecond, system_time->wMilliseconds); +} + +/** + * Read client time zone information (TS_TIME_ZONE_INFORMATION).\n + * @msdn{cc240477} + * @param s stream + * @param settings settings + */ + +BOOL rdp_read_client_time_zone(STREAM* s, rdpSettings* settings) +{ + char* str; + TIME_ZONE_INFO* clientTimeZone; + + if (stream_get_left(s) < 172) + return FALSE; + + clientTimeZone = settings->ClientTimeZone; + + stream_read_UINT32(s, clientTimeZone->bias); /* Bias */ + + /* standardName (64 bytes) */ + ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) stream_get_tail(s), 64 / 2, &str, 0, NULL, NULL); + stream_seek(s, 64); + strncpy(clientTimeZone->standardName, str, sizeof(clientTimeZone->standardName)); + free(str); + + rdp_read_system_time(s, &clientTimeZone->standardDate); /* StandardDate */ + stream_read_UINT32(s, clientTimeZone->standardBias); /* StandardBias */ + + /* daylightName (64 bytes) */ + ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) stream_get_tail(s), 64 / 2, &str, 0, NULL, NULL); + stream_seek(s, 64); + strncpy(clientTimeZone->daylightName, str, sizeof(clientTimeZone->daylightName)); + free(str); + + rdp_read_system_time(s, &clientTimeZone->daylightDate); /* DaylightDate */ + stream_read_UINT32(s, clientTimeZone->daylightBias); /* DaylightBias */ + + return TRUE; +} + +/** + * Write client time zone information (TS_TIME_ZONE_INFORMATION).\n + * @msdn{cc240477} + * @param s stream + * @param settings settings + */ + +void rdp_write_client_time_zone(STREAM* s, rdpSettings* settings) +{ + UINT32 bias; + INT32 sbias; + UINT32 bias2c; + WCHAR* standardName; + WCHAR* daylightName; + int standardNameLength; + int daylightNameLength; + TIME_ZONE_INFO* clientTimeZone; + + clientTimeZone = settings->ClientTimeZone; + freerdp_time_zone_detect(clientTimeZone); + + standardNameLength = ConvertToUnicode(CP_UTF8, 0, clientTimeZone->standardName, -1, &standardName, 0) * 2; + daylightNameLength = ConvertToUnicode(CP_UTF8, 0, clientTimeZone->daylightName, -1, &daylightName, 0) * 2; + + if (standardNameLength > 62) + standardNameLength = 62; + + if (daylightNameLength > 62) + daylightNameLength = 62; + + /* UTC = LocalTime + Bias <-> Bias = UTC - LocalTime */ + + /* Translate from biases used throughout libfreerdp-locale/timezone.c + * to what RDP expects, which is minutes *west* of UTC. + * Though MS-RDPBCGR specifies bias as unsigned, two's complement + * (a negative integer) works fine for zones east of UTC. + */ + + if (clientTimeZone->bias <= 720) + bias = -1 * clientTimeZone->bias; + else + bias = 1440 - clientTimeZone->bias; + + stream_write_UINT32(s, bias); /* Bias */ + + /* standardName (64 bytes) */ + stream_write(s, standardName, standardNameLength); + stream_write_zero(s, 64 - standardNameLength); + + rdp_write_system_time(s, &clientTimeZone->standardDate); /* StandardDate */ + + DEBUG_TIMEZONE("bias=%d stdName='%s' dlName='%s'", + bias, clientTimeZone->standardName, clientTimeZone->daylightName); + + sbias = clientTimeZone->standardBias - clientTimeZone->bias; + + if (sbias < 0) + bias2c = (UINT32) sbias; + else + bias2c = ~((UINT32) sbias) + 1; + + /* Note that StandardBias is ignored if no valid standardDate is provided. */ + stream_write_UINT32(s, bias2c); /* StandardBias */ + DEBUG_TIMEZONE("StandardBias=%d", bias2c); + + /* daylightName (64 bytes) */ + stream_write(s, daylightName, daylightNameLength); + stream_write_zero(s, 64 - daylightNameLength); + + rdp_write_system_time(s, &clientTimeZone->daylightDate); /* DaylightDate */ + + sbias = clientTimeZone->daylightBias - clientTimeZone->bias; + + if (sbias < 0) + bias2c = (UINT32) sbias; + else + bias2c = ~((UINT32) sbias) + 1; + + /* Note that DaylightBias is ignored if no valid daylightDate is provided. */ + stream_write_UINT32(s, bias2c); /* DaylightBias */ + DEBUG_TIMEZONE("DaylightBias=%d", bias2c); + + free(standardName); + free(daylightName); +} diff --git a/pool/shard003/C/0066691_main.c b/pool/shard003/C/0066691_main.c new file mode 100644 index 0000000000000000000000000000000000000000..f387dbdbea7440a092ef51c271bf46904e43565d --- /dev/null +++ b/pool/shard003/C/0066691_main.c @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2021 Inria + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @ingroup tests + * @{ + * + * @file + * @brief Test application for the qr-code-generator package + * + * @author Alexandre Abadie + * + * @} + */ + +#include + +#include +#include + +#include "test_utils/expect.h" + +#include "qrcodegen.h" + +#ifdef MODULE_DISP_DEV +#include "disp_dev.h" +#endif + +#ifndef MESSAGE_TO_ENCODE +#define MESSAGE_TO_ENCODE "unknown" +#endif + +/* Compute buffer sizes based on the message to encode len to avoid a + * failed assertion in qrcodegen */ +#define ENCODER_VERSION (sizeof(MESSAGE_TO_ENCODE) >> 3) +static uint8_t qr0[qrcodegen_BUFFER_LEN_FOR_VERSION(ENCODER_VERSION)]; +static uint8_t buffer[qrcodegen_BUFFER_LEN_FOR_VERSION(ENCODER_VERSION)]; + +#ifdef MODULE_DISP_DEV +#ifdef LCD_SCREEN_WIDTH +#define DISPLAY_BUFFER_MAX_SIZE (LCD_SCREEN_WIDTH) +#else +#define DISPLAY_BUFFER_MAX_SIZE (320) +#endif +static uint16_t display_buffer[DISPLAY_BUFFER_MAX_SIZE] = { 0 }; +#endif + +int main(void) +{ + expect(ENCODER_VERSION <= qrcodegen_VERSION_MAX); + + if (!qrcodegen_encodeText(MESSAGE_TO_ENCODE, + buffer, qr0, qrcodegen_Ecc_MEDIUM, + qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, + qrcodegen_Mask_AUTO, true)) { + puts("Encoding error"); + return -1; + } + + int size = qrcodegen_getSize(qr0); + +#ifdef MODULE_DISP_DEV + /* Use the first screen */ + disp_dev_reg_t *disp_dev = disp_dev_reg_find_screen(0); + if (!disp_dev) { + puts("No screen found!"); + return -1; + } + disp_dev_backlight_on(); + + /* Compute scaling factor and height/width offsets */ + const uint8_t scale = disp_dev_height(disp_dev->dev) / size; + const uint8_t w_offset = (disp_dev_width(disp_dev->dev) - (size * scale)) / 2; + const uint8_t h_offset = (disp_dev_height(disp_dev->dev) - (size * scale)) / 2; + + /* Clear the screen */ + for (uint16_t y = 0; y < disp_dev_height(disp_dev->dev); y ++) { + disp_dev_map(disp_dev->dev, 0, disp_dev_width(disp_dev->dev) - 1, y, y, display_buffer); + } + + /* Prepare a subset of the display buffer for white tiles */ + for (int w = 0; w < scale; w++) { + for (int h = 0; h < scale; h++) { + display_buffer[w + h * scale] = UINT16_MAX; + } + } +#endif + + for (int y = 0; y < size; y++) { + for (int x = 0; x < size; x++) { +#ifdef MODULE_DISP_DEV + if (qrcodegen_getModule(qr0, x, y)) { + disp_dev_map(disp_dev->dev, + w_offset + (x * scale), w_offset + ((x + 1)* scale) - 1, + h_offset + (y * scale), h_offset + ((y + 1)* scale) - 1, + display_buffer); + } +#endif + printf("%s", qrcodegen_getModule(qr0, x, y) ? "██" : " "); + + } + puts(""); + } + + return 0; +} diff --git a/pool/shard003/C/0066696_puppy.c b/pool/shard003/C/0066696_puppy.c new file mode 100644 index 0000000000000000000000000000000000000000..fb636aad4e9d66b35c8d328d9963dc54f0a3da03 --- /dev/null +++ b/pool/shard003/C/0066696_puppy.c @@ -0,0 +1,90 @@ +#include "distro/puppy.h" + +#include +#include + +#include "distro/distro-utils.h" +#include "utils.h" + +distro_info_node_t *distro_puppy(string_node_t *files, const char *dst, const char *name, lickdir_t *lick) { + distro_info_t *i = new_empty_distro_info(); + size_t initrd_str_len = 0; + + for(const string_node_t *f = files; f != NULL; f = f->next) { + const char *n = f->val; + + if(i->kernel == NULL && (strstr(n, "vmlinu") || strstr(n, "VMLINU"))) { + i->kernel = menu_path(concat_strs(3, dst, "/", n)); + } + if(strstr(n, "initr") || strstr(n, "INITR")) { + // Issue #32 has an example of when an ISO might have two + // initrd files: `initrd` and `initrd-nano.xz`. As a + // heuristic, take the one with the smaller name. + const size_t n_len = strlen(n); + if (i->initrd == NULL || n_len < initrd_str_len) { + if (i->initrd) { + free(i->initrd); + } + i->initrd = menu_path(concat_strs(3, dst, "/", n)); + initrd_str_len = n_len; + } + } + } + + // Make sure we have a kernel. Without this, we segfault when generating + // a menu entry (and it doesn't make sense to continue + // if we don't have a kernel). + if(i->kernel == NULL) { + free_distro_info(i); + if(lick->err == NULL) + lick->err = strdup2("No kernel found"); + return NULL; + } + + char *dst_menu_full = menu_path(strdup2(dst)); + char *dst_menu = dst_menu_full; + while(*dst_menu == '/') + ++dst_menu; + distro_info_node_t *ret = NULL; + if(i->kernel) { + distro_info_t *i2 = copy_distro_info(i); + i->options = concat_strs(2, "pfix=fsck dofsck psubdir=", dst_menu); + // TODO: savefile=none and dofsck is for fatdog. + // Fatdog should probably be its own distro + i2->options = concat_strs(2, + "pfix=ram savefile=none psubdir=", dst_menu); + i2->name = concat_strs(2, name, " (no save file)"); + ret = new_distro_info_node_t(i2, ret); + } + i->name = strdup2(name); + ret = new_distro_info_node_t(i, ret); + + free(dst_menu_full); + return ret; +} + +int distro_puppy_filter(const char *f) { + if(!strcasecmp(f, "boot.cat") + || !strcasecmp(f, "boot.msg") + || !strcasecmp(f, "help.msg") + || !strcasecmp(f, "help2.msg") + || !strcasecmp(f, "isolinux.bin") + || !strcasecmp(f, "isolinux.cfg") + || !strcasecmp(f, "logo.16") + || !strcasecmp(f, "README.HTM") + || strstr(f, "/")) { + return 0; + } + + return 1; +} + +distro_t *get_distro_puppy() { + return new_distro( + DISTRO_PUPPY, + DISTRO_PUPPY_KEY, + "Puppy Linux", + distro_puppy, + distro_puppy_filter + ); +} diff --git a/pool/shard003/C/0066697_intel_gt_pm_irq.c b/pool/shard003/C/0066697_intel_gt_pm_irq.c new file mode 100644 index 0000000000000000000000000000000000000000..811a11ed181cdf521182e9b27bde89542bd36dee --- /dev/null +++ b/pool/shard003/C/0066697_intel_gt_pm_irq.c @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: MIT +/* + * Copyright © 2019 Intel Corporation + */ + +#include "i915_drv.h" +#include "i915_reg.h" +#include "intel_gt.h" +#include "intel_gt_irq.h" +#include "intel_gt_pm_irq.h" + +static void write_pm_imr(struct intel_gt *gt) +{ + struct drm_i915_private *i915 = gt->i915; + struct intel_uncore *uncore = gt->uncore; + u32 mask = gt->pm_imr; + i915_reg_t reg; + + if (INTEL_GEN(i915) >= 11) { + reg = GEN11_GPM_WGBOXPERF_INTR_MASK; + mask <<= 16; /* pm is in upper half */ + } else if (INTEL_GEN(i915) >= 8) { + reg = GEN8_GT_IMR(2); + } else { + reg = GEN6_PMIMR; + } + + intel_uncore_write(uncore, reg, mask); +} + +static void gen6_gt_pm_update_irq(struct intel_gt *gt, + u32 interrupt_mask, + u32 enabled_irq_mask) +{ + u32 new_val; + + WARN_ON(enabled_irq_mask & ~interrupt_mask); + + lockdep_assert_held(>->irq_lock); + + new_val = gt->pm_imr; + new_val &= ~interrupt_mask; + new_val |= ~enabled_irq_mask & interrupt_mask; + + if (new_val != gt->pm_imr) { + gt->pm_imr = new_val; + write_pm_imr(gt); + } +} + +void gen6_gt_pm_unmask_irq(struct intel_gt *gt, u32 mask) +{ + gen6_gt_pm_update_irq(gt, mask, mask); +} + +void gen6_gt_pm_mask_irq(struct intel_gt *gt, u32 mask) +{ + gen6_gt_pm_update_irq(gt, mask, 0); +} + +void gen6_gt_pm_reset_iir(struct intel_gt *gt, u32 reset_mask) +{ + struct intel_uncore *uncore = gt->uncore; + i915_reg_t reg = INTEL_GEN(gt->i915) >= 8 ? GEN8_GT_IIR(2) : GEN6_PMIIR; + + lockdep_assert_held(>->irq_lock); + + intel_uncore_write(uncore, reg, reset_mask); + intel_uncore_write(uncore, reg, reset_mask); + intel_uncore_posting_read(uncore, reg); +} + +static void write_pm_ier(struct intel_gt *gt) +{ + struct drm_i915_private *i915 = gt->i915; + struct intel_uncore *uncore = gt->uncore; + u32 mask = gt->pm_ier; + i915_reg_t reg; + + if (INTEL_GEN(i915) >= 11) { + reg = GEN11_GPM_WGBOXPERF_INTR_ENABLE; + mask <<= 16; /* pm is in upper half */ + } else if (INTEL_GEN(i915) >= 8) { + reg = GEN8_GT_IER(2); + } else { + reg = GEN6_PMIER; + } + + intel_uncore_write(uncore, reg, mask); +} + +void gen6_gt_pm_enable_irq(struct intel_gt *gt, u32 enable_mask) +{ + lockdep_assert_held(>->irq_lock); + + gt->pm_ier |= enable_mask; + write_pm_ier(gt); + gen6_gt_pm_unmask_irq(gt, enable_mask); +} + +void gen6_gt_pm_disable_irq(struct intel_gt *gt, u32 disable_mask) +{ + lockdep_assert_held(>->irq_lock); + + gt->pm_ier &= ~disable_mask; + gen6_gt_pm_mask_irq(gt, disable_mask); + write_pm_ier(gt); +} diff --git a/pool/shard003/C/0066700_toggle_select.c b/pool/shard003/C/0066700_toggle_select.c new file mode 100644 index 0000000000000000000000000000000000000000..f3e7a51a07c495aabd216c922bff4bd964b44911 --- /dev/null +++ b/pool/shard003/C/0066700_toggle_select.c @@ -0,0 +1,201 @@ +/* + This project 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. + + Deviation 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 Deviation. If not, see . + */ + +#include "common.h" +#include "pages.h" +#include "gui/gui.h" +#include "config/model.h" + +static struct toggleselect_obj * const gui = &gui_objs.u.toggleselect; +static struct toggle_select_page * const tp = &pagemem.u.toggle_select_page; + +static const int NUM_COLS = 8; + +#include "../common/_toggle_select.c" + +static unsigned _action_cb(u32 button, unsigned flags, void *data); +static s8 current_toggleicon = 0; + +static void tglico_select_cb(guiObject_t *obj, s8 press_type, const void *data) +{ + (void)obj; + if (press_type == -1) { + // --> data = (ToggleNumber << 12) | (IconNumber << 8) | IconPosition + u8 IconPosition = ((long)data ) & 0xff; + u8 IconNumber = ((long)data >> 8 ) & 0x0f; + Model.pagecfg2.elem[tp->tglidx].extra[IconNumber] = IconPosition; + show_iconsel_page(IconNumber); + } +} + +static void revert_cb(guiObject_t *obj, const void *data) +{ + (void)data; + (void)obj; + memcpy(Model.pagecfg2.elem[tp->tglidx].extra, tp->tglicons, sizeof(tp->tglicons)); + show_iconsel_page(0); +} + +static guiObject_t *getobj_cb(int relrow, int col, void *data) +{ + (void)data; + int idx; + if (col == -1) { + idx = relrow * NUM_COLS + NUM_COLS -1; + if (relrow == 3) { + while(! OBJ_IS_USED(&gui->symbolicon[idx])) + idx--; + } + } else { + idx = relrow * NUM_COLS + col; + } + return (guiObject_t *)&gui->symbolicon[idx]; +} + +static int row_cb(int absrow, int relrow, int y, void *data) +{ + int SelectedIcon = (long)data; + struct ImageMap img; + int idx = 0; + int i; + for(i = 0; i < NUM_COLS * absrow; i++) { + idx = get_next_icon(idx); + if (idx < 0) { + return 0; + } + } + for(i = 0; i < NUM_COLS; i++) { + img = TGLICO_GetImage(idx); + int x = 22 + i * (TOGGLEICON_WIDTH+4); + GUI_CreateImageOffset(&gui->symbolicon[relrow * NUM_COLS + i], x, y, TOGGLEICON_WIDTH, TOGGLEICON_HEIGHT, + img.x_off, img.y_off, img.file, tglico_select_cb, + (void *)((long)(SelectedIcon << 8) | idx)); + idx = get_next_icon(idx); + if(idx < 0) + break; + } + return i; +} + +static void show_iconsel_page(int SelectedIcon) +{ + struct ImageMap img; + u16 w; + PAGE_RemoveAllObjects(); + PAGE_SetActionCB(_action_cb); + PAGE_SetModal(0); + memset(gui, 0, sizeof(*gui)); + current_toggleicon = SelectedIcon; + u8 toggleinput = MIXER_SRC(Model.pagecfg2.elem[tp->tglidx].src); + int num_positions = INPUT_NumSwitchPos(toggleinput); + if(num_positions < 2) + num_positions = 2; + + //Header + PAGE_ShowHeader(INPUT_SourceNameAbbrevSwitch(tempstring, toggleinput)); + labelDesc.style = LABEL_CENTER; + w = 50; + GUI_CreateButtonPlateText(&gui->revert, LCD_WIDTH - w, 0, w, ITEM_HEIGHT, &labelDesc, NULL, 0, revert_cb, (void *)_tr("Revert")); + + labelDesc.style = LABEL_UNDERLINE; + + GUI_CreateRect(&gui->separator, 12 + TOGGLEICON_WIDTH, ITEM_HEIGHT, 1, LCD_HEIGHT-ITEM_HEIGHT, &labelDesc); + + int row = ITEM_HEIGHT + 5; + GUI_CreateLabelBox(&gui->togglelabel[0], 0, row, 10, ITEM_HEIGHT, SelectedIcon == 0 ? &labelDesc : &DEFAULT_FONT, NULL, NULL, "0:"); + img = TGLICO_GetImage(Model.pagecfg2.elem[tp->tglidx].extra[0]); + GUI_CreateImageOffset(&gui->toggleicon[0], 10, row, TOGGLEICON_WIDTH, TOGGLEICON_HEIGHT, img.x_off, img.y_off, img.file, + NULL, //SelectedIcon == 0 ? tglico_reset_cb : tglico_setpos_cb, + (void *)0L); + + row += ITEM_HEIGHT + 2; + GUI_CreateLabelBox(&gui->togglelabel[1], 0, row, 10, ITEM_HEIGHT, SelectedIcon == 1 ? &labelDesc : &DEFAULT_FONT, NULL, NULL, "1:"); + img = TGLICO_GetImage(Model.pagecfg2.elem[tp->tglidx].extra[1]); + GUI_CreateImageOffset(&gui->toggleicon[1], 10, row, TOGGLEICON_WIDTH, TOGGLEICON_HEIGHT, img.x_off, img.y_off, img.file, + NULL, //SelectedIcon == 1 ? tglico_reset_cb : tglico_setpos_cb, + (void *)1L); + + if (num_positions == 3) { + row += ITEM_HEIGHT + 2; + GUI_CreateLabelBox(&gui->togglelabel[2], 0, row, 10, ITEM_HEIGHT, SelectedIcon == 2 ? &labelDesc : &DEFAULT_FONT, NULL, NULL, "2:"); + img = TGLICO_GetImage(Model.pagecfg2.elem[tp->tglidx].extra[2]); + GUI_CreateImageOffset(&gui->toggleicon[2], 10, row, TOGGLEICON_WIDTH, TOGGLEICON_HEIGHT, img.x_off, img.y_off, img.file, + NULL, //SelectedIcon == 2 ? tglico_reset_cb : tglico_setpos_cb, + (void *)2L); + } + + int count = get_toggle_icon_count(); + int rows = (count + NUM_COLS - 1) / NUM_COLS; + + GUI_CreateScrollable(&gui->scrollable, 22, ITEM_HEIGHT + 2, LCD_WIDTH - 22, 4 *(TOGGLEICON_HEIGHT + 1), + TOGGLEICON_HEIGHT + 1, rows, row_cb, getobj_cb, NULL, (void *)(long)SelectedIcon); + //GUI_SetSelected(GUI_ShowScrollableRowOffset(&gui->scrollable, Model.pagecfg.tglico[tp->tglidx][SelectedIcon])); +} + +void navigate_toggleicons(s8 direction) { + u8 toggleinput = MIXER_SRC(Model.pagecfg2.elem[tp->tglidx].src); + int num_positions = INPUT_NumSwitchPos(toggleinput); + if(num_positions < 2) + num_positions = 2; + current_toggleicon += direction; + if (current_toggleicon < 0) + current_toggleicon = num_positions -1; + else if (current_toggleicon >= num_positions) + current_toggleicon = 0; + show_iconsel_page(current_toggleicon); +} + +void navigate_symbolicons(s8 direction) { + guiObject_t *obj = GUI_GetSelected(); + if (direction == -1) + GUI_SetSelected((guiObject_t *)GUI_GetPrevSelectable(obj)); + else + GUI_SetSelected((guiObject_t *)GUI_GetNextSelectable(obj)); + return; + obj = GUI_GetSelected(); + if (obj == (guiObject_t *)&gui->toggleicon[0] + || obj == (guiObject_t *)&gui->toggleicon[1] + || obj == (guiObject_t *)&gui->toggleicon[2]) + { + // skip toggle icon for right/left pressing + if (direction == -1) + GUI_SetSelected((guiObject_t *)&gui->revert); + else { + GUI_SetSelected((guiObject_t *)&gui->symbolicon[0]); + } + } +} + +unsigned _action_cb(u32 button, unsigned flags, void *data) +{ + (void)data; + if ((flags & BUTTON_PRESS) || (flags & BUTTON_LONGPRESS)) { + if (CHAN_ButtonIsPressed(button, BUT_EXIT)) + PAGE_MainLayoutInit(-1); + else if (CHAN_ButtonIsPressed(button, BUT_UP)) + navigate_toggleicons(-1); + else if (CHAN_ButtonIsPressed(button, BUT_DOWN)) + navigate_toggleicons(1); + else if (CHAN_ButtonIsPressed(button, BUT_LEFT)) + navigate_symbolicons(-1); + else if (CHAN_ButtonIsPressed(button, BUT_RIGHT)) + navigate_symbolicons(1); + else { + // only one callback can handle a button press, so we don't handle BUT_ENTER here, let it handled by press cb + return 0; + } + } + return 1; +} diff --git a/pool/shard003/C/0066709_listtab.c b/pool/shard003/C/0066709_listtab.c new file mode 100644 index 0000000000000000000000000000000000000000..3972cfe8d11a50dca95b7a35b35ead3b62fe5ef1 --- /dev/null +++ b/pool/shard003/C/0066709_listtab.c @@ -0,0 +1,64 @@ +/*! + \file db/drivers/listtab.c + + \brief Low level OGR SQL driver + + (C) 2004-2009 by the GRASS Development Team + This program is free software under the GNU General Public License + (>=v2). Read the file COPYING that comes with GRASS for details. + + \author Radim Blazek + \author Some updates by Martin Landa +*/ + +#include +#include +#include + +#include + +#include "globals.h" +#include "proto.h" + +/*! + \brief List tables + + \param[out] tlist list of tables + \param[out] tcount number of tables + \param system list also system tables (unused) + + \return DB_OK on success + \return DB_FAILED on failure +*/ +int db__driver_list_tables(dbString ** tlist, int *tcount, int system) +{ + int i, nlayers; + dbString *list; + OGRLayerH hLayer; + OGRFeatureDefnH hFeatureDefn; + + init_error(); + *tlist = NULL; + *tcount = 0; + + nlayers = OGR_DS_GetLayerCount(hDs); + G_debug(3, "%d layers found", nlayers); + + list = db_alloc_string_array(nlayers); + + if (list == NULL) { + append_error(_("Unable to db_alloc_string_array()")); + report_error(); + return DB_FAILED; + } + + for (i = 0; i < nlayers; i++) { + hLayer = OGR_DS_GetLayer(hDs, i); + hFeatureDefn = OGR_L_GetLayerDefn(hLayer); + db_set_string(&(list[i]), (char *)OGR_FD_GetName(hFeatureDefn)); + } + + *tlist = list; + *tcount = nlayers; + return DB_OK; +} diff --git a/pool/shard003/C/0066717_gendb.c b/pool/shard003/C/0066717_gendb.c new file mode 100644 index 0000000000000000000000000000000000000000..aa2130bb0783dbc8321a31fd0f9e4955ef9c44d3 --- /dev/null +++ b/pool/shard003/C/0066717_gendb.c @@ -0,0 +1,122 @@ +/* + Unix SMB/CIFS implementation. + + common share info functions + + Copyright (C) Andrew Tridgell 2004 + Copyright (C) Tim Potter 2004 + + 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., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +#include "includes.h" +#include "lib/ldb/include/ldb.h" +#include "lib/ldb/include/ldb_errors.h" + +/* + search the sam for the specified attributes - va_list variant +*/ +int gendb_search_v(struct ldb_context *ldb, + TALLOC_CTX *mem_ctx, + struct ldb_dn *basedn, + struct ldb_message ***msgs, + const char * const *attrs, + const char *format, + va_list ap) _PRINTF_ATTRIBUTE(6,0) +{ + enum ldb_scope scope = LDB_SCOPE_SUBTREE; + struct ldb_result *res; + char *expr = NULL; + int ret; + + if (format) { + expr = talloc_vasprintf(mem_ctx, format, ap); + if (expr == NULL) { + return -1; + } + } else { + scope = LDB_SCOPE_BASE; + } + + res = NULL; + + ret = ldb_search(ldb, basedn, scope, expr, attrs, &res); + + if (ret == LDB_SUCCESS) { + talloc_steal(mem_ctx, res->msgs); + + DEBUG(6,("gendb_search_v: %s %s -> %d\n", + basedn?ldb_dn_get_linearized(basedn):"NULL", + expr?expr:"NULL", res->count)); + + ret = res->count; + *msgs = res->msgs; + talloc_free(res); + } else { + DEBUG(4,("gendb_search_v: search failed: %s", ldb_errstring(ldb))); + ret = -1; + } + + talloc_free(expr); + + return ret; +} + +/* + search the LDB for the specified attributes - varargs variant +*/ +int gendb_search(struct ldb_context *ldb, + TALLOC_CTX *mem_ctx, + struct ldb_dn *basedn, + struct ldb_message ***res, + const char * const *attrs, + const char *format, ...) _PRINTF_ATTRIBUTE(6,7) +{ + va_list ap; + int count; + + va_start(ap, format); + count = gendb_search_v(ldb, mem_ctx, basedn, res, attrs, format, ap); + va_end(ap); + + return count; +} + +/* + search the LDB for a specified record (by DN) +*/ + +int gendb_search_dn(struct ldb_context *ldb, + TALLOC_CTX *mem_ctx, + struct ldb_dn *dn, + struct ldb_message ***res, + const char * const *attrs) +{ + return gendb_search(ldb, mem_ctx, dn, res, attrs, NULL); +} + +/* + setup some initial ldif in a ldb +*/ +int gendb_add_ldif(struct ldb_context *ldb, const char *ldif_string) +{ + struct ldb_ldif *ldif; + int ret; + ldif = ldb_ldif_read_string(ldb, &ldif_string); + if (ldif == NULL) return -1; + ret = ldb_add(ldb, ldif->msg); + talloc_free(ldif); + return ret; +} diff --git a/pool/shard003/C/0066728_pcf8591.c b/pool/shard003/C/0066728_pcf8591.c new file mode 100644 index 0000000000000000000000000000000000000000..0c860564fde29f142e64da9f6b443c9cd14cf81d --- /dev/null +++ b/pool/shard003/C/0066728_pcf8591.c @@ -0,0 +1,90 @@ +/* + * pcf8591.c: + * Extend wiringPi with the PCF8591 I2C GPIO Analog expander chip + * The chip has 1 8-bit DAC and 4 x 8-bit ADCs + * Copyright (c) 2013 Gordon Henderson + *********************************************************************** + * This file is part of wiringPi: + * https://projects.drogon.net/raspberry-pi/wiringpi/ + * + * wiringPi 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. + * + * wiringPi 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 wiringPi. + * If not, see . + *********************************************************************** + */ + +#include + +#include "wiringPi.h" +#include "wiringPiI2C.h" + +#include "pcf8591.h" + + +/* + * myAnalogWrite: + ********************************************************************************* + */ + +static void myAnalogWrite (struct wiringPiNodeStruct *node, int pin, int value) +{ + unsigned char b [2] ; + b [0] = 0x40 ; + b [1] = value & 0xFF ; + write (node->fd, b, 2) ; +} + + +/* + * myAnalogRead: + ********************************************************************************* + */ + +static int myAnalogRead (struct wiringPiNodeStruct *node, int pin) +{ + int x ; + + wiringPiI2CWrite (node->fd, 0x40 | ((pin - node->pinBase) & 3)) ; + + x = wiringPiI2CRead (node->fd) ; // Throw away the first read + x = wiringPiI2CRead (node->fd) ; + + return x ; +} + + +/* + * pcf8591Setup: + * Create a new instance of a PCF8591 I2C GPIO interface. We know it + * has 4 pins, (4 analog inputs and 1 analog output which we'll shadow + * input 0) so all we need to know here is the I2C address and the + * user-defined pin base. + ********************************************************************************* + */ + +int pcf8591Setup (const int pinBase, const int i2cAddress) +{ + int fd ; + struct wiringPiNodeStruct *node ; + + if ((fd = wiringPiI2CSetup (i2cAddress)) < 0) + return fd ; + + node = wiringPiNewNode (pinBase, 4) ; + + node->fd = fd ; + node->analogRead = myAnalogRead ; + node->analogWrite = myAnalogWrite ; + + return 0 ; +} diff --git a/pool/shard003/C/0066729_main.c b/pool/shard003/C/0066729_main.c new file mode 100644 index 0000000000000000000000000000000000000000..0696ae241b3c091e776797a953388166e9d8d245 --- /dev/null +++ b/pool/shard003/C/0066729_main.c @@ -0,0 +1,178 @@ +/* +\\ "Polymorph" +// +\\ Virtual Machine and Emulator Stack +*/ +#include "plugin.h" + +STATIC CONST USED struct Resident RomTag = +{ + RTC_MATCHWORD, + ( struct Resident* ) &RomTag, + ( struct Resident* ) &RomTag + 1, + RTF_AUTOINIT|RTF_NATIVE, + LIBRARY_VERSION, + NT_LIBRARY, + 0, + (APTR) LibName, + (APTR) LibIdentity, + (APTR) InitTable +}; + +CONST APTR LibManagerTable[] = +{ + (APTR)&MCALL_Obtain, + (APTR)&MCALL_Release, + NULL, + NULL, + (APTR)&LCALL_Open, + (APTR)&LCALL_Close, + (APTR)&LCALL_Expunge, + NULL, + (APTR)-1 +}; + +CONST struct TagItem LibManagerTags[] = +{ + { MIT_Name, (ULONG)"__library" }, + { MIT_VectorTable, (ULONG)LibManagerTable }, + { MIT_Version, 1 }, + { TAG_END, 0} +}; + +CONST struct TagItem InitTable[] = +{ + { CLT_DataSize, sizeof( struct LIBRARY_CLASS ) }, + { CLT_InitFunc, ( ULONG ) LCALL_Init }, + { CLT_Interfaces, ( ULONG ) LibInterfaces }, + { CLT_NoLegacyIFace, TRUE }, + {TAG_END, 0} +}; + +STATIC CONST BYTE LibName[] = LIBRARY_NAME; +STATIC CONST BYTE LibIdentity[] = LIBRARY_IDENTITY; + +int32 _start(void) +{ + return -1; +} + +struct library *LCALL_Init(struct LIBRARY_CLASS *Self, + BPTR SegmentList, + struct Interface *Executive) +{ + APTR rc=Self; + struct ExecIFace *IExec = (struct ExecIFace *)Executive; + struct Library *Base = NULL; + + Self->IExec = (struct ExecIFace *)Executive; + Self->Library.lib_Node.ln_Type = NT_LIBRARY; + Self->Library.lib_Node.ln_Pri = 0; + Self->Library.lib_Node.ln_Name = (APTR)LibName; + Self->Library.lib_Flags = LIBF_SUMUSED | LIBF_CHANGED; + Self->Library.lib_Version = LIBRARY_VERSION; + Self->Library.lib_Revision = LIBRARY_REVISION; + Self->Library.lib_IdString = (APTR)LibIdentity; + Self->SegmentList = SegmentList; + + if((Base = IExec->OpenLibrary("graphics.library",50L))) + Self->IGfx = (APTR)IExec->GetInterface(Base,"main",1L,NULL); + + if((Base = IExec->OpenLibrary("intuition.library",50L))) + Self->IIntuition = (APTR)IExec->GetInterface(Base,"main",1L,NULL); + + if((Base = IExec->OpenLibrary("dos.library",53L))) + Self->IDOS = (APTR)IExec->GetInterface(Base,"main",1L,NULL); + + if((Base = IExec->OpenLibrary("utility.library",50L))) + Self->IUtility = (APTR)IExec->GetInterface(Base,"main",1L,NULL); + + if((Base = IExec->OpenLibrary("locale.library",50L))) + Self->ILocale = (APTR)IExec->GetInterface(Base,"main",1L,NULL); + + return(rc); +} + +struct Library *LCALL_Open(struct LibraryManagerInterface *Iface, ULONG version) +{ + APTR rc = (APTR) Iface->Data.LibBase; + struct LIBRARY_CLASS *Self = (APTR) Iface->Data.LibBase; + Self->Library.lib_Flags &= ~LIBF_DELEXP; + Self->Library.lib_OpenCnt++; + return(rc); +} + +APTR LCALL_Close(struct LibraryManagerInterface *Iface) +{ + APTR rc=NULL; + struct LIBRARY_CLASS *Self = (APTR) Iface->Data.LibBase; + Self->Library.lib_OpenCnt--; + return(rc); +} + +APTR LCALL_Expunge(struct LibraryManagerInterface *Iface) +{ + struct ExecIFace *IExec = (struct ExecIFace *)(*(struct ExecBase **)4)->MainInterface; + APTR rc=NULL; + struct LIBRARY_CLASS *Self = (APTR) Iface->Data.LibBase; + struct Library *Base = NULL; + if(Self->Library.lib_OpenCnt) + { + Self->Library.lib_Flags |= LIBF_DELEXP; + }else{ + + if(Self->ILocale) + { + Base = Self->ILocale->Data.LibBase; + IExec->DropInterface((APTR)Self->ILocale); + IExec->CloseLibrary((APTR)Base); + } + + if(Self->IUtility) + { + Base = Self->IUtility->Data.LibBase; + IExec->DropInterface((APTR)Self->IUtility); + IExec->CloseLibrary((APTR)Base); + } + + if(Self->IDOS) + { + Base = Self->IDOS->Data.LibBase; + IExec->DropInterface((APTR)Self->IDOS); + IExec->CloseLibrary((APTR)Base); + } + + if(Self->IIntuition) + { + Base = Self->IIntuition->Data.LibBase; + IExec->DropInterface((APTR)Self->IIntuition); + IExec->CloseLibrary((APTR)Base); + } + + if(Self->IGfx) + { + Base = Self->IGfx->Data.LibBase; + IExec->DropInterface((APTR)Self->IGfx); + IExec->CloseLibrary((APTR)Base); + } + + IExec->Remove((APTR)Self); + IExec->DeleteLibrary((APTR)Self); + }; + return(rc); +} + +APTR LCALL_Reserved(void) +{ + return(NULL); +} + +ULONG MCALL_Obtain(struct Interface *Iface) +{ + return(Iface->Data.RefCount++); +}; + +ULONG MCALL_Release(struct Interface *Iface) +{ + return(Iface->Data.RefCount--); +}; diff --git a/pool/shard003/C/0066745_pl190.c b/pool/shard003/C/0066745_pl190.c new file mode 100644 index 0000000000000000000000000000000000000000..26ee4e57f07698101fc5d58681c47af9bce71df2 --- /dev/null +++ b/pool/shard003/C/0066745_pl190.c @@ -0,0 +1,201 @@ +/** + * Copyright (c) 2012 Jean-Christophe Dubois. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * @file pl190.c + * @author Jean-Christophe Dubois (jcd@tribudubois.net) + * @brief PL190 Vectored Interrupt Controller source + */ + +#include +#include + +#define VERSATILE_VIC_MAX_NR 1 + +struct pl190_chip_data { + u32 irq_offset; + virtual_addr_t cpu_base; +}; + +static struct pl190_chip_data pl190_data[VERSATILE_VIC_MAX_NR]; + +static inline void pl190_write(u32 val, virtual_addr_t addr) +{ + arch_writel(val, (void *)(addr)); +} + +static inline u32 pl190_read(virtual_addr_t addr) +{ + return arch_readl((void *)(addr)); +} + +int pl190_active_irq(u32 pl190_nr) +{ + u32 int_status; + + if (VERSATILE_VIC_MAX_NR <= pl190_nr) { + return -1; + } + + int_status = + pl190_read(pl190_data[pl190_nr].cpu_base + + PL190_IRQ_STATUS); + + if (int_status) { + int ret; + + for (ret = 0; ret < 32; ret++) { + if ((int_status >> ret) & 1) { + break; + } + } + + ret += pl190_data[pl190_nr].irq_offset; + + return ret; + } else { + return -1; + } +} + +int pl190_eoi_irq(u32 pl190_nr, u32 irq) +{ + u32 mask; + + if (VERSATILE_VIC_MAX_NR <= pl190_nr) { + return -1; + } + + if (irq < pl190_data[pl190_nr].irq_offset) { + return -1; + } + + mask = 1 << (irq - pl190_data[pl190_nr].irq_offset); + + pl190_write(mask, + pl190_data[pl190_nr].cpu_base + + PL190_INT_ENABLE_CLEAR); + + pl190_write(mask, + pl190_data[pl190_nr].cpu_base + + PL190_INT_SOFT_CLEAR); + + pl190_write(mask, + pl190_data[pl190_nr].cpu_base + + PL190_INT_ENABLE); + + return 0; +} + +int pl190_mask(u32 pl190_nr, u32 irq) +{ + u32 mask; + + if (VERSATILE_VIC_MAX_NR <= pl190_nr) { + return -1; + } + + if (irq < pl190_data[pl190_nr].irq_offset) { + return -1; + } + + mask = 1 << (irq - pl190_data[pl190_nr].irq_offset); + + pl190_write(mask, + pl190_data[pl190_nr].cpu_base + + PL190_INT_ENABLE_CLEAR); + + return 0; +} + +int pl190_unmask(u32 pl190_nr, u32 irq) +{ + u32 mask; + + if (VERSATILE_VIC_MAX_NR <= pl190_nr) { + return -1; + } + + if (irq < pl190_data[pl190_nr].irq_offset) { + return -1; + } + + mask = 1 << (irq - pl190_data[pl190_nr].irq_offset); + + pl190_write(mask, + pl190_data[pl190_nr].cpu_base + + PL190_INT_ENABLE); + + return 0; +} + +int pl190_cpu_init(u32 pl190_nr, virtual_addr_t base) +{ + //unsigned int i; + + if (pl190_nr >= VERSATILE_VIC_MAX_NR) { + return -1; + } + + pl190_data[pl190_nr].cpu_base = base; + + /* We have 32 interrupts per PL190 */ + pl190_data[pl190_nr].irq_offset = 32 * pl190_nr; + + pl190_write(0, + pl190_data[pl190_nr].cpu_base + + PL190_INT_SELECT); + pl190_write(0, + pl190_data[pl190_nr].cpu_base + + PL190_INT_ENABLE); + pl190_write(~0, + pl190_data[pl190_nr].cpu_base + + PL190_INT_ENABLE_CLEAR); + pl190_write(0, + pl190_data[pl190_nr].cpu_base + + PL190_IRQ_STATUS); + pl190_write(0, pl190_data[pl190_nr].cpu_base + PL190_ITCR); + pl190_write(~0, + pl190_data[pl190_nr].cpu_base + + PL190_INT_SOFT_CLEAR); + +#if 0 + pl190_write(0, + pl190_data[pl190_nr].cpu_base + + PL190_VECT_ADDR); + for (i = 0; i < 19; i++) { + unsigned int value = + pl190_read(pl190_data[pl190_nr].cpu_base + + PL190_VECT_ADDR); + pl190_write(value, + pl190_data[pl190_nr].cpu_base + + PL190_VECT_ADDR); + } + + for (i = 0; i < 16; i++) { + pl190_write(VIC_VECT_CNTL_ENABLE | i, + pl190_data[pl190_nr].cpu_base + + PL190_VECT_CNTL0 + (i * 4)); + } + + pl190_write(32, + pl190_data[pl190_nr].cpu_base + + PL190_DEF_VECT_ADDR); +#endif + + return 0; +} diff --git a/pool/shard003/C/0066758_xellf.c b/pool/shard003/C/0066758_xellf.c new file mode 100644 index 0000000000000000000000000000000000000000..cdf87e70877eeaecdebfbc9f2292df23ddcc144c --- /dev/null +++ b/pool/shard003/C/0066758_xellf.c @@ -0,0 +1,43 @@ + +/* Driver for routine ellf */ + +#include +#include +#include +#include +#define NRANSI +#include "nr.h" +#include "nrutil.h" + +#define MAXSTR 80 + +#define FAC (3.1415926535/180.0) + +int main(void) +{ + char txt[MAXSTR]; + int i,nval; + float ak,alpha,phi,val; + FILE *fp; + + if ((fp = fopen("fncval.dat","r")) == NULL) + nrerror("Data file fncval.dat not found\n"); + fgets(txt,MAXSTR,fp); + while (strncmp(txt,"Legendre Elliptic Integral First Kind",37)) { + fgets(txt,MAXSTR,fp); + if (feof(fp)) nrerror("Data not found in fncval.dat\n"); + } + fscanf(fp,"%d %*s",&nval); + printf("\n%s\n",txt); + printf("%5s %10s %11s %22s\n","phi","sin(alpha)","actual","ellf(phi,ak)"); + for (i=1;i<=nval;i++) { + fscanf(fp,"%f %f %f",&phi,&alpha,&val); + alpha=alpha*FAC; + ak=sin(alpha); + phi=phi*FAC; + printf("%6.2f %6.2f %18.6e %18.6e\n",phi,ak,val,ellf(phi,ak)); + } + fclose(fp); + return 0; +} +#undef NRANSI diff --git a/pool/shard003/C/0066764_timer.c b/pool/shard003/C/0066764_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..5c40357c471170b6251f4bb9c02a021f8ce29c34 --- /dev/null +++ b/pool/shard003/C/0066764_timer.c @@ -0,0 +1,156 @@ +/* + * Timer Init + * + * This module initializes TIMER 2 for on the MCF5272 for benchmarks. + * + * Copyright (C) 2000 OKTET Ltd., St.-Petersburg, Russia + * Author: Victor V. Vengerov + * + * Based on work: + * Author: + * David Fiddes, D.J@fiddes.surfaid.org + * http://www.calm.hw.ac.uk/davidf/coldfire/ + * + * COPYRIGHT (c) 1989-1998. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + */ + +#include +#include +#include + +#define TRR2_VAL 65530 + +uint32_t Timer_interrupts; + +bool benchmark_timer_find_average_overhead; + +/* External assembler interrupt handler routine */ +extern rtems_isr timerisr(rtems_vector_number vector); + + +/* benchmark_timer_initialize -- + * Initialize timer 2 for accurate time measurement. + * + * PARAMETERS: + * none + * + * RETURNS: + * none + */ +void +benchmark_timer_initialize(void) +{ + uint32_t icr; + /* Catch timer2 interrupts */ + set_vector(timerisr, BSP_INTVEC_TMR2, 0); + + /* Reset Timer */ + g_timer_regs->tmr2 = MCF5272_TMR_RST; + g_timer_regs->tmr2 = MCF5272_TMR_CLK_STOP; + g_timer_regs->tmr2 = MCF5272_TMR_RST; + g_timer_regs->tcn2 = 0; /* reset counter */ + Timer_interrupts = 0; /* Clear timer ISR counter */ + g_timer_regs->ter2 = MCF5272_TER_REF | MCF5272_TER_CAP; + g_timer_regs->trr2 = TRR2_VAL -1 ; + + + /* Set Timer 2 prescaler so that it counts in microseconds */ + g_timer_regs->tmr2 = ( + (((BSP_SYSTEM_FREQUENCY / 1000000) - 1) << MCF5272_TMR_PS_SHIFT) | + MCF5272_TMR_CE_DISABLE | + MCF5272_TMR_ORI | + MCF5272_TMR_FRR | + MCF5272_TMR_CLK_MSTR | + MCF5272_TMR_RST); + + /* Initialize interrupts for timer2 */ + icr = g_intctrl_regs->icr1; + icr = icr & ~(MCF5272_ICR1_TMR2_MASK | MCF5272_ICR1_TMR2_PI); + icr |= (MCF5272_ICR1_TMR2_IPL(BSP_INTLVL_TMR2) | MCF5272_ICR1_TMR2_PI); + g_intctrl_regs->icr1 = icr; + +} + +/* + * The following controls the behavior of benchmark_timer_read(). + * + * FIND_AVG_OVERHEAD * instructs the routine to return the "raw" count. + * + * AVG_OVEREHAD is the overhead for starting and stopping the timer. It + * is usually deducted from the number returned. + * + * LEAST_VALID is the lowest number this routine should trust. Numbers + * below this are "noise" and zero is returned. + */ + +#define AVG_OVERHEAD 0 /* It typically takes 2.0 microseconds */ + /* (Y countdowns) to start/stop the timer. */ + /* This value is in microseconds. */ +#define LEAST_VALID 1 /* Don't trust a clicks value lower than this */ + +/* benchmark_timer_read -- + * Read timer value in microsecond units since timer start. + * + * PARAMETERS: + * none + * + * RETURNS: + * number of microseconds since timer has been started + */ +int +benchmark_timer_read( void ) +{ + uint16_t clicks; + uint32_t total; + + /* + * Read the timer and see how many clicks it has been since counter + * rolled over. + */ + clicks = g_timer_regs->tcn2; + + /* Stop Timer... */ + g_timer_regs->tmr2 = MCF5272_TMR_CLK_STOP | MCF5272_TMR_RST; + + /* + * Total is calculated by taking into account the number of timer + * overflow interrupts since the timer was initialized and clicks + * since the last interrupts. + */ + + total = (Timer_interrupts * TRR2_VAL) + clicks; + + if ( benchmark_timer_find_average_overhead == 1 ) + return total; /* in XXX microsecond units */ + + if ( total < LEAST_VALID ) + return 0; /* below timer resolution */ + + /* + * Return the count in microseconds + */ + return (total - AVG_OVERHEAD); +} + +/* benchmark_timer_disable_subtracting_average_overhead -- + * This routine is invoked by the "Check Timer" (tmck) test in the + * RTEMS Timing Test Suite. It makes the benchmark_timer_read routine not + * subtract the overhead required to initialize and read the benchmark + * timer. + * + * PARAMETERS: + * find_flag - bool flag, true if overhead must not be subtracted. + * + * RETURNS: + * none + */ +void +benchmark_timer_disable_subtracting_average_overhead(bool find_flag) +{ + benchmark_timer_find_average_overhead = find_flag; +} diff --git a/pool/shard003/C/0066766_st_stats.c b/pool/shard003/C/0066766_st_stats.c new file mode 100644 index 0000000000000000000000000000000000000000..621019b25158916e999aecba64df96aacdd72a38 --- /dev/null +++ b/pool/shard003/C/0066766_st_stats.c @@ -0,0 +1,103 @@ +/* + * stats -- code to create statistics about subnet_files, ipam_files, .. + * + * Copyright (C) 2018 Etienne Basset + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2 of the GNU General Public License + * as published by the Free Software Foundation. + */ +#include +#include +#include "debug.h" +#include "iptools.h" +#include "st_list.h" +#include "st_hashtab.h" +#include "st_scanf.h" +#include "st_options.h" +#include "st_stats.h" +#include "st_object.h" +#include "st_printf.h" + + +unsigned int hash_ipaddr(const void *key, int len) +{ + const struct ip_addr *a = key; + + if (a->ip_ver == IPV4_A) + return djb_hash(&a->ip, 4); + if (a->ip_ver == IPV6_A) + return djb_hash(&a->ip6, 16); + fprintf(stderr, "cannot hash unknown ip version %d\n", a->ip_ver); + return 0; +} + +unsigned int hash_subnet(const void *key, int len) +{ + const struct subnet *a = key; + + if (a->ip_addr.ip_ver == IPV4_A || a->ip_addr.ip_ver == IPV4_N) + return djb_hash(&a->ip_addr.ip, 4) * a->mask; + if (a->ip_addr.ip_ver == IPV6_A || a->ip_addr.ip_ver == IPV6_N) + return djb_hash(&a->ip_addr.ip6, 16) * a->mask; + fprintf(stderr, "cannot hash unknown ip version %d\n", a->ip_ver); + return 0; +} + +int ipam_stats(struct ipam_file *ipam, const char *statvalue) +{ + int res, ea_index = -1; + unsigned long i; + struct hash_table ht; + struct stat_bucket *sb; + struct ipam_ea *ea; + struct subnet *subnet; + st_list head; + + if (!strcmp(statvalue, "subnet")) { + res = alloc_hash_tab(&ht, ipam->nr, &hash_subnet); + if (res < 0) + return res; + + for (i = 0; i < ipam->nr; i++) { + subnet = &ipam->lines[i].subnet; + increase_key_stat(&ht, (char *)subnet, sizeof(*subnet)); + } + } else { + res = alloc_hash_tab(&ht, ipam->nr, &djb_hash); + for (i = 0; i < ipam->ea_nr; i++) { + if (!strcmp(statvalue, ipam->ea[i].name)) + ea_index = i; + } + if (ea_index < 0) { + fprintf(stderr, "unknown EA '%s'\n", statvalue); + return -1; + } + for (i = 0; i < ipam->nr; i++) { + ea = &ipam->lines[i].ea[ea_index]; + if (ea->value) + increase_key_stat(&ht, ea->value, ea->len); + } + } + init_list(&head); + sort_stat_table(&ht, &head); + + if (strcmp(statvalue, "subnet")) { + list_for_each_entry(sb, &head, list) { + printf("%s,%s,%lu\n", + statvalue, (char *)sb->key, sb->count); + free_stat_bucket(sb); + } + } else { + list_for_each_entry(sb, &head, list) { + st_printf("%s,%P,%lu\n", + statvalue, *((struct subnet *)sb->key), sb->count); + free_stat_bucket(sb); + } + } + /* we cannot use free_stat_hash_tab since the call to sort_stat_table modified + * the structure of the hash table + */ + st_free(ht.tab, ht.max_nr * sizeof(struct st_list)); + return 1; +} diff --git a/pool/shard003/C/0066771_llist_test.c b/pool/shard003/C/0066771_llist_test.c new file mode 100644 index 0000000000000000000000000000000000000000..046c8fda77bd222247a6d622b37cd30368b70e3e --- /dev/null +++ b/pool/shard003/C/0066771_llist_test.c @@ -0,0 +1,83 @@ +/* Author: Jared Klingenberger */ + +#include +#include +#include "llist.h" + +void iter_print(node *n) { + printf("value: %d\n", *(int*)n->data); +} + +bool test_equals(void *a, void *b) { + return *(int*)a == *(int*)b; +} + +void node_free(node *n) { free(n); } + +void *llist_find(llist *l, void *data) { + return llist_test(l, data, test_equals); +} + +void llist_print(llist *l); +bool find_and_remove(llist *l, int value); +node *alloc_node(int *data); + +int main() { + llist *l = malloc(sizeof(llist)); + llist_init(l); + + int x = 4, y = 8; + + printf("Adding some...\n"); + + llist_append(l, alloc_node(&x)); + llist_append(l, alloc_node(&y)); + llist_append(l, alloc_node(&x)); + llist_append(l, alloc_node(&y)); + llist_append(l, alloc_node(&x)); + llist_append(l, alloc_node(&y)); + + llist_print(l); + + printf("Removing some...\n"); + + int q = x, p = y+1; + if (!find_and_remove(l, q)) + printf("Value %d not present in list\n", q); + if (!find_and_remove(l, p)) + printf("Value %d not present in list\n", p); + + void iter_remove(node *n) { + iter_print(n); + llist_remove(l, n); + node_free(n); + } + llist_map(l, iter_remove); + + llist_print(l); + + llist_destroy(l, node_free); + free(l); + + return 0; +} + +void llist_print(llist *l) { + llist_map(l, iter_print); +} + +bool find_and_remove(llist *l, int value) { + node *n = llist_find(l, &value); + if (n) { + llist_remove(l, n); + node_free(n); + } + return (n != NULL); +} + +node *alloc_node(int *data) { + node *n = malloc(sizeof(node)); + llist_node_init(n); + n->data = data; + return n; +} diff --git a/pool/shard003/C/0066786_6obj.c b/pool/shard003/C/0066786_6obj.c new file mode 100644 index 0000000000000000000000000000000000000000..8d316d97ab2a767efb7f395cd5fd32a8cff8a67f --- /dev/null +++ b/pool/shard003/C/0066786_6obj.c @@ -0,0 +1,156 @@ +/* + * This file is part of the UCB release of Plan 9. It is subject to the license + * terms in the LICENSE file found in the top-level directory of this + * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No + * part of the UCB release of Plan 9, including this file, may be copied, + * modified, propagated, or distributed except according to the terms contained + * in the LICENSE file. + */ + +/* + * 6obj.c - identify and parse an amd64 object file + */ +#include +#include +#include +#include +#include "6c/6.out.h" +#include "obj.h" + +typedef struct Addr Addr; +struct Addr +{ + char sym; + char flags; +}; +static Addr addr(Biobuf*); +static char type2char(int); +static void skip(Biobuf*, int); + +int +_is6(char *t) +{ + uchar *s = (uchar*)t; + + return s[0] == (ANAME&0xff) /* aslo = ANAME */ + && s[1] == ((ANAME>>8)&0xff) + && s[2] == D_FILE /* type */ + && s[3] == 1 /* sym */ + && s[4] == '<'; /* name of file */ +} + +int +_read6(Biobuf *bp, Prog* p) +{ + int as, n, c; + Addr a; + + as = Bgetc(bp); /* as(low) */ + if(as < 0) + return 0; + c = Bgetc(bp); /* as(high) */ + if(c < 0) + return 0; + as |= ((c & 0xff) << 8); + p->kind = aNone; + p->sig = 0; + if(as == ANAME || as == ASIGNAME){ + if(as == ASIGNAME){ + Bread(bp, &p->sig, 4); + p->sig = leswal(p->sig); + } + p->kind = aName; + p->type = type2char(Bgetc(bp)); /* type */ + p->sym = Bgetc(bp); /* sym */ + n = 0; + for(;;) { + as = Bgetc(bp); + if(as < 0) + return 0; + n++; + if(as == 0) + break; + } + p->id = malloc(n); + if(p->id == 0) + return 0; + Bseek(bp, -n, 1); + if(Bread(bp, p->id, n) != n) + return 0; + return 1; + } + if(as == ATEXT) + p->kind = aText; + if(as == AGLOBL) + p->kind = aData; + skip(bp, 4); /* lineno(4) */ + a = addr(bp); + addr(bp); + if(!(a.flags & T_SYM)) + p->kind = aNone; + p->sym = a.sym; + return 1; +} + +static Addr +addr(Biobuf *bp) +{ + Addr a; + int t; + long l; + vlong off; + + off = 0; + a.sym = -1; + a.flags = Bgetc(bp); /* flags */ + if(a.flags & T_INDEX) + skip(bp, 2); + if(a.flags & T_OFFSET){ + l = Bgetc(bp); + l |= Bgetc(bp) << 8; + l |= Bgetc(bp) << 16; + l |= Bgetc(bp) << 24; + off = l; + if(a.flags & T_64){ + l = Bgetc(bp); + l |= Bgetc(bp) << 8; + l |= Bgetc(bp) << 16; + l |= Bgetc(bp) << 24; + off = ((vlong)l << 32) | (off & 0xFFFFFFFF); + } + if(off < 0) + off = -off; + } + if(a.flags & T_SYM) + a.sym = Bgetc(bp); + if(a.flags & T_FCONST) + skip(bp, 8); + else + if(a.flags & T_SCONST) + skip(bp, NSNAME); + if(a.flags & T_TYPE) { + t = Bgetc(bp); + if(a.sym > 0 && (t==D_PARAM || t==D_AUTO)) + _offset(a.sym, off); + } + return a; +} + +static char +type2char(int t) +{ + switch(t){ + case D_EXTERN: return 'U'; + case D_STATIC: return 'b'; + case D_AUTO: return 'a'; + case D_PARAM: return 'p'; + default: return UNKNOWN; + } +} + +static void +skip(Biobuf *bp, int n) +{ + while (n-- > 0) + Bgetc(bp); +} diff --git a/pool/shard003/C/0066795_fn_2.c b/pool/shard003/C/0066795_fn_2.c new file mode 100644 index 0000000000000000000000000000000000000000..ca45ae391826632d9fe967b16535c16a6c7cfc44 --- /dev/null +++ b/pool/shard003/C/0066795_fn_2.c @@ -0,0 +1,68 @@ +/* + * Copyright (c) 1997-1999, 2003 Massachusetts Institute of Technology + * + * 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 + * + */ + +/* This file was automatically generated --- DO NOT EDIT */ +/* Generated on Mon Mar 24 02:05:37 EST 2003 */ + +#include "fftw-int.h" +#include "fftw.h" + +/* Generated by: /homee/stevenj/cvs/fftw/gensrc/genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -notwiddle 2 */ + +/* + * This function contains 4 FP additions, 0 FP multiplications, + * (or, 4 additions, 0 multiplications, 0 fused multiply/add), + * 4 stack variables, and 8 memory accesses + */ + +/* + * Generator Id's : + * $Id: fn_2.c,v 1.1 2008/10/17 06:13:18 scuri Exp $ + * $Id: fn_2.c,v 1.1 2008/10/17 06:13:18 scuri Exp $ + * $Id: fn_2.c,v 1.1 2008/10/17 06:13:18 scuri Exp $ + */ + +void fftw_no_twiddle_2(const fftw_complex *input, fftw_complex *output, + int istride, int ostride) +{ + fftw_real tmp1; + fftw_real tmp2; + fftw_real tmp3; + fftw_real tmp4; + ASSERT_ALIGNED_DOUBLE; + tmp1 = c_re(input[0]); + tmp2 = c_re(input[istride]); + c_re(output[ostride]) = tmp1 - tmp2; + c_re(output[0]) = tmp1 + tmp2; + tmp3 = c_im(input[0]); + tmp4 = c_im(input[istride]); + c_im(output[ostride]) = tmp3 - tmp4; + c_im(output[0]) = tmp3 + tmp4; +} + +fftw_codelet_desc fftw_no_twiddle_2_desc = { + "fftw_no_twiddle_2", + (void (*)()) fftw_no_twiddle_2, + 2, + FFTW_FORWARD, + FFTW_NOTW, + 45, + 0, + (const int *) 0, +}; diff --git a/pool/shard003/C/0066799_task3.c b/pool/shard003/C/0066799_task3.c new file mode 100644 index 0000000000000000000000000000000000000000..fea26390b7ae158e0f4434067d5fb9b5adf9296b --- /dev/null +++ b/pool/shard003/C/0066799_task3.c @@ -0,0 +1,29 @@ +/* + * COPYRIGHT (c) 1989-2011. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "system.h" + +rtems_task Task_3( + rtems_task_argument argument +) +{ + rtems_status_code status; + + puts( "TA3 - rtems_task_wake_after - sleep 5 seconds" ); + status = rtems_task_wake_after( 5*rtems_clock_get_ticks_per_second() ); + directive_failed( status, "rtems_task_wake_after in TA3" ); + + puts( "TA3 - rtems_task_delete - delete self" ); + status = rtems_task_delete( RTEMS_SELF ); + directive_failed( status, "rtems_task_delete of TA3" ); +} diff --git a/pool/shard003/C/0066810_m5272.c b/pool/shard003/C/0066810_m5272.c new file mode 100644 index 0000000000000000000000000000000000000000..734dab657fe376da4e0ffe4a5b0977f411d9999f --- /dev/null +++ b/pool/shard003/C/0066810_m5272.c @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-2.0 +/***************************************************************************/ + +/* + * m5272.c -- platform support for ColdFire 5272 based boards + * + * Copyright (C) 1999-2002, Greg Ungerer (gerg@snapgear.com) + * Copyright (C) 2001-2002, SnapGear Inc. (www.snapgear.com) + */ + +/***************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************/ + +/* + * Some platforms need software versions of the GPIO data registers. + */ +unsigned short ppdata; +unsigned char ledbank = 0xff; + +/***************************************************************************/ + +DEFINE_CLK(pll, "pll.0", MCF_CLK); +DEFINE_CLK(sys, "sys.0", MCF_BUSCLK); + +static struct clk_lookup m5272_clk_lookup[] = { + CLKDEV_INIT(NULL, "pll.0", &clk_pll), + CLKDEV_INIT(NULL, "sys.0", &clk_sys), + CLKDEV_INIT("mcftmr.0", NULL, &clk_sys), + CLKDEV_INIT("mcftmr.1", NULL, &clk_sys), + CLKDEV_INIT("mcftmr.2", NULL, &clk_sys), + CLKDEV_INIT("mcftmr.3", NULL, &clk_sys), + CLKDEV_INIT("mcfuart.0", NULL, &clk_sys), + CLKDEV_INIT("mcfuart.1", NULL, &clk_sys), + CLKDEV_INIT("mcfqspi.0", NULL, &clk_sys), + CLKDEV_INIT("fec.0", NULL, &clk_sys), +}; + +/***************************************************************************/ + +static void __init m5272_uarts_init(void) +{ + u32 v; + + /* Enable the output lines for the serial ports */ + v = readl(MCFSIM_PBCNT); + v = (v & ~0x000000ff) | 0x00000055; + writel(v, MCFSIM_PBCNT); + + v = readl(MCFSIM_PDCNT); + v = (v & ~0x000003fc) | 0x000002a8; + writel(v, MCFSIM_PDCNT); +} + +/***************************************************************************/ + +static void m5272_cpu_reset(void) +{ + local_irq_disable(); + /* Set watchdog to reset, and enabled */ + __raw_writew(0, MCFSIM_WIRR); + __raw_writew(1, MCFSIM_WRRR); + __raw_writew(0, MCFSIM_WCR); + for (;;) + /* wait for watchdog to timeout */; +} + +/***************************************************************************/ + +void __init config_BSP(char *commandp, int size) +{ +#if defined (CONFIG_MOD5272) + /* Set base of device vectors to be 64 */ + writeb(0x40, MCFSIM_PIVR); +#endif + +#if defined(CONFIG_NETtel) || defined(CONFIG_SCALES) + /* Copy command line from FLASH to local buffer... */ + memcpy(commandp, (char *) 0xf0004000, size); + commandp[size-1] = 0; +#elif defined(CONFIG_CANCam) + /* Copy command line from FLASH to local buffer... */ + memcpy(commandp, (char *) 0xf0010000, size); + commandp[size-1] = 0; +#endif + + mach_reset = m5272_cpu_reset; + mach_sched_init = hw_timer_init; +} + +/***************************************************************************/ + +/* + * Some 5272 based boards have the FEC ethernet directly connected to + * an ethernet switch. In this case we need to use the fixed phy type, + * and we need to declare it early in boot. + */ +static struct fixed_phy_status nettel_fixed_phy_status __initdata = { + .link = 1, + .speed = 100, + .duplex = 0, +}; + +/***************************************************************************/ + +static int __init init_BSP(void) +{ + m5272_uarts_init(); + fixed_phy_add(PHY_POLL, 0, &nettel_fixed_phy_status); + clkdev_add_table(m5272_clk_lookup, ARRAY_SIZE(m5272_clk_lookup)); + return 0; +} + +arch_initcall(init_BSP); + +/***************************************************************************/ diff --git a/pool/shard003/C/0066826_getline-zephyr.c b/pool/shard003/C/0066826_getline-zephyr.c new file mode 100644 index 0000000000000000000000000000000000000000..9de5aa2ae40484f178ddeaf8579bbd623f787d46 --- /dev/null +++ b/pool/shard003/C/0066826_getline-zephyr.c @@ -0,0 +1,57 @@ +/* Copyright (c) 2016 Linaro + * + * 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 "getline-zephyr.h" + +/* While app processes one input line, Zephyr will have another line + buffer to accumulate more console input. */ +static struct uart_console_input line_bufs[2]; + +static struct k_fifo free_queue; +static struct k_fifo used_queue; + +char *zephyr_getline(void) +{ + static struct uart_console_input *cmd; + + /* Recycle cmd buffer returned previous time */ + if (cmd != NULL) + { + k_fifo_put(&free_queue, cmd); + } + + cmd = k_fifo_get(&used_queue, K_FOREVER); + return cmd->line; +} + +void zephyr_getline_init(void) +{ + int i; + + k_fifo_init(&used_queue); + k_fifo_init(&free_queue); + for (i = 0; i < sizeof(line_bufs) / sizeof(*line_bufs); i++) + { + k_fifo_put(&free_queue, &line_bufs[i]); + } + + /* Zephyr UART handler takes an empty buffer from free_queue, + stores UART input in it until EOL, and then puts it into + used_queue. */ + uart_register_input(&free_queue, &used_queue, NULL); +} diff --git a/pool/shard003/C/0066827_CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52a.c b/pool/shard003/C/0066827_CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52a.c new file mode 100644 index 0000000000000000000000000000000000000000..66bdfe62bf99bbae3d1a4f8f2226150587e73623 --- /dev/null +++ b/pool/shard003/C/0066827_CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52a.c @@ -0,0 +1,171 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52a.c +Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml +Template File: sources-sink-52a.tmpl.c +*/ +/* + * @description + * CWE: 194 Unexpected Sign Extension + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Positive integer + * Sink: strncpy + * BadSink : Copy strings using strncpy() with the length of data + * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files + * + * */ + +#include "std_testcase.h" + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else /* NOT _WIN32 */ +#include +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +/* Must be at least 8 for atoi() to work properly */ +#define CHAR_ARRAY_SIZE 8 +#define IP_ADDRESS "127.0.0.1" + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52b_badSink(short data); + +void CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52_bad() +{ + short data; + /* Initialize data */ + data = 0; + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + int tempInt; + struct sockaddr_in service; + SOCKET connectSocket = INVALID_SOCKET; + char inputBuffer[CHAR_ARRAY_SIZE]; + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (connectSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = inet_addr(IP_ADDRESS); + service.sin_port = htons(TCP_PORT); + if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed, make sure to recv one + * less char than is in the recv_buf in order to append a terminator */ + /* FLAW: Use a value input from the network */ + recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* NUL-terminate string */ + inputBuffer[recvResult] = '\0'; + /* Convert to short - ensure int to short conversion will be successful and if + * not ensure that data will be negative */ + tempInt = atoi(inputBuffer); + if (tempInt > SHRT_MAX || tempInt < SHRT_MIN) + { + data = -1; + } + else + { + data = tempInt; + } + } + while (0); + if (connectSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(connectSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52b_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declaration */ +void CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52b_goodG2BSink(short data); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + short data; + /* Initialize data */ + data = 0; + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52b_goodG2BSink(data); +} + +void CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE194_Unexpected_Sign_Extension__connect_socket_strncpy_52_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard003/C/0066832_bug-regex18.c b/pool/shard003/C/0066832_bug-regex18.c new file mode 100644 index 0000000000000000000000000000000000000000..d1fca5e75073f492765e9d896c011517426eb3ea --- /dev/null +++ b/pool/shard003/C/0066832_bug-regex18.c @@ -0,0 +1,99 @@ +/* Turkish regular expression tests. + Copyright (C) 2002-2013 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Jakub Jelinek , 2002. + + The GNU C 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. + + The GNU C 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 the GNU C Library; if not, see + . */ + +#include +#include +#include +#include +#include +#include + +/* Tests supposed to match. */ +struct +{ + const char *pattern; + const char *string; + int flags, nmatch; + regmatch_t rm[5]; +} tests[] = { + /* \xc4\xb0 LATIN CAPITAL LETTER I WITH DOT ABOVE + \xc4\xb1 LATIN SMALL LETTER DOTLESS I + \xe2\x80\x94 EM DASH */ + { "\xc4\xb0I*\xc4\xb1$", "aBi\xc4\xb1\xc4\xb1I", REG_ICASE, 2, + { { 2, 8 }, { -1, -1 } } }, + { "[\xc4\xb0x]I*\xc4\xb1$", "aBi\xc4\xb1\xc4\xb1I", REG_ICASE, 2, + { { 2, 8 }, { -1, -1 } } }, + { "[^x]I*\xc4\xb1$", "aBi\xc4\xb1\xc4\xb1I", REG_ICASE, 2, + { { 2, 8 }, { -1, -1 } } }, + { "([[:alpha:]]i[[:xdigit:]])(\xc4\xb1*)(\xc4\xb0{2})", + "\xe2\x80\x94\xc4\xb1\xc4\xb0""fIi\xc4\xb0ii", REG_ICASE | REG_EXTENDED, + 4, { { 3, 12 }, { 3, 8 }, { 8, 9 }, { 9, 12 } } }, + { "\xc4\xb1i(i)*()(\\s\xc4\xb0|\\SI)", "SIi\xc4\xb0\xc4\xb0 is", + REG_ICASE | REG_EXTENDED, 4, { { 1, 9 }, { 5, 7 }, { 7, 7 }, { 7, 9 } } }, + { "\xc4\xb1i(i)*()(\\s\xc4\xb0|\\SI)", "\xc4\xb1\xc4\xb0\xc4\xb0iJ\xc4\xb1", + REG_ICASE | REG_EXTENDED, 4, + { { 0, 10 }, { 6, 7 }, { 7, 7 }, { 7, 10 } } }, +}; + +int +main (void) +{ + regex_t re; + regmatch_t rm[5]; + size_t i; + int n, ret = 0; + + setlocale (LC_ALL, "tr_TR.UTF-8"); + for (i = 0; i < sizeof (tests) / sizeof (tests[0]); ++i) + { + n = regcomp (&re, tests[i].pattern, tests[i].flags); + if (n != 0) + { + char buf[500]; + regerror (n, &re, buf, sizeof (buf)); + printf ("regcomp %zd failed: %s\n", i, buf); + ret = 1; + continue; + } + + if (regexec (&re, tests[i].string, tests[i].nmatch, rm, 0)) + { + printf ("regexec %zd failed\n", i); + ret = 1; + regfree (&re); + continue; + } + + for (n = 0; n < tests[i].nmatch; ++n) + if (rm[n].rm_so != tests[i].rm[n].rm_so + || rm[n].rm_eo != tests[i].rm[n].rm_eo) + { + if (tests[i].rm[n].rm_so == -1 && tests[i].rm[n].rm_eo == -1) + break; + printf ("regexec match failure rm[%d] %d..%d\n", + n, rm[n].rm_so, rm[n].rm_eo); + ret = 1; + break; + } + + regfree (&re); + } + + return ret; +} diff --git a/pool/shard003/C/0066862_peer_search_receptor.c b/pool/shard003/C/0066862_peer_search_receptor.c new file mode 100644 index 0000000000000000000000000000000000000000..4d43020a538abef352865d395356dbf371d12531 --- /dev/null +++ b/pool/shard003/C/0066862_peer_search_receptor.c @@ -0,0 +1,430 @@ +/** + * \file peer_search_receptor.c + * + * \brief Receptor functionalities in Peer Search Process - Performance Analyzer + * application + * Copyright (c) 2013-2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page 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. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. + * + * \asf_license_stop + */ + +/* + * Copyright (c) 2014, Atmel Corporation All rights reserved. + * + * Licensed under Atmel's Limited License Agreement --> EULA.txt + */ +/* === INCLUDES ============================================================ */ + /** + * Support and FAQ: visit
    Atmel Support + */ + +#include +#include "tal.h" +#include "tal_helper.h" +#include "ieee_const.h" +#include "app_init.h" +#include "app_frame_format.h" +#include "app_peer_search.h" + +/** + * \addtogroup group_peer_search_receptor + * \{ + */ + +/* === TYPES =============================================================== */ + +/* Peer search rx states */ +typedef enum { + PEER_RSP_SEND, + WAIT_FOR_PEER_CONF, + PEER_SEARCH_RECEPTOR_SUCCESS, + NUM_PEER_SEARCH_RECEPTOR_STATES +} peer_search_receptor_state_t; + +/* === MACROS ============================================================== */ + +/* Timer values for the timer used in peer search */ +#define PEER_RESPONSE_TIMEOUT_IN_MICRO_SEC (200000) + +/* === PROTOTYPES ========================================================== */ + +static void peer_rsp_send_init(void *arg); +static void peer_rsp_send_tx_done_cb(retval_t status, frame_info_t *frame); + +static void app_peer_conf_tmr_handler_cb(void *parameter); +static int send_peer_rsp(uint64_t *addr); + +static void wait_for_conf_init(void *arg); +static void wait_for_conf_rx_cb(frame_info_t *frame); +static void wait_for_conf_exit(void); + +/* === GLOBALS ============================================================= */ +/* Peer process seq number */ +static uint8_t seq_num; + +static peer_state_function_t const peer_search_receptor_state_table[ + NUM_PEER_SEARCH_RECEPTOR_STATES] = { + { /* PEER_RSP_SEND */ + peer_rsp_send_init, + NULL, + peer_rsp_send_tx_done_cb, + NULL, + NULL, + }, + { /* WAIT_FOR_PEER_CONF */ + wait_for_conf_init, + NULL, + NULL, + wait_for_conf_rx_cb, + wait_for_conf_exit, + }, +}; +/* ! \} */ +/* === IMPLEMENTATION ====================================================== */ + +/* Main state tasks for Peer Search */ + +/* + * \brief Application task to start peer search + * + * \param mode starts the peer search in this particular mode + */ +void peer_search_receptor_init(void *arg) +{ + pib_value_t pib_value; + peer_search_receptor_arg_t *arg_ptr = (peer_search_receptor_arg_t *)arg; + + /* Change LED pattern */ + app_led_event(LED_EVENT_START_PEER_SEARCH); + + /* Peer process seq number */ + seq_num = rand(); + + /* assign a random address */ + do { + node_info.peer_short_addr = rand(); + /* Make sure random number is not zero */ + } while (!node_info.peer_short_addr); + + /* Set my address which my peer send me */ + pib_value.pib_value_16bit = arg_ptr->my_short_addr; + tal_pib_set(macShortAddress, &pib_value); + +#ifdef EXT_RF_FRONT_END_CTRL + /* Disable RF front end control during peer search process*/ + tal_ext_pa_ctrl(PA_EXT_DISABLE); + /* Make sure that Tx power is at max, when PA_EXT is disabled */ + tal_set_tx_pwr(REGISTER_VALUE, 0x00); +#endif +} + +/* + * \brief Application task handling peer search + * + * This function + * - Implements the peer search state machine. + */ +void peer_search_receptor_task() +{ + peer_search_receptor_state_t sub_state + = (peer_search_receptor_state_t)node_info.sub_state; + + if (peer_search_receptor_state_table[sub_state].peer_state_task) { + peer_search_receptor_state_table[sub_state].peer_state_task(); + } +} + +/* + * \brief Callback that is called once tx is done. + * + * \param status Status of the transmission procedure + * \param frame Pointer to the transmitted frame structure + */ +void peer_search_receptor_tx_done_cb(retval_t status, frame_info_t *frame) +{ + peer_search_receptor_state_t sub_state + = (peer_search_receptor_state_t)node_info.sub_state; + + if (peer_search_receptor_state_table[sub_state]. + peer_state_tx_frame_done_cb) { + peer_search_receptor_state_table[sub_state]. + peer_state_tx_frame_done_cb(status, frame); + } +} + +/* + * \brief Callback that is called if data has been received by trx. + * + * \param frame Pointer to received frame + */ +void peer_search_receptor_rx_cb(frame_info_t *frame) +{ + peer_search_receptor_state_t sub_state + = (peer_search_receptor_state_t)node_info.sub_state; + + if (peer_search_receptor_state_table[sub_state].peer_state_rx_frame_cb) + { + peer_search_receptor_state_table[sub_state]. + peer_state_rx_frame_cb(frame); + } +} + +/* + * Function to set the sub state of state machine + */ +void peer_search_receptor_set_sub_state(uint8_t state, void *arg) +{ + peer_search_receptor_state_t new_state + = (peer_search_receptor_state_t)state; + + /* Exit the old state */ + if (new_state && + peer_search_receptor_state_table[node_info.sub_state]. + peer_state_exit) { + peer_search_receptor_state_table[node_info.sub_state]. + peer_state_exit(); + } + + /* Change and welcome to new sub state */ + node_info.sub_state = new_state; + + if (peer_search_receptor_state_table[new_state].peer_state_init) { + peer_search_receptor_state_table[new_state].peer_state_init(arg); + } +} + +/* + * \brief Function to exit peer search receptor state. + * + * This function + * - Implements the peer search state machine. + */ +void peer_search_receptor_exit(void) +{ + /* Exit the old sub state */ + if (peer_search_receptor_state_table[node_info.sub_state]. + peer_state_exit) { + peer_search_receptor_state_table[node_info.sub_state]. + peer_state_exit(); + } +} + +/* Sub state tasks for Peer Search */ + +/** + * \brief Application task handling peer search + * + * This function + * - Implements the peer search state machine. + */ +static void peer_rsp_send_init(void *arg) +{ + peer_search_receptor_arg_t *arg_ptr = (peer_search_receptor_arg_t *)arg; + + if (send_peer_rsp(&(arg_ptr->peer_ieee_addr))) { + print_event(PRINT_PEER_SEARCH_FAILED); + /* PEER RSP send failed - so change to WAIT_FOR_EVENT state*/ + set_main_state(WAIT_FOR_EVENT, 0); + } +} + +/** + * \brief Callback that is called once tx is done in PEER_RSP_SEND state. + * + * \param status Status of the transmission procedure + * \param frame Pointer to the transmitted frame structure + */ +static void peer_rsp_send_tx_done_cb(retval_t status, frame_info_t *frame) +{ + if (status == MAC_SUCCESS) { + peer_search_receptor_set_sub_state(WAIT_FOR_PEER_CONF, 0); + } else { + print_event(PRINT_PEER_SEARCH_FAILED); + /* No PEER RSP send failed so change to WAIT_FOR_EVENT state*/ + set_main_state(WAIT_FOR_EVENT, 0); + } + + /* Keep compiler happy */ + frame = frame; +} + +/** + * \brief Send peer response. This is a unicast send to the node which + * had earlier send the peer request + * + * \param src_addr The address which had been sent as payload of peer request + * it becomes the source address of node which sent peer rsp + * \param seq_num Sequence number of the Peer request frame + */ +static int send_peer_rsp(uint64_t *dst_addr) +{ + uint16_t payload_length; + app_payload_t msg; + peer_rsp_t *data; + + /* Fill the payload */ + msg.cmd_id = PEER_RESPONSE; + + seq_num++; + msg.seq_num = seq_num; + + data = (peer_rsp_t *)&msg.payload; + + /* Issues an address for the peer. If tis node gets connected then + * peer node changes its short address to this value + */ + data->nwk_addr = node_info.peer_short_addr; + + payload_length = ((sizeof(app_payload_t) - + sizeof(general_pkt_t)) + + sizeof(peer_rsp_t)); + + return(transmit_frame(FCF_LONG_ADDR, + (uint8_t *)(dst_addr), + FCF_SHORT_ADDR, + seq_num, /* seq_num used as msdu handle + **/ + (uint8_t *)&msg, + payload_length, + 1)); +} + +/** + * \brief Function to initialize wait for peer search conf state. + * + * This function + * - Implements the peer search state machine. + */ +static void wait_for_conf_init(void *arg) +{ + sw_timer_start(APP_TIMER_TO_TX, + PEER_RESPONSE_TIMEOUT_IN_MICRO_SEC, + SW_TIMEOUT_RELATIVE, + (FUNC_PTR)app_peer_conf_tmr_handler_cb, + NULL); + + /* Keep compiler happy */ + arg = arg; +} + +/** + * \brief Callback that is called once tx is done in wait for peer search conf + * state. + * + * \param status Status of the transmission procedure + * \param frame Pointer to the transmitted frame structure + */ +static void wait_for_conf_rx_cb(frame_info_t *mac_frame_info) +{ + app_payload_t *msg; + + if (*(mac_frame_info->mpdu) == (FRAME_OVERHEAD + + ((sizeof(app_payload_t) + - sizeof(general_pkt_t)) + + sizeof(peer_conf_t)))) { + /* Point to the message : 1 =>size is first byte and 2=>FCS*/ + msg + = (app_payload_t *)(mac_frame_info->mpdu + 1 + + FRAME_OVERHEAD - 2); + if ((msg->cmd_id) == PEER_CONFIRM) { + if (node_info.peer_short_addr == + (msg->payload.peer_conf_data.nwk_addr)) + { + print_event(PRINT_PEER_SEARCH_SUCCESS); + app_led_event(LED_EVENT_PEER_SEARCH_DONE); + switch (node_info.main_state) { + case PEER_SEARCH_RANGE_RX: + + /* Peer success - set the board to + * RANGE_TEST_TX_OFF state */ + set_main_state(RANGE_TEST_TX_OFF, 0); + break; + + case PEER_SEARCH_PER_RX: + + /* Peer success - set the board to + * RANGE_TEST_TX_OFF state */ + set_main_state(PER_TEST_RECEPTOR, 0); + break; + + /* To keep the GCC compiler happy */ + case INIT: + case WAIT_FOR_EVENT: + case PEER_SEARCH_RANGE_TX: + case PEER_SEARCH_PER_TX: + case RANGE_TEST_TX_ON: + case RANGE_TEST_TX_OFF: + case SINGLE_NODE_TESTS: + case PER_TEST_INITIATOR: + case PER_TEST_RECEPTOR: + case NUM_MAIN_STATES: + break; + + default: /* Do nothing */ + break; + } + } + } + } +} + +/** + * \brief Function to exit wait for peer search conf state. + * + * This function + * - Implements the peer search state machine. + */ +static void wait_for_conf_exit(void) +{ + /* stop the timer as node leaves this sub state */ + sw_timer_stop(APP_TIMER_TO_TX); +} + +/** + * \brief Timer handler for supporting peer search + * + * \param parameter pass parameters to timer handler + */ +static void app_peer_conf_tmr_handler_cb(void *parameter) +{ + print_event(PRINT_PEER_SEARCH_FAILED); + /* No PEER CONF so change to WAIT_FOR_EVENT state*/ + set_main_state(WAIT_FOR_EVENT, 0); + + /* keep compiler happy */ + parameter = parameter; +} + +/* EOF */ diff --git a/pool/shard003/C/0066877_memchunkhax.c b/pool/shard003/C/0066877_memchunkhax.c new file mode 100644 index 0000000000000000000000000000000000000000..508be8becbb2c4b5b34e18bdaf4205661afee020 --- /dev/null +++ b/pool/shard003/C/0066877_memchunkhax.c @@ -0,0 +1,104 @@ +#include "memchunkhax.h" + +#include +#include +#include "firmcompat.h" +#include "appcompat.h" +#include "arm11_tools.h" + +static void gspwn_copy(void *dest, void *src, uint32_t length, int check, int check_offset) +{ + // We'll use some memory to check the copy is being done right. + void *check_mem = (void *)APP_CHECK_MEM; + int *check_loc = (int *)(check_mem + check_offset); + + while(*check_loc != check) { + memcpy32(check_mem, check_mem, 0x10000); + app->GSPGPU_FlushDataCache(src, length); + + uint32_t arr1[] = {4, (uint32_t)src, (uint32_t)dest, length, + 0xFFFFFFFF, 0xFFFFFFFF, 8, 0}; + app->nn__gxlow__CTR__CmdReqQueueTx__TryEnqueue((void *)app->gpuHandle, arr1); + + app->GSPGPU_FlushDataCache(check_mem, 0x10); + + uint32_t arr2[] = {4, (uint32_t)dest, (uint32_t)check_mem, check_offset + 4, + 0xFFFFFFFF, 0xFFFFFFFF, 8, 0}; + app->nn__gxlow__CTR__CmdReqQueueTx__TryEnqueue((void *)app->gpuHandle, arr2); + + memcpy32(check_mem, check_mem, 0x10000); + } +} + +#if defined(ENTRY_MSET) +static void build_nop_slide(uint32_t *dest, unsigned int len) +{ + unsigned int i; + for (i = 0; i < len; i++) { + dest[i] = 0xE1A00000; // ARM instruction: nop + } + dest[i - 1] = 0xE12FFF1E; // ARM instruction: bx lr +} +#endif + +__attribute__((naked)) +static void corrupted_svcCreateThread(__attribute__((unused)) void (*func)()) +{ + __asm__ volatile ("svc 8"); +} + +void memchunk_arm11hax(void (*func)()) +{ + // I need some memory locations to use + uint32_t *mem_hax_mem = (uint32_t *)APP_MEM_HAX_MEM; + uint32_t *mem_hax_mem_free = (uint32_t *)((uint32_t)mem_hax_mem + 0x1000); + + // There's not much documentation on this code. + // I've never studied the logic of it, so I can't describe it in more detail. + + // Free some random chunk of memory + uint32_t tmp_addr; + svcControlMemory(&tmp_addr, mem_hax_mem_free, NULL, 0x1000, 1 /* MEMOP_FREE */, 0); + + // arm11_buffer is the location that is copied *from* when using gspwn_copy + uint32_t *arm11_buffer = (uint32_t *)APP_ARM11_BUFFER; + arm11_buffer[0] = 1; + arm11_buffer[1] = fw->kernel_patch_address; + arm11_buffer[2] = 0; + arm11_buffer[3] = 0; + + // Copy the arm11_buffer to the freed memory with gspwn + gspwn_copy(mem_hax_mem_free, arm11_buffer, 0x10, fw->kernel_patch_address, 4); + + // Trigger kernel write + svcControlMemory(&tmp_addr, mem_hax_mem, NULL, 0x1000, 1 /* MEMOP_FREE */, 0); + + // Tricks to clear the instruction cache +#if defined(ENTRY_MSET) + int slide_len = 0x1000; + + // Build a NOP slide + build_nop_slide(arm11_buffer, slide_len); + + // Copy the NOP slide + gspwn_copy((void *)(0x14000000 + fw->app_code_offset + 0x4000), arm11_buffer, + slide_len * 4, 0xE1A00000, 0); + + // Run the NOP slide + ((void (*)())0x104000)(); +#elif defined(ENTRY_SPIDER) + // Fills the bottom buffer with a random pattern + void *src = (void *)0x18000000; + for (int i = 0; i < 3; i++) { // Do it 3 times to be safe + app->GSPGPU_FlushDataCache(src, 0x00038400); + app->GX_SetTextureCopy(src, (void *)0x1F48F000, 0x00038400, 0, 0, 0, 0, 8); + svcSleepThread(0x400000LL); + app->GSPGPU_FlushDataCache(src, 0x00038400); + app->GX_SetTextureCopy(src, (void *)0x1F4C7800, 0x00038400, 0, 0, 0, 0, 8); + svcSleepThread(0x400000LL); + } +#endif + + // Get into arm11 + corrupted_svcCreateThread(func); +} diff --git a/pool/shard003/C/0066894_saltos.c b/pool/shard003/C/0066894_saltos.c new file mode 100644 index 0000000000000000000000000000000000000000..af4f93a629deaffb37ce24bc68ad643b9fda6593 --- /dev/null +++ b/pool/shard003/C/0066894_saltos.c @@ -0,0 +1,279 @@ +/* + * File: saltos.c + * Este módulo contiene las funciones para operar con dos tipos de listas + * enlazadas: una lista de saltos conocidos y una lista de saltos pendientes + * de calcular. + * + * 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. + * + * 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 "saltos.h" +#include +#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/pool/shard003/C/0066899_wnl90to77.c b/pool/shard003/C/0066899_wnl90to77.c new file mode 100644 index 0000000000000000000000000000000000000000..5868fb08564a2f560fa714cc4814fe78a57b725d --- /dev/null +++ b/pool/shard003/C/0066899_wnl90to77.c @@ -0,0 +1,353 @@ +/* + + Copyright (C) 2000, 2001, Silicon Graphics, Inc. All Rights Reserved. + + This program is free software; you can redistribute it and/or modify it + under the terms of version 2.1 of the GNU Lesser General Public License + as published by the Free Software Foundation. + + This program is distributed in the hope that it would be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + Further, this software is distributed without any warranty that it is + free of the rightful claim of any third person regarding infringement + or the like. Any license provided herein, whether implied or + otherwise, applies only to this software file. Patent licenses, if + any, provided herein do not apply to combinations of this program with + other software, or any other product whatsoever. + + You should have received a copy of the GNU Lesser General Public + License along with this program; if not, write the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, + USA. + + Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, + Mountain View, CA 94043, or: + + http://www.sgi.com + + For further information regarding this notice, see: + + http://oss.sgi.com/projects/GenInfo/NoticeExplan + +*/ + + + +#pragma ident "@(#) libf/fio/wnl90to77.c 92.2 06/21/99 10:37:55" + +#include +#include +#include +#include +#include "fio.h" +#include "namelist.h" +#include "wnl90def.h" + +/* + * _wnl90to77 - called by library routine wnl90.c to write a cf77 + * namelist output file. + * + * Synopsis + * int _wnl90to77( css, + * unit *cup, + * nmlist_group *namlist, + * void *stck, + * int errf); + * + * Where + * css pointer to css + * cup pointer to the unit information + * namlist pointer to the namelist table. + * stck pointer to stack space which is passed + * to each call to _FWN for a particular + * statement. This is used by the library. + * errf Error processing flag. + * + * Return value + * errn + */ + +int +_wnl90to77( + FIOSPTR css, + unit *cup, + nmlist_group *namlist, + void *stck, + int errf) +{ + register int errn; /* Error number */ + char *wptr; /* pointer to group name */ + unsigned long wlen; /* group name length */ + unsigned wcount; /* count of namelist items */ + int icnt; + char *varptr; /* ptr to group_obj_list_item */ + unsigned long varlen; /* len to group_obj_list_item */ + nmlist_goli_t *nlvar; /* ptr to next variable entry */ + long eqlchr; /* hold nl equal character */ + long sepchr; /* hold nl delimiter character */ + long nlchr; /* hold nl group character */ + long trmchr; /* hold nl terminator character */ + int trmsize; /* size of terminator character */ + +/**************************************************************************** + * Data Transfer Section + ***************************************************************************/ + + errn = 0; + wcount = namlist->icount; /* count of list items */ + + /* set up one set of variables to use where f77 mode */ + + eqlchr = OUT_EQ; + sepchr = OUT_SEP; + nlchr = OUT_CHAR; + trmchr = OUT_CHAR; + trmsize = 6; + NLCHAR(OUT_ECHO); /* blank or echo char */ + NLCHAR(nlchr); /* ampersand or WNLDELM */ + + wptr = _fcdtocp(namlist->group_name); /* ptr to groupname */ + wlen = _fcdlen(namlist->group_name); /* len of groupname */ + + /* If length of groupname exceeds recl, put out an error */ + + if ((wlen + 4) > cup->unmlsize) { + errn = FENLNMSZ; + ERROR0(errf, css, errn); + } + + /* Move namelist group name to output buffer */ + + for (icnt = 0; icnt < wlen; icnt++) { + *cup->ulineptr++ = *wptr++; + cup->ulinemax++; + } + + NLCHAR(' '); /* write blank */ + NLCHAR(' '); /* write blank */ + + /* WNLLINE specifies one variable per record */ + + NLINE(); /* new line */ + + nlvar = namlist->goli; /* group object pointer */ + + while (wcount-- && (errn == 0)) { + varptr = _fcdtocp(nlvar->goli_name); + varlen = _fcdlen(nlvar->goli_name); + + /* If length of variable name exceeds recl, issue an err */ + + if (varlen > cup->unmlsize) { + /* error: group object name too big for rec size */ + errn = FENLNMSZ; + ERROR0(errf, css, errn); + } + else + if (varlen > (cup->unmlsize - cup->ulinemax)) { + NLWFLUSH(); + NLCHAR(' '); /* write blank */ + NLCHAR(' '); /* write blank */ + } + + /* Write namelist group object name to output buffer */ + + for (icnt = 0; icnt < varlen; icnt++) { + *cup->ulineptr++ = varptr[icnt]; + cup->ulinemax++; + } + + /* Flush output buffer if blank=blank will not fit */ + + if ((cup->unmlsize - cup->ulinemax) < 3) { + NLWFLUSH(); + NLCHAR(' '); /* write blank */ + } + + /* Write equal size or replacement character after name */ + + NLCHAR(' '); /* write blank */ + NLCHAR(eqlchr); /* write equal sign */ + NLCHAR(' '); /* write blank */ + + /* Setting ldwinit is needed before first call to _ld_write */ + + css->u.fmt.u.le.ldwinit = 1; + + /* Write the value of the namelist group object */ + + switch (nlvar->valtype) { + + case IO_SCALAR: + { + void *vaddr; + type_packet tip; /* Type information packet */ + nmlist_scalar_t *nlscalar; /* nmlist scalar entry */ + + nlscalar = nlvar->goli_addr.ptr; + tip.type90 = nlscalar->tinfo.type; + tip.type77 = -1; + tip.intlen = nlscalar->tinfo.int_len; + tip.extlen = tip.intlen; + tip.elsize = tip.intlen >> 3; + tip.cnvindx = 0; + tip.count = 1; + tip.stride = 1; + + /* Assertions */ + + assert (tip.type90 >= DVTYPE_TYPELESS && + tip.type90 <= DVTYPE_ASCII); + assert (tip.intlen > 0); + + if (tip.type90 == DVTYPE_ASCII) { + vaddr = _fcdtocp(nlscalar->scal_addr.charptr); + + tip.elsize = tip.elsize * + _fcdlen(nlscalar->scal_addr.charptr); + } + else + vaddr = nlscalar->scal_addr.ptr; + + /* Do not allow double complex for 77 mode */ + + if ((tip.type90 == DVTYPE_COMPLEX && + tip.elsize == (sizeof(_f_dble) * 2))) + errn = FENLDBCP; + else /* Use list-directed write */ + errn = _ld_write(css, cup, vaddr, &tip, 0); + + break; + } + + case IO_DOPEVEC: + { + register short nc; + register long extent; + void *vaddr; + type_packet tip; + DopeVectorType *nldv; + + nldv = nlvar->goli_addr.dv; /* ptr to dope vec */ + + /* Assertions */ + + assert (nldv != NULL); + assert (nldv->type_lens.int_len > 0); + + tip.type90 = nldv->type_lens.type; + tip.type77 = -1; + tip.intlen = nldv->type_lens.int_len; + tip.extlen = tip.intlen; + tip.elsize = tip.intlen >> 3; + tip.cnvindx = 0; + tip.stride = 1; + + if (tip.type90 == DVTYPE_ASCII) { + vaddr = _fcdtocp(nldv->base_addr.charptr); + tip.elsize = tip.elsize * + _fcdlen(nldv->base_addr.charptr); + } + else + vaddr = nldv->base_addr.a.ptr; + + extent = 1; + + for (nc = 0; nc < nldv->n_dim; nc++) + extent = extent * nldv->dimension[nc].extent; + + tip.count = extent; + + /* Assertions */ + + assert (tip.elsize > 0 && extent > 0); + + /* Do not allow double complex for 77 mode */ + + if ((tip.type90 == DVTYPE_COMPLEX && + tip.elsize == (sizeof(_f_dble) * 2))) + errn = FENLDBCP; + else /* Use list-directed write */ + errn = _ld_write(css, cup, vaddr, &tip, 0); + + break; + } + + case IO_STRUC_A: + case IO_STRUC_S: + { + /* Do not allow structures for 77 mode */ + errn = FENLSTCT; + } + + default: + errn = FEINTUNK; /* Internal error */ + } /* switch */ + + if (errn != 0) { + ERROR0(errf, css, errn); + } + + /* Flush out last item to record buffer */ + + errn = _ld_write(css, cup, (void *) NULL, &__tip_null, 0); + + if (errn != 0) { + ERROR0(errf, css, errn); + } + + if (wcount > 0) { + if ((cup->unmlsize - cup->ulinemax) < 2) { + NLWFLUSH(); + NLCHAR(' '); /* write delimiter */ + NLCHAR(' '); /* write delimiter */ + css->u.fmt.u.le.ldwinit = 1;/* suppress comma */ + } + else { + NLCHAR(sepchr); /* write comma */ + NLCHAR(' '); /* write delimiter */ + css->u.fmt.u.le.ldwinit = 1;/* suppress comma */ + NLINE(); /* new line */ + } + } + +#if defined(__mips) && (_MIPS_SZLONG == 32) + nlvar = (nmlist_goli_t*)((long *)nlvar + 3 + + (sizeof(_fcd))/(sizeof(long))); +#else + nlvar = (nmlist_goli_t*)((long *)nlvar + 2 + + (sizeof(_fcd))/(sizeof(long))); +#endif + } + + if (cup->ulinemax > 2) { + NLINE(); /* new line */ + } + + if ((cup->unmlsize - cup->ulinemax) < trmsize) { + NLWFLUSH(); + NLCHAR(' '); /* write blank */ + } + + /* CF77 ends namelist with compat character (does accept slash) */ + + NLCHAR(' '); /* write blank */ + NLCHAR(trmchr); /* write ending slash */ + NLCHAR('E'); /* write END */ + NLCHAR('N'); + NLCHAR('D'); + NLWFLUSH(); + + if (errn != 0) + cup->uflag = cup->uflag | _UERRC; /* Set error status */ + +/**************************************************************************** + * + * Statement Finalization Section + * + ***************************************************************************/ +finalization: + return(errn); +} diff --git a/pool/shard003/C/0066997_bn_mp_clear_multi.c b/pool/shard003/C/0066997_bn_mp_clear_multi.c new file mode 100644 index 0000000000000000000000000000000000000000..e5e3da340aea90acc05fcc6119eaac7d6b920acf --- /dev/null +++ b/pool/shard003/C/0066997_bn_mp_clear_multi.c @@ -0,0 +1,34 @@ +#include +#ifdef BN_MP_CLEAR_MULTI_C +/* LibTomMath, multiple-precision integer library -- Tom St Denis + * + * LibTomMath is a library that provides multiple-precision + * integer arithmetic as well as number theoretic functionality. + * + * The library was designed directly after the MPI library by + * Michael Fromberger but has been written from scratch with + * additional optimizations in place. + * + * The library is free for all purposes without any express + * guarantee it works. + * + * Tom St Denis, tomstdenis@gmail.com, http://libtom.org + */ +#include + +void mp_clear_multi(mp_int *mp, ...) +{ + mp_int* next_mp = mp; + va_list args; + va_start(args, mp); + while (next_mp != NULL) { + mp_clear(next_mp); + next_mp = va_arg(args, mp_int*); + } + va_end(args); +} +#endif + +/* $Source: /cvs/libtom/libtommath/bn_mp_clear_multi.c,v $ */ +/* $Revision: 1.4 $ */ +/* $Date: 2006/12/28 01:25:13 $ */ diff --git a/pool/shard003/C/0066998_audiotest.c b/pool/shard003/C/0066998_audiotest.c new file mode 100644 index 0000000000000000000000000000000000000000..d3473a51d930f338ca72f44e8084ae3d593dfa0d --- /dev/null +++ b/pool/shard003/C/0066998_audiotest.c @@ -0,0 +1,269 @@ +/* $Id: audiotest.c 369517 2012-07-01 17:28:57Z file $ */ +/* + * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) + * Copyright (C) 2003-2008 Benny Prijono + * + * 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 + +#define THIS_FILE "audiotest.c" + +/* Test duration in msec */ +#define DURATION 10000 + +/* Skip the first msec from the calculation */ +#define SKIP_DURATION 1000 + +/* Division helper */ +#define DIV_ROUND_UP(a,b) (((a) + ((b) - 1)) / (b)) +#define DIV_ROUND(a,b) (((a) + ((b)/2 - 1)) / (b)) + +struct stream_data +{ + pj_uint32_t first_timestamp; + pj_uint32_t last_timestamp; + pj_timestamp last_called; + pj_math_stat delay; +}; + +struct test_data +{ + pj_pool_t *pool; + const pjmedia_aud_param *param; + pjmedia_aud_test_results *result; + pj_bool_t running; + pj_bool_t has_error; + pj_mutex_t *mutex; + + struct stream_data capture_data; + struct stream_data playback_data; +}; + +static pj_status_t play_cb(void *user_data, pjmedia_frame *frame) +{ + struct test_data *test_data = (struct test_data *)user_data; + struct stream_data *strm_data = &test_data->playback_data; + + pj_mutex_lock(test_data->mutex); + + /* Skip frames when test is not started or test has finished */ + if (!test_data->running) { + pj_bzero(frame->buf, frame->size); + pj_mutex_unlock(test_data->mutex); + return PJ_SUCCESS; + } + + /* Save last timestamp seen (to calculate drift) */ + strm_data->last_timestamp = frame->timestamp.u32.lo; + + if (strm_data->last_called.u64 == 0) { + /* Init vars. */ + pj_get_timestamp(&strm_data->last_called); + pj_math_stat_init(&strm_data->delay); + strm_data->first_timestamp = frame->timestamp.u32.lo; + } else { + pj_timestamp now; + unsigned delay; + + /* Calculate frame interval */ + pj_get_timestamp(&now); + delay = pj_elapsed_usec(&strm_data->last_called, &now); + strm_data->last_called = now; + + /* Update frame interval statistic */ + pj_math_stat_update(&strm_data->delay, delay); + } + + pj_bzero(frame->buf, frame->size); + + pj_mutex_unlock(test_data->mutex); + + return PJ_SUCCESS; +} + +static pj_status_t rec_cb(void *user_data, pjmedia_frame *frame) +{ + struct test_data *test_data = (struct test_data*)user_data; + struct stream_data *strm_data = &test_data->capture_data; + + pj_mutex_lock(test_data->mutex); + + /* Skip frames when test is not started or test has finished */ + if (!test_data->running) { + pj_mutex_unlock(test_data->mutex); + return PJ_SUCCESS; + } + + /* Save last timestamp seen (to calculate drift) */ + strm_data->last_timestamp = frame->timestamp.u32.lo; + + if (strm_data->last_called.u64 == 0) { + /* Init vars. */ + pj_get_timestamp(&strm_data->last_called); + pj_math_stat_init(&strm_data->delay); + strm_data->first_timestamp = frame->timestamp.u32.lo; + } else { + pj_timestamp now; + unsigned delay; + + /* Calculate frame interval */ + pj_get_timestamp(&now); + delay = pj_elapsed_usec(&strm_data->last_called, &now); + strm_data->last_called = now; + + /* Update frame interval statistic */ + pj_math_stat_update(&strm_data->delay, delay); + } + + pj_mutex_unlock(test_data->mutex); + return PJ_SUCCESS; +} + +static void app_perror(const char *title, pj_status_t status) +{ + char errmsg[PJ_ERR_MSG_SIZE]; + + pj_strerror(status, errmsg, sizeof(errmsg)); + printf( "%s: %s (err=%d)\n", + title, errmsg, status); +} + + +PJ_DEF(pj_status_t) pjmedia_aud_test( const pjmedia_aud_param *param, + pjmedia_aud_test_results *result) +{ + pj_status_t status = PJ_SUCCESS; + pjmedia_aud_stream *strm; + struct test_data test_data; + unsigned ptime, tmp; + + /* + * Init test parameters + */ + pj_bzero(&test_data, sizeof(test_data)); + test_data.param = param; + test_data.result = result; + + test_data.pool = pj_pool_create(pjmedia_aud_subsys_get_pool_factory(), + "audtest", 1000, 1000, NULL); + pj_mutex_create_simple(test_data.pool, "sndtest", &test_data.mutex); + + /* + * Open device. + */ + status = pjmedia_aud_stream_create(test_data.param, &rec_cb, &play_cb, + &test_data, &strm); + if (status != PJ_SUCCESS) { + app_perror("Unable to open device", status); + pj_pool_release(test_data.pool); + return status; + } + + + /* Sleep for a while to let sound device "settles" */ + pj_thread_sleep(200); + + /* + * Start the stream. + */ + status = pjmedia_aud_stream_start(strm); + if (status != PJ_SUCCESS) { + app_perror("Unable to start capture stream", status); + pjmedia_aud_stream_destroy(strm); + pj_pool_release(test_data.pool); + return status; + } + + PJ_LOG(3,(THIS_FILE, + " Please wait while test is in progress (~%d secs)..", + (DURATION+SKIP_DURATION)/1000)); + + /* Let the stream runs for few msec/sec to get stable result. + * (capture normally begins with frames available simultaneously). + */ + pj_thread_sleep(SKIP_DURATION); + + + /* Begin gather data */ + test_data.running = 1; + + /* + * Let the test runs for a while. + */ + pj_thread_sleep(DURATION); + + + /* + * Close stream. + */ + test_data.running = 0; + pjmedia_aud_stream_destroy(strm); + pj_pool_release(test_data.pool); + + + /* + * Gather results + */ + ptime = param->samples_per_frame * 1000 / param->clock_rate; + + tmp = pj_math_stat_get_stddev(&test_data.capture_data.delay); + result->rec.frame_cnt = test_data.capture_data.delay.n; + result->rec.min_interval = DIV_ROUND(test_data.capture_data.delay.min, 1000); + result->rec.max_interval = DIV_ROUND(test_data.capture_data.delay.max, 1000); + result->rec.avg_interval = DIV_ROUND(test_data.capture_data.delay.mean, 1000); + result->rec.dev_interval = DIV_ROUND(tmp, 1000); + result->rec.max_burst = DIV_ROUND_UP(result->rec.max_interval, ptime); + + tmp = pj_math_stat_get_stddev(&test_data.playback_data.delay); + result->play.frame_cnt = test_data.playback_data.delay.n; + result->play.min_interval = DIV_ROUND(test_data.playback_data.delay.min, 1000); + result->play.max_interval = DIV_ROUND(test_data.playback_data.delay.max, 1000); + result->play.avg_interval = DIV_ROUND(test_data.playback_data.delay.mean, 1000); + result->play.dev_interval = DIV_ROUND(tmp, 1000); + result->play.max_burst = DIV_ROUND_UP(result->play.max_interval, ptime); + + /* Check drifting */ + if (param->dir == PJMEDIA_DIR_CAPTURE_PLAYBACK) { + int play_diff, cap_diff, drift; + + play_diff = test_data.playback_data.last_timestamp - + test_data.playback_data.first_timestamp; + cap_diff = test_data.capture_data.last_timestamp - + test_data.capture_data.first_timestamp; + drift = play_diff > cap_diff? play_diff - cap_diff : + cap_diff - play_diff; + + /* Allow one frame tolerance for clock drift detection */ + if (drift < (int)param->samples_per_frame) { + result->rec_drift_per_sec = 0; + } else { + unsigned msec_dur; + + msec_dur = (test_data.capture_data.last_timestamp - + test_data.capture_data.first_timestamp) * 1000 / + test_data.param->clock_rate; + + result->rec_drift_per_sec = drift * 1000 / msec_dur; + + } + } + + return test_data.has_error? PJ_EUNKNOWN : PJ_SUCCESS; +} + diff --git a/pool/shard003/C/0067003_mexchol.c b/pool/shard003/C/0067003_mexchol.c new file mode 100644 index 0000000000000000000000000000000000000000..8edca964fb0ef32904b36085cab5ee36c1021352 --- /dev/null +++ b/pool/shard003/C/0067003_mexchol.c @@ -0,0 +1,52 @@ +/************************************************************************ +* U = mexchol(X) X = U'*U +* Computes upper-triangular Cholesky factor U of full symmetric positive +* definite matrix X. +* +* Uses LAPACK routine DPOTRF +************************************************************************/ + +#include "mex.h" +#include + +/******************************************************************** + PROCEDURE mexFunction - Entry for Matlab +*********************************************************************/ +void mexFunction(const int nlhs, mxArray *plhs[], + const int nrhs, const mxArray *prhs[]) +{ + int n; + double *x, *info; + char *chn; + int infotmp=0, j,k,jn; + + + if(nrhs < 1) + mexErrMsgTxt("mexchol: requires 1 input arguments."); + if(nlhs > 1) + mexErrMsgTxt("mexchol: requires 1 output argument."); + + x = mxGetPr(prhs[0]); + if (mxIsSparse(prhs[0])) + mexErrMsgTxt("Sparse X not supported by mexchol."); + n = mxGetM(prhs[0]); + if ( n != mxGetN(prhs[0]) ) + mexErrMsgTxt("X should be square."); + plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL); + info = mxGetPr(plhs[0]); + + chn = "U"; + dpotrf(chn, &n, x, &n, &infotmp); + info[0] = (double)infotmp; + /***** make lower triangular part of x zero *****/ + for (j=0; j *b ? 1 : 0; +} + +TEST_GROUP(quick_sort); + +TEST_SETUP(quick_sort) +{ +} + +TEST_TEAR_DOWN(quick_sort) +{ +} + +TEST(quick_sort, SelectPivot) +{ + int a[] = {10, 6, 9, 4}; + int t = partition(a, sizeof(int), 0, 3, &compare); + + TEST_ASSERT_NOT_EQUAL(-1, t) + TEST_ASSERT_EQUAL_INT(6, a[0]); + +} + +TEST(quick_sort, OneSort) +{ + int a[] = {10}; + quick_sort(a, sizeof(int), 0, 0, compare); + + TEST_ASSERT_EQUAL_INT(10, a[0]); +} + +TEST(quick_sort, TwoSort) +{ + int a[] = {10, 6}; + quick_sort(a, sizeof(int), 0, 1, compare); + + TEST_ASSERT_EQUAL_INT(6, a[0]); + TEST_ASSERT_EQUAL_INT(10, a[1]); +} + +TEST(quick_sort, ThreeSort) +{ + int a[] = {10, 6, 9}; + quick_sort(a, sizeof(int), 0, 2, compare); + + TEST_ASSERT_EQUAL_INT(6, a[0]); + TEST_ASSERT_EQUAL_INT(9, a[1]); + TEST_ASSERT_EQUAL_INT(10, a[2]); +} + +TEST(quick_sort, AnySort) +{ + int a[] = {10, 6, 9, 15, 15, 100, 50}; + quick_sort(a, sizeof(int), 0, 6, compare); + + TEST_ASSERT_EQUAL_INT(6, a[0]); + TEST_ASSERT_EQUAL_INT(9, a[1]); + TEST_ASSERT_EQUAL_INT(10, a[2]); + TEST_ASSERT_EQUAL_INT(15, a[3]); + TEST_ASSERT_EQUAL_INT(15, a[4]); + TEST_ASSERT_EQUAL_INT(50, a[5]); + TEST_ASSERT_EQUAL_INT(100, a[6]); +} + diff --git a/pool/shard003/C/0067013_version.c b/pool/shard003/C/0067013_version.c new file mode 100644 index 0000000000000000000000000000000000000000..f01e7e04c30e4799ae63d02f0892ca4dda75ce09 --- /dev/null +++ b/pool/shard003/C/0067013_version.c @@ -0,0 +1,289 @@ +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% V V EEEEE RRRR SSSSS IIIII OOO N N % +% V V E R R SS I O O NN N % +% V V EEE RRRR SSS I O O N N N % +% V V E R R SS I O O N NN % +% V EEEEE R R SSSSS IIIII OOO N N % +% % +% % +% MagickCore Version and Copyright Methods % +% % +% Software Design % +% John Cristy % +% September 2002 % +% % +% % +% Copyright 1999-2013 ImageMagick Studio LLC, a non-profit organization % +% dedicated to making software imaging solutions freely available. % +% % +% You may not use this file except in compliance with the License. You may % +% obtain a copy of the License at % +% % +% http://www.imagemagick.org/script/license.php % +% % +% 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 "MagickCore/studio.h" +#include "MagickCore/configure.h" +#include "MagickCore/exception.h" +#include "MagickCore/exception-private.h" +#include "MagickCore/hashmap.h" +#include "MagickCore/locale_.h" +#include "MagickCore/option.h" +#include "MagickCore/string_.h" +#include "MagickCore/utility.h" +#include "MagickCore/utility-private.h" +#include "MagickCore/version.h" + +/* + Define declarations. +*/ +#define MagickURLFilename "index.html" + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% G e t M a g i c k C o p y r i g h t % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% GetMagickCopyright() returns the ImageMagick API copyright as a string. +% +% The format of the GetMagickCopyright method is: +% +% const char *GetMagickCopyright(void) +% +*/ +MagickExport const char *GetMagickCopyright(void) +{ + return(MagickCopyright); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% G e t M a g i c k F e a t u r e s % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% GetMagickFeatures() returns the ImageMagick features. +% +% The format of the GetMagickFeatures method is: +% +% const char *GetMagickFeatures(void) +% +% No parameters are required. +% +*/ +MagickExport const char *GetMagickFeatures(void) +{ + return(MagickFeatures); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% G e t M a g i c k H o m e U R L % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% GetMagickHomeURL() returns the ImageMagick home URL. +% +% The format of the GetMagickHomeURL method is: +% +% char *GetMagickHomeURL(void) +% +*/ +MagickExport char *GetMagickHomeURL(void) +{ + char + path[MaxTextExtent]; + + const char + *element; + + ExceptionInfo + *exception; + + LinkedListInfo + *paths; + + exception=AcquireExceptionInfo(); + paths=GetConfigurePaths(MagickURLFilename,exception); + exception=DestroyExceptionInfo(exception); + if (paths == (LinkedListInfo *) NULL) + return(ConstantString(MagickHomeURL)); + element=(const char *) GetNextValueInLinkedList(paths); + while (element != (const char *) NULL) + { + (void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",element, + DirectorySeparator,MagickURLFilename); + if (IsPathAccessible(path) != MagickFalse) + return(ConstantString(path)); + element=(const char *) GetNextValueInLinkedList(paths); + } + return(ConstantString(MagickHomeURL)); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% G e t M a g i c k P a c k a g e N a m e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% GetMagickPackageName() returns the ImageMagick package name. +% +% The format of the GetMagickName method is: +% +% const char *GetMagickName(void) +% +% No parameters are required. +% +*/ +MagickExport const char *GetMagickPackageName(void) +{ + return(MagickPackageName); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% G e t M a g i c k Q u a n t u m D e p t h % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% GetMagickQuantumDepth() returns the ImageMagick quantum depth. +% +% The format of the GetMagickQuantumDepth method is: +% +% const char *GetMagickQuantumDepth(size_t *depth) +% +% A description of each parameter follows: +% +% o depth: the quantum depth is returned as a number. +% +*/ +MagickExport const char *GetMagickQuantumDepth(size_t *depth) +{ + if (depth != (size_t *) NULL) + *depth=(size_t) MAGICKCORE_QUANTUM_DEPTH; + return(MagickQuantumDepth); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% G e t M a g i c k Q u a n t u m R a n g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% GetMagickQuantumRange() returns the ImageMagick quantum range. +% +% The format of the GetMagickQuantumRange method is: +% +% const char *GetMagickQuantumRange(size_t *range) +% +% A description of each parameter follows: +% +% o range: the quantum range is returned as a number. +% +*/ +MagickExport const char *GetMagickQuantumRange(size_t *range) +{ + if (range != (size_t *) NULL) + *range=(size_t) QuantumRange; + return(MagickQuantumRange); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% G e t M a g i c k R e l e a s e D a t e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% GetMagickReleaseDate() returns the ImageMagick release date. +% +% The format of the GetMagickReleaseDate method is: +% +% const char *GetMagickReleaseDate(void) +% +% No parameters are required. +% +*/ +MagickExport const char *GetMagickReleaseDate(void) +{ + return(MagickReleaseDate); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% G e t M a g i c k V e r s i o n % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% GetMagickVersion() returns the ImageMagick API version as a string and +% as a number. +% +% The format of the GetMagickVersion method is: +% +% const char *GetMagickVersion(size_t *version) +% +% A description of each parameter follows: +% +% o version: the ImageMagick version is returned as a number. +% +*/ +MagickExport const char *GetMagickVersion(size_t *version) +{ + if (version != (size_t *) NULL) + *version=MagickLibVersion; + return(MagickVersion); +} diff --git a/pool/shard003/C/0067018_Mockery_Command.c b/pool/shard003/C/0067018_Mockery_Command.c new file mode 100644 index 0000000000000000000000000000000000000000..c42e9506b16646f0ed3e876f05620d06350ba552 --- /dev/null +++ b/pool/shard003/C/0067018_Mockery_Command.c @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include +#include +#include +#include + + +static int __run_action(Command *command) +{ + int argc; + char **argv; + dbg_str(DBG_DETAIL, "mockery start"); + + argc = command->argc; + argv = command->argv; + if (argc == 2) { + int targc = argc - 1; + execute_test_designated_func(argv[1], (void *)&targc, argv + 1); + } else { + debugger_set_all_businesses_level(debugger_gp, 1, 6); + execute_test_funcs(); + } + + dbg_str(DBG_DETAIL, "mockery end"); + + return 1; +} + + +static int __construct(Command *command, char *init_str) +{ + command->set(command, "/Command/name", "mockery"); + + return 0; +} + +static int __deconstruct(Command *command) +{ + return 0; +} + +static class_info_entry_t test_command_class_info[] = { + Init_Obj___Entry(0, Command, parent), + Init_Nfunc_Entry(1, Mockery_Command, construct, __construct), + Init_Nfunc_Entry(2, Mockery_Command, deconstruct, __deconstruct), + Init_Vfunc_Entry(3, Mockery_Command, run_action, __run_action), + Init_End___Entry(4, Mockery_Command), +}; +REGISTER_APP_CMD("Mockery_Command", test_command_class_info); diff --git a/pool/shard003/C/0067025_LED.c b/pool/shard003/C/0067025_LED.c new file mode 100644 index 0000000000000000000000000000000000000000..69cfc6ae666a8a8a440a2f408ae062784bfe6dfe --- /dev/null +++ b/pool/shard003/C/0067025_LED.c @@ -0,0 +1,60 @@ +/* + * LED.c + * input file : LED.idl + * generated at : Mon Feb 09 15:09:24 +0900 2009 + */ + +#include +#include +#include +#include "CORBA_Object.h" +#include "Giop.h" +#include "Orbe.h" +#include "LED.h" + + +void dispatch(Req *req, Reply *reply, Giop_Hdr *header) +{ + u8 *req_ptr; + u8 *reply_ptr; + u8 *start; + + req_ptr = req->body; + reply_ptr = start = reply->body; + +if (strcmp((void*)req->operation, "turnOn") == 0) { + CORBA_long ID; + +ID = Orbe_exchangeLong(*(u32*)req_ptr); +req_ptr += sizeof(CORBA_long); + +void result = LED_turnOn(NULL, ID, NULL); + + +} +if (strcmp((void*)req->operation, "turnOff") == 0) { + CORBA_long ID; + +ID = Orbe_exchangeLong(*(u32*)req_ptr); +req_ptr += sizeof(CORBA_long); + +void result = LED_turnOff(NULL, ID, NULL); + + +} +if (strcmp((void*)req->operation, "getState") == 0) { + CORBA_long ID; + +ID = Orbe_exchangeLong(*(u32*)req_ptr); +req_ptr += sizeof(CORBA_long); + +CORBA_boolean result = LED_getState(NULL, ID, NULL); + +*reply_ptr = result; +reply_ptr += sizeof(CORBA_boolean); + +} + + reply->body_size = (size_t) (reply_ptr - start); +} + diff --git a/pool/shard003/C/0067026_virtualmouse.c b/pool/shard003/C/0067026_virtualmouse.c new file mode 100644 index 0000000000000000000000000000000000000000..bfe464eab114ffa8fdf02956cf3aa13c83ffa72e --- /dev/null +++ b/pool/shard003/C/0067026_virtualmouse.c @@ -0,0 +1,158 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int vmouse_major = 200; + +static struct input_dev* vmouse_idev = NULL; + +int vmouse_open(struct inode* inode, struct file* filp) +{ + return 0; +} + +int vmouse_release(struct inode* inode, struct file* filp) +{ + return 0; +} + +ssize_t vmouse_read(struct file* filp, char __user *buf, size_t count, loff_t* f_pos) +{ + printk(KERN_INFO"%s\n", __func__); + return count; +} + +struct mouse_event +{ + int flag; + int x; + int y; +}; + +ssize_t vmouse_write(struct file* filp, const char __user * buf, size_t count, loff_t* f_pos) +{ + int ret = 0; + struct mouse_event event; + + while(ret < count) + { + if(copy_from_user(&event, buf + ret, sizeof(event))) + { + return -EFAULT; + } + ret += sizeof(event); + + if(event.flag == 2) + { + input_report_rel(vmouse_idev, REL_X, event.x); + input_report_rel(vmouse_idev, REL_Y, event.y); + input_sync(vmouse_idev); + } else if (event.flag == 1) { + input_report_key(vmouse_idev, BTN_MOUSE, event.x); + input_sync(vmouse_idev); + }else if (event.flag == 0) { + input_report_key(vmouse_idev, BTN_RIGHT, event.x); + input_sync(vmouse_idev); + } else if(event.flag == 3) + { + input_report_rel(vmouse_idev, REL_WHEEL, event.x); + input_report_rel(vmouse_idev, REL_HWHEEL, event.y); + input_sync(vmouse_idev); + } + } + + return ret; +} + +static struct file_operations vmouse_fops = +{ + .owner = THIS_MODULE, + .open = vmouse_open, + .release = vmouse_release, + .read = vmouse_read, + .write = vmouse_write, +}; + +static int vmouse_input_dev_open(struct input_dev* idev) +{ + printk(KERN_INFO"%s \n", __func__); + + return 0; +} + +static void vmouse_input_dev_close(struct input_dev* idev) +{ + printk(KERN_INFO"%s \n", __func__); + + return; +} + +static int vmouse_input_dev_setup(void) +{ + int ret = 0; + vmouse_idev = input_allocate_device(); + + if(vmouse_idev == NULL) + { + return -ENOMEM; + } + + vmouse_idev->name = "vmouse"; + vmouse_idev->phys = "vmouse/input0"; + vmouse_idev->id.bustype = BUS_HOST; + vmouse_idev->id.product = 0x0001; + vmouse_idev->id.vendor = 0x0002; + vmouse_idev->id.version = 0x0100; + vmouse_idev->open = vmouse_input_dev_open; + vmouse_idev->close = vmouse_input_dev_close; + + vmouse_idev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL); + vmouse_idev->keybit[BIT_WORD(BTN_LEFT)] = BIT_MASK(BTN_LEFT) | + BIT_MASK(BTN_MIDDLE) | BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_TOUCH); + vmouse_idev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y) | BIT_MASK(REL_WHEEL) | BIT_MASK(REL_HWHEEL); + + ret = input_register_device(vmouse_idev); + + return ret; +} + +static struct miscdevice mouse_dev = { + .minor = MISC_DYNAMIC_MINOR, + .name = "vmouse", + .fops = &vmouse_fops, +}; + +static int __init vmouse_init(void) +{ + int result = misc_register(&mouse_dev); + vmouse_input_dev_setup(); + + return result; +} + +static void __exit vmouse_cleanup(void) +{ + input_unregister_device(vmouse_idev); + misc_deregister(&mouse_dev); + + return; +} + +module_init(vmouse_init); +module_exit(vmouse_cleanup); + +MODULE_AUTHOR("marco "); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard003/C/0067027_imap-ssl.c b/pool/shard003/C/0067027_imap-ssl.c new file mode 100644 index 0000000000000000000000000000000000000000..ce890c97bf4516ec1f08d77ace522758c267e239 --- /dev/null +++ b/pool/shard003/C/0067027_imap-ssl.c @@ -0,0 +1,92 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* + * IMAP example using SSL + * + */ + +#include +#include + +/* This is a simple example showing how to fetch mail using libcurl's IMAP + * capabilities. It builds on the imap-fetch.c example adding transport + * security to protect the authentication details from being snooped. + * + * Note that this example requires libcurl 7.30.0 or above. + */ + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + + curl = curl_easy_init(); + if(curl) { + /* Set username and password */ + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + /* This will fetch message 1 from the user's inbox. Note the use of + * imaps:// rather than imap:// to request a SSL based connection. */ + curl_easy_setopt(curl, CURLOPT_URL, + "imaps://imap.example.com/INBOX/;UID=1"); + + /* If you want to connect to a site who isn't using a certificate that is + * signed by one of the certs in the CA bundle you have, you can skip the + * verification of the server's certificate. This makes the connection + * A LOT LESS SECURE. + * + * If you have a CA cert for the server stored someplace else than in the + * default bundle, then the CURLOPT_CAPATH option might come handy for + * you. */ +#ifdef SKIP_PEER_VERIFICATION + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); +#endif + + /* If the site you're connecting to uses a different host name that what + * they have mentioned in their server certificate's commonName (or + * subjectAltName) fields, libcurl will refuse to connect. You can skip + * this check, but this will make the connection less secure. */ +#ifdef SKIP_HOSTNAME_VERIFICATION + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); +#endif + + /* Since the traffic will be encrypted, it is very useful to turn on debug + * information within libcurl to see what is happening during the + * transfer */ + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + /* Perform the fetch */ + res = curl_easy_perform(curl); + + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* Always cleanup */ + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/pool/shard003/C/0067028_ui-commands-impl.c b/pool/shard003/C/0067028_ui-commands-impl.c new file mode 100644 index 0000000000000000000000000000000000000000..2ceeca10a0a83e73ddbc3507ab281f6c22a9039c --- /dev/null +++ b/pool/shard003/C/0067028_ui-commands-impl.c @@ -0,0 +1,256 @@ +/* Copyright (C) 2010 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. +*/ + +/* + * Contains the UI-side implementation of the "core-ui-control" service that is + * part of the UI control protocol. Here we handle UI control commands received + * from the Core. + */ + +#include +#include "android/looper.h" +#include "android/async-utils.h" +#include "android/sync-utils.h" +#include "android/utils/system.h" +#include "android/utils/debug.h" +#include "android/utils/panic.h" +#include "android/protocol/core-connection.h" +#include "android/protocol/ui-commands-impl.h" +#include "android/protocol/ui-commands-api.h" + +/* Enumerates states for the command reader in UICmdImpl instance. */ +typedef enum UICmdImplState { + /* The reader is waiting on command header. */ + EXPECTS_HEADER, + + /* The reader is waiting on command parameters. */ + EXPECTS_PARAMETERS, +} UICmdImplState; + +/* Descriptor for the UI-side of the "core-ui-control" service. */ +typedef struct UICmdImpl { + /* Core connection established for this service. */ + CoreConnection* core_connection; + + /* Socket descriptor for the UI service. */ + int sock; + + /* Custom i/o handler */ + LoopIo io[1]; + + /* Command reader state. */ + UICmdImplState reader_state; + + /* Incoming command header. */ + UICmdHeader cmd_header; + + /* Reader's buffer. This field can point to the cmd_header field of this + * structure (when we expect a command header), or to a buffer allocated for + * the (when we expect command parameters). */ + uint8_t* reader_buffer; + + /* Offset in the reader's buffer where to read next chunk of data. */ + size_t reader_offset; + + /* Total number of bytes the reader expects to read. */ + size_t reader_bytes; +} UICmdImpl; + +/* Implemented in android/qemulator.c */ +extern void android_emulator_set_window_scale(double scale, int is_dpi); + +/* One and only one UICmdImpl instance. */ +static UICmdImpl _uiCmdImpl; + +/* Display brightness change callback. */ +static AndroidHwLightBrightnessCallback _brightness_change_callback = NULL; +static void* _brightness_change_callback_param = NULL; + +/* Handles UI control command received from the core. + * Param: + * uicmd - UICmdImpl instance that received the command. + * header - UI control command header. + * data - Command parameters formatted accordingly to the command type. + */ +static void +_uiCmdImpl_handle_command(UICmdImpl* uicmd, + const UICmdHeader* header, + const uint8_t* data) +{ + switch (header->cmd_type) { + case AUICMD_SET_WINDOWS_SCALE: + { + UICmdSetWindowsScale* cmd = (UICmdSetWindowsScale*)data; + android_emulator_set_window_scale(cmd->scale, cmd->is_dpi); + break; + } + + case AUICMD_CHANGE_DISP_BRIGHTNESS: + { + UICmdChangeDispBrightness* cmd = (UICmdChangeDispBrightness*)data; + if (_brightness_change_callback != NULL) { + _brightness_change_callback(_brightness_change_callback_param, + cmd->light, cmd->brightness); + } + break; + } + + default: + derror("Unknown command %d is received from the Core\n", + header->cmd_type); + break; + } +} + +/* Asynchronous I/O callback reading UI control commands. + * Param: + * opaque - UICmdImpl instance. + */ +static void +_uiCmdImpl_io_callback(void* opaque, int fd, unsigned events) +{ + UICmdImpl* uicmd = opaque; + int status; + + // Read requests while they are immediately available. + for (;;) { + // Read next chunk of data. + status = socket_recv(uicmd->sock, + uicmd->reader_buffer + uicmd->reader_offset, + uicmd->reader_bytes - uicmd->reader_offset); + if (status == 0) { + /* Disconnection, meaning that the core process got terminated. */ + fprintf(stderr, "core-ui-control service got disconnected\n"); + uiCmdImpl_destroy(); + return; + } + if (status < 0) { + if (errno == EINTR) { + /* loop on EINTR */ + continue; + } else if (errno == EWOULDBLOCK || errno == EAGAIN) { + // Chunk is not avalable at this point. Come back later. + return; + } + } + + uicmd->reader_offset += status; + if (uicmd->reader_offset != uicmd->reader_bytes) { + // There are still some data left in the pipe. + continue; + } + + // All expected data has been read. Time to change the state. + if (uicmd->reader_state == EXPECTS_HEADER) { + // Header has been read. + if (uicmd->cmd_header.cmd_param_size) { + // Prepare for the command parameters. + uicmd->reader_state = EXPECTS_PARAMETERS; + uicmd->reader_offset = 0; + uicmd->reader_bytes = uicmd->cmd_header.cmd_param_size; + uicmd->reader_buffer = malloc(uicmd->reader_bytes); + if (uicmd->reader_buffer == NULL) { + APANIC("Unable to allocate memory for UI command parameters.\n"); + } + } else { + // This command doesn't have any parameters. Handle it now. + _uiCmdImpl_handle_command(uicmd, &uicmd->cmd_header, NULL); + // Prepare for the next command header. + uicmd->reader_state = EXPECTS_HEADER; + uicmd->reader_offset = 0; + uicmd->reader_bytes = sizeof(uicmd->cmd_header); + uicmd->reader_buffer = (uint8_t*)&uicmd->cmd_header; + } + } else { + // All command data is in. Handle it. + _uiCmdImpl_handle_command(uicmd, &uicmd->cmd_header, + uicmd->reader_buffer); + // Prepare for the next command header. + free(uicmd->reader_buffer); + uicmd->reader_state = EXPECTS_HEADER; + uicmd->reader_offset = 0; + uicmd->reader_bytes = sizeof(uicmd->cmd_header); + uicmd->reader_buffer = (uint8_t*)&uicmd->cmd_header; + } + } +} + +int +uiCmdImpl_create(SockAddress* console_socket, Looper* looper) +{ + UICmdImpl* uicmd = &_uiCmdImpl; + char* handshake = NULL; + + // Setup command reader. + uicmd->reader_buffer = (uint8_t*)&uicmd->cmd_header; + uicmd->reader_state = EXPECTS_HEADER; + uicmd->reader_offset = 0; + uicmd->reader_bytes = sizeof(UICmdHeader); + + // Connect to the core-ui-control service. + uicmd->core_connection = + core_connection_create_and_switch(console_socket, "core-ui-control", + &handshake); + if (uicmd->core_connection == NULL) { + derror("Unable to connect to the core-ui-control service: %s\n", + errno_str); + return -1; + } + + // Initialize UI command reader. + uicmd->sock = core_connection_get_socket(uicmd->core_connection); + loopIo_init(uicmd->io, looper, uicmd->sock, + _uiCmdImpl_io_callback, + &_uiCmdImpl); + loopIo_wantRead(uicmd->io); + + fprintf(stdout, "core-ui-control is now connected to the core at %s.", + sock_address_to_string(console_socket)); + if (handshake != NULL) { + if (handshake[0] != '\0') { + fprintf(stdout, " Handshake: %s", handshake); + } + free(handshake); + } + fprintf(stdout, "\n"); + + return 0; +} + +void +uiCmdImpl_destroy(void) +{ + UICmdImpl* uicmd = &_uiCmdImpl; + + if (uicmd->core_connection != NULL) { + // Disable I/O callbacks. + loopIo_done(uicmd->io); + core_connection_close(uicmd->core_connection); + core_connection_free(uicmd->core_connection); + uicmd->core_connection = NULL; + } + // Properly deallocate the reader buffer. + if (uicmd->reader_buffer != NULL && + uicmd->reader_buffer != (uint8_t*)&uicmd->cmd_header) { + free(uicmd->reader_buffer); + uicmd->reader_buffer = (uint8_t*)&uicmd->cmd_header; + } +} + +int +uicmd_set_brightness_change_callback(AndroidHwLightBrightnessCallback callback, + void* opaque) +{ + _brightness_change_callback = callback; + _brightness_change_callback_param = opaque; + return 0; +} diff --git a/pool/shard003/C/0067035_path.c b/pool/shard003/C/0067035_path.c new file mode 100644 index 0000000000000000000000000000000000000000..bdb09df79dccc32a6dfffba81526704a13314b0b --- /dev/null +++ b/pool/shard003/C/0067035_path.c @@ -0,0 +1,43 @@ +/* + * 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 Library 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. + * + * If you have any questions, comments, suggestions, or fixes please + * email me at: imre.leber@worldonline.be + */ + +#include +#include + +#define DIR_SEPARATOR "\\" + +/*-------------------------------------------------------------------------*/ +/* Appends a trailing directory separator to the path, but only if it is */ +/* missing. */ +/*-------------------------------------------------------------------------*/ + +char *addsep(char *path) +{ + int path_length; + + path_length=strlen(path); + if (path[path_length-1] != *DIR_SEPARATOR) + { + path[path_length]=*DIR_SEPARATOR; + path[path_length+1]='\0'; + } // end if. + + return path; + +} // end addsep. diff --git a/pool/shard003/C/0067044_decim_f32.c b/pool/shard003/C/0067044_decim_f32.c new file mode 100644 index 0000000000000000000000000000000000000000..ea805d13f47be4ee07d22523ed30b9da0fc86cd2 --- /dev/null +++ b/pool/shard003/C/0067044_decim_f32.c @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2021 Stephanos Ioannidis + * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include +#include "../../common/test_common.h" + +#include "decim_f32.pat" + +#define SNR_ERROR_THRESH ((float32_t)100) +#define REL_ERROR_THRESH (8.0e-4) +#define STATE_BUF_LEN (16 + 768 - 1) + +static void test_arm_fir_decimate_f32(void) +{ + uint32_t decim_factor, tap_count; + size_t sample_index, block_size, ref_size; + size_t sample_count = ARRAY_SIZE(in_config_decim) / 4; + size_t length = ARRAY_SIZE(ref_decim); + const uint32_t *config = in_config_decim; + const float32_t *input = (const float32_t *)in_val_decim; + const float32_t *coeff = (const float32_t *)in_coeff_decim; + const float32_t *ref = (const float32_t *)ref_decim; + float32_t *state, *output_buf, *output; + arm_status status; + arm_fir_decimate_instance_f32 inst; + + /* Allocate buffers */ + state = malloc(STATE_BUF_LEN * sizeof(float32_t)); + zassert_not_null(state, ASSERT_MSG_BUFFER_ALLOC_FAILED); + + output_buf = malloc(length * sizeof(float32_t)); + zassert_not_null(output_buf, ASSERT_MSG_BUFFER_ALLOC_FAILED); + + output = output_buf; + + /* Enumerate samples */ + for (sample_index = 0; sample_index < sample_count; sample_index++) { + /* Resolve sample configurations */ + decim_factor = config[0]; + tap_count = config[1]; + block_size = config[2]; + ref_size = config[3]; + + /* Initialise instance */ + status = arm_fir_decimate_init_f32(&inst, tap_count, + decim_factor, coeff, state, + block_size); + + zassert_equal(status, ARM_MATH_SUCCESS, + ASSERT_MSG_INCORRECT_COMP_RESULT); + + /* Run test function */ + arm_fir_decimate_f32(&inst, input, output, block_size); + + /* Increment pointers */ + input += block_size; + output += ref_size; + coeff += tap_count; + config += 4; + } + + /* Validate output */ + zassert_true( + test_snr_error_f32(length, output_buf, ref, SNR_ERROR_THRESH), + ASSERT_MSG_SNR_LIMIT_EXCEED); + + zassert_true( + test_rel_error_f32(length, output_buf, ref, REL_ERROR_THRESH), + ASSERT_MSG_REL_ERROR_LIMIT_EXCEED); + + /* Free buffers */ + free(state); + free(output_buf); +} + +static void test_arm_fir_interpolate_f32(void) +{ + uint32_t filter_length, tap_count; + size_t sample_index, block_size, ref_size; + size_t sample_count = ARRAY_SIZE(in_config_interp) / 4; + size_t length = ARRAY_SIZE(ref_interp); + const uint32_t *config = in_config_interp; + const float32_t *input = (const float32_t *)in_val_interp; + const float32_t *coeff = (const float32_t *)in_coeff_interp; + const float32_t *ref = (const float32_t *)ref_interp; + float32_t *state, *output_buf, *output; + arm_status status; + arm_fir_interpolate_instance_f32 inst; + + /* Allocate buffers */ + state = malloc(STATE_BUF_LEN * sizeof(float32_t)); + zassert_not_null(state, ASSERT_MSG_BUFFER_ALLOC_FAILED); + + output_buf = malloc(length * sizeof(float32_t)); + zassert_not_null(output_buf, ASSERT_MSG_BUFFER_ALLOC_FAILED); + + output = output_buf; + + /* Enumerate samples */ + for (sample_index = 0; sample_index < sample_count; sample_index++) { + /* Resolve sample configurations */ + filter_length = config[0]; + tap_count = config[1]; + block_size = config[2]; + ref_size = config[3]; + + /* Initialise instance */ + status = arm_fir_interpolate_init_f32(&inst, filter_length, + tap_count, coeff, + state, block_size); + + zassert_equal(status, ARM_MATH_SUCCESS, + ASSERT_MSG_INCORRECT_COMP_RESULT); + + /* Run test function */ + arm_fir_interpolate_f32(&inst, input, output, block_size); + + /* Increment pointers */ + input += block_size; + output += ref_size; + coeff += tap_count; + config += 4; + } + + /* Validate output */ + zassert_true( + test_snr_error_f32(length, output_buf, ref, SNR_ERROR_THRESH), + ASSERT_MSG_SNR_LIMIT_EXCEED); + + zassert_true( + test_rel_error_f32(length, output_buf, ref, REL_ERROR_THRESH), + ASSERT_MSG_REL_ERROR_LIMIT_EXCEED); + + /* Free buffers */ + free(state); + free(output_buf); +} + +void test_filtering_decim_f32(void) +{ + ztest_test_suite(filtering_decim_f32, + ztest_unit_test(test_arm_fir_decimate_f32), + ztest_unit_test(test_arm_fir_interpolate_f32) + ); + + ztest_run_test_suite(filtering_decim_f32); +} diff --git a/pool/shard003/C/0067045_helper.c b/pool/shard003/C/0067045_helper.c new file mode 100644 index 0000000000000000000000000000000000000000..5cfe889ad460fe7eea2d57fbd34b67d9202e119a --- /dev/null +++ b/pool/shard003/C/0067045_helper.c @@ -0,0 +1,174 @@ +/* + * Moxie helper routines. + * + * Copyright (c) 2008, 2009, 2010, 2013 Anthony Green + * + * 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 General Public License + * along with this program. If not, see . + */ + +#include +#include +#include + +#include "config.h" +#include "cpu.h" +#include "mmu.h" +#include "exec/exec-all.h" +#include "qemu/host-utils.h" +#include "helper.h" + +#define MMUSUFFIX _mmu + +#define SHIFT 0 +#include "exec/softmmu_template.h" + +#define SHIFT 1 +#include "exec/softmmu_template.h" + +#define SHIFT 2 +#include "exec/softmmu_template.h" + +#define SHIFT 3 +#include "exec/softmmu_template.h" + +/* Try to fill the TLB and return an exception if error. If retaddr is + NULL, it means that the function was called in C code (i.e. not + from generated code or from helper.c) */ +void tlb_fill(CPUMoxieState *env, target_ulong addr, int is_write, int mmu_idx, + uintptr_t retaddr) +{ + int ret; + + ret = cpu_moxie_handle_mmu_fault(env, addr, is_write, mmu_idx); + if (unlikely(ret)) { + if (retaddr) { + cpu_restore_state(env, retaddr); + } + } + cpu_loop_exit(env); +} + +void helper_raise_exception(CPUMoxieState *env, int ex) +{ + env->exception_index = ex; + /* Stash the exception type. */ + env->sregs[2] = ex; + /* Stash the address where the exception occurred. */ + cpu_restore_state(env, GETPC()); + env->sregs[5] = env->pc; + /* Jump the the exception handline routine. */ + env->pc = env->sregs[1]; + cpu_loop_exit(env); +} + +uint32_t helper_div(CPUMoxieState *env, uint32_t a, uint32_t b) +{ + if (unlikely(b == 0)) { + helper_raise_exception(env, MOXIE_EX_DIV0); + return 0; + } + if (unlikely(a == INT_MIN && b == -1)) { + return INT_MIN; + } + + return (int32_t)a / (int32_t)b; +} + +uint32_t helper_udiv(CPUMoxieState *env, uint32_t a, uint32_t b) +{ + if (unlikely(b == 0)) { + helper_raise_exception(env, MOXIE_EX_DIV0); + return 0; + } + return a / b; +} + +void helper_debug(CPUMoxieState *env) +{ + env->exception_index = EXCP_DEBUG; + cpu_loop_exit(env); +} + +#if defined(CONFIG_USER_ONLY) + +void moxie_cpu_do_interrupt(CPUState *env) +{ + env->exception_index = -1; +} + +int cpu_moxie_handle_mmu_fault(CPUMoxieState *env, target_ulong address, + int rw, int mmu_idx) +{ + env->exception_index = 0xaa; + env->debug1 = address; + cpu_dump_state(env, stderr, fprintf, 0); + return 1; +} + +hwaddr cpu_get_phys_page_debug(CPUState *env, target_ulong addr) +{ + return addr; +} + +#else /* !CONFIG_USER_ONLY */ + +int cpu_moxie_handle_mmu_fault(CPUMoxieState *env, target_ulong address, + int rw, int mmu_idx) +{ + MoxieMMUResult res; + int prot, miss; + target_ulong phy; + int r = 1; + + address &= TARGET_PAGE_MASK; + prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC; + miss = moxie_mmu_translate(&res, env, address, rw, mmu_idx); + if (miss) { + /* handle the miss. */ + phy = 0; + env->exception_index = MOXIE_EX_MMU_MISS; + } else { + phy = res.phy; + r = 0; + } + tlb_set_page(env, address, phy, prot, mmu_idx, TARGET_PAGE_SIZE); + return r; +} + + +void moxie_cpu_do_interrupt(CPUState *cs) +{ + MoxieCPU *cpu = MOXIE_CPU(cs); + CPUMoxieState *env = &cpu->env; + + switch (env->exception_index) { + case MOXIE_EX_BREAK: + break; + default: + break; + } +} + +hwaddr cpu_get_phys_page_debug(CPUMoxieState *env, target_ulong addr) +{ + uint32_t phy = addr; + MoxieMMUResult res; + int miss; + miss = moxie_mmu_translate(&res, env, addr, 0, 0); + if (!miss) { + phy = res.phy; + } + return phy; +} +#endif diff --git a/pool/shard003/C/0067051_strided_acc_onelock.c b/pool/shard003/C/0067051_strided_acc_onelock.c new file mode 100644 index 0000000000000000000000000000000000000000..55ecde262c37d559f196e3a8bb1210251544192a --- /dev/null +++ b/pool/shard003/C/0067051_strided_acc_onelock.c @@ -0,0 +1,85 @@ +/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ +/* + * (C) 2001 by Argonne National Laboratory. + * See COPYRIGHT in top-level directory. + */ + +/* One-Sided MPI 2-D Strided Accumulate Test + * + * Author: James Dinan + * Date : December, 2010 + * + * This code performs one-sided accumulate into a 2d patch of a shared array. + */ + +#include +#include +#include +#include +#include "mpitest.h" +#include "squelch.h" + +#define XDIM 1024 +#define YDIM 1024 +#define ITERATIONS 10 + +int main(int argc, char **argv) { + int i, j, rank, nranks, peer, bufsize, errors; + double *buffer, *src_buf; + MPI_Win buf_win; + + MTest_Init(&argc, &argv); + + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &nranks); + + bufsize = XDIM * YDIM * sizeof(double); + MPI_Alloc_mem(bufsize, MPI_INFO_NULL, &buffer); + MPI_Alloc_mem(bufsize, MPI_INFO_NULL, &src_buf); + + for (i = 0; i < XDIM*YDIM; i++) { + *(buffer + i) = 1.0 + rank; + *(src_buf + i) = 1.0 + rank; + } + + MPI_Win_create(buffer, bufsize, 1, MPI_INFO_NULL, MPI_COMM_WORLD, &buf_win); + + peer = (rank+1) % nranks; + + for (i = 0; i < ITERATIONS; i++) { + + MPI_Win_lock(MPI_LOCK_EXCLUSIVE, peer, 0, buf_win); + + for (j = 0; j < YDIM; j++) { + MPI_Accumulate(src_buf + j*XDIM, XDIM, MPI_DOUBLE, peer, + j*XDIM*sizeof(double), XDIM, MPI_DOUBLE, MPI_SUM, buf_win); + } + + MPI_Win_unlock(peer, buf_win); + } + + MPI_Barrier(MPI_COMM_WORLD); + + MPI_Win_lock(MPI_LOCK_EXCLUSIVE, rank, 0, buf_win); + for (i = errors = 0; i < XDIM; i++) { + for (j = 0; j < YDIM; j++) { + const double actual = *(buffer + i + j*XDIM); + const double expected = (1.0 + rank) + (1.0 + ((rank+nranks-1)%nranks)) * (ITERATIONS); + if (fabs(actual - expected) > 1.0e-10) { + SQUELCH( printf("%d: Data validation failed at [%d, %d] expected=%f actual=%f\n", + rank, j, i, expected, actual); ); + errors++; + fflush(stdout); + } + } + } + MPI_Win_unlock(rank, buf_win); + + MPI_Win_free(&buf_win); + MPI_Free_mem(buffer); + MPI_Free_mem(src_buf); + + MTest_Finalize( errors ); + MPI_Finalize(); + return MTestReturnValue( errors ); +} diff --git a/pool/shard003/C/0067082_soft_spi.c b/pool/shard003/C/0067082_soft_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..b6dd426027eadcbe707db16e2b646b56bc23789d --- /dev/null +++ b/pool/shard003/C/0067082_soft_spi.c @@ -0,0 +1,53 @@ +/* + * Copyright(C) 2010 by Stefan Siegl + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * For more information on the GPL, please go to: + * http://www.gnu.org/copyleft/gpl.html + */ + +#include "config.h" + +#include +#include "spi_soft.h" + +uint8_t +spi_soft_send(uint8_t outdata) +{ + DDR_CONFIG_IN(SOFT_SPI_MISO); + + uint8_t j, indata = indata; + for(j = 0; j < 8; j++) + { + if(outdata & 0x80) + PIN_SET(SOFT_SPI_MOSI); + else + PIN_CLEAR(SOFT_SPI_MOSI); + + PIN_SET(SOFT_SPI_SCK); + indata <<= 1; + + if(PIN_HIGH(SOFT_SPI_MISO)) + indata |= 1; + + PIN_CLEAR(SOFT_SPI_SCK); + + outdata <<= 1; + } + + DDR_CONFIG_OUT(SOFT_SPI_MISO); + return indata; +} diff --git a/pool/shard003/C/0067084_main.c b/pool/shard003/C/0067084_main.c new file mode 100644 index 0000000000000000000000000000000000000000..d966b08aa857a883b49d9e0ef8d4fff25377e3d6 --- /dev/null +++ b/pool/shard003/C/0067084_main.c @@ -0,0 +1,280 @@ +/* + Filename: main.c + created: 13.9.2005 + + This commandline tool is intended to provide simple headtracking features to + SuperCollider3 applications such as AmbIEM. It uses the ARToolKit for visual + pattern recognition and transmitts the data using OpenSound Control packages + + Copyright (C) IEM 2005, Christopher Frauenberger [frauenberger@iem.at] + + 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. + + IEM - Institute of Electronic Music and Acoustics, Graz + Inffeldgasse 10/3, 8010 Graz, Austria + http://iem.at +*/ + +#include +#include +#include +#include + +#ifdef _WIN32 + #include + #include +#else + #include + #include + #include +#endif + +#ifndef __APPLE__ + #include + #include +#else + #include + #include +#endif + +#include +#include +#include +#include +#include + +#include "OSC-client.h" + +#ifdef _WIN32 + char *vconf = "flipV,showDlg"; // see video.h for a list of supported parameters +#else + char *vconf = ""; +#endif + +int xsize, ysize; +int thresh = 100; +int count = 0; + +char *cparam_name = "./camera_para.dat"; +ARParam cparam; + +char *patt_name = "./patt.hiro"; +int patt_id; +double patt_width = 80.0; +double patt_center[2] = {0.0, 0.0}; +double patt_trans[3][4]; + +int sockfd; +struct sockaddr_in serverAddress; +OSCbuf *oscbuf; + +static void init(void); +static void cleanup(void); +static void mainLoop(void); +static void keyEvent(void); +static void sendOSC(double, double, double); + +int main(int argc, char **argv) +{ + int port; + char *server; + OSCbuf myBuf; + char bytes[1000]; + + if (argc > 2) { port = atoi(argv[2]); } + else { port = 57120; }; + if (argc > 1) { strcpy(server, argv[1]); } + else { server = "127.0.0.1"; }; + + printf("Connecting to server %s:%i \n", server, port); + + // init the AR stuff and GLUT to be able to see the captured image in the setup dialog + int ac = 0; char *av = ""; + glutInit(&ac, av); + init(); + + // init networking connection + if ( (sockfd = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 ) { + printf("Cant create socket, exiting.\n"); + exit(1); + } + bzero( &serverAddress, sizeof(serverAddress) ); + serverAddress.sin_family = AF_INET; + serverAddress.sin_port = htons( port ); + inet_pton( AF_INET, server , &serverAddress.sin_addr ); + + // init the OSC Buffer + oscbuf = &myBuf; + OSC_initBuffer(oscbuf, 1000, bytes); + + arVideoCapStart(); + argMainLoop( NULL, keyEvent, mainLoop ); + return (0); +} + +/* keyEvent */ +static void keyEvent(void) +{ + +}; + +/* main loop */ +static void mainLoop(void) +{ + ARUint8 *dataPtr; + ARMarkerInfo *marker_info; + int marker_num; + int j, k; + int i,u; + + /* grab a vide frame */ + if( (dataPtr = (ARUint8 *)arVideoGetImage()) == NULL ) { + arUtilSleep(2); + return; + } + if( count == 0 ) arUtilTimerReset(); + count++; + + argDrawMode2D(); + argDispImage( dataPtr, 0,0 ); + + /* detect the markers in the video frame */ + if( arDetectMarker(dataPtr, thresh, &marker_info, &marker_num) < 0 ) { + cleanup(); + exit(0); + } + + arVideoCapNext(); + + /* check for object visibility */ + k = -1; + for( j = 0; j < marker_num; j++ ) { + if( patt_id == marker_info[j].id ) { + if( k == -1 ) k = j; + else if( marker_info[k].cf < marker_info[j].cf ) k = j; + } + } + if( k == -1 ) { + argSwapBuffers(); + return; + } + + /* get the transformation between the marker and the real camera */ + arGetTransMat(&marker_info[k], patt_center, patt_width, patt_trans); + + // calculate the three rotatioin from the patt_trans matrix + // this is the result of a mind cracking research in transformation matrices + // see http://fly.cc.fer.hr/~unreal/theredbook/appendixg.html for details + double r31, r11, r33; + double alpha, beta, gamma; + r31 = patt_trans[0][2]; + r11 = patt_trans[0][0]; + r33 = patt_trans[2][2]; + + beta = asin(r31); + alpha = acos(r33/cos(beta)); + gamma = acos(r11/cos(beta)); + + // send the data through OSC + // if we are confident enough that the marker is detected + if (marker_info[k].cf > 0.8) { + sendOSC(alpha, beta, gamma); + } + argSwapBuffers(); +} + +static void init( void ) +{ + ARParam wparam; + + /* open the video path */ + if( arVideoOpen( vconf ) < 0 ) exit(0); + /* find the size of the window */ + if( arVideoInqSize(&xsize, &ysize) < 0 ) exit(0); + printf("Image size (x,y) = (%d,%d)\n", xsize, ysize); + + /* set the initial camera parameters */ + if( arParamLoad(cparam_name, 1, &wparam) < 0 ) { + printf("Camera parameter load error !!\n"); + exit(0); + } + arParamChangeSize( &wparam, xsize, ysize, &cparam ); + arInitCparam( &cparam ); + printf("*** Camera Parameter ***\n"); + arParamDisp( &cparam ); + + if( (patt_id=arLoadPatt(patt_name)) < 0 ) { + printf("pattern load error !!\n"); + exit(0); + } + + /* open the graphics window */ + argInit( &cparam, 1.0, 0, 0, 0, 0 ); +} + + +/* sendOSC called in the mainLoop to send all the data via OSC connection */ +static void sendOSC(double alpha, double beta, double gamma) +{ + int i; + OSCTimeTag tt; + tt = OSCTT_CurrentTime(); + + OSC_resetBuffer(oscbuf); + + if (OSC_openBundle(oscbuf, tt)) { + printf("** OSC ERROR: %s\n", OSC_errorMessage); + } + + if (OSC_writeAddressAndTypes(oscbuf, "/client", ",sfff")) { + printf("** OSC ERROR: %s\n", OSC_errorMessage); + } + + if (OSC_writeStringArg(oscbuf, "headtracker")) { + printf("** OSC ERROR: %s\n", OSC_errorMessage); + } + + if (OSC_writeFloatArg(oscbuf, alpha)) { + printf("** OSC ERROR: %s\n", OSC_errorMessage); + } + + if (OSC_writeFloatArg(oscbuf, beta)) { + printf("** OSC ERROR: %s\n", OSC_errorMessage); + } + + if (OSC_writeFloatArg(oscbuf, gamma)) { + printf("** OSC ERROR: %s\n", OSC_errorMessage); + } + + OSC_closeAllBundles(oscbuf); + + if (OSC_isBufferDone(oscbuf)) + { + sendto(sockfd, OSC_getPacket(oscbuf), OSC_packetSize(oscbuf), 0, &serverAddress, sizeof(serverAddress)); + } + else { + printf("** OSC ERROR: %s\n", OSC_errorMessage); + } + +} + + +/* cleanup function called when program exits */ +static void cleanup(void) +{ + arVideoCapStop(); + arVideoClose(); + argCleanup(); +} diff --git a/pool/shard003/C/0067090_simpavg_cp_communicate.c b/pool/shard003/C/0067090_simpavg_cp_communicate.c new file mode 100644 index 0000000000000000000000000000000000000000..876b5e808c741f7ce6b2bf458cf98ecb9d7b652b --- /dev/null +++ b/pool/shard003/C/0067090_simpavg_cp_communicate.c @@ -0,0 +1,86 @@ +#include "standard_include.h" +#include "../typ_defs/typedefs_class.h" +#include "../typ_defs/typedefs_gen.h" +#include "../typ_defs/typedefs_bnd.h" +#include "../typ_defs/typedefs_cp.h" +#include "../proto_defs/proto_output_cp_local.h" +#include "../proto_defs/proto_communicate_wrappers.h" + +/*==========================================================================*/ + +void simpavg_cp_communicate(CP *cp,STAT_AVG *stat_avg,COMMUNICATE *communicate,PTENS *ptens) + +/*==========================================================================*/ + {/*begin routine*/ +#include "../typ_defs/typ_mask.h" + + +/*==========================================================================*/ + int i,iii; + double cp_ehart_tmp=0.0; + double cp_eext_tmp=0.0; + double cp_exc_tmp=0.0; + double cp_muxc_tmp=0.0; + double cp_enl_tmp=0.0; + double cp_eke_tmp=0.0; + double kinet_cp_tmp=0.0; + double kinet_cp_nhc_tmp=0.0; + double vpotnhc_cp_tmp=0.0; + double pvten_temp[10]; + MPI_Comm comm_states = communicate->world; + + /*=======================================================================*/ + /* II)Electron DFT Energies */ + Reduce(&(stat_avg->cp_ehart), &cp_ehart_tmp,1,MPI_DOUBLE, + MPI_SUM,0,comm_states); + Reduce(&(stat_avg->cp_eext), &cp_eext_tmp,1,MPI_DOUBLE, + MPI_SUM,0,comm_states); + Reduce(&(stat_avg->cp_exc), &cp_exc_tmp,1,MPI_DOUBLE, + MPI_SUM,0,comm_states); + Reduce(&(stat_avg->cp_muxc), &cp_muxc_tmp,1,MPI_DOUBLE, + MPI_SUM,0,comm_states); + Reduce(&(stat_avg->cp_enl), &cp_enl_tmp,1,MPI_DOUBLE, + MPI_SUM,0,comm_states); + Reduce(&(stat_avg->cp_eke), &cp_eke_tmp,1,MPI_DOUBLE, + MPI_SUM,0,comm_states); + + for(i=1;i<=9;i++){pvten_temp[i]=0.0;} + Reduce(&(ptens->pvten_tot[1]), &(pvten_temp[1]),9,MPI_DOUBLE, + MPI_SUM,0,comm_states); + + stat_avg->cp_ehart = cp_ehart_tmp; + stat_avg->cp_eext = cp_eext_tmp; + stat_avg->cp_exc = cp_exc_tmp; + stat_avg->cp_muxc = cp_muxc_tmp; + stat_avg->cp_enl = cp_enl_tmp; + stat_avg->cp_eke = cp_eke_tmp; + + for(i=1;i<=9;i++){ptens->pvten_tot[i] = pvten_temp[i];} + + /*=======================================================================*/ + /* III)Electron Nose-Hoover quantities and fictitious electon KE */ + + Reduce(&(stat_avg->kinet_cp), &kinet_cp_tmp,1,MPI_DOUBLE, + MPI_SUM,0,comm_states); + stat_avg->kinet_cp = kinet_cp_tmp; + + if(cp->cptherm_info.num_c_nhc > 0){ + Reduce(&(stat_avg->kinet_nhc_cp), &kinet_cp_nhc_tmp,1,MPI_DOUBLE, + MPI_SUM,0,comm_states); + Reduce(&(stat_avg->vpotnhc_cp), &vpotnhc_cp_tmp,1,MPI_DOUBLE, + MPI_SUM,0,comm_states); + stat_avg->kinet_nhc_cp = kinet_cp_nhc_tmp; + stat_avg->vpotnhc_cp = vpotnhc_cp_tmp; + }/* endif */ + + + /*=======================================================================*/ + }/*end routine*/ + /*=======================================================================*/ + + + + + + + diff --git a/pool/shard003/C/0067094_dir.c b/pool/shard003/C/0067094_dir.c new file mode 100644 index 0000000000000000000000000000000000000000..18c307cf4eb85795643b93e404ef4374dc2439da --- /dev/null +++ b/pool/shard003/C/0067094_dir.c @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include "dir.h" +#include "options.h" + +typedef struct dirent* Directory; + +int is_current_or_parent(const Directory directory) { + return ( + strcmp(directory->d_name, ".") == 0 + || strcmp(directory->d_name, "..") == 0 + ); +} + +void listdir(const char *name, int level, survey survey) +{ + DIR *dir; + Directory directory; + + if (!(dir = opendir(name))) { + return; + } + + if (!(directory = readdir(dir))) { + return; + } + + do { + if (directory->d_type == DT_DIR) { + char path[1024]; + int len = snprintf(path, sizeof(path)-1, "%s/%s", name, directory->d_name); + path[len] = 0; + + if (is_current_or_parent(directory)) { + continue; + } + + listdir(path, level + 1, survey); + } + else { + char *dot = strrchr(directory->d_name, '.'); + if (dot && !strcmp(dot, options->extension)) { + char* fullPath = malloc(strlen(name) + strlen(directory->d_name) + 2); + strcpy(fullPath, name); + strcat(fullPath, "/"); + strcat(fullPath, directory->d_name); + survey(fullPath); + } + } + } while (directory = readdir(dir)); + + closedir(dir); +} diff --git a/pool/shard003/C/0067108_owl-common.c b/pool/shard003/C/0067108_owl-common.c new file mode 100644 index 0000000000000000000000000000000000000000..4de97cc7cb54d5a7199233bfd36cf3688b29ee12 --- /dev/null +++ b/pool/shard003/C/0067108_owl-common.c @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-2.0+ +// +// OWL common clock driver +// +// Copyright (c) 2014 Actions Semi Inc. +// Author: David Liu +// +// Copyright (c) 2018 Linaro Ltd. +// Author: Manivannan Sadhasivam + +#include +#include +#include +#include + +#include "owl-common.h" + +static const struct regmap_config owl_regmap_config = { + .reg_bits = 32, + .reg_stride = 4, + .val_bits = 32, + .max_register = 0x00cc, + .fast_io = true, +}; + +static void owl_clk_set_regmap(const struct owl_clk_desc *desc, + struct regmap *regmap) +{ + int i; + struct owl_clk_common *clks; + + for (i = 0; i < desc->num_clks; i++) { + clks = desc->clks[i]; + if (!clks) + continue; + + clks->regmap = regmap; + } +} + +int owl_clk_regmap_init(struct platform_device *pdev, + struct owl_clk_desc *desc) +{ + void __iomem *base; + struct regmap *regmap; + struct resource *res; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + base = devm_ioremap_resource(&pdev->dev, res); + if (IS_ERR(base)) + return PTR_ERR(base); + + regmap = devm_regmap_init_mmio(&pdev->dev, base, &owl_regmap_config); + if (IS_ERR(regmap)) { + pr_err("failed to init regmap\n"); + return PTR_ERR(regmap); + } + + owl_clk_set_regmap(desc, regmap); + desc->regmap = regmap; + + return 0; +} + +int owl_clk_probe(struct device *dev, struct clk_hw_onecell_data *hw_clks) +{ + int i, ret; + struct clk_hw *hw; + + for (i = 0; i < hw_clks->num; i++) { + const char *name; + + hw = hw_clks->hws[i]; + if (IS_ERR_OR_NULL(hw)) + continue; + + name = hw->init->name; + ret = devm_clk_hw_register(dev, hw); + if (ret) { + dev_err(dev, "Couldn't register clock %d - %s\n", + i, name); + return ret; + } + } + + ret = devm_of_clk_add_hw_provider(dev, of_clk_hw_onecell_get, hw_clks); + if (ret) + dev_err(dev, "Failed to add clock provider\n"); + + return ret; +} diff --git a/pool/shard003/C/0067125_add4.c b/pool/shard003/C/0067125_add4.c new file mode 100644 index 0000000000000000000000000000000000000000..ca370c522897fdadc4a6f02eda7a25df25bf5fc4 --- /dev/null +++ b/pool/shard003/C/0067125_add4.c @@ -0,0 +1,82 @@ +#include "gpsim_assert.h" + +unsigned char failures = 0; + +//bit bit0 = 0; +int int0 = 0; +int int1 = 0; +char char0 = 0; +char char1 = 0; +long long0 = 0; +long long1 = 0; +unsigned long ulong0 = 0; +unsigned long ulong1 = 0; +#define NULL 0 +char *cP0=NULL; +char *cP1=NULL; +int *iP0=NULL; +int *iP1=NULL; + +void +done() +{ + ASSERT(MANGLE(failures) == 0); + PASSED(); +} + +/* pointer to char arithmetic */ + +void pc_add(void) +{ + + if(*cP1) + failures++; + + *cP1 += 1; + if(*cP1 != 1) + failures++; + + if(char0 != 1) + failures++; + + char0++; + + if(*cP1 != 2) + failures++; + + char1 = char0 + *cP1; + + if(char1 != 4) + failures++; +} + +/* pointer to integer arithmetic */ +void pi_add(void) +{ + if(*iP0) + failures++; + + *iP0 += 1; + + if(*iP0 != 1) + failures++; + + if(int0 != 1) + failures++; + + int1 = int0 + *iP0; + if(int1 != 2) + failures++; +} + +void main(void) +{ + + cP1 = &char0; + pc_add(); + + iP0 = &int0; + pi_add(); + + done(); +} diff --git a/pool/shard003/C/0067133_spdif_transciever.c b/pool/shard003/C/0067133_spdif_transciever.c new file mode 100644 index 0000000000000000000000000000000000000000..8efbda40a38f876c230c2625b4001c2fd5066741 --- /dev/null +++ b/pool/shard003/C/0067133_spdif_transciever.c @@ -0,0 +1,113 @@ +/* + * ALSA SoC SPDIF DIT driver + * + * This driver is used by controllers which can operate in DIT (SPDI/F) where + * no codec is needed. This file provides stub codec that can be used + * in these configurations. TI DaVinci Audio controller uses this driver. + * + * Author: Steve Chen, + * Copyright: (C) 2009 MontaVista Software, Inc., + * Copyright: (C) 2009 Texas Instruments, India + * Copyright (c) 2009-2014, NVIDIA CORPORATION. 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 version 2 as + * published by the Free Software Foundation. + */ + + +#include +#include +#include +#include +#include +#include +#include + +#define DRV_NAME "spdif-dit" + +#define STUB_RATES SNDRV_PCM_RATE_8000_96000 +#define STUB_FORMATS SNDRV_PCM_FMTBIT_S16_LE + +static int spdif_probe(struct snd_soc_codec *codec) { + codec->dapm.idle_bias_off = 1; + return 0; +} + +static const struct snd_soc_dapm_widget spdif_dapm_widgets[] = { + SND_SOC_DAPM_VMID("spdif dummy Vmid"), + SND_SOC_DAPM_OUTPUT("OUT"), + SND_SOC_DAPM_INPUT("IN"), +}; + +static const struct snd_soc_dapm_route spdif_intercon[] = { + { "OUT", NULL, "Playback" }, + { "Capture", NULL, "IN" }, + +}; + +static int spdif_write(struct snd_soc_codec * codec, unsigned int reg, + unsigned int val){ + return 0; +} + +static unsigned int spdif_read(struct snd_soc_codec *codec, unsigned int reg) { + return 0; +} + +static struct snd_soc_codec_driver soc_codec_spdif_dit = { + .probe = spdif_probe, + .dapm_widgets = spdif_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(spdif_dapm_widgets), + .dapm_routes = spdif_intercon, + .num_dapm_routes = ARRAY_SIZE(spdif_intercon), + .read = spdif_read, + .write = spdif_write, +}; + +static struct snd_soc_dai_driver dit_stub_dai = { + .name = "dit-hifi", + .playback = { + .stream_name = "Playback", + .channels_min = 1, + .channels_max = 384, + .rates = STUB_RATES, + .formats = STUB_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 384, + .rates = STUB_RATES, + .formats = STUB_FORMATS, + }, +}; + +static int spdif_dit_probe(struct platform_device *pdev) +{ + return snd_soc_register_codec(&pdev->dev, + &soc_codec_spdif_dit, &dit_stub_dai, 1); + +} + +static int spdif_dit_remove(struct platform_device *pdev) +{ + snd_soc_unregister_codec(&pdev->dev); + return 0; +} + +static struct platform_driver spdif_dit_driver = { + .probe = spdif_dit_probe, + .remove = spdif_dit_remove, + .driver = { + .name = DRV_NAME, + .owner = THIS_MODULE, + }, +}; + +module_platform_driver(spdif_dit_driver); + +MODULE_AUTHOR("Steve Chen "); +MODULE_DESCRIPTION("SPDIF dummy codec driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:" DRV_NAME); diff --git a/pool/shard003/C/0067140_ech_lib.c b/pool/shard003/C/0067140_ech_lib.c new file mode 100644 index 0000000000000000000000000000000000000000..363d2fe23b3603944117b15aa5d11cf53c8caddd --- /dev/null +++ b/pool/shard003/C/0067140_ech_lib.c @@ -0,0 +1,226 @@ +/* crypto/ecdh/ech_lib.c */ +/* ==================================================================== + * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. + * + * The Elliptic Curve Public-Key Crypto Library (ECC Code) included + * herein is developed by SUN MICROSYSTEMS, INC., and is contributed + * to the OpenSSL project. + * + * The ECC Code is licensed pursuant to the OpenSSL open source + * license provided below. + * + * The ECDH software is originally written by Douglas Stebila of + * Sun Microsystems Laboratories. + * + */ +/* ==================================================================== + * Copyright (c) 1998-2003 The OpenSSL Project. 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 acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED 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 OpenSSL PROJECT OR + * ITS 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. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include "ech_locl.h" +#include +#ifndef OPENSSL_NO_ENGINE +# include +#endif +#include + +static const ECDH_METHOD *default_ECDH_method = NULL; + +static void *ecdh_data_new(void); +static void *ecdh_data_dup(void *); +static void ecdh_data_free(void *); + +void ECDH_set_default_method(const ECDH_METHOD *meth) +{ + default_ECDH_method = meth; +} + +const ECDH_METHOD *ECDH_get_default_method(void) +{ + if (!default_ECDH_method) + default_ECDH_method = ECDH_OpenSSL(); + return default_ECDH_method; +} + +int ECDH_set_method(EC_KEY *eckey, const ECDH_METHOD *meth) +{ + ECDH_DATA *ecdh; + + ecdh = ecdh_check(eckey); + + if (ecdh == NULL) + return 0; + +#ifndef OPENSSL_NO_ENGINE + if (ecdh->engine) { + ENGINE_finish(ecdh->engine); + ecdh->engine = NULL; + } +#endif + ecdh->meth = meth; + return 1; +} + +static ECDH_DATA *ECDH_DATA_new_method(ENGINE *engine) +{ + ECDH_DATA *ret; + + ret = OPENSSL_malloc(sizeof(*ret)); + if (ret == NULL) { + ECDHerr(ECDH_F_ECDH_DATA_NEW_METHOD, ERR_R_MALLOC_FAILURE); + return (NULL); + } + + ret->init = NULL; + + ret->meth = ECDH_get_default_method(); + ret->engine = engine; +#ifndef OPENSSL_NO_ENGINE + if (!ret->engine) + ret->engine = ENGINE_get_default_ECDH(); + if (ret->engine) { + ret->meth = ENGINE_get_ECDH(ret->engine); + if (!ret->meth) { + ECDHerr(ECDH_F_ECDH_DATA_NEW_METHOD, ERR_R_ENGINE_LIB); + ENGINE_finish(ret->engine); + OPENSSL_free(ret); + return NULL; + } + } +#endif + + ret->flags = ret->meth->flags; + CRYPTO_new_ex_data(CRYPTO_EX_INDEX_ECDH, ret, &ret->ex_data); + return (ret); +} + +static void *ecdh_data_new(void) +{ + return (void *)ECDH_DATA_new_method(NULL); +} + +static void *ecdh_data_dup(void *data) +{ + ECDH_DATA *r = (ECDH_DATA *)data; + + /* XXX: dummy operation */ + if (r == NULL) + return NULL; + + return (void *)ecdh_data_new(); +} + +void ecdh_data_free(void *data) +{ + ECDH_DATA *r = (ECDH_DATA *)data; + +#ifndef OPENSSL_NO_ENGINE + if (r->engine) + ENGINE_finish(r->engine); +#endif + + CRYPTO_free_ex_data(CRYPTO_EX_INDEX_ECDH, r, &r->ex_data); + OPENSSL_clear_free((void *)r, sizeof(ECDH_DATA)); +} + +ECDH_DATA *ecdh_check(EC_KEY *key) +{ + ECDH_DATA *ecdh_data; + + void *data = EC_KEY_get_key_method_data(key, ecdh_data_dup, + ecdh_data_free, ecdh_data_free); + if (data == NULL) { + ecdh_data = (ECDH_DATA *)ecdh_data_new(); + if (ecdh_data == NULL) + return NULL; + data = EC_KEY_insert_key_method_data(key, (void *)ecdh_data, + ecdh_data_dup, ecdh_data_free, + ecdh_data_free); + if (data != NULL) { + /* + * Another thread raced us to install the key_method data and + * won. + */ + ecdh_data_free(ecdh_data); + ecdh_data = (ECDH_DATA *)data; + } + } else + ecdh_data = (ECDH_DATA *)data; + + return ecdh_data; +} + +int ECDH_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func, + CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func) +{ + return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_ECDH, argl, argp, + new_func, dup_func, free_func); +} + +int ECDH_set_ex_data(EC_KEY *d, int idx, void *arg) +{ + ECDH_DATA *ecdh; + ecdh = ecdh_check(d); + if (ecdh == NULL) + return 0; + return (CRYPTO_set_ex_data(&ecdh->ex_data, idx, arg)); +} + +void *ECDH_get_ex_data(EC_KEY *d, int idx) +{ + ECDH_DATA *ecdh; + ecdh = ecdh_check(d); + if (ecdh == NULL) + return NULL; + return (CRYPTO_get_ex_data(&ecdh->ex_data, idx)); +} diff --git a/pool/shard003/C/0067141_extest.c b/pool/shard003/C/0067141_extest.c new file mode 100644 index 0000000000000000000000000000000000000000..f84e8c4802cfd9439437208251ea059ecb72ff4f --- /dev/null +++ b/pool/shard003/C/0067141_extest.c @@ -0,0 +1,195 @@ +/* + --- Version 3.3 91-11-26 15:54 --- + + EXTEST.C: EXEC function with memory swap - Test program. + + Public domain software by + + Thomas Wagner + Ferrari electronic GmbH + Beusselstrasse 27 + D-1000 Berlin 21 + Germany +*/ + +#include "compat.h" +#include "exec.h" + +/**/ +#define ENGLISH 1 +/**/ + +#ifdef ENGLISH +int help (void) +{ + puts ("Usage: EXTEST [options]"); + puts ("Options:"); + puts (" -E do not use EMS for swapping"); + puts (" -X do not use XMS for swapping"); + puts (" -F do not use File for swapping"); + puts (" -T Terminate after EXEC (no swap)"); + puts (" -N do Not swap"); + puts (" -C do not Copy environment"); + puts (" -H Hide swapfile"); + puts (" -Z Try XMS first, then EMS"); + + return 1; +} +#else +int help (void) +{ + puts ("Benutzung: EXTEST [Optionen]"); + puts ("Optionen:"); + puts (" -E bei Auslagern kein EMS benutzen"); + puts (" -X bei Auslagern kein XMS benutzen"); + puts (" -F bei Auslagern keine Datei benutzen"); + puts (" -T Terminieren nach EXEC (keine Auslagerung)"); + puts (" -N Nicht Auslagern"); + puts (" -C Umgebungsvariablen nicht kopieren"); + puts (" -H Auslagerungsdatei 'hidden'"); + puts (" -Z Zuerst XMS versuchen, dann EMS"); + + return 1; +} +#endif + +#ifdef ENGLISH +int spcheck (int cmdbat, int swapping, char *execfn, char *progpars) +{ + if (swapping > 0) + { + switch (swap_prep.swapmethod) + { + case USE_EMS: + printf ("Swapping to EMS handle %d\n", swap_prep.handle); + break; + + case USE_XMS: + printf ("Swapping to XMS handle %d\n", swap_prep.handle); + break; + + case USE_FILE: + printf ("Swapping to File <%s>\n", swap_prep.swapfilename); + break; + } + } + printf ("Executing %s %s\n\n", execfn, progpars); + if (cmdbat == 3 && strstr (progpars, "/c") == NULL) + puts ("Enter EXIT to return to EXTEST"); + + return 0; +} +#else +int spcheck (int cmdbat, int swapping, char *execfn, char *progpars) +{ + if (swapping > 0) + { + switch (swap_prep.swapmethod) + { + case USE_EMS: + printf ("Auslagerung auf EMS Handle %d\n", swap_prep.handle); + break; + + case USE_XMS: + printf ("Auslagerung auf XMS Handle %d\n", swap_prep.handle); + break; + + case USE_FILE: + printf ("Auslagerung auf Datei <%s>\n", swap_prep.swapfilename); + break; + } + } + printf ("Ausfhren %s %s\n\n", execfn, progpars); + if (cmdbat == 3 && strstr (progpars, "/c") == NULL) + puts ("Geben Sie EXIT ein um zu EXTEST zurckzukehren"); + + return 0; +} +#endif + +char tmpdir[80]="\\."; + +int main (int argc, char **argv) +{ + static char fn [255], par [130]; + char *com; + int i; + char far *x; + char far *y; + int method; + unsigned needed; + char **env; +/* + union REGS regs; +*/ + + method = USE_ALL; + needed = 0xffff; + env = environ; + spawn_check = spcheck; + + for (i = 1; i < argc; i++) + { + if (argv [i][0] != '-' && argv [i][0] != '/') + return help (); + com = &argv [i][1]; + do + { + switch (toupper (*com)) + { + case 'E': method &= ~USE_EMS; break; + case 'X': method &= ~USE_XMS; break; + case 'F': method &= ~USE_FILE; break; + case 'T': method = 0; break; + case 'N': needed = 0; break; + case 'C': env = NULL; break; + case 'H': method |= HIDE_FILE; break; + case 'Z': method |= XMS_FIRST; break; + case '-': break; + case '/': break; + default: return help (); + } + com++; + } while (*com); + } + + x = (char far *)farmalloc (64L * 1024L); + y = (char far *)farmalloc (64L * 1024L); + +#ifdef ENGLISH + putenv ("XYZ=This is an environment string for the spawned process"); +#else + putenv ("XYZ=Dies ist eine Umgebungsvariable fr den aufgerufenen Prozeá"); +#endif + + while (1) + { +#ifdef ENGLISH + printf ("\nEXEC filename,params ('.' to exit): "); +#else + printf ("\nDateiname,Parameter ('.' beendet): "); +#endif + gets (fn); + + if (fn [0] == '.') + return 0; + + com = strchr (fn, ','); + if (com != NULL) + { + strcpy (par, &com [1]); + *com = 0; + } + else + par [0] = 0; + + i = do_exec (fn, par, method, needed, env); + +#ifdef ENGLISH + printf ("\nDO_EXEC returns %04x\n", i); +#else + printf ("\nDO_EXEC liefert %04x\n", i); +#endif + } +} + diff --git a/pool/shard003/C/0067142_tunnel.c b/pool/shard003/C/0067142_tunnel.c new file mode 100644 index 0000000000000000000000000000000000000000..104340d44ed2d1b477dc2773e2db4044060880a1 --- /dev/null +++ b/pool/shard003/C/0067142_tunnel.c @@ -0,0 +1,169 @@ +/* + * Copyright (C)2006 USAGI/WIDE 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 + */ +/* + * split from ip_tunnel.c + */ +/* + * Author: + * Masahide NAKAMURA @USAGI + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" +#include "tunnel.h" + +const char *tnl_strproto(__u8 proto) +{ + static char buf[16]; + + switch (proto) { + case IPPROTO_IPIP: + strcpy(buf, "ip"); + break; + case IPPROTO_GRE: + strcpy(buf, "gre"); + break; + case IPPROTO_IPV6: + strcpy(buf, "ipv6"); + break; + case 0: + strcpy(buf, "any"); + break; + default: + strcpy(buf, "unknown"); + break; + } + + return buf; +} + +int tnl_ioctl_get_ifindex(const char *dev) +{ + struct ifreq ifr; + int fd; + int err; + + strncpy(ifr.ifr_name, dev, IFNAMSIZ); + fd = socket(preferred_family, SOCK_DGRAM, 0); + err = ioctl(fd, SIOCGIFINDEX, &ifr); + if (err) { + perror("ioctl"); + return 0; + } + close(fd); + return ifr.ifr_ifindex; +} + +int tnl_ioctl_get_iftype(const char *dev) +{ + struct ifreq ifr; + int fd; + int err; + + strncpy(ifr.ifr_name, dev, IFNAMSIZ); + fd = socket(preferred_family, SOCK_DGRAM, 0); + err = ioctl(fd, SIOCGIFHWADDR, &ifr); + if (err) { + perror("ioctl"); + return -1; + } + close(fd); + return ifr.ifr_addr.sa_family; +} + + +char * tnl_ioctl_get_ifname(int idx) +{ + static struct ifreq ifr; + int fd; + int err; + + ifr.ifr_ifindex = idx; + fd = socket(preferred_family, SOCK_DGRAM, 0); + err = ioctl(fd, SIOCGIFNAME, &ifr); + if (err) { + perror("ioctl"); + return NULL; + } + close(fd); + return ifr.ifr_name; +} + +int tnl_get_ioctl(const char *basedev, void *p) +{ + struct ifreq ifr; + int fd; + int err; + + strncpy(ifr.ifr_name, basedev, IFNAMSIZ); + ifr.ifr_ifru.ifru_data = (void*)p; + fd = socket(preferred_family, SOCK_DGRAM, 0); + err = ioctl(fd, SIOCGETTUNNEL, &ifr); + if (err) + perror("ioctl"); + close(fd); + return err; +} + +int tnl_add_ioctl(int cmd, const char *basedev, const char *name, void *p) +{ + struct ifreq ifr; + int fd; + int err; + + if (cmd == SIOCCHGTUNNEL && name[0]) + strncpy(ifr.ifr_name, name, IFNAMSIZ); + else + strncpy(ifr.ifr_name, basedev, IFNAMSIZ); + ifr.ifr_ifru.ifru_data = p; + fd = socket(preferred_family, SOCK_DGRAM, 0); + err = ioctl(fd, cmd, &ifr); + if (err) + perror("ioctl"); + close(fd); + return err; +} + +int tnl_del_ioctl(const char *basedev, const char *name, void *p) +{ + struct ifreq ifr; + int fd; + int err; + + if (name[0]) + strncpy(ifr.ifr_name, name, IFNAMSIZ); + else + strncpy(ifr.ifr_name, basedev, IFNAMSIZ); + ifr.ifr_ifru.ifru_data = p; + fd = socket(preferred_family, SOCK_DGRAM, 0); + err = ioctl(fd, SIOCDELTUNNEL, &ifr); + if (err) + perror("ioctl"); + close(fd); + return err; +} diff --git a/pool/shard003/C/0067156_lantiq-flash.c b/pool/shard003/C/0067156_lantiq-flash.c new file mode 100644 index 0000000000000000000000000000000000000000..795143366c158b6eb59374895e12c933d9135c52 --- /dev/null +++ b/pool/shard003/C/0067156_lantiq-flash.c @@ -0,0 +1,248 @@ +/* + * 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. + * + * Copyright (C) 2004 Liu Peng Infineon IFAP DC COM CPE + * Copyright (C) 2010 John Crispin + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +/* + * The NOR flash is connected to the same external bus unit (EBU) as PCI. + * To make PCI work we need to enable the endianness swapping for the address + * written to the EBU. This endianness swapping works for PCI correctly but + * fails for attached NOR devices. To workaround this we need to use a complex + * map. The workaround involves swapping all addresses whilst probing the chip. + * Once probing is complete we stop swapping the addresses but swizzle the + * unlock addresses to ensure that access to the NOR device works correctly. + */ + +enum +{ + LTQ_NOR_PROBING, + LTQ_NOR_NORMAL +}; + +struct ltq_mtd +{ + struct resource *res; + struct mtd_info *mtd; + struct map_info *map; +}; + +static const char ltq_map_name[] = "ltq_nor"; + +static map_word +ltq_read16(struct map_info *map, unsigned long adr) +{ + unsigned long flags; + map_word temp; + + if (map->map_priv_1 == LTQ_NOR_PROBING) + { + adr ^= 2; + } + + spin_lock_irqsave(&ebu_lock, flags); + temp.x[0] = *(u16 *)(map->virt + adr); + spin_unlock_irqrestore(&ebu_lock, flags); + return temp; +} + +static void +ltq_write16(struct map_info *map, map_word d, unsigned long adr) +{ + unsigned long flags; + + if (map->map_priv_1 == LTQ_NOR_PROBING) + { + adr ^= 2; + } + + spin_lock_irqsave(&ebu_lock, flags); + *(u16 *)(map->virt + adr) = d.x[0]; + spin_unlock_irqrestore(&ebu_lock, flags); +} + +/* + * The following 2 functions copy data between iomem and a cached memory + * section. As memcpy() makes use of pre-fetching we cannot use it here. + * The normal alternative of using memcpy_{to,from}io also makes use of + * memcpy() on MIPS so it is not applicable either. We are therefore stuck + * with having to use our own loop. + */ +static void +ltq_copy_from(struct map_info *map, void *to, + unsigned long from, ssize_t len) +{ + unsigned char *f = (unsigned char *)map->virt + from; + unsigned char *t = (unsigned char *)to; + unsigned long flags; + + spin_lock_irqsave(&ebu_lock, flags); + + while (len--) + { + *t++ = *f++; + } + + spin_unlock_irqrestore(&ebu_lock, flags); +} + +static void +ltq_copy_to(struct map_info *map, unsigned long to, + const void *from, ssize_t len) +{ + unsigned char *f = (unsigned char *)from; + unsigned char *t = (unsigned char *)map->virt + to; + unsigned long flags; + + spin_lock_irqsave(&ebu_lock, flags); + + while (len--) + { + *t++ = *f++; + } + + spin_unlock_irqrestore(&ebu_lock, flags); +} + +static int +ltq_mtd_probe(struct platform_device *pdev) +{ + struct ltq_mtd *ltq_mtd; + struct cfi_private *cfi; + int err; + + if (of_machine_is_compatible("lantiq,falcon") && + (ltq_boot_select() != BS_FLASH)) + { + dev_err(&pdev->dev, "invalid bootstrap options\n"); + return -ENODEV; + } + + ltq_mtd = devm_kzalloc(&pdev->dev, sizeof(struct ltq_mtd), GFP_KERNEL); + + if (!ltq_mtd) + { + return -ENOMEM; + } + + platform_set_drvdata(pdev, ltq_mtd); + + ltq_mtd->res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + + if (!ltq_mtd->res) + { + dev_err(&pdev->dev, "failed to get memory resource\n"); + return -ENOENT; + } + + ltq_mtd->map = devm_kzalloc(&pdev->dev, sizeof(struct map_info), + GFP_KERNEL); + + if (!ltq_mtd->map) + { + return -ENOMEM; + } + + ltq_mtd->map->phys = ltq_mtd->res->start; + ltq_mtd->map->size = resource_size(ltq_mtd->res); + ltq_mtd->map->virt = devm_ioremap_resource(&pdev->dev, ltq_mtd->res); + + if (IS_ERR(ltq_mtd->map->virt)) + { + return PTR_ERR(ltq_mtd->map->virt); + } + + ltq_mtd->map->name = ltq_map_name; + ltq_mtd->map->bankwidth = 2; + ltq_mtd->map->read = ltq_read16; + ltq_mtd->map->write = ltq_write16; + ltq_mtd->map->copy_from = ltq_copy_from; + ltq_mtd->map->copy_to = ltq_copy_to; + + ltq_mtd->map->map_priv_1 = LTQ_NOR_PROBING; + ltq_mtd->mtd = do_map_probe("cfi_probe", ltq_mtd->map); + ltq_mtd->map->map_priv_1 = LTQ_NOR_NORMAL; + + if (!ltq_mtd->mtd) + { + dev_err(&pdev->dev, "probing failed\n"); + return -ENXIO; + } + + ltq_mtd->mtd->dev.parent = &pdev->dev; + mtd_set_of_node(ltq_mtd->mtd, pdev->dev.of_node); + + cfi = ltq_mtd->map->fldrv_priv; + cfi->addr_unlock1 ^= 1; + cfi->addr_unlock2 ^= 1; + + err = mtd_device_register(ltq_mtd->mtd, NULL, 0); + + if (err) + { + dev_err(&pdev->dev, "failed to add partitions\n"); + goto err_destroy; + } + + return 0; + +err_destroy: + map_destroy(ltq_mtd->mtd); + return err; +} + +static int +ltq_mtd_remove(struct platform_device *pdev) +{ + struct ltq_mtd *ltq_mtd = platform_get_drvdata(pdev); + + if (ltq_mtd && ltq_mtd->mtd) + { + mtd_device_unregister(ltq_mtd->mtd); + map_destroy(ltq_mtd->mtd); + } + + return 0; +} + +static const struct of_device_id ltq_mtd_match[] = +{ + { .compatible = "lantiq,nor" }, + {}, +}; +MODULE_DEVICE_TABLE(of, ltq_mtd_match); + +static struct platform_driver ltq_mtd_driver = +{ + .probe = ltq_mtd_probe, + .remove = ltq_mtd_remove, + .driver = { + .name = "ltq-nor", + .of_match_table = ltq_mtd_match, + }, +}; + +module_platform_driver(ltq_mtd_driver); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("John Crispin "); +MODULE_DESCRIPTION("Lantiq SoC NOR"); diff --git a/pool/shard003/C/0067172_CSALBR.c b/pool/shard003/C/0067172_CSALBR.c new file mode 100644 index 0000000000000000000000000000000000000000..2e452eafbca97c036bcb9f4a0f3c925fdef2cbc4 --- /dev/null +++ b/pool/shard003/C/0067172_CSALBR.c @@ -0,0 +1,99 @@ +/* CSALBR.f -- translated by f2c (version 19970805). + You must link the resulting object file with the libraries: + -lf2c -lm (in that order) +*/ + +#ifdef __cplusplus +extern "C" { +#endif +/* OTB patches: replace "f2c.h" by "otb_6S.h" */ +/*#include "f2c.h"*/ +#include "otb_6S.h" + +/*< subroutine csalbr(xtau,xalb) >*/ +/* Subroutine */ int csalbr_(doublereal *xtau, doublereal *xalb) +{ + /* Builtin functions */ + double exp(doublereal); + + /* Local variables */ + extern doublereal fintexp3_(doublereal *); + +/*< real xtau,xalb,fintexp3 >*/ +/*< xalb=(3*xtau-fintexp3(xtau)*(4+2*xtau)+2*exp(-xtau)) >*/ + *xalb = *xtau * 3 - fintexp3_(xtau) * (*xtau * 2 + 4) + exp(-(*xtau)) * 2; +/*< xalb=xalb/(4.+3*xtau) >*/ + *xalb /= *xtau * 3 + 4.; +/*< return >*/ + return 0; +/*< end >*/ +} /* csalbr_ */ + +/*< real function fintexp3(xtau) >*/ +doublereal fintexp3_(doublereal *xtau) +{ + /* System generated locals */ + doublereal ret_val; + + /* Builtin functions */ + double exp(doublereal); + + /* Local variables */ + extern doublereal fintexp1_(doublereal *); + doublereal xx; + +/*< real xx,xtau,fintexp1 >*/ +/*< xx=(exp(-xtau)*(1.-xtau)+xtau*xtau*fintexp1(xtau))/2. >*/ + xx = (exp(-(*xtau)) * (1. - *xtau) + *xtau * *xtau * fintexp1_(xtau)) / + 2.; +/*< fintexp3=xx >*/ + ret_val = xx; +/*< return >*/ + return ret_val; +/*< end >*/ +} /* fintexp3_ */ + +/*< real function fintexp1(xtau) >*/ +doublereal fintexp1_(doublereal *xtau) +{ + /* Initialized data */ + + static doublereal a[6] = { -.57721566,.99999193,-.24991055,.05519968, + -.00976004,.00107857 }; + + /* System generated locals */ + doublereal ret_val; + + /* Builtin functions */ + double log(doublereal); + + /* Local variables */ + integer i__; + doublereal xx, xftau; + +/* accuracy 2e-07... for 0*/ +/*< integer i >*/ +/*< >*/ +/*< xx=a(0) >*/ + xx = a[0]; +/*< xftau=1. >*/ + xftau = 1.; +/*< do i=1,5 >*/ + for (i__ = 1; i__ <= 5; ++i__) { +/*< xftau=xftau*xtau >*/ + xftau *= *xtau; +/*< xx=xx+a(i)*xftau >*/ + xx += a[i__] * xftau; +/*< enddo >*/ + } +/*< fintexp1=xx-log(xtau) >*/ + ret_val = xx - log(*xtau); +/*< return >*/ + return ret_val; +/*< end >*/ +} /* fintexp1_ */ + +#ifdef __cplusplus + } +#endif diff --git a/pool/shard003/C/0067190_clk-mmc-phase.c b/pool/shard003/C/0067190_clk-mmc-phase.c new file mode 100644 index 0000000000000000000000000000000000000000..077fcdc7908bb9f3791fe20bc60a0266327ca050 --- /dev/null +++ b/pool/shard003/C/0067190_clk-mmc-phase.c @@ -0,0 +1,169 @@ +/* + * Copyright 2014 Google, Inc + * Author: Alexandru M Stan + * + * 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. + */ + +#include +#include +#include +#include +#include +#include "clk.h" + +struct rockchip_mmc_clock { + struct clk_hw hw; + void __iomem *reg; + int id; + int shift; +}; + +#define to_mmc_clock(_hw) container_of(_hw, struct rockchip_mmc_clock, hw) + +#define RK3288_MMC_CLKGEN_DIV 2 + +static unsigned long rockchip_mmc_recalc(struct clk_hw *hw, + unsigned long parent_rate) +{ + return parent_rate / RK3288_MMC_CLKGEN_DIV; +} + +#define ROCKCHIP_MMC_DELAY_SEL BIT(10) +#define ROCKCHIP_MMC_DEGREE_MASK 0x3 +#define ROCKCHIP_MMC_DELAYNUM_OFFSET 2 +#define ROCKCHIP_MMC_DELAYNUM_MASK (0xff << ROCKCHIP_MMC_DELAYNUM_OFFSET) + +#define PSECS_PER_SEC 1000000000000LL + +/* + * Each fine delay is between 44ps-77ps. Assume each fine delay is 60ps to + * simplify calculations. So 45degs could be anywhere between 33deg and 57.8deg. + */ +#define ROCKCHIP_MMC_DELAY_ELEMENT_PSEC 60 + +static int rockchip_mmc_get_phase(struct clk_hw *hw) +{ + struct rockchip_mmc_clock *mmc_clock = to_mmc_clock(hw); + unsigned long rate = clk_get_rate(hw->clk); + u32 raw_value; + u16 degrees; + u32 delay_num = 0; + + raw_value = readl(mmc_clock->reg) >> (mmc_clock->shift); + + degrees = (raw_value & ROCKCHIP_MMC_DEGREE_MASK) * 90; + + if (raw_value & ROCKCHIP_MMC_DELAY_SEL) { + /* degrees/delaynum * 10000 */ + unsigned long factor = (ROCKCHIP_MMC_DELAY_ELEMENT_PSEC / 10) * + 36 * (rate / 1000000); + + delay_num = (raw_value & ROCKCHIP_MMC_DELAYNUM_MASK); + delay_num >>= ROCKCHIP_MMC_DELAYNUM_OFFSET; + degrees += DIV_ROUND_CLOSEST(delay_num * factor, 10000); + } + + return degrees % 360; +} + +static int rockchip_mmc_set_phase(struct clk_hw *hw, int degrees) +{ + struct rockchip_mmc_clock *mmc_clock = to_mmc_clock(hw); + unsigned long rate = clk_get_rate(hw->clk); + u8 nineties, remainder; + u8 delay_num; + u32 raw_value; + u32 delay; + + nineties = degrees / 90; + remainder = (degrees % 90); + + /* + * Due to the inexact nature of the "fine" delay, we might + * actually go non-monotonic. We don't go _too_ monotonic + * though, so we should be OK. Here are options of how we may + * work: + * + * Ideally we end up with: + * 1.0, 2.0, ..., 69.0, 70.0, ..., 89.0, 90.0 + * + * On one extreme (if delay is actually 44ps): + * .73, 1.5, ..., 50.6, 51.3, ..., 65.3, 90.0 + * The other (if delay is actually 77ps): + * 1.3, 2.6, ..., 88.6. 89.8, ..., 114.0, 90 + * + * It's possible we might make a delay that is up to 25 + * degrees off from what we think we're making. That's OK + * though because we should be REALLY far from any bad range. + */ + + /* + * Convert to delay; do a little extra work to make sure we + * don't overflow 32-bit / 64-bit numbers. + */ + delay = 10000000; /* PSECS_PER_SEC / 10000 / 10 */ + delay *= remainder; + delay = DIV_ROUND_CLOSEST(delay, + (rate / 1000) * 36 * + (ROCKCHIP_MMC_DELAY_ELEMENT_PSEC / 10)); + + delay_num = (u8) min_t(u32, delay, 255); + + raw_value = delay_num ? ROCKCHIP_MMC_DELAY_SEL : 0; + raw_value |= delay_num << ROCKCHIP_MMC_DELAYNUM_OFFSET; + raw_value |= nineties; + writel(HIWORD_UPDATE(raw_value, 0x07ff, mmc_clock->shift), + mmc_clock->reg); + + pr_debug("%s->set_phase(%d) delay_nums=%u reg[0x%p]=0x%03x actual_degrees=%d\n", + clk_hw_get_name(hw), degrees, delay_num, + mmc_clock->reg, raw_value>>(mmc_clock->shift), + rockchip_mmc_get_phase(hw) + ); + + return 0; +} + +static const struct clk_ops rockchip_mmc_clk_ops = { + .recalc_rate = rockchip_mmc_recalc, + .get_phase = rockchip_mmc_get_phase, + .set_phase = rockchip_mmc_set_phase, +}; + +struct clk *rockchip_clk_register_mmc(const char *name, + const char *const *parent_names, u8 num_parents, + void __iomem *reg, int shift) +{ + struct clk_init_data init; + struct rockchip_mmc_clock *mmc_clock; + struct clk *clk; + + mmc_clock = kmalloc(sizeof(*mmc_clock), GFP_KERNEL); + if (!mmc_clock) + return ERR_PTR(-ENOMEM); + + init.name = name; + init.flags = 0; + init.num_parents = num_parents; + init.parent_names = parent_names; + init.ops = &rockchip_mmc_clk_ops; + + mmc_clock->hw.init = &init; + mmc_clock->reg = reg; + mmc_clock->shift = shift; + + clk = clk_register(NULL, &mmc_clock->hw); + if (IS_ERR(clk)) + kfree(mmc_clock); + + return clk; +} diff --git a/pool/shard003/C/0067197_hugetlbpage.c b/pool/shard003/C/0067197_hugetlbpage.c new file mode 100644 index 0000000000000000000000000000000000000000..5b65dc0a6bec2fce282df2780a8659ba73422db0 --- /dev/null +++ b/pool/shard003/C/0067197_hugetlbpage.c @@ -0,0 +1,212 @@ +/* + * IA-64 Huge TLB Page Support for Kernel. + * + * Copyright (C) 2002-2004 Rohit Seth + * Copyright (C) 2003-2004 Ken Chen + * + * Sep, 2003: add numa support + * Feb, 2004: dynamic hugetlb page size via boot parameter + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +unsigned int hpage_shift = HPAGE_SHIFT_DEFAULT; +EXPORT_SYMBOL(hpage_shift); + +pte_t * +huge_pte_alloc(struct mm_struct *mm, unsigned long addr, unsigned long sz) +{ + unsigned long taddr = htlbpage_to_page(addr); + pgd_t *pgd; + pud_t *pud; + pmd_t *pmd; + pte_t *pte = NULL; + + pgd = pgd_offset(mm, taddr); + pud = pud_alloc(mm, pgd, taddr); + if (pud) { + pmd = pmd_alloc(mm, pud, taddr); + if (pmd) + pte = pte_alloc_map(mm, NULL, pmd, taddr); + } + return pte; +} + +pte_t * +huge_pte_offset (struct mm_struct *mm, unsigned long addr) +{ + unsigned long taddr = htlbpage_to_page(addr); + pgd_t *pgd; + pud_t *pud; + pmd_t *pmd; + pte_t *pte = NULL; + + pgd = pgd_offset(mm, taddr); + if (pgd_present(*pgd)) { + pud = pud_offset(pgd, taddr); + if (pud_present(*pud)) { + pmd = pmd_offset(pud, taddr); + if (pmd_present(*pmd)) + pte = pte_offset_map(pmd, taddr); + } + } + + return pte; +} + +int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep) +{ + return 0; +} + +#define mk_pte_huge(entry) { pte_val(entry) |= _PAGE_P; } + +/* + * Don't actually need to do any preparation, but need to make sure + * the address is in the right region. + */ +int prepare_hugepage_range(struct file *file, + unsigned long addr, unsigned long len) +{ + if (len & ~HPAGE_MASK) + return -EINVAL; + if (addr & ~HPAGE_MASK) + return -EINVAL; + if (REGION_NUMBER(addr) != RGN_HPAGE) + return -EINVAL; + + return 0; +} + +struct page *follow_huge_addr(struct mm_struct *mm, unsigned long addr, int write) +{ + struct page *page; + pte_t *ptep; + + if (REGION_NUMBER(addr) != RGN_HPAGE) + return ERR_PTR(-EINVAL); + + ptep = huge_pte_offset(mm, addr); + if (!ptep || pte_none(*ptep)) + return NULL; + page = pte_page(*ptep); + page += ((addr & ~HPAGE_MASK) >> PAGE_SHIFT); + return page; +} +int pmd_huge(pmd_t pmd) +{ + return 0; +} + +int pud_huge(pud_t pud) +{ + return 0; +} + +int pmd_huge_support(void) +{ + return 0; +} + +struct page * +follow_huge_pmd(struct mm_struct *mm, unsigned long address, pmd_t *pmd, int write) +{ + return NULL; +} + +void hugetlb_free_pgd_range(struct mmu_gather *tlb, + unsigned long addr, unsigned long end, + unsigned long floor, unsigned long ceiling) +{ + /* + * This is called to free hugetlb page tables. + * + * The offset of these addresses from the base of the hugetlb + * region must be scaled down by HPAGE_SIZE/PAGE_SIZE so that + * the standard free_pgd_range will free the right page tables. + * + * If floor and ceiling are also in the hugetlb region, they + * must likewise be scaled down; but if outside, left unchanged. + */ + + addr = htlbpage_to_page(addr); + end = htlbpage_to_page(end); + if (REGION_NUMBER(floor) == RGN_HPAGE) + floor = htlbpage_to_page(floor); + if (REGION_NUMBER(ceiling) == RGN_HPAGE) + ceiling = htlbpage_to_page(ceiling); + + free_pgd_range(tlb, addr, end, floor, ceiling); +} + +unsigned long hugetlb_get_unmapped_area(struct file *file, unsigned long addr, unsigned long len, + unsigned long pgoff, unsigned long flags) +{ + struct vm_area_struct *vmm; + + if (len > RGN_MAP_LIMIT) + return -ENOMEM; + if (len & ~HPAGE_MASK) + return -EINVAL; + + /* Handle MAP_FIXED */ + if (flags & MAP_FIXED) { + if (prepare_hugepage_range(file, addr, len)) + return -EINVAL; + return addr; + } + + /* This code assumes that RGN_HPAGE != 0. */ + if ((REGION_NUMBER(addr) != RGN_HPAGE) || (addr & (HPAGE_SIZE - 1))) + addr = HPAGE_REGION_BASE; + else + addr = ALIGN(addr, HPAGE_SIZE); + for (vmm = find_vma(current->mm, addr); ; vmm = vmm->vm_next) { + /* At this point: (!vmm || addr < vmm->vm_end). */ + if (REGION_OFFSET(addr) + len > RGN_MAP_LIMIT) + return -ENOMEM; + if (!vmm || (addr + len) <= vmm->vm_start) + return addr; + addr = ALIGN(vmm->vm_end, HPAGE_SIZE); + } +} + +static int __init hugetlb_setup_sz(char *str) +{ + u64 tr_pages; + unsigned long long size; + + if (ia64_pal_vm_page_size(&tr_pages, NULL) != 0) + /* + * shouldn't happen, but just in case. + */ + tr_pages = 0x15557000UL; + + size = memparse(str, &str); + if (*str || !is_power_of_2(size) || !(tr_pages & size) || + size <= PAGE_SIZE || + size >= (1UL << PAGE_SHIFT << MAX_ORDER)) { + printk(KERN_WARNING "Invalid huge page size specified\n"); + return 1; + } + + hpage_shift = __ffs(size); + /* + * boot cpu already executed ia64_mmu_init, and has HPAGE_SHIFT_DEFAULT + * override here with new page shift. + */ + ia64_set_rr(HPAGE_REGION_BASE, hpage_shift << 2); + return 0; +} +early_param("hugepagesz", hugetlb_setup_sz); diff --git a/pool/shard003/C/0067208_declare-1.c b/pool/shard003/C/0067208_declare-1.c new file mode 100644 index 0000000000000000000000000000000000000000..c63a68dbab75adaeffd373a296045e4b683c839b --- /dev/null +++ b/pool/shard003/C/0067208_declare-1.c @@ -0,0 +1,122 @@ +/* { dg-do run { target openacc_nvidia_accel_selected } } */ + +#include +#include +#include + +#define N 8 + +void +subr2 (int *a) +{ + int i; + int f[N]; +#pragma acc declare copyout (f) + +#pragma acc parallel copy (a[0:N]) + { + for (i = 0; i < N; i++) + { + f[i] = a[i]; + a[i] = f[i] + f[i] + f[i]; + } + } +} + +void +subr1 (int *a) +{ + int f[N]; +#pragma acc declare copy (f) + +#pragma acc parallel copy (a[0:N]) + { + int i; + + for (i = 0; i < N; i++) + { + f[i] = a[i]; + a[i] = f[i] + f[i]; + } + } +} + +int b[8]; +#pragma acc declare create (b) + +int d[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; +#pragma acc declare copyin (d) + +int +main (int argc, char **argv) +{ + int a[N]; + int e[N]; +#pragma acc declare create (e) + int i; + + for (i = 0; i < N; i++) + a[i] = i + 1; + + if (!acc_is_present (&b, sizeof (b))) + abort (); + + if (!acc_is_present (&d, sizeof (d))) + abort (); + + if (!acc_is_present (&e, sizeof (e))) + abort (); + +#pragma acc parallel copyin (a[0:N]) + { + for (i = 0; i < N; i++) + { + b[i] = a[i]; + a[i] = b[i]; + } + } + + for (i = 0; i < N; i++) + { + if (a[i] != i + 1) + abort (); + } + +#pragma acc parallel copy (a[0:N]) + { + for (i = 0; i < N; i++) + { + e[i] = a[i] + d[i]; + a[i] = e[i]; + } + } + + for (i = 0; i < N; i++) + { + if (a[i] != (i + 1) * 2) + abort (); + } + + for (i = 0; i < N; i++) + { + a[i] = 1234; + } + + subr1 (&a[0]); + + for (i = 0; i < N; i++) + { + if (a[i] != 1234 * 2) + abort (); + } + + subr2 (&a[0]); + + for (i = 0; i < 1; i++) + { + if (a[i] != 1234 * 6) + abort (); + } + + return 0; +} diff --git a/pool/shard003/C/0067210_subsensor.c b/pool/shard003/C/0067210_subsensor.c new file mode 100644 index 0000000000000000000000000000000000000000..507e027d744f0c1f90fba718f8d4d8492126da29 --- /dev/null +++ b/pool/shard003/C/0067210_subsensor.c @@ -0,0 +1,241 @@ +/* + * A V4L2 driver for SYS.LSI S5K4ECGX cameras. + * + * Copyright 2006 One Laptop Per Child Association, Inc. Written + * by Jonathan Corbet with substantial inspiration from Mark + * McClelland's ovcamchip code. + * + * Copyright 2006-7 Jonathan Corbet + *jpeg + * This file may be distributed under the terms of the GNU General + * Public License, version 2. + */ +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +MODULE_AUTHOR("Vincent Wan "); +MODULE_DESCRIPTION("A low-level driver for sub sensors"); +MODULE_LICENSE("GPL"); + +/* + * Basic window sizes. These probably belong somewhere more globally + * useful. + */ +#define WQXGA_WIDTH 2560 +#define WQXGA_HEIGHT 1920 + +#define Wide4M_WIDTH 2560 +#define Wide4M_HEIGHT 1536 + +#define QXGA_WIDTH 2048 +#define QXGA_HEIGHT 1536 + +#define Wide2_4M_WIDTH 2048 +#define Wide2_4M_HEIGHT 1232 + +#define UXGA_WIDTH 1600 +#define UXGA_HEIGHT 1200 + +#define Wide1_5M_WIDTH 1600 +#define Wide1_5M_HEIGHT 960 + +#define SXGA_WIDTH 1280 +#define SXGA_HEIGHT 960 +#define XGA_WIDTH 1024 +#define XGA_HEIGHT 768 +#define D1_WIDTH 720 +#define D1_HEIGHT 480 + +#define Wide4K_WIDTH 800 +#define Wide4K_HEIGHT 480 + +#define VGA_WIDTH 640 +#define VGA_HEIGHT 480 +#define QVGA_WIDTH 320 +#define QVGA_HEIGHT 240 +#define CIF_WIDTH 352 +#define CIF_HEIGHT 288 +#define QCIF_WIDTH 176 +#define QCIF_HEIGHT 144 +#define ROTATED_QCIF_WIDTH 144 +#define ROTATED_QCIF_HEIGHT 176 +#define THUMB_WIDTH 160 +#define THUMB_HEIGHT 120 + +struct subsensor_info { + struct v4l2_subdev subdev; + +}; + +struct subsensor_datafmt { + enum v4l2_mbus_pixelcode code; + enum v4l2_colorspace colorspace; +}; + +static const struct subsensor_datafmt subsensor_colour_fmts[] = { + {V4L2_MBUS_FMT_UYVY8_2X8, V4L2_COLORSPACE_JPEG}, +}; + +static struct subsensor_win_size { + int width; + int height; +} subsensor_win_sizes[] = { + /* VGA */ + { + .width = VGA_WIDTH, + .height = VGA_HEIGHT, + }, + /* QVGA */ + { + .width = QVGA_WIDTH, + .height = QVGA_HEIGHT, + }, + /* QCIF */ + { + .width = QCIF_WIDTH, + .height = QCIF_HEIGHT, + }, + /* 720*480 */ + { + .width = D1_WIDTH, + .height = D1_HEIGHT, + }, +}; +static int subsensor_enum_fsizes(struct v4l2_subdev *sd, + struct v4l2_frmsizeenum *fsize) +{ + struct i2c_client *client = v4l2_get_subdevdata(sd); + + if (!fsize) + return -EINVAL; + + fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE; + + /* abuse pixel_format, in fact, it is xlate->code*/ + switch (fsize->pixel_format) { + case V4L2_MBUS_FMT_UYVY8_2X8: + case V4L2_MBUS_FMT_VYUY8_2X8: + if (fsize->index >= ARRAY_SIZE(subsensor_win_sizes)) { + dev_warn(&client->dev, + "subsensor unsupported size %d!\n", fsize->index); + return -EINVAL; + } + fsize->discrete.height = subsensor_win_sizes[fsize->index].height; + fsize->discrete.width = subsensor_win_sizes[fsize->index].width; + break; + + default: + dev_err(&client->dev, "subsensor unsupported format!\n"); + return -EINVAL; + } + return 0; +} + + +static int subsensor_enum_fmt(struct v4l2_subdev *sd, + unsigned int index, + enum v4l2_mbus_pixelcode *code) +{ + if (index >= ARRAY_SIZE(subsensor_colour_fmts)) + return -EINVAL; + *code = subsensor_colour_fmts[index].code; + return 0; +} + +static struct v4l2_subdev_core_ops subsensor_core_ops = { +}; +static struct v4l2_subdev_video_ops subsensor_video_ops = { + .enum_mbus_fmt = subsensor_enum_fmt, + .enum_mbus_fsizes = subsensor_enum_fsizes, +}; + +static struct v4l2_subdev_ops subsensor_subdev_ops = { + .core = &subsensor_core_ops, + .video = &subsensor_video_ops, +}; + +static int subsensor_video_probe(struct soc_camera_device *icd, + struct i2c_client *client) +{ + Cam_Printk(KERN_NOTICE "=========Marvell sub sensor detected is ok!==========\n"); + return 0; +} + +static int subsensor_probe(struct i2c_client *client, + const struct i2c_device_id *did) +{ + struct soc_camera_device *icd = client->dev.platform_data; + struct subsensor_info *priv; + int ret; + + printk("------------subsensor_probe--------------\n"); + + if (!icd) { + dev_err(&client->dev, "Missing soc-camera data!\n"); + return -EINVAL; + } + + priv = kzalloc(sizeof(struct subsensor_info), GFP_KERNEL); + if (!priv) { + dev_err(&client->dev, "Failed to allocate private data!\n"); + return -ENOMEM; + } + + v4l2_i2c_subdev_init(&priv->subdev, client, &subsensor_subdev_ops); + + ret = subsensor_video_probe(icd, client); + if (ret < 0) { + kfree(priv); + } + + printk("------------subsensor_probe---return --ret = %d---------\n", ret); + return ret; +} + +static int subsensor_remove(struct i2c_client *client) +{ + return 0; +} + +static struct i2c_device_id subsensor_idtable[] = { + { "subsensor", 1 }, + { } +}; + +static struct i2c_driver subsensor_driver = { + .driver = { + .name = "subsensor", + }, + .id_table = subsensor_idtable, + .probe = subsensor_probe, + .remove = subsensor_remove, +}; + +/* + * Module initialization + */ +static int __init subsensor_mod_init(void) +{ + int ret =0; + Cam_Printk(KERN_NOTICE "Marvell sub sensor driver, at your service\n"); + ret = i2c_add_driver(&subsensor_driver); + Cam_Printk(KERN_NOTICE "Marvell sub sensor :%d \n ",ret); + return ret; +} + +static void __exit subsensor_mod_exit(void) +{ + i2c_del_driver(&subsensor_driver); +} + +module_init(subsensor_mod_init); +module_exit(subsensor_mod_exit); + diff --git a/pool/shard003/C/0067211_udevadm-test.c b/pool/shard003/C/0067211_udevadm-test.c new file mode 100644 index 0000000000000000000000000000000000000000..542c56eb1a2cd3f9aac13f58103428a1dd0f1563 --- /dev/null +++ b/pool/shard003/C/0067211_udevadm-test.c @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2003-2004 Greg Kroah-Hartman + * Copyright (C) 2004-2008 Kay Sievers + * + * 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 +#include +#include +#include +#include +#include +#include +#include + +#include "udev.h" +#include "udev-util.h" + +static void help(void) { + + printf("%s test OPTIONS \n\n" + "Test an event run.\n" + " -h --help Show this help\n" + " --version Show package version\n" + " -a --action=ACTION Set action string\n" + " -N --resolve-names=early|late|never When to resolve names\n" + , program_invocation_short_name); +} + +static int adm_test(struct udev *udev, int argc, char *argv[]) { + int resolve_names = 1; + char filename[UTIL_PATH_SIZE]; + const char *action = "add"; + const char *syspath = NULL; + struct udev_list_entry *entry; + _cleanup_udev_rules_unref_ struct udev_rules *rules = NULL; + _cleanup_udev_device_unref_ struct udev_device *dev = NULL; + _cleanup_udev_event_unref_ struct udev_event *event = NULL; + sigset_t mask, sigmask_orig; + int rc = 0, c; + + static const struct option options[] = { + { "action", required_argument, NULL, 'a' }, + { "resolve-names", required_argument, NULL, 'N' }, + { "help", no_argument, NULL, 'h' }, + {} + }; + + log_debug("version %s", VERSION); + + while((c = getopt_long(argc, argv, "a:N:h", options, NULL)) >= 0) + switch (c) { + case 'a': + action = optarg; + break; + case 'N': + if (streq (optarg, "early")) { + resolve_names = 1; + } else if (streq (optarg, "late")) { + resolve_names = 0; + } else if (streq (optarg, "never")) { + resolve_names = -1; + } else { + fprintf(stderr, "resolve-names must be early, late or never\n"); + log_error("resolve-names must be early, late or never"); + exit(EXIT_FAILURE); + } + break; + case 'h': + help(); + exit(EXIT_SUCCESS); + case '?': + exit(EXIT_FAILURE); + default: + assert_not_reached("Unknown option"); + } + + syspath = argv[optind]; + if (syspath == NULL) { + fprintf(stderr, "syspath parameter missing\n"); + rc = 2; + goto out; + } + + printf("This program is for debugging only, it does not run any program\n" + "specified by a RUN key. It may show incorrect results, because\n" + "some values may be different, or not available at a simulation run.\n" + "\n"); + + sigprocmask(SIG_SETMASK, NULL, &sigmask_orig); + + udev_builtin_init(udev); + + rules = udev_rules_new(udev, resolve_names); + if (rules == NULL) { + fprintf(stderr, "error reading rules\n"); + rc = 3; + goto out; + } + + /* add /sys if needed */ + if (!startswith(syspath, "/sys")) + strscpyl(filename, sizeof(filename), "/sys", syspath, NULL); + else + strscpy(filename, sizeof(filename), syspath); + util_remove_trailing_chars(filename, '/'); + + dev = udev_device_new_from_syspath(udev, filename); + if (dev == NULL) { + fprintf(stderr, "unable to open device '%s'\n", filename); + rc = 4; + goto out; + } + + /* skip reading of db, but read kernel parameters */ + udev_device_set_info_loaded(dev); + udev_device_read_uevent_file(dev); + + udev_device_set_action(dev, action); + event = udev_event_new(dev); + + sigfillset(&mask); + sigprocmask(SIG_SETMASK, &mask, &sigmask_orig); + event->fd_signal = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC); + if (event->fd_signal < 0) { + fprintf(stderr, "error creating signalfd\n"); + rc = 5; + goto out; + } + + udev_event_execute_rules(event, + 60 * USEC_PER_SEC, 20 * USEC_PER_SEC, + NULL, + rules, + &sigmask_orig); + + udev_list_entry_foreach(entry, udev_device_get_properties_list_entry(dev)) + printf("%s=%s\n", udev_list_entry_get_name(entry), udev_list_entry_get_value(entry)); + + udev_list_entry_foreach(entry, udev_list_get_entry(&event->run_list)) { + char program[UTIL_PATH_SIZE]; + + udev_event_apply_format(event, udev_list_entry_get_name(entry), program, sizeof(program)); + printf("run: '%s'\n", program); + } +out: + if (event != NULL && event->fd_signal >= 0) + close(event->fd_signal); + udev_builtin_exit(udev); + return rc; +} + +const struct udevadm_cmd udevadm_test = { + .name = "test", + .cmd = adm_test, + .help = "Test an event run", + .debug = true, +}; diff --git a/pool/shard003/C/0067214_interpreter.c b/pool/shard003/C/0067214_interpreter.c new file mode 100644 index 0000000000000000000000000000000000000000..653a0b3a7d89bee1722675d83e6776213d3d2113 --- /dev/null +++ b/pool/shard003/C/0067214_interpreter.c @@ -0,0 +1,73 @@ +/* +* Copyright (C) 2013 Joey Toppin +* +* See COPYING at the top-level directory of this distribution or: +* . +*/ + +#include +#include +#include +#include +#include +#include + +#include "command.h" +#include "color.h" +#include "parser.h" + + +/*! Starts an interpreter for terminal interaction with the provided command + * pool. The interpreter runs as long as QUIT has a value of zero. */ +void start_interpreter(RLC_CMD pool[]) +{ + int QUIT = 0; + + struct sigaction EXIT; + EXIT.sa_handler = cleanup; + sigaction(SIGINT, &EXIT, NULL); + + for(; QUIT == 0;) { + char *line = readline("> "); + if(NULL == line) { + QUIT = 1; + cleanup(); + } + if(line) { + if(strcmp(line, "quit") == 0 || strcmp(line, "q") == 0 ) { + QUIT = 1; + cleanup(); + } else { + add_history(line); + process_line(line, pool); + free(line); + } + } + } +} + + +/*! Processes the returned line from the interpreter. + * If "line" is found in the standard command pool, its associated function. + * is executed. If line is not found in the standard command pool continue to + * match it against the program colors. + * If the line does not match any program colors, line is checked for + * arithmetic. */ +void process_line(char *line, RLC_CMD pool[]) +{ + int itr; + for(itr = 0; pool[itr].cmd; itr++) { + if(strcmp(line, pool[itr].cmd) == 0) { + if(strcmp(line, "list") == 0) { + pool[itr].func(RLC_PATH); + return; + } else { + pool[itr].func(); + return; + } + } + } + find_color(line, RLC_PATH, 0); + find_arithmetic(line); + find_request(line); +} diff --git a/pool/shard003/C/0067224_frontend_salamander.c b/pool/shard003/C/0067224_frontend_salamander.c new file mode 100644 index 0000000000000000000000000000000000000000..280e193271aed11dd74e205542296701a4c17812 --- /dev/null +++ b/pool/shard003/C/0067224_frontend_salamander.c @@ -0,0 +1,196 @@ +/* RetroArch - A frontend for libretro. + * Copyright (C) 2010-2014 - Hans-Kristian Arntzen + * Copyright (C) 2011-2016 - Daniel De Matteis + * + * 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 +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_CONFIG_H +#include "../config.h" +#endif + +#include "frontend_driver.h" +#include "../defaults.h" +#include "../verbosity.h" + +struct defaults g_defaults; + +/*We need to set libretro to the first entry in the cores + * directory so that it will be saved to the config file + */ +static void find_first_libretro_core(char *first_file, + size_t size_of_first_file, const char *dir, + const char * ext) +{ + size_t i; + bool ret = false; + struct string_list *list = dir_list_new(dir, ext, false, true, false, false); + + if (!list) + { + RARCH_ERR("Couldn't read directory." + " Cannot infer default libretro core.\n"); + return; + } + + RARCH_LOG("Searching for valid libretro implementation in: \"%s\".\n", + dir); + + for (i = 0; i < list->size && !ret; i++) + { + char fname[PATH_MAX_LENGTH] = {0}; + char salamander_name[PATH_MAX_LENGTH] = {0}; + const char *libretro_elem = (const char*)list->elems[i].data; + + RARCH_LOG("Checking library: \"%s\".\n", libretro_elem); + + if (!libretro_elem) + continue; + + fill_pathname_base(fname, libretro_elem, sizeof(fname)); + + if (!frontend_driver_get_salamander_basename( + salamander_name, sizeof(salamander_name))) + break; + + if (!strncmp(fname, salamander_name, sizeof(fname))) + { + if (list->size == (i + 1)) + { + RARCH_WARN("Entry is RetroArch Salamander itself, " + "but is last entry. No choice but to set it.\n"); + strlcpy(first_file, fname, size_of_first_file); + } + + continue; + } + + strlcpy(first_file, fname, size_of_first_file); + RARCH_LOG("First found libretro core is: \"%s\".\n", first_file); + ret = true; + } + + dir_list_free(list); +} + +/* Last fallback - we'll need to start the first executable file + * we can find in the RetroArch cores directory. + */ +static void find_and_set_first_file(char *s, size_t len, + const char *ext) +{ + + char first_file[PATH_MAX_LENGTH] = {0}; + find_first_libretro_core(first_file, sizeof(first_file), + g_defaults.dir.core, ext); + + if (string_is_empty(first_file)) + { + RARCH_ERR("Failed last fallback - RetroArch Salamander will exit.\n"); + return; + } + + fill_pathname_join(s, g_defaults.dir.core, first_file, len); + RARCH_LOG("libretro_path now set to: %s.\n", s); +} + +static void salamander_init(char *s, size_t len) +{ + /* normal executable loading path */ + bool config_exists = config_file_exists(g_defaults.path.config); + + if (config_exists) + { + char tmp_str[PATH_MAX_LENGTH] = {0}; + config_file_t * conf = (config_file_t*) + config_file_new(g_defaults.path.config); + + if (conf) + { + config_get_array(conf, "libretro_path", tmp_str, sizeof(tmp_str)); + config_file_free(conf); + + if (!string_is_equal(tmp_str, "builtin")) + strlcpy(s, tmp_str, len); + } +#ifdef GEKKO + /* stupid libfat bug or something; sometimes it says + * the file is there when it doesn't. */ + else + { + config_exists = false; + } +#endif + } + + if (!config_exists || string_is_equal(s, "")) + { + char executable_name[PATH_MAX_LENGTH] = {0}; + + frontend_driver_get_core_extension( + executable_name, sizeof(executable_name)); + find_and_set_first_file(s, len, executable_name); + } + else + RARCH_LOG("Start [%s] found in retroarch.cfg.\n", s); + + if (!config_exists) + { + config_file_t *conf = (config_file_t*)config_file_new(NULL); + + if (conf) + { + config_set_string(conf, "libretro_path", s); + config_file_write(conf, g_defaults.path.config); + config_file_free(conf); + } + } +} + +int main(int argc, char *argv[]) +{ + char libretro_path[PATH_MAX_LENGTH] = {0}; + void *args = NULL; + struct rarch_main_wrap *wrap_args = NULL; + frontend_ctx_driver_t *frontend_ctx = (frontend_ctx_driver_t*)frontend_ctx_init_first(); + + if (!frontend_ctx) + return 0; + + if (frontend_ctx && frontend_ctx->init) + frontend_ctx->init(args); + + if (frontend_ctx && frontend_ctx->environment_get) + frontend_ctx->environment_get(&argc, argv, args, wrap_args); + + salamander_init(libretro_path, sizeof(libretro_path)); + + if (frontend_ctx && frontend_ctx->deinit) + frontend_ctx->deinit(args); + + if (frontend_ctx && frontend_ctx->exitspawn) + frontend_ctx->exitspawn(libretro_path, sizeof(libretro_path)); + + return 1; +} diff --git a/pool/shard003/C/0067226_acm2717.c b/pool/shard003/C/0067226_acm2717.c new file mode 100644 index 0000000000000000000000000000000000000000..7e792ac72ca763518a1884b2dfe42044fd21e26e --- /dev/null +++ b/pool/shard003/C/0067226_acm2717.c @@ -0,0 +1,70 @@ +#include +#include +#include +#include +#include +const int MAX = 100000000; +const int MIN = -100000000; +using namespace std; +struct node +{ + int x; + int step; + friend bool operator < (node a, node b) + { + return a.step > b.step; + } +}; +struct node now, after; +int n, m, visit[200100]; +void bfs(); +int main() +{ + int i, j, k; + while (scanf("%d %d", &n, &m) != EOF) + { + bfs(); + printf("%d\n", now.step); + } + return 0; +} +void bfs() +{ + priority_queueq; + + int i, j, k; + for (i = 0; i < 200100; i++) + visit[i] = MAX; + now.x = n; + now.step = 0; + visit[n] = 0; + q.push(now); + while (!q.empty()) + { + now = q.top(); + q.pop(); + if (now.x == m) + return; + after.x = now.x * 2; + after.step = now.step + 1; + if (visit[after.x] > after.step && after.x >= 0 && after.x < 200100) + { + q.push(after); + visit[after.x] = after.step; + } + after.x = now.x + 1; + after.step = now.step + 1; + if (visit[after.x] > after.step && after.x >= 0 && after.x < 200100) + { + q.push(after); + visit[after.x] = after.step; + } + after.x = now.x - 1; + after.step = now.step + 1; + if (visit[after.x] > after.step && after.x >= 0 && after.x < 200100) + { + q.push(after); + visit[after.x] = after.step; + } + } +} diff --git a/pool/shard003/C/0067238_cli_pipe_schannel.c b/pool/shard003/C/0067238_cli_pipe_schannel.c new file mode 100644 index 0000000000000000000000000000000000000000..0ee2a8551ff8f736f8e9abbac46b220342f78f88 --- /dev/null +++ b/pool/shard003/C/0067238_cli_pipe_schannel.c @@ -0,0 +1,234 @@ +/* + * Unix SMB/CIFS implementation. + * RPC Pipe client / server routines + * Largely rewritten by Jeremy Allison 2005. + * + * 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 "includes.h" +#include "../librpc/gen_ndr/ndr_schannel.h" +#include "../librpc/gen_ndr/ndr_netlogon.h" +#include "../libcli/auth/schannel.h" +#include "rpc_client/cli_netlogon.h" +#include "rpc_client/cli_pipe.h" +#include "librpc/gen_ndr/ndr_dcerpc.h" +#include "librpc/rpc/dcerpc.h" +#include "passdb.h" +#include "libsmb/libsmb.h" +#include "auth/gensec/gensec.h" + +#undef DBGC_CLASS +#define DBGC_CLASS DBGC_RPC_CLI + + +/**************************************************************************** + Get a the schannel session key out of an already opened netlogon pipe. + ****************************************************************************/ +static NTSTATUS get_schannel_session_key_common(struct rpc_pipe_client *netlogon_pipe, + struct cli_state *cli, + const char *domain, + uint32 *pneg_flags) +{ + enum netr_SchannelType sec_chan_type = 0; + unsigned char machine_pwd[16]; + const char *machine_account; + NTSTATUS status; + + /* Get the machine account credentials from secrets.tdb. */ + if (!get_trust_pw_hash(domain, machine_pwd, &machine_account, + &sec_chan_type)) + { + DEBUG(0, ("get_schannel_session_key: could not fetch " + "trust account password for domain '%s'\n", + domain)); + return NT_STATUS_CANT_ACCESS_DOMAIN_INFO; + } + + status = rpccli_netlogon_setup_creds(netlogon_pipe, + cli_state_remote_name(cli), /* server name */ + domain, /* domain */ + lp_netbios_name(), /* client name */ + machine_account, /* machine account name */ + machine_pwd, + sec_chan_type, + pneg_flags); + + if (!NT_STATUS_IS_OK(status)) { + DEBUG(3, ("get_schannel_session_key_common: " + "rpccli_netlogon_setup_creds failed with result %s " + "to server %s, domain %s, machine account %s.\n", + nt_errstr(status), cli_state_remote_name(cli), domain, + machine_account )); + return status; + } + + if (((*pneg_flags) & NETLOGON_NEG_SCHANNEL) == 0) { + DEBUG(3, ("get_schannel_session_key: Server %s did not offer schannel\n", + cli_state_remote_name(cli))); + return NT_STATUS_INVALID_NETWORK_RESPONSE; + } + + return NT_STATUS_OK; +} + +/**************************************************************************** + Open a named pipe to an SMB server and bind using schannel (bind type 68). + Fetch the session key ourselves using a temporary netlogon pipe. This + version uses an ntlmssp auth bound netlogon pipe to get the key. + ****************************************************************************/ + +static NTSTATUS get_schannel_session_key_auth_ntlmssp(struct cli_state *cli, + const char *domain, + const char *username, + const char *password, + uint32 *pneg_flags, + struct rpc_pipe_client **presult) +{ + struct rpc_pipe_client *netlogon_pipe = NULL; + NTSTATUS status; + + status = cli_rpc_pipe_open_spnego( + cli, &ndr_table_netlogon, NCACN_NP, + GENSEC_OID_NTLMSSP, + DCERPC_AUTH_LEVEL_PRIVACY, + cli_state_remote_name(cli), + domain, username, password, &netlogon_pipe); + if (!NT_STATUS_IS_OK(status)) { + return status; + } + + status = get_schannel_session_key_common(netlogon_pipe, cli, domain, + pneg_flags); + if (!NT_STATUS_IS_OK(status)) { + TALLOC_FREE(netlogon_pipe); + return status; + } + + *presult = netlogon_pipe; + return NT_STATUS_OK; +} + +/**************************************************************************** + Open a named pipe to an SMB server and bind using schannel (bind type 68). + Fetch the session key ourselves using a temporary netlogon pipe. This version + uses an ntlmssp bind to get the session key. + ****************************************************************************/ + +NTSTATUS cli_rpc_pipe_open_ntlmssp_auth_schannel(struct cli_state *cli, + const struct ndr_syntax_id *interface, + enum dcerpc_transport_t transport, + enum dcerpc_AuthLevel auth_level, + const char *domain, + const char *username, + const char *password, + struct rpc_pipe_client **presult) +{ + uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS; + struct rpc_pipe_client *netlogon_pipe = NULL; + struct rpc_pipe_client *result = NULL; + NTSTATUS status; + + status = get_schannel_session_key_auth_ntlmssp( + cli, domain, username, password, &neg_flags, &netlogon_pipe); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(0,("cli_rpc_pipe_open_ntlmssp_auth_schannel: failed to get schannel session " + "key from server %s for domain %s.\n", + cli_state_remote_name(cli), domain )); + return status; + } + + status = cli_rpc_pipe_open_schannel_with_key( + cli, interface, transport, auth_level, domain, &netlogon_pipe->dc, + &result); + + /* Now we've bound using the session key we can close the netlog pipe. */ + TALLOC_FREE(netlogon_pipe); + + if (NT_STATUS_IS_OK(status)) { + *presult = result; + } + return status; +} + +/**************************************************************************** + Open a named pipe to an SMB server and bind using schannel (bind type 68). + Fetch the session key ourselves using a temporary netlogon pipe. + ****************************************************************************/ + +NTSTATUS cli_rpc_pipe_open_schannel(struct cli_state *cli, + const struct ndr_syntax_id *interface, + enum dcerpc_transport_t transport, + enum dcerpc_AuthLevel auth_level, + const char *domain, + struct rpc_pipe_client **presult) +{ + uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS; + struct rpc_pipe_client *netlogon_pipe = NULL; + struct rpc_pipe_client *result = NULL; + NTSTATUS status; + + status = get_schannel_session_key(cli, domain, &neg_flags, + &netlogon_pipe); + if (!NT_STATUS_IS_OK(status)) { + DEBUG(0,("cli_rpc_pipe_open_schannel: failed to get schannel session " + "key from server %s for domain %s.\n", + cli_state_remote_name(cli), domain )); + return status; + } + + status = cli_rpc_pipe_open_schannel_with_key( + cli, interface, transport, auth_level, domain, &netlogon_pipe->dc, + &result); + + /* Now we've bound using the session key we can close the netlog pipe. */ + TALLOC_FREE(netlogon_pipe); + + if (NT_STATUS_IS_OK(status)) { + *presult = result; + } + + return status; +} + +/**************************************************************************** + Open a netlogon pipe and get the schannel session key. + Now exposed to external callers. + ****************************************************************************/ + + +NTSTATUS get_schannel_session_key(struct cli_state *cli, + const char *domain, + uint32 *pneg_flags, + struct rpc_pipe_client **presult) +{ + struct rpc_pipe_client *netlogon_pipe = NULL; + NTSTATUS status; + + status = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon.syntax_id, + &netlogon_pipe); + if (!NT_STATUS_IS_OK(status)) { + return status; + } + + status = get_schannel_session_key_common(netlogon_pipe, cli, domain, + pneg_flags); + if (!NT_STATUS_IS_OK(status)) { + TALLOC_FREE(netlogon_pipe); + return status; + } + + *presult = netlogon_pipe; + return NT_STATUS_OK; +} diff --git a/pool/shard003/C/0067239_20070212-1.c b/pool/shard003/C/0067239_20070212-1.c new file mode 100644 index 0000000000000000000000000000000000000000..efda7f9cf66867f256f5d0e34a683951f41aeb14 --- /dev/null +++ b/pool/shard003/C/0067239_20070212-1.c @@ -0,0 +1,26 @@ +struct f +{ + int i; +}; + +int g(int i, int c, struct f *ff, int *p) +{ + int *t; + if (c) + t = &i; + else + t = &ff->i; + *p = 0; + return *t; +} + +extern void abort(void); + +int main() +{ + struct f f; + f.i = 1; + if (g(5, 0, &f, &f.i) != 0) + abort (); + return 0; +} diff --git a/pool/shard003/C/0067243_scheduler.c b/pool/shard003/C/0067243_scheduler.c new file mode 100644 index 0000000000000000000000000000000000000000..b2368ef8ac048f72294bea5f1d2df9b3b0a70d21 --- /dev/null +++ b/pool/shard003/C/0067243_scheduler.c @@ -0,0 +1,265 @@ +// +// scheduler.c +// Firedrake +// +// Created by Sidney Just +// Copyright (c) 2012 by Sidney Just +// 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 +#include +#include +#include +#include +#include +#include "scheduler.h" + +static process_t *_process_firstProcess = NULL; +static process_t *_process_currentProcess = NULL; +static process_t *_sd_deadProcess = NULL; +static thread_t *_sd_deadThread = NULL; + +spinlock_t _sd_lock = SPINLOCK_INIT; + +process_t *process_getCurrentProcess() +{ + return _process_currentProcess; +} + +process_t *process_getFirstProcess() +{ + return _process_firstProcess; +} + +process_t *process_getCollectableProcesses() +{ + spinlock_lock(&_sd_lock); + + process_t *process = _sd_deadProcess; + _sd_deadProcess = NULL; + + spinlock_unlock(&_sd_lock); + return process; +} + +thread_t *thread_getCollectableThreads() +{ + spinlock_lock(&_sd_lock); + + thread_t *thread = _sd_deadThread; + _sd_deadThread = NULL; + + spinlock_unlock(&_sd_lock); + return thread; +} + +thread_t *thread_getCurrentThread() +{ + return _process_currentProcess->scheduledThread; +} + +void _process_setFirstProcess(process_t *process) +{ + _process_firstProcess = process; + _process_currentProcess = process; +} + +// MARK: Scheduler helper +static inline process_t *_sd_processPreviousProcess(process_t *process) +{ + process_t *previous = _process_firstProcess; + while(previous) + { + if(previous->next == process) + return previous; + + previous = previous->next; + } + + return NULL; +} + +static inline thread_t *_sd_threadPreviousThread(thread_t *thread) +{ + process_t *process = thread->process; + thread_t *previous = process->mainThread; + + while(previous) + { + if(previous->next == thread) + return previous; + + previous = previous->next; + } + + return NULL; +} + + +// MARK: Scheduler + +uint32_t sd_schedule(uint32_t esp) +{ + process_t *process = _process_currentProcess; + thread_t *thread = process->scheduledThread; + + if(esp) + { + // Try to obtain the lock, if we can't, we simply return to the current process + // The reason behind this is that its possible that the currently scheduled thread holds the lock in which case we would deadlock ourself + bool result = spinlock_tryLock(&_sd_lock); + if(!result) + return esp; + + thread->esp = esp; + thread->hasBeenRunning = true; + } + + // Check if the process or thread died + if(process->died || thread->died) + { + if(process->died || thread == process->mainThread) + { + process_t *previous = _sd_processPreviousProcess(process); + previous->next = process->next; + + process->next = _sd_deadProcess; + _sd_deadProcess = process; + + process = previous->next ? previous->next : _process_firstProcess; + thread = process->scheduledThread; + } + else + if(thread->died) + { + thread_t *previous = _sd_threadPreviousThread(thread); + previous->next = thread->next; + + thread->next = _sd_deadThread; + _sd_deadThread = thread; + + thread = previous->next ? previous->next : process->mainThread; + process->scheduledThread = thread; + } + } + + // Update the thread + thread->usedTicks ++; + while(thread->usedTicks >= thread->wantedTicks || thread->blocked > 0 || thread->died) + { + thread->usedTicks = 0; + + if(thread->sleeping) + { + timestamp_t timestamp = time_getTimestamp(); + + if(timestamp >= thread->wakeupCall) + { + thread->sleeping = false; + thread->blocked --; + + if(thread->blocked == 0 && thread->died != false) + break; + } + } + + // Update the scheduled thread + thread = thread->next ? thread->next : process->mainThread; + process->scheduledThread = thread; + + // Find a new process + process = process->next ? process->next : _process_firstProcess; + thread = process->scheduledThread; + + if(process->died) // Remotely killed process + { + _process_currentProcess = process; + return sd_schedule(0x0); + } + } + + _process_currentProcess = process; + ir_trampoline_map->pagedir = process->pdirectory; + ir_trampoline_map->tss.esp0 = thread->esp + sizeof(cpu_state_t); + + thread->wasNice = false; + + spinlock_unlock(&_sd_lock); + return thread->esp; +} + +uint32_t sd_schedule_kernel(uint32_t esp) +{ + process_t *process = _process_currentProcess; + thread_t *thread = process->scheduledThread; + + thread->wasNice = true; + thread->usedTicks = thread->wantedTicks; + + return sd_schedule(esp); +} + + + +void sd_yield() +{ + __asm__ volatile("int $0x31"); +} + +void sd_threadExit() +{ + thread_t *thread = thread_getCurrentThread(); + thread->died = true; + + while(1) + sd_yield(); +} + + +extern uintptr_t spinlock_wait; + +void sd_disableScheduler() +{ + spinlock_lock(&_sd_lock); + + // Also, since there is no rescheduling possible anymore, let's reinsert those nops back into the spinlock code + uint8_t *buffer = (uint8_t *)&spinlock_wait; + *(buffer ++) = 0x90; + *(buffer ++) = 0x90; +} + +bool sd_init(void *UNUSED(ingored)) +{ + process_t *process = process_createKernel(); + thread_t *thread = process->mainThread; + thread_setName(thread, "kerneld"); + + // Prepare everything for the kernel task + ir_trampoline_map->pagedir = process->pdirectory; + ir_trampoline_map->tss.esp0 = thread->esp + sizeof(cpu_state_t); + + // Setup the interrupt handler and enable interrupts now that we have a stack for the interrupt handler + ir_setInterruptHandler(sd_schedule_kernel, 0x31); + ir_enableInterrupts(false); + + // Now that the interrupt handler are in place, fixup spinlock_lock! + // See /system/lock.S for more details + uint8_t *buffer = (uint8_t *)&spinlock_wait; + *(buffer ++) = 0xcd; + *(buffer ++) = 0x31; + + return (process != NULL); +} diff --git a/pool/shard003/C/0067252_usb-hcd-uhci-test.c b/pool/shard003/C/0067252_usb-hcd-uhci-test.c new file mode 100644 index 0000000000000000000000000000000000000000..7a117b64d90c802ffeecd5cd092a196eac725a43 --- /dev/null +++ b/pool/shard003/C/0067252_usb-hcd-uhci-test.c @@ -0,0 +1,88 @@ +/* + * QTest testcase for USB UHCI controller + * + * Copyright (c) 2014 HUAWEI TECHNOLOGIES CO., LTD. + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + */ + +#include "qemu/osdep.h" +#include "libqtest-single.h" +#include "libqos/libqos.h" +#include "libqos/usb.h" +#include "libqos/libqos-pc.h" +#include "libqos/libqos-spapr.h" +#include "hw/usb/uhci-regs.h" + +static QOSState *qs; + +static void test_uhci_init(void) +{ +} + +static void test_port(int port) +{ + struct qhc uhci; + + g_assert(port > 0); + qusb_pci_init_one(qs->pcibus, &uhci, QPCI_DEVFN(0x1d, 0), 4); + uhci_port_test(&uhci, port - 1, UHCI_PORT_CCS); + uhci_deinit(&uhci); +} + +static void test_port_1(void) +{ + test_port(1); +} + +static void test_port_2(void) +{ + test_port(2); +} + +static void test_uhci_hotplug(void) +{ + usb_test_hotplug(global_qtest, "uhci", "2", test_port_2); +} + +static void test_usb_storage_hotplug(void) +{ + QTestState *qts = global_qtest; + + qtest_qmp_device_add(qts, "usb-storage", "usbdev0", "{'drive': 'drive0'}"); + + qtest_qmp_device_del(qts, "usbdev0"); +} + +int main(int argc, char **argv) +{ + const char *arch = qtest_get_arch(); + const char *cmd = "-device piix3-usb-uhci,id=uhci,addr=1d.0" + " -drive id=drive0,if=none,file=null-co://," + "file.read-zeroes=on,format=raw" + " -device usb-tablet,bus=uhci.0,port=1"; + int ret; + + g_test_init(&argc, &argv, NULL); + + qtest_add_func("/uhci/pci/init", test_uhci_init); + qtest_add_func("/uhci/pci/port1", test_port_1); + qtest_add_func("/uhci/pci/hotplug", test_uhci_hotplug); + qtest_add_func("/uhci/pci/hotplug/usb-storage", test_usb_storage_hotplug); + + if (strcmp(arch, "i386") == 0 || strcmp(arch, "x86_64") == 0) { + qs = qtest_pc_boot(cmd); + } else if (strcmp(arch, "ppc64") == 0) { + qs = qtest_spapr_boot(cmd); + } else { + g_printerr("usb-hcd-uhci-test tests are only " + "available on x86 or ppc64\n"); + exit(EXIT_FAILURE); + } + global_qtest = qs->qts; + ret = g_test_run(); + qtest_shutdown(qs); + + return ret; +} diff --git a/pool/shard003/C/0067265_r_flot.c b/pool/shard003/C/0067265_r_flot.c new file mode 100644 index 0000000000000000000000000000000000000000..cd8af8ac7ce712ae3f4830e841c924e56c7101c8 --- /dev/null +++ b/pool/shard003/C/0067265_r_flot.c @@ -0,0 +1,108 @@ +/* +** CXSC is a C++ library for eXtended Scientific Computing (V 2.5.4) +** +** Copyright (C) 1990-2000 Institut fuer Angewandte Mathematik, +** Universitaet Karlsruhe, Germany +** (C) 2000-2014 Wiss. Rechnen/Softwaretechnologie +** Universitaet Wuppertal, Germany +** +** This library is free software; you can redistribute it and/or +** modify it under the terms of the GNU Library 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 +** Library General Public License for more details. +** +** You should have received a copy of the GNU Library General Public +** License along with this library; if not, write to the Free +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +/* CVS $Id: r_flot.c,v 1.21 2014/01/30 17:24:12 cxsc Exp $ */ + +/****************************************************************/ +/* */ +/* Filename : r_flot.c */ +/* */ +/* Entries : a_real r_flot(i) */ +/* a_intg i; */ +/* */ +/* Arguments : */ +/* i = integer value to be converted */ +/* */ +/* Description : Convert integer value to real. */ +/* */ +/****************************************************************/ + +#ifndef ALL_IN_ONE +#ifdef AIX +#include "/u/p88c/runtime/o_defs.h" +#else +#include "o_defs.h" +#endif +#define local +#endif + +#ifdef LINT_ARGS +local a_real r_flot(a_intg i) +#else +local a_real r_flot(i) + +a_intg i; +#endif + { + a_real m; + a_btyp mant[D_U_RATIO]; + a_bool vz = FALSE; + a_intg expo; + + E_TPUSH("r_flot") + + B_CLEAR(mant,D_U_RATIO) + + if (i==0) expo = -CHARAC; + else + { + if (i<0) + { + vz = TRUE; + mant[0] = (i==MININT) ? (a_btyp)i : -i; + } + else + mant[0] = i; + + expo = EXPO_SHIFT; + + /* normalization of mantissa */ + if ( SHFT_MASK & mant[0] ) + { + do + { + b_shr1(mant,D_U_RATIO); + expo++; + } + while (SHFT_MASK & mant[0]); + } + else + { + while ( (HIDDEN_BIT & mant[0])==ZERO ) + { + mant[0] <<= 1; + expo--; + } + } + } + + b_comp(&m,expo,mant,vz); + + E_TPOPP("r_flot") + return(m); + } + + + + + diff --git a/pool/shard003/C/0067269_js-parser-tagged-template-literal.c b/pool/shard003/C/0067269_js-parser-tagged-template-literal.c new file mode 100644 index 0000000000000000000000000000000000000000..560a3e58111c534098f21a1664a5fe022cc85c4f --- /dev/null +++ b/pool/shard003/C/0067269_js-parser-tagged-template-literal.c @@ -0,0 +1,165 @@ +/* Copyright JS Foundation and other contributors, http://js.foundation + * + * 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 "js-parser-tagged-template-literal.h" +#include "js-lexer.h" +#include "ecma-array-object.h" +#include "ecma-builtin-helpers.h" +#include "ecma-gc.h" +#include "ecma-helpers.h" +#include "ecma-objects.h" + +/* \addtogroup parser Parser + * @{ + * + * \addtogroup jsparser JavaScript + * @{ + * + * \addtogroup jsparser_tagged_template_literal Tagged template literal + * @{ + */ + +#if JERRY_ESNEXT +/** + * Append the cooked and raw string to the corresponding array + */ +void +parser_tagged_template_literal_append_strings (parser_context_t *context_p, /**< parser context */ + ecma_object_t *template_obj_p, /**< template object */ + ecma_object_t *raw_strings_p, /**< raw strings object */ + uint32_t prop_idx) /**< property index to set the values */ +{ + lexer_lit_location_t *lit_loc_p = &context_p->token.lit_location; + + if (lit_loc_p->length == 0 && !(lit_loc_p->status_flags & LEXER_LIT_LOCATION_HAS_ESCAPE)) + { + ecma_builtin_helper_def_prop_by_index (template_obj_p, + prop_idx, + ecma_make_magic_string_value (LIT_MAGIC_STRING__EMPTY), + ECMA_PROPERTY_FLAG_ENUMERABLE); + + ecma_builtin_helper_def_prop_by_index (raw_strings_p, + prop_idx, + ecma_make_magic_string_value (LIT_MAGIC_STRING__EMPTY), + ECMA_PROPERTY_FLAG_ENUMERABLE); + return; + } + + uint8_t local_byte_array[LEXER_MAX_LITERAL_LOCAL_BUFFER_SIZE]; + const uint8_t *source_p = lexer_convert_literal_to_chars (context_p, + &context_p->token.lit_location, + local_byte_array, + LEXER_STRING_NO_OPTS); + + ecma_string_t *raw_str_p; + ecma_string_t *cooked_str_p = ((lit_loc_p->status_flags & LEXER_FLAG_ASCII) + ? ecma_new_ecma_string_from_ascii (source_p, lit_loc_p->length) + : ecma_new_ecma_string_from_utf8 (source_p, lit_loc_p->length)); + + parser_free_allocated_buffer (context_p); + + if (lit_loc_p->status_flags & LEXER_LIT_LOCATION_HAS_ESCAPE) + { + context_p->source_p = context_p->token.lit_location.char_p - 1; + lexer_parse_string (context_p, LEXER_STRING_RAW); + source_p = lexer_convert_literal_to_chars (context_p, + &context_p->token.lit_location, + local_byte_array, + LEXER_STRING_RAW); + + raw_str_p = ((lit_loc_p->status_flags & LEXER_FLAG_ASCII) + ? ecma_new_ecma_string_from_ascii (source_p, lit_loc_p->length) + : ecma_new_ecma_string_from_utf8 (source_p, lit_loc_p->length)); + + parser_free_allocated_buffer (context_p); + } + else + { + ecma_ref_ecma_string (cooked_str_p); + raw_str_p = cooked_str_p; + } + + ecma_builtin_helper_def_prop_by_index (template_obj_p, + prop_idx, + ecma_make_string_value (cooked_str_p), + ECMA_PROPERTY_FLAG_ENUMERABLE); + + ecma_builtin_helper_def_prop_by_index (raw_strings_p, + prop_idx, + ecma_make_string_value (raw_str_p), + ECMA_PROPERTY_FLAG_ENUMERABLE); + + ecma_deref_ecma_string (cooked_str_p); + ecma_deref_ecma_string (raw_str_p); +} /* parser_tagged_template_literal_append_strings */ + +/** + * Create new tagged template literal object + * + * @return pointer to the allocated object + */ +ecma_object_t * +parser_new_tagged_template_literal (ecma_object_t **raw_strings_p) /**< [out] raw strings object */ +{ + ecma_object_t *template_obj_p = ecma_op_new_array_object (0); + *raw_strings_p = ecma_op_new_array_object (0); + + ecma_extended_object_t *template_ext_obj_p = (ecma_extended_object_t *) template_obj_p; + ecma_extended_object_t *raw_ext_obj_p = (ecma_extended_object_t *) *raw_strings_p; + + const uint8_t flags = ECMA_PROPERTY_VIRTUAL | ECMA_PROPERTY_FLAG_WRITABLE | ECMA_FAST_ARRAY_FLAG; + JERRY_ASSERT (template_ext_obj_p->u.array.length_prop_and_hole_count == flags); + JERRY_ASSERT (raw_ext_obj_p->u.array.length_prop_and_hole_count == flags); + + template_ext_obj_p->u.array.length_prop_and_hole_count = flags | ECMA_ARRAY_TEMPLATE_LITERAL; + raw_ext_obj_p->u.array.length_prop_and_hole_count = flags | ECMA_ARRAY_TEMPLATE_LITERAL; + + ecma_builtin_helper_def_prop (template_obj_p, + ecma_get_magic_string (LIT_MAGIC_STRING_RAW), + ecma_make_object_value (*raw_strings_p), + ECMA_PROPERTY_FIXED); + + return template_obj_p; +} /* parser_new_tagged_template_literal */ + +/** + * Set integrity level of the given template array object to "frozen" + */ +static void +parser_tagged_template_literal_freeze_array (ecma_object_t *obj_p) +{ + JERRY_ASSERT (ecma_get_object_type (obj_p) == ECMA_OBJECT_TYPE_ARRAY); + ecma_op_ordinary_object_prevent_extensions (obj_p); + ecma_extended_object_t *ext_obj_p = (ecma_extended_object_t *) obj_p; + ext_obj_p->u.array.length_prop_and_hole_count &= (uint32_t) ~ECMA_PROPERTY_FLAG_WRITABLE; +} /* parser_tagged_template_literal_freeze_array */ + +/** + * Finalize the tagged template object + */ +void +parser_tagged_template_literal_finalize (ecma_object_t *template_obj_p, /**< template object */ + ecma_object_t *raw_strings_p) /**< raw strings object */ +{ + parser_tagged_template_literal_freeze_array (template_obj_p); + parser_tagged_template_literal_freeze_array (raw_strings_p); +} /* parser_tagged_template_literal_finalize */ +#endif /* JERRY_ESNEXT */ + +/** + * @} + * @} + * @} + */ diff --git a/pool/shard003/C/0067277_main.c b/pool/shard003/C/0067277_main.c new file mode 100644 index 0000000000000000000000000000000000000000..9030eb9bc9359ec6dbe8a7a1ecfb22702023d02e --- /dev/null +++ b/pool/shard003/C/0067277_main.c @@ -0,0 +1,28 @@ +#include + +int main(void) { + printf ("\nreadline started\n\n"); + + int i; + char line[81]; + void readLine (char buffer[]); + + readLine (line); + printf ("%s\n\n", line); + + printf ("\nreadline ended\n\n"); + + return 0; +} + +void readLine (char buffer[]) { + char character; + int i = 0; + do { + character = getchar (); + buffer[i] = character; + ++i; + } while ( character != '\n' ); + + buffer [i - 1] = '\0'; +} \ No newline at end of file diff --git a/pool/shard003/C/0067296_nfs3acl.c b/pool/shard003/C/0067296_nfs3acl.c new file mode 100644 index 0000000000000000000000000000000000000000..e0c4846bad922be3307add94510a9b96330f691b --- /dev/null +++ b/pool/shard003/C/0067296_nfs3acl.c @@ -0,0 +1,266 @@ +/* + * Process version 3 NFSACL requests. + * + * Copyright (C) 2002-2003 Andreas Gruenbacher + */ + +#include "nfsd.h" +/* FIXME: nfsacl.h is a broken header */ +#include +#include "cache.h" +#include "xdr3.h" +#include "vfs.h" + +#define RETURN_STATUS(st) { resp->status = (st); return (st); } + +/* + * NULL call. + */ +static __be32 +nfsd3_proc_null(struct svc_rqst *rqstp, void *argp, void *resp) +{ + return nfs_ok; +} + +/* + * Get the Access and/or Default ACL of a file. + */ +static __be32 nfsd3_proc_getacl(struct svc_rqst * rqstp, + struct nfsd3_getaclargs *argp, struct nfsd3_getaclres *resp) +{ + svc_fh *fh; + struct posix_acl *acl; + __be32 nfserr = 0; + + fh = fh_copy(&resp->fh, &argp->fh); + nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_NOP); + if (nfserr) + RETURN_STATUS(nfserr); + + if (argp->mask & ~(NFS_ACL|NFS_ACLCNT|NFS_DFACL|NFS_DFACLCNT)) + RETURN_STATUS(nfserr_inval); + resp->mask = argp->mask; + + if (resp->mask & (NFS_ACL|NFS_ACLCNT)) { + acl = nfsd_get_posix_acl(fh, ACL_TYPE_ACCESS); + if (IS_ERR(acl)) { + int err = PTR_ERR(acl); + + if (err == -ENODATA || err == -EOPNOTSUPP) + acl = NULL; + else { + nfserr = nfserrno(err); + goto fail; + } + } + if (acl == NULL) { + /* Solaris returns the inode's minimum ACL. */ + + struct inode *inode = fh->fh_dentry->d_inode; + acl = posix_acl_from_mode(inode->i_mode, GFP_KERNEL); + } + resp->acl_access = acl; + } + if (resp->mask & (NFS_DFACL|NFS_DFACLCNT)) { + /* Check how Solaris handles requests for the Default ACL + of a non-directory! */ + + acl = nfsd_get_posix_acl(fh, ACL_TYPE_DEFAULT); + if (IS_ERR(acl)) { + int err = PTR_ERR(acl); + + if (err == -ENODATA || err == -EOPNOTSUPP) + acl = NULL; + else { + nfserr = nfserrno(err); + goto fail; + } + } + resp->acl_default = acl; + } + + /* resp->acl_{access,default} are released in nfs3svc_release_getacl. */ + RETURN_STATUS(0); + +fail: + posix_acl_release(resp->acl_access); + posix_acl_release(resp->acl_default); + RETURN_STATUS(nfserr); +} + +/* + * Set the Access and/or Default ACL of a file. + */ +static __be32 nfsd3_proc_setacl(struct svc_rqst * rqstp, + struct nfsd3_setaclargs *argp, + struct nfsd3_attrstat *resp) +{ + svc_fh *fh; + __be32 nfserr = 0; + + fh = fh_copy(&resp->fh, &argp->fh); + nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); + + if (!nfserr) { + nfserr = nfserrno( nfsd_set_posix_acl( + fh, ACL_TYPE_ACCESS, argp->acl_access) ); + } + if (!nfserr) { + nfserr = nfserrno( nfsd_set_posix_acl( + fh, ACL_TYPE_DEFAULT, argp->acl_default) ); + } + + /* argp->acl_{access,default} may have been allocated in + nfs3svc_decode_setaclargs. */ + posix_acl_release(argp->acl_access); + posix_acl_release(argp->acl_default); + RETURN_STATUS(nfserr); +} + +/* + * XDR decode functions + */ +static int nfs3svc_decode_getaclargs(struct svc_rqst *rqstp, __be32 *p, + struct nfsd3_getaclargs *args) +{ + if (!(p = nfs3svc_decode_fh(p, &args->fh))) + return 0; + args->mask = ntohl(*p); p++; + + return xdr_argsize_check(rqstp, p); +} + + +static int nfs3svc_decode_setaclargs(struct svc_rqst *rqstp, __be32 *p, + struct nfsd3_setaclargs *args) +{ + struct kvec *head = rqstp->rq_arg.head; + unsigned int base; + int n; + + if (!(p = nfs3svc_decode_fh(p, &args->fh))) + return 0; + args->mask = ntohl(*p++); + if (args->mask & ~(NFS_ACL|NFS_ACLCNT|NFS_DFACL|NFS_DFACLCNT) || + !xdr_argsize_check(rqstp, p)) + return 0; + + base = (char *)p - (char *)head->iov_base; + n = nfsacl_decode(&rqstp->rq_arg, base, NULL, + (args->mask & NFS_ACL) ? + &args->acl_access : NULL); + if (n > 0) + n = nfsacl_decode(&rqstp->rq_arg, base + n, NULL, + (args->mask & NFS_DFACL) ? + &args->acl_default : NULL); + return (n > 0); +} + +/* + * XDR encode functions + */ + +/* GETACL */ +static int nfs3svc_encode_getaclres(struct svc_rqst *rqstp, __be32 *p, + struct nfsd3_getaclres *resp) +{ + struct dentry *dentry = resp->fh.fh_dentry; + + p = nfs3svc_encode_post_op_attr(rqstp, p, &resp->fh); + if (resp->status == 0 && dentry && dentry->d_inode) { + struct inode *inode = dentry->d_inode; + struct kvec *head = rqstp->rq_res.head; + unsigned int base; + int n; + int w; + + *p++ = htonl(resp->mask); + if (!xdr_ressize_check(rqstp, p)) + return 0; + base = (char *)p - (char *)head->iov_base; + + rqstp->rq_res.page_len = w = nfsacl_size( + (resp->mask & NFS_ACL) ? resp->acl_access : NULL, + (resp->mask & NFS_DFACL) ? resp->acl_default : NULL); + while (w > 0) { + if (!rqstp->rq_respages[rqstp->rq_resused++]) + return 0; + w -= PAGE_SIZE; + } + + n = nfsacl_encode(&rqstp->rq_res, base, inode, + resp->acl_access, + resp->mask & NFS_ACL, 0); + if (n > 0) + n = nfsacl_encode(&rqstp->rq_res, base + n, inode, + resp->acl_default, + resp->mask & NFS_DFACL, + NFS_ACL_DEFAULT); + if (n <= 0) + return 0; + } else + if (!xdr_ressize_check(rqstp, p)) + return 0; + + return 1; +} + +/* SETACL */ +static int nfs3svc_encode_setaclres(struct svc_rqst *rqstp, __be32 *p, + struct nfsd3_attrstat *resp) +{ + p = nfs3svc_encode_post_op_attr(rqstp, p, &resp->fh); + + return xdr_ressize_check(rqstp, p); +} + +/* + * XDR release functions + */ +static int nfs3svc_release_getacl(struct svc_rqst *rqstp, __be32 *p, + struct nfsd3_getaclres *resp) +{ + fh_put(&resp->fh); + posix_acl_release(resp->acl_access); + posix_acl_release(resp->acl_default); + return 1; +} + +#define nfs3svc_decode_voidargs NULL +#define nfs3svc_release_void NULL +#define nfsd3_setaclres nfsd3_attrstat +#define nfsd3_voidres nfsd3_voidargs +struct nfsd3_voidargs { int dummy; }; + +#define PROC(name, argt, rest, relt, cache, respsize) \ + { (svc_procfunc) nfsd3_proc_##name, \ + (kxdrproc_t) nfs3svc_decode_##argt##args, \ + (kxdrproc_t) nfs3svc_encode_##rest##res, \ + (kxdrproc_t) nfs3svc_release_##relt, \ + sizeof(struct nfsd3_##argt##args), \ + sizeof(struct nfsd3_##rest##res), \ + 0, \ + cache, \ + respsize, \ + } + +#define ST 1 /* status*/ +#define AT 21 /* attributes */ +#define pAT (1+AT) /* post attributes - conditional */ +#define ACL (1+NFS_ACL_MAX_ENTRIES*3) /* Access Control List */ + +static struct svc_procedure nfsd_acl_procedures3[] = { + PROC(null, void, void, void, RC_NOCACHE, ST), + PROC(getacl, getacl, getacl, getacl, RC_NOCACHE, ST+1+2*(1+ACL)), + PROC(setacl, setacl, setacl, fhandle, RC_NOCACHE, ST+pAT), +}; + +struct svc_version nfsd_acl_version3 = { + .vs_vers = 3, + .vs_nproc = 3, + .vs_proc = nfsd_acl_procedures3, + .vs_dispatch = nfsd_dispatch, + .vs_xdrsize = NFS3_SVC_XDRSIZE, + .vs_hidden = 0, +}; + diff --git a/pool/shard003/C/0067301_clock-sh7785.c b/pool/shard003/C/0067301_clock-sh7785.c new file mode 100644 index 0000000000000000000000000000000000000000..fca351378bbce69c0a545f43eafbfc4e50c4f589 --- /dev/null +++ b/pool/shard003/C/0067301_clock-sh7785.c @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * arch/sh/kernel/cpu/sh4a/clock-sh7785.c + * + * SH7785 support for the clock framework + * + * Copyright (C) 2007 - 2010 Paul Mundt + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Default rate for the root input clock, reset this with clk_set_rate() + * from the platform code. + */ +static struct clk extal_clk = { + .rate = 33333333, +}; + +static unsigned long pll_recalc(struct clk *clk) +{ + int multiplier; + + multiplier = test_mode_pin(MODE_PIN4) ? 36 : 72; + + return clk->parent->rate * multiplier; +} + +static struct sh_clk_ops pll_clk_ops = { + .recalc = pll_recalc, +}; + +static struct clk pll_clk = { + .ops = &pll_clk_ops, + .parent = &extal_clk, + .flags = CLK_ENABLE_ON_INIT, +}; + +static struct clk *clks[] = { + &extal_clk, + &pll_clk, +}; + +static unsigned int div2[] = { 1, 2, 4, 6, 8, 12, 16, 18, + 24, 32, 36, 48 }; + +static struct clk_div_mult_table div4_div_mult_table = { + .divisors = div2, + .nr_divisors = ARRAY_SIZE(div2), +}; + +static struct clk_div4_table div4_table = { + .div_mult_table = &div4_div_mult_table, +}; + +enum { DIV4_I, DIV4_U, DIV4_SH, DIV4_B, DIV4_DDR, DIV4_GA, + DIV4_DU, DIV4_P, DIV4_NR }; + +#define DIV4(_bit, _mask, _flags) \ + SH_CLK_DIV4(&pll_clk, FRQMR1, _bit, _mask, _flags) + +struct clk div4_clks[DIV4_NR] = { + [DIV4_P] = DIV4(0, 0x0f80, 0), + [DIV4_DU] = DIV4(4, 0x0ff0, 0), + [DIV4_GA] = DIV4(8, 0x0030, 0), + [DIV4_DDR] = DIV4(12, 0x000c, CLK_ENABLE_ON_INIT), + [DIV4_B] = DIV4(16, 0x0fe0, CLK_ENABLE_ON_INIT), + [DIV4_SH] = DIV4(20, 0x000c, CLK_ENABLE_ON_INIT), + [DIV4_U] = DIV4(24, 0x000c, CLK_ENABLE_ON_INIT), + [DIV4_I] = DIV4(28, 0x000e, CLK_ENABLE_ON_INIT), +}; + +#define MSTPCR0 0xffc80030 +#define MSTPCR1 0xffc80034 + +enum { MSTP029, MSTP028, MSTP027, MSTP026, MSTP025, MSTP024, + MSTP021, MSTP020, MSTP017, MSTP016, + MSTP013, MSTP012, MSTP009, MSTP008, MSTP003, MSTP002, + MSTP119, MSTP117, MSTP105, MSTP104, MSTP100, + MSTP_NR }; + +static struct clk mstp_clks[MSTP_NR] = { + /* MSTPCR0 */ + [MSTP029] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 29, 0), + [MSTP028] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 28, 0), + [MSTP027] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 27, 0), + [MSTP026] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 26, 0), + [MSTP025] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 25, 0), + [MSTP024] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 24, 0), + [MSTP021] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 21, 0), + [MSTP020] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 20, 0), + [MSTP017] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 17, 0), + [MSTP016] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 16, 0), + [MSTP013] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 13, 0), + [MSTP012] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 12, 0), + [MSTP009] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 9, 0), + [MSTP008] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 8, 0), + [MSTP003] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 3, 0), + [MSTP002] = SH_CLK_MSTP32(&div4_clks[DIV4_P], MSTPCR0, 2, 0), + + /* MSTPCR1 */ + [MSTP119] = SH_CLK_MSTP32(NULL, MSTPCR1, 19, 0), + [MSTP117] = SH_CLK_MSTP32(NULL, MSTPCR1, 17, 0), + [MSTP105] = SH_CLK_MSTP32(NULL, MSTPCR1, 5, 0), + [MSTP104] = SH_CLK_MSTP32(NULL, MSTPCR1, 4, 0), + [MSTP100] = SH_CLK_MSTP32(NULL, MSTPCR1, 0, 0), +}; + +static struct clk_lookup lookups[] = { + /* main clocks */ + CLKDEV_CON_ID("extal", &extal_clk), + CLKDEV_CON_ID("pll_clk", &pll_clk), + + /* DIV4 clocks */ + CLKDEV_CON_ID("peripheral_clk", &div4_clks[DIV4_P]), + CLKDEV_CON_ID("du_clk", &div4_clks[DIV4_DU]), + CLKDEV_CON_ID("ga_clk", &div4_clks[DIV4_GA]), + CLKDEV_CON_ID("ddr_clk", &div4_clks[DIV4_DDR]), + CLKDEV_CON_ID("bus_clk", &div4_clks[DIV4_B]), + CLKDEV_CON_ID("shyway_clk", &div4_clks[DIV4_SH]), + CLKDEV_CON_ID("umem_clk", &div4_clks[DIV4_U]), + CLKDEV_CON_ID("cpu_clk", &div4_clks[DIV4_I]), + + /* MSTP32 clocks */ + CLKDEV_ICK_ID("fck", "sh-sci.5", &mstp_clks[MSTP029]), + CLKDEV_ICK_ID("fck", "sh-sci.4", &mstp_clks[MSTP028]), + CLKDEV_ICK_ID("fck", "sh-sci.3", &mstp_clks[MSTP027]), + CLKDEV_ICK_ID("fck", "sh-sci.2", &mstp_clks[MSTP026]), + CLKDEV_ICK_ID("fck", "sh-sci.1", &mstp_clks[MSTP025]), + CLKDEV_ICK_ID("fck", "sh-sci.0", &mstp_clks[MSTP024]), + + CLKDEV_CON_ID("ssi1_fck", &mstp_clks[MSTP021]), + CLKDEV_CON_ID("ssi0_fck", &mstp_clks[MSTP020]), + CLKDEV_CON_ID("hac1_fck", &mstp_clks[MSTP017]), + CLKDEV_CON_ID("hac0_fck", &mstp_clks[MSTP016]), + CLKDEV_CON_ID("mmcif_fck", &mstp_clks[MSTP013]), + CLKDEV_CON_ID("flctl_fck", &mstp_clks[MSTP012]), + + CLKDEV_ICK_ID("fck", "sh-tmu.0", &mstp_clks[MSTP008]), + CLKDEV_ICK_ID("fck", "sh-tmu.1", &mstp_clks[MSTP009]), + + CLKDEV_CON_ID("siof_fck", &mstp_clks[MSTP003]), + CLKDEV_CON_ID("hspi_fck", &mstp_clks[MSTP002]), + CLKDEV_CON_ID("hudi_fck", &mstp_clks[MSTP119]), + CLKDEV_CON_ID("ubc0", &mstp_clks[MSTP117]), + CLKDEV_CON_ID("dmac_11_6_fck", &mstp_clks[MSTP105]), + CLKDEV_CON_ID("dmac_5_0_fck", &mstp_clks[MSTP104]), + CLKDEV_CON_ID("gdta_fck", &mstp_clks[MSTP100]), +}; + +int __init arch_clk_init(void) +{ + int i, ret = 0; + + for (i = 0; i < ARRAY_SIZE(clks); i++) + ret |= clk_register(clks[i]); + + clkdev_add_table(lookups, ARRAY_SIZE(lookups)); + + if (!ret) + ret = sh_clk_div4_register(div4_clks, ARRAY_SIZE(div4_clks), + &div4_table); + if (!ret) + ret = sh_clk_mstp_register(mstp_clks, MSTP_NR); + + return ret; +} diff --git a/pool/shard003/C/0067307_hyperv.c b/pool/shard003/C/0067307_hyperv.c new file mode 100644 index 0000000000000000000000000000000000000000..39a230f11970127e773f28b4b6a6f5c9acf3801e --- /dev/null +++ b/pool/shard003/C/0067307_hyperv.c @@ -0,0 +1,140 @@ +/* + * QEMU KVM Hyper-V support + * + * Copyright (C) 2015 Andrey Smetanin + * + * Authors: + * Andrey Smetanin + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + * + */ + +#include "qemu/osdep.h" +#include "hyperv.h" +#include "standard-headers/asm-x86/hyperv.h" + +int kvm_hv_handle_exit(X86CPU *cpu, struct kvm_hyperv_exit *exit) +{ + CPUX86State *env = &cpu->env; + + switch (exit->type) { + case KVM_EXIT_HYPERV_SYNIC: + if (!cpu->hyperv_synic) { + return -1; + } + + /* + * For now just track changes in SynIC control and msg/evt pages msr's. + * When SynIC messaging/events processing will be added in future + * here we will do messages queues flushing and pages remapping. + */ + switch (exit->u.synic.msr) { + case HV_X64_MSR_SCONTROL: + env->msr_hv_synic_control = exit->u.synic.control; + break; + case HV_X64_MSR_SIMP: + env->msr_hv_synic_msg_page = exit->u.synic.msg_page; + break; + case HV_X64_MSR_SIEFP: + env->msr_hv_synic_evt_page = exit->u.synic.evt_page; + break; + default: + return -1; + } + return 0; + case KVM_EXIT_HYPERV_HCALL: { + uint16_t code; + + code = exit->u.hcall.input & 0xffff; + switch (code) { + case HVCALL_POST_MESSAGE: + case HVCALL_SIGNAL_EVENT: + default: + exit->u.hcall.result = HV_STATUS_INVALID_HYPERCALL_CODE; + return 0; + } + } + default: + return -1; + } +} + +static void kvm_hv_sint_ack_handler(EventNotifier *notifier) +{ + HvSintRoute *sint_route = container_of(notifier, HvSintRoute, + sint_ack_notifier); + event_notifier_test_and_clear(notifier); + if (sint_route->sint_ack_clb) { + sint_route->sint_ack_clb(sint_route); + } +} + +HvSintRoute *kvm_hv_sint_route_create(uint32_t vcpu_id, uint32_t sint, + HvSintAckClb sint_ack_clb) +{ + HvSintRoute *sint_route; + int r, gsi; + + sint_route = g_malloc0(sizeof(*sint_route)); + r = event_notifier_init(&sint_route->sint_set_notifier, false); + if (r) { + goto err; + } + + r = event_notifier_init(&sint_route->sint_ack_notifier, false); + if (r) { + goto err_sint_set_notifier; + } + + event_notifier_set_handler(&sint_route->sint_ack_notifier, false, + kvm_hv_sint_ack_handler); + + gsi = kvm_irqchip_add_hv_sint_route(kvm_state, vcpu_id, sint); + if (gsi < 0) { + goto err_gsi; + } + + r = kvm_irqchip_add_irqfd_notifier_gsi(kvm_state, + &sint_route->sint_set_notifier, + &sint_route->sint_ack_notifier, gsi); + if (r) { + goto err_irqfd; + } + sint_route->gsi = gsi; + sint_route->sint_ack_clb = sint_ack_clb; + sint_route->vcpu_id = vcpu_id; + sint_route->sint = sint; + + return sint_route; + +err_irqfd: + kvm_irqchip_release_virq(kvm_state, gsi); +err_gsi: + event_notifier_set_handler(&sint_route->sint_ack_notifier, false, NULL); + event_notifier_cleanup(&sint_route->sint_ack_notifier); +err_sint_set_notifier: + event_notifier_cleanup(&sint_route->sint_set_notifier); +err: + g_free(sint_route); + + return NULL; +} + +void kvm_hv_sint_route_destroy(HvSintRoute *sint_route) +{ + kvm_irqchip_remove_irqfd_notifier_gsi(kvm_state, + &sint_route->sint_set_notifier, + sint_route->gsi); + kvm_irqchip_release_virq(kvm_state, sint_route->gsi); + event_notifier_set_handler(&sint_route->sint_ack_notifier, false, NULL); + event_notifier_cleanup(&sint_route->sint_ack_notifier); + event_notifier_cleanup(&sint_route->sint_set_notifier); + g_free(sint_route); +} + +int kvm_hv_sint_route_set_sint(HvSintRoute *sint_route) +{ + return event_notifier_set(&sint_route->sint_set_notifier); +} diff --git a/pool/shard003/C/0067314_filestatTests.c b/pool/shard003/C/0067314_filestatTests.c new file mode 100644 index 0000000000000000000000000000000000000000..1afd8f9fc23955eab91efdfeb3d74a5b0b4ebe72 --- /dev/null +++ b/pool/shard003/C/0067314_filestatTests.c @@ -0,0 +1,20 @@ +#include "CuTest.h" +#include + +CuSuite *CuGetSuite(); +CuSuite *CuStringGetSuite(); + +int RunAllTests(void) { + CuString *output = CuStringNew(); + CuSuite *suite = CuSuiteNew(); + CuSuiteAddSuite(suite, filestatGetSuite()); + CuSuiteRun(suite); + CuSuiteSummary(suite, output); + CuSuiteDetails(suite, output); + printf("%s\n", output->buffer); + return suite->failCount; +} + +int main(void) { + return RunAllTests(); +} \ No newline at end of file diff --git a/pool/shard003/C/0067328_config_test_save_one_fcb.c b/pool/shard003/C/0067328_config_test_save_one_fcb.c new file mode 100644 index 0000000000000000000000000000000000000000..1ae991581d27eab5d0a83f5b38af05bec5cdeb98 --- /dev/null +++ b/pool/shard003/C/0067328_config_test_save_one_fcb.c @@ -0,0 +1,57 @@ +/* + * 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 "conf_test_fcb2.h" + +TEST_CASE_SELF(config_test_save_one_fcb) +{ + int rc; + struct conf_fcb2 cf; + + config_wipe_srcs(); + config_wipe_fcb2(fcb_range, CONF_TEST_FCB_RANGE_CNT); + + cf.cf2_fcb.f_magic = MYNEWT_VAL(CONFIG_FCB_MAGIC); + cf.cf2_fcb.f_range_cnt = CONF_TEST_FCB_RANGE_CNT; + cf.cf2_fcb.f_sector_cnt = fcb_range[0].fsr_sector_count; + cf.cf2_fcb.f_ranges = fcb_range; + + rc = conf_fcb2_src(&cf); + TEST_ASSERT(rc == 0); + + rc = conf_fcb2_dst(&cf); + TEST_ASSERT(rc == 0); + + val8 = 33; + rc = conf_save(); + TEST_ASSERT(rc == 0); + + rc = conf_save_one("myfoo/mybar", "42"); + TEST_ASSERT(rc == 0); + + rc = conf_load(); + TEST_ASSERT(rc == 0); + TEST_ASSERT(val8 == 42); + + rc = conf_save_one("myfoo/mybar", "44"); + TEST_ASSERT(rc == 0); + + rc = conf_load(); + TEST_ASSERT(rc == 0); + TEST_ASSERT(val8 == 44); +} diff --git a/pool/shard003/C/0067332_fd-ostream.c b/pool/shard003/C/0067332_fd-ostream.c new file mode 100644 index 0000000000000000000000000000000000000000..3f2047c8b499cd53057c09a4d1150f7f30e05f77 --- /dev/null +++ b/pool/shard003/C/0067332_fd-ostream.c @@ -0,0 +1,219 @@ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ + +#line 1 "fd-ostream.oo.c" +/* Output stream referring to a file descriptor. + Copyright (C) 2006-2007, 2015-2016 Free Software Foundation, Inc. + Written by Bruno Haible , 2006. + + 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 + +/* Specification. */ +#include "fd-ostream.h" + +#include +#include +#include +#include + +#include "error.h" +#include "full-write.h" +#include "xalloc.h" +#include "gettext.h" + +#define _(str) gettext (str) + +#line 39 "fd-ostream.c" +#if !IS_CPLUSPLUS +#define fd_ostream_representation any_ostream_representation +#endif +#include "fd_ostream.priv.h" + +const typeinfo_t fd_ostream_typeinfo = { "fd_ostream" }; + +static const typeinfo_t * const fd_ostream_superclasses[] = + { fd_ostream_SUPERCLASSES }; + +#define super ostream_vtable + +#line 43 "fd-ostream.oo.c" + +#define BUFSIZE 4096 + +/* Implementation of ostream_t methods. */ + +static void +fd_ostream__write_mem (fd_ostream_t stream, const void *data, size_t len) +{ + if (len > 0) + { + if (stream->buffer != NULL) + { + /* Buffered. */ + assert (stream->avail > 0); + #if 0 /* unoptimized */ + do + { + size_t n = (len <= stream->avail ? len : stream->avail); + if (n > 0) + { + memcpy (stream->buffer + BUFSIZE - stream->avail, data, n); + data = (char *) data + n; + stream->avail -= n; + len -= n; + } + if (stream->avail == 0) + { + if (full_write (stream->fd, stream->buffer, BUFSIZE) < BUFSIZE) + error (EXIT_FAILURE, errno, _("error writing to %s"), + stream->filename); + stream->avail = BUFSIZE; + } + } + while (len > 0); + #else /* optimized */ + if (len < stream->avail) + { + /* Move the data into the buffer. */ + memcpy (stream->buffer + BUFSIZE - stream->avail, data, len); + stream->avail -= len; + } + else + { + /* Split the data into: + - a first chunk, which is added to the buffer and output, + - a series of chunks of size BUFSIZE, which can be output + directly, without going through the buffer, and + - a last chunk, which is copied to the buffer. */ + size_t n = stream->avail; + memcpy (stream->buffer + BUFSIZE - stream->avail, data, n); + data = (char *) data + n; + len -= n; + if (full_write (stream->fd, stream->buffer, BUFSIZE) < BUFSIZE) + error (EXIT_FAILURE, errno, _("error writing to %s"), + stream->filename); + + while (len >= BUFSIZE) + { + if (full_write (stream->fd, data, BUFSIZE) < BUFSIZE) + error (EXIT_FAILURE, errno, _("error writing to %s"), + stream->filename); + data = (char *) data + BUFSIZE; + len -= BUFSIZE; + } + + if (len > 0) + memcpy (stream->buffer, data, len); + stream->avail = BUFSIZE - len; + } + #endif + assert (stream->avail > 0); + } + else + { + /* Unbuffered. */ + if (full_write (stream->fd, data, len) < len) + error (EXIT_FAILURE, errno, _("error writing to %s"), + stream->filename); + } + } +} + +static void +fd_ostream__flush (fd_ostream_t stream) +{ + if (stream->buffer != NULL && stream->avail < BUFSIZE) + { + size_t filled = BUFSIZE - stream->avail; + if (full_write (stream->fd, stream->buffer, filled) < filled) + error (EXIT_FAILURE, errno, _("error writing to %s"), stream->filename); + stream->avail = BUFSIZE; + } +} + +static void +fd_ostream__free (fd_ostream_t stream) +{ + fd_ostream_flush (stream); + free (stream->filename); + free (stream); +} + +/* Constructor. */ + +fd_ostream_t +fd_ostream_create (int fd, const char *filename, bool buffered) +{ + fd_ostream_t stream = + (struct fd_ostream_representation *) + xmalloc (sizeof (struct fd_ostream_representation) + + (buffered ? BUFSIZE : 0)); + + stream->base.vtable = &fd_ostream_vtable; + stream->fd = fd; + stream->filename = xstrdup (filename); + if (buffered) + { + stream->buffer = + (char *) (void *) stream + sizeof (struct fd_ostream_representation); + stream->avail = BUFSIZE; + } + else + stream->buffer = NULL; + + return stream; +} + +#line 180 "fd-ostream.c" + +const struct fd_ostream_implementation fd_ostream_vtable = +{ + fd_ostream_superclasses, + sizeof (fd_ostream_superclasses) / sizeof (fd_ostream_superclasses[0]), + sizeof (struct fd_ostream_representation), + fd_ostream__write_mem, + fd_ostream__flush, + fd_ostream__free, +}; + +#if !HAVE_INLINE + +/* Define the functions that invoke the methods. */ + +void +fd_ostream_write_mem (fd_ostream_t first_arg, const void *data, size_t len) +{ + const struct fd_ostream_implementation *vtable = + ((struct fd_ostream_representation_header *) (struct fd_ostream_representation *) first_arg)->vtable; + vtable->write_mem (first_arg,data,len); +} + +void +fd_ostream_flush (fd_ostream_t first_arg) +{ + const struct fd_ostream_implementation *vtable = + ((struct fd_ostream_representation_header *) (struct fd_ostream_representation *) first_arg)->vtable; + vtable->flush (first_arg); +} + +void +fd_ostream_free (fd_ostream_t first_arg) +{ + const struct fd_ostream_implementation *vtable = + ((struct fd_ostream_representation_header *) (struct fd_ostream_representation *) first_arg)->vtable; + vtable->free (first_arg); +} + +#endif diff --git a/pool/shard003/C/0067337_ima_queue.c b/pool/shard003/C/0067337_ima_queue.c new file mode 100644 index 0000000000000000000000000000000000000000..0e41dc1df1d4fe0e76eb2e72f538334047e83219 --- /dev/null +++ b/pool/shard003/C/0067337_ima_queue.c @@ -0,0 +1,213 @@ +/* + * Copyright (C) 2005,2006,2007,2008 IBM Corporation + * + * Authors: + * Serge Hallyn + * Reiner Sailer + * Mimi Zohar + * + * 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. + * + * File: ima_queue.c + * Implements queues that store template measurements and + * maintains aggregate over the stored measurements + * in the pre-configured TPM PCR (if available). + * The measurement list is append-only. No entry is + * ever removed or changed during the boot-cycle. + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include "ima.h" + +#define AUDIT_CAUSE_LEN_MAX 32 + +LIST_HEAD(ima_measurements); /* list of all measurements */ +#ifdef CONFIG_IMA_KEXEC +static unsigned long binary_runtime_size; +#else +static unsigned long binary_runtime_size = ULONG_MAX; +#endif + +/* key: inode (before secure-hashing a file) */ +struct ima_h_table ima_htable = { + .len = ATOMIC_LONG_INIT(0), + .violations = ATOMIC_LONG_INIT(0), + .queue[0 ... IMA_MEASURE_HTABLE_SIZE - 1] = HLIST_HEAD_INIT +}; + +/* mutex protects atomicity of extending measurement list + * and extending the TPM PCR aggregate. Since tpm_extend can take + * long (and the tpm driver uses a mutex), we can't use the spinlock. + */ +static DEFINE_MUTEX(ima_extend_list_mutex); + +/* lookup up the digest value in the hash table, and return the entry */ +static struct ima_queue_entry *ima_lookup_digest_entry(u8 *digest_value, + int pcr) +{ + struct ima_queue_entry *qe, *ret = NULL; + unsigned int key; + int rc; + + key = ima_hash_key(digest_value); + rcu_read_lock(); + hlist_for_each_entry_rcu(qe, &ima_htable.queue[key], hnext) { + rc = memcmp(qe->entry->digest, digest_value, TPM_DIGEST_SIZE); + if ((rc == 0) && (qe->entry->pcr == pcr)) { + ret = qe; + break; + } + } + rcu_read_unlock(); + return ret; +} + +/* + * Calculate the memory required for serializing a single + * binary_runtime_measurement list entry, which contains a + * couple of variable length fields (e.g template name and data). + */ +static int get_binary_runtime_size(struct ima_template_entry *entry) +{ + int size = 0; + + size += sizeof(u32); /* pcr */ + size += sizeof(entry->digest); + size += sizeof(int); /* template name size field */ + size += strlen(entry->template_desc->name); + size += sizeof(entry->template_data_len); + size += entry->template_data_len; + return size; +} + +/* ima_add_template_entry helper function: + * - Add template entry to the measurement list and hash table, for + * all entries except those carried across kexec. + * + * (Called with ima_extend_list_mutex held.) + */ +static int ima_add_digest_entry(struct ima_template_entry *entry, + bool update_htable) +{ + struct ima_queue_entry *qe; + unsigned int key; + + qe = kmalloc(sizeof(*qe), GFP_KERNEL); + if (qe == NULL) { + pr_err("OUT OF MEMORY ERROR creating queue entry\n"); + return -ENOMEM; + } + qe->entry = entry; + + INIT_LIST_HEAD(&qe->later); + list_add_tail_rcu(&qe->later, &ima_measurements); + + atomic_long_inc(&ima_htable.len); + if (update_htable) { + key = ima_hash_key(entry->digest); + hlist_add_head_rcu(&qe->hnext, &ima_htable.queue[key]); + } + + if (binary_runtime_size != ULONG_MAX) { + int size; + + size = get_binary_runtime_size(entry); + binary_runtime_size = (binary_runtime_size < ULONG_MAX - size) ? + binary_runtime_size + size : ULONG_MAX; + } + return 0; +} + +/* + * Return the amount of memory required for serializing the + * entire binary_runtime_measurement list, including the ima_kexec_hdr + * structure. + */ +unsigned long ima_get_binary_runtime_size(void) +{ + if (binary_runtime_size >= (ULONG_MAX - sizeof(struct ima_kexec_hdr))) + return ULONG_MAX; + else + return binary_runtime_size + sizeof(struct ima_kexec_hdr); +}; + +static int ima_pcr_extend(const u8 *hash, int pcr) +{ + int result = 0; + + if (!ima_tpm_chip) + return result; + + result = tpm_pcr_extend(ima_tpm_chip, pcr, hash); + if (result != 0) + pr_err("Error Communicating to TPM chip, result: %d\n", result); + return result; +} + +/* + * Add template entry to the measurement list and hash table, and + * extend the pcr. + * + * On systems which support carrying the IMA measurement list across + * kexec, maintain the total memory size required for serializing the + * binary_runtime_measurements. + */ +int ima_add_template_entry(struct ima_template_entry *entry, int violation, + const char *op, struct inode *inode, + const unsigned char *filename) +{ + u8 digest[TPM_DIGEST_SIZE]; + const char *audit_cause = "hash_added"; + char tpm_audit_cause[AUDIT_CAUSE_LEN_MAX]; + int audit_info = 1; + int result = 0, tpmresult = 0; + + mutex_lock(&ima_extend_list_mutex); + if (!violation) { + memcpy(digest, entry->digest, sizeof(digest)); + if (ima_lookup_digest_entry(digest, entry->pcr)) { + audit_cause = "hash_exists"; + result = -EEXIST; + goto out; + } + } + + result = ima_add_digest_entry(entry, 1); + if (result < 0) { + audit_cause = "ENOMEM"; + audit_info = 0; + goto out; + } + + if (violation) /* invalidate pcr */ + memset(digest, 0xff, sizeof(digest)); + + tpmresult = ima_pcr_extend(digest, entry->pcr); + if (tpmresult != 0) { + snprintf(tpm_audit_cause, AUDIT_CAUSE_LEN_MAX, "TPM_error(%d)", + tpmresult); + audit_cause = tpm_audit_cause; + audit_info = 0; + } +out: + mutex_unlock(&ima_extend_list_mutex); + integrity_audit_msg(AUDIT_INTEGRITY_PCR, inode, filename, + op, audit_cause, result, audit_info); + return result; +} + +int ima_restore_measurement_entry(struct ima_template_entry *entry) +{ + int result = 0; + + mutex_lock(&ima_extend_list_mutex); + result = ima_add_digest_entry(entry, 0); + mutex_unlock(&ima_extend_list_mutex); + return result; +} diff --git a/pool/shard003/C/0067343_void_pointers.c b/pool/shard003/C/0067343_void_pointers.c new file mode 100644 index 0000000000000000000000000000000000000000..4f5a0fff64b63666cff965316b6a33d99aa0e490 --- /dev/null +++ b/pool/shard003/C/0067343_void_pointers.c @@ -0,0 +1,53 @@ + + +/* void_pointers.c */ +/* Playing around with void pointers and structs. */ +/* This code is released to the public domain. */ +/* "Share and enjoy..." ;) */ + + +#include +#include +#include +#include + + +typedef struct +{ + char name[30]; + int intval; + char charval[40]; +} data; + + +/* A data "object". This has a value. */ +void makedata(void *val) +{ + data *dp = (data*)val ; + printf("%s \n%d \n%s \n", dp->name, dp->intval, dp->charval); +} + + +int main() +{ + + data d; + + strcpy(d.name, "Just a test"); + d.intval = 123; + strcpy(d.charval, "More stuff"); + + makedata(&d); + + return 0; + +} + + + + + + + + + diff --git a/pool/shard003/C/0067349_avx512bw-vpcmpgtub-1.c b/pool/shard003/C/0067349_avx512bw-vpcmpgtub-1.c new file mode 100644 index 0000000000000000000000000000000000000000..c2a78c4a34ee60b79450775a6fcb11cb4d960a73 --- /dev/null +++ b/pool/shard003/C/0067349_avx512bw-vpcmpgtub-1.c @@ -0,0 +1,28 @@ +/* { dg-do compile } */ +/* { dg-options "-mavx512bw -mavx512vl -O2" } */ +/* { dg-final { scan-assembler "vpcmpub\[ \\t\]+\[^\n\]*%zmm\[0-9\]\[^\n\]*%k\[1-7\]\[^\{\]" } } */ +/* { dg-final { scan-assembler "vpcmpub\[ \\t\]+\[^\n\]*%ymm\[0-9\]\[^\n\]*%k\[1-7\]\[^\{\]" } } */ +/* { dg-final { scan-assembler "vpcmpub\[ \\t\]+\[^\n\]*%xmm\[0-9\]\[^\n\]*%k\[1-7\]\[^\{\]" } } */ +/* { dg-final { scan-assembler "vpcmpub\[ \\t\]+\[^\n\]*%zmm\[0-9\]\[^\n\]*%k\[1-7\]\{%k\[1-7\]\}" } } */ +/* { dg-final { scan-assembler "vpcmpub\[ \\t\]+\[^\n\]*%ymm\[0-9\]\[^\n\]*%k\[1-7\]\{%k\[1-7\]\}" } } */ +/* { dg-final { scan-assembler "vpcmpub\[ \\t\]+\[^\n\]*%xmm\[0-9\]\[^\n\]*%k\[1-7\]\{%k\[1-7\]\}" } } */ + +#include + +volatile __m512i x512; +volatile __m256i x256; +volatile __m128i x128; +volatile __mmask16 m16; +volatile __mmask32 m32; +volatile __mmask64 m64; + +void extern +avx512bw_test (void) +{ + m16 = _mm_cmpgt_epu8_mask (x128, x128); + m32 = _mm256_cmpgt_epu8_mask (x256, x256); + m64 = _mm512_cmpgt_epu8_mask (x512, x512); + m16 = _mm_mask_cmpgt_epu8_mask (3, x128, x128); + m32 = _mm256_mask_cmpgt_epu8_mask (3, x256, x256); + m64 = _mm512_mask_cmpgt_epu8_mask (3, x512, x512); +} diff --git a/pool/shard003/C/0067355_dhd_log.c b/pool/shard003/C/0067355_dhd_log.c new file mode 100644 index 0000000000000000000000000000000000000000..b2fea655e62d19f05dd7fdb2ab569d66ac0f1af5 --- /dev/null +++ b/pool/shard003/C/0067355_dhd_log.c @@ -0,0 +1,79 @@ +/* + * DHD logging module for internal debug + * + * Copyright (C) 1999-2016, Broadcom Corporation + * + * Unless you and Broadcom execute a separate written software license + * agreement governing use of this software, this software is licensed to you + * under the terms of the GNU General Public License version 2 (the "GPL"), + * available at http://www.broadcom.com/licenses/GPLv2.php, with the + * following added to such license: + * + * As a special exception, the copyright holders of this software give you + * permission to link this software with independent modules, and to copy and + * distribute the resulting executable under terms of your choice, provided that + * you also meet, for each linked independent module, the terms and conditions of + * the license of that module. An independent module is a module which is not + * derived from this software. The special exception does not apply to any + * modifications of the software. + * + * Notwithstanding the above, under no circumstances may you combine this + * software in any way with any other Broadcom software provided under a license + * other than the GPL, without Broadcom's express prior written consent. + * + * + * <> + * + * $Id: dhd_sdio.c 281456 2011-09-02 01:49:45Z $ + */ + +#include +#include + +#include +#include +#include + +#include + +void dhd_blog(char *cp, int size) +{ +#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 29)) + static struct socket * _udpSocket = NULL; + struct sockaddr_in _saAddr; + struct iovec iov; + struct msghdr msg; + if (sock_create(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &_udpSocket) >= 0) + { + + { + memset(&_saAddr, 0, sizeof(_saAddr)); + _saAddr.sin_family = AF_INET; + _saAddr.sin_port = htons(7651); + _saAddr.sin_addr.s_addr = in_aton("10.19.74.43"); + + iov.iov_base = cp; + iov.iov_len = size; + + msg.msg_name = &_saAddr; + msg.msg_namelen = sizeof(struct sockaddr_in); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = NULL; + msg.msg_controllen = 0; + msg.msg_flags = 0; + + { + mm_segment_t fs = get_fs(); + set_fs(get_ds()); + + sock_sendmsg(_udpSocket, &msg, size); + + set_fs(fs); + } + } + + sock_release(_udpSocket); + } +#endif /* #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 25)) */ +} diff --git a/pool/shard003/C/0067365_netgroup.c b/pool/shard003/C/0067365_netgroup.c new file mode 100644 index 0000000000000000000000000000000000000000..fb65b57bce49caae06fa99d91e678ca2f568a5d3 --- /dev/null +++ b/pool/shard003/C/0067365_netgroup.c @@ -0,0 +1,83 @@ +/* $NetBSD: netgroup.c,v 1.7 2012/03/20 20:34:58 matt Exp $ */ + +/*- + * Copyright (c) 1999 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Christos Zoulas. + * + * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 +__RCSID("$NetBSD: netgroup.c,v 1.7 2012/03/20 20:34:58 matt Exp $"); + +#include +#include +#include +#include + +static void usage __P((void)) __dead; +int main __P((int, char *[])); + +static void +usage(void) +{ + + (void)fprintf(stderr, "usage: %s [-hud] \n", getprogname()); + exit(1); +} + +int +main(int argc, char *argv[]) +{ + int c, i = 0; + const char *p[3]; + + while ((c = getopt(argc, argv, "hud")) != -1) + switch (c) { + case 'h': + i = 0; + break; + case 'u': + i = 1; + break; + case 'd': + i = 2; + break; + default: + usage(); + } + + if (optind >= argc) + usage(); + + for(; optind < argc; optind++) { + setnetgrent(argv[optind]); + while (getnetgrent(&p[0], &p[1], &p[2])) + if (p[i]) + printf("%s\n", p[i]); + endnetgrent(); + } + return 0; +} diff --git a/pool/shard003/C/0067369_mod_traffic.c b/pool/shard003/C/0067369_mod_traffic.c new file mode 100644 index 0000000000000000000000000000000000000000..ff8d04e8a95a5c8c28d0fec40c1d1d73cf037cec --- /dev/null +++ b/pool/shard003/C/0067369_mod_traffic.c @@ -0,0 +1,77 @@ +#include "tsar.h" + +char *traffic_usage = " --traffic Net traffic statistics"; + +/* + * Structure for traffic infomation. + */ +struct stats_traffic { + unsigned long long bytein; + unsigned long long byteout; + unsigned long long pktin; + unsigned long long pktout; +} ; + +#define STATS_TRAFFIC_SIZE (sizeof(struct stats_traffic)) + + +/* + * collect traffic infomation + */ +static void read_traffic_stats(struct module *mod) +{ + FILE *fp; + char line[LEN_4096] = {0}; + char buf[LEN_4096] = {0}; + memset(buf, 0, LEN_4096); + struct stats_traffic total_st, cur_st; + memset(&total_st, 0, sizeof(struct stats_traffic)); + memset(&cur_st, 0, sizeof(struct stats_traffic)); + char *p = NULL; + int len = 0; + + if ((fp = fopen(NET_DEV, "r")) == NULL) { + return; + } + + memset(&total_st, 0, sizeof(cur_st)); + + while (fgets(line, LEN_4096, fp) != NULL) { + if (strstr(line, "eth") || strstr(line, "bond") || strstr(line, "p2p")) { + memset(&cur_st, 0, sizeof(cur_st)); + p = strchr(line, ':'); + sscanf(p + 1, "%llu %llu %*u %*u %*u %*u %*u %*u " + "%llu %llu %*u %*u %*u %*u %*u %*u", + &cur_st.bytein, + &cur_st.pktin, + &cur_st.byteout, + &cur_st.pktout); + + total_st.bytein += cur_st.bytein; + total_st.byteout += cur_st.byteout; + total_st.pktin += cur_st.pktin; + total_st.pktout += cur_st.pktout; + } + } + + len = sprintf(buf, "%lld,%lld,%lld,%lld", + total_st.bytein, + total_st.byteout, + total_st.pktin, + total_st.pktout); + buf[len] = '\0'; + set_mod_record(mod, buf); + fclose(fp); +} + +static struct mod_info traffic_info[] ={ + {" bytin", DETAIL_BIT, 0, STATS_SUB_INTER}, + {"bytout", DETAIL_BIT, 0, STATS_SUB_INTER}, + {" pktin", SUMMARY_BIT, 0, STATS_SUB_INTER}, + {"pktout", SUMMARY_BIT, 0, STATS_SUB_INTER} +}; + +void mod_register(struct module *mod) +{ + register_mod_fileds(mod, "--traffic", traffic_usage, traffic_info, 4, read_traffic_stats, NULL); +} diff --git a/pool/shard003/C/0067381_basic_example.c b/pool/shard003/C/0067381_basic_example.c new file mode 100644 index 0000000000000000000000000000000000000000..a79984468b09c3e7bc052ba9540d4e6312431561 --- /dev/null +++ b/pool/shard003/C/0067381_basic_example.c @@ -0,0 +1,84 @@ +/************************************************************************/ +/* */ +/* basic_example.c demo project for the PmodJSTK IP */ +/* */ +/************************************************************************/ +/* Author: Samuel Lowe` */ +/* Copyright 2016, Digilent Inc. */ +/************************************************************************/ +/* + 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 +*/ +/************************************************************************/ +/* File Description: */ +/* */ +/* This demo reads the calibrated data from the PmodJSTK2 and prints */ +/* the X and Y values while mapping the axis to the LED. */ +/* If the buttons on the JSTK are pressed, the LED will turn green */ +/* */ +/************************************************************************/ +/* Revision History: */ +/* */ +/* 06/27/2016(SamL): Created */ +/* */ +/************************************************************************/ +/* Baud Rates: */ +/* */ +/* Microblaze: 9600 or what was specified in UARTlite core */ +/* Zynq: 115200 */ +/* */ +/************************************************************************/ + +#include +#include "platform.h" +#include "xil_printf.h" +#include "PmodJSTK2.h" + +PmodJSTK2 joystick; + +int main() +{ + u16 Ydata; + u16 Xdata; + + init_platform(); + + //init joystick + JSTK2_begin(&joystick, XPAR_PMODJSTK2_0_AXI_LITE_SPI_BASEADDR); + + //set no inversion + JSTK2_setInversion(&joystick, 0, 1); + + xil_printf("\n\rJoystick Demo\n"); + + + while(1){ + //get coord values + Ydata = JSTK2_getY(&joystick); + Xdata = JSTK2_getX(&joystick); + xil_printf("\n\rX: %d Y: %d BTN: %x",Xdata, Ydata, JSTK2_getBtns(&joystick)); + delay(50000); + + //set led from btns and axis + if(JSTK2_getBtns(&joystick)) + JSTK2_setLed(&joystick, 0, 255, 0); + else + JSTK2_setLed(&joystick, Xdata, 0, Ydata); + + } + + cleanup_platform(); + return 0; +} diff --git a/pool/shard003/C/0067389_sigaltstack.c b/pool/shard003/C/0067389_sigaltstack.c new file mode 100644 index 0000000000000000000000000000000000000000..39f2bedab5b7e39876ae901b4d81e64032c889f7 --- /dev/null +++ b/pool/shard003/C/0067389_sigaltstack.c @@ -0,0 +1,96 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2004, 2007, 2008 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 . + + Please email any bugs, comments, and/or additions to this file to: + bug-gdb@prep.ai.mit.edu */ + +#include +#include +#include +#include +#include + +enum level { MAIN, OUTER, INNER, LEAF, NR_LEVELS }; + +/* Levels completed flag. */ +volatile enum level level = NR_LEVELS; + +void catcher (int signal); + +void +thrower (enum level next_level, int sig, int itimer, int on_stack) +{ + level = next_level; + /* Set up the signal handler. */ + { + struct sigaction act; + memset (&act, 0, sizeof (act)); + act.sa_handler = catcher; + act.sa_flags |= on_stack; + sigaction (sig, &act, NULL); + } + /* Set up a one-off timer. A timer, rather than SIGSEGV, is used as + after a timer handler finishes the interrupted code can safely + resume. */ + { + struct itimerval itime; + memset (&itime, 0, sizeof (itime)); + itime.it_value.tv_usec = 250 * 1000; + setitimer (itimer, &itime, NULL); + } + /* Wait. */ + while (level != LEAF); +} + +void +catcher (int signal) +{ + /* Find the next level. */ + switch (level) + { + case MAIN: + thrower (OUTER, SIGALRM, ITIMER_REAL, SA_ONSTACK); + break; + case OUTER: + thrower (INNER, SIGVTALRM, ITIMER_VIRTUAL, SA_ONSTACK); + break; + case INNER: + level = LEAF; + return; + } +} + + +main () +{ + /* Set up the altstack. */ + { + static char stack[SIGSTKSZ * NR_LEVELS]; + stack_t alt; + memset (&alt, 0, sizeof (alt)); + alt.ss_sp = stack; + alt.ss_size = SIGSTKSZ; + alt.ss_flags = 0; + if (sigaltstack (&alt, NULL) < 0) + { + perror ("sigaltstack"); + exit (0); + } + } + level = MAIN; + catcher (0); +} diff --git a/pool/shard003/C/0067395_tm_stm32f4_button.c b/pool/shard003/C/0067395_tm_stm32f4_button.c new file mode 100644 index 0000000000000000000000000000000000000000..06113e3da053313e3baea3c2a355a1a4cc4fd5b3 --- /dev/null +++ b/pool/shard003/C/0067395_tm_stm32f4_button.c @@ -0,0 +1,172 @@ +/** + * |---------------------------------------------------------------------- + * | Copyright (C) Tilen Majerle, 2015 + * | + * | 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 + * | 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 "tm_stm32f4_button.h" + +/* Button states */ +#define BUTTON_STATE_START 0 +#define BUTTON_STATE_PRESSED 1 +#define BUTTON_STATE_WAITRELEASE 2 + +/* Internal structure */ +typedef struct { + TM_BUTTON_t* Buttons[BUTTON_MAX_BUTTONS]; + uint16_t ButtonsCount; +} TM_BUTTON_INT_t; +static TM_BUTTON_INT_t Buttons; + +/* Internal functions */ +void TM_BUTTON_INT_CheckButton(TM_BUTTON_t* ButtonStruct); + +TM_BUTTON_t* TM_BUTTON_Init(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, uint8_t ButtonState, void (*ButtonHandler)(TM_BUTTON_PressType_t)) { + TM_BUTTON_t* ButtonStruct; + TM_GPIO_PuPd_t P; + + /* Init delay function */ + TM_DELAY_Init(); + + /* Check if available */ + if (Buttons.ButtonsCount >= BUTTON_MAX_BUTTONS) { + return NULL; + } + + /* Allocate memory for button */ + ButtonStruct = (TM_BUTTON_t *) malloc(sizeof(TM_BUTTON_t)); + + /* Check if allocated */ + if (ButtonStruct == NULL) { + return NULL; + } + + /* Save settings */ + ButtonStruct->GPIOx = GPIOx; + ButtonStruct->GPIO_Pin = GPIO_Pin; + ButtonStruct->GPIO_State = ButtonState ? 1 : 0; + ButtonStruct->ButtonHandler = ButtonHandler; + ButtonStruct->State = BUTTON_STATE_START; + + /* Set default values */ + ButtonStruct->PressNormalTime = BUTTON_NORMAL_PRESS_TIME; + ButtonStruct->PressLongTime = BUTTON_LONG_PRESS_TIME; + + /* Init pin with pull resistor */ + if (ButtonStruct->GPIO_State) { + /* Pulldown */ + P = TM_GPIO_PuPd_DOWN; + } else { + /* Pullup */ + P = TM_GPIO_PuPd_UP; + } + + /* Init GPIO pin as input with proper pull resistor */ + TM_GPIO_Init(GPIOx, GPIO_Pin, TM_GPIO_Mode_IN, TM_GPIO_OType_PP, P, TM_GPIO_Speed_Low); + + /* Save button */ + Buttons.Buttons[Buttons.ButtonsCount++] = ButtonStruct; + + /* Return button pointer */ + return ButtonStruct; +} + +TM_BUTTON_t* TM_BUTTON_SetPressTime(TM_BUTTON_t* ButtonStruct, uint16_t Normal, uint16_t Long) { + /* Set values */ + ButtonStruct->PressNormalTime = Normal; + ButtonStruct->PressLongTime = Long; + + /* Return pointer */ + return ButtonStruct; +} + +void TM_BUTTON_Update(void) { + uint16_t i; + + /* Go through all buttons */ + for (i = 0; i < Buttons.ButtonsCount; i++) { + TM_BUTTON_INT_CheckButton(Buttons.Buttons[i]); + } +} + +/* Internal functions */ +void TM_BUTTON_INT_CheckButton(TM_BUTTON_t* ButtonStruct) { + uint8_t status = TM_GPIO_GetInputPinValue(ButtonStruct->GPIOx, ButtonStruct->GPIO_Pin); + uint32_t now = TM_DELAY_Time(); + + /* First stage */ + if (ButtonStruct->State == BUTTON_STATE_START) { + /* Check if pressed */ + if (status == ButtonStruct->GPIO_State) { + /* Button pressed, go to stage BUTTON_STATE_START */ + ButtonStruct->State = BUTTON_STATE_PRESSED; + + /* Save pressed time */ + ButtonStruct->StartTime = now; + + /* Button pressed OK, call function */ + if (ButtonStruct->ButtonHandler) { + /* Call function callback */ + ButtonStruct->ButtonHandler(TM_BUTTON_PressType_OnPressed); + } + } + } + + if (ButtonStruct->State == BUTTON_STATE_PRESSED) { + /* Button still pressed */ + /* Check for long press */ + if (status == ButtonStruct->GPIO_State) { + if (now > (ButtonStruct->StartTime + ButtonStruct->PressLongTime)) { + /* Button pressed OK, call function */ + if (ButtonStruct->ButtonHandler) { + /* Call function callback */ + ButtonStruct->ButtonHandler(TM_BUTTON_PressType_Long); + } + + /* Go to stage BUTTON_STATE_WAITRELEASE */ + ButtonStruct->State = BUTTON_STATE_WAITRELEASE; + } + } else if (status != ButtonStruct->GPIO_State) { + /* Not pressed */ + if (now > (ButtonStruct->StartTime + ButtonStruct->PressNormalTime)) { + /* Button pressed OK, call function */ + if (ButtonStruct->ButtonHandler) { + /* Call function callback */ + ButtonStruct->ButtonHandler(TM_BUTTON_PressType_Normal); + } + + /* Go to stage BUTTON_STATE_WAITRELEASE */ + ButtonStruct->State = BUTTON_STATE_WAITRELEASE; + } else { + /* Go to state BUTTON_STATE_START */ + ButtonStruct->State = BUTTON_STATE_START; + } + } else { + /* Go to state BUTTON_STATE_START */ + ButtonStruct->State = BUTTON_STATE_START; + } + } + + if (ButtonStruct->State == BUTTON_STATE_WAITRELEASE) { + /* Wait till button released */ + if (status != ButtonStruct->GPIO_State) { + /* Go to stage 0 again */ + ButtonStruct->State = BUTTON_STATE_START; + } + } + + /* Save current status */ + ButtonStruct->LastStatus = status; +} diff --git a/pool/shard003/C/0067400_processchain.c b/pool/shard003/C/0067400_processchain.c new file mode 100644 index 0000000000000000000000000000000000000000..9eec6d179f068b42a311936ebf0cc6fd5d9b8ebf --- /dev/null +++ b/pool/shard003/C/0067400_processchain.c @@ -0,0 +1,117 @@ +/* ********************************************************** + * Copyright (c) 2006 VMware, 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 VMware, 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 VMWARE, 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. + */ + +/* FIXME: nothing here tests that a child is under DR */ +#include "tools.h" +#include "Windows.h" + +#ifdef USE_DYNAMO +#include "dynamorio.h" +#endif + +/* undefine this for a performance test */ +#ifndef NIGHTLY_REGRESSION +# define NIGHTLY_REGRESSION +#endif + +#ifdef NIGHTLY_REGRESSION +# define DEPTH 5 +#else +# define DEPTH 10 +#endif + +static int depth = DEPTH; + +static int +main(int argc, char **argv) +{ + STARTUPINFO si = { sizeof(STARTUPINFO) }; + PROCESS_INFORMATION pi; + char cmdline[128]; + DWORD result = 0; + + INIT(); + USE_USER32(); /* can't be in runall otherwise! */ + +#ifdef USE_DYNAMO + dynamorio_app_init(); + dynamorio_app_start(); +#endif + + if (argc == 1) { + /* normal execution */ + + _snprintf(cmdline, sizeof(cmdline), "%s %d", argv[0], depth); + + print("starting chain %d...\n", depth); + + } + + if (argc == 2) { + depth = atoi(argv[1]); + print("subprocess %d running.\n", depth); + + _snprintf(cmdline, sizeof(cmdline), "%s %d", argv[0], depth-1); + } + + if (depth != 0) { + if (!CreateProcess(argv[0], + cmdline, + NULL, + NULL, + FALSE, + 0, + NULL, + NULL, + &si, + &pi)) + print("CreateProcess failure\n"); + else { + DWORD exit_code = 0; + print("waiting for child\n"); + WaitForSingleObject(pi.hProcess, INFINITE); + if (!GetExitCodeProcess(pi.hProcess, &exit_code)) { + print("GetExitCodeProcess failure %d\n", GetLastError()); + } else { + print("process returned %d\n", exit_code); + } + } + } + +#ifdef USE_DYNAMO + dynamorio_app_stop(); + dynamorio_app_exit(); +#endif + + return depth * 10; + /* make sure not 259 STILL_ACTIVE which may be returned by GetExitCodeProcess() */ +} diff --git a/pool/shard003/C/0067406_error_last.c b/pool/shard003/C/0067406_error_last.c new file mode 100644 index 0000000000000000000000000000000000000000..7629cf74b76a4db2bb3fcd0e36e4f21748028c93 --- /dev/null +++ b/pool/shard003/C/0067406_error_last.c @@ -0,0 +1,46 @@ +/* + * hebimath - arbitrary precision arithmetic library + * See LICENSE file for copyright and license details + */ + +#include "../internal.h" + +#if !defined USE_THREAD_LOCAL && defined USE_THREADS + +struct lastarg { + struct hebi_error *err; + jmp_buf env; +}; + +HEBI_NORETURN +static void +lasthandler(void *arg, const struct hebi_error *err) +{ + struct lastarg *larg = arg; + if (larg->err) + *larg->err = *err; + longjmp(larg->env, 1); +} + +#endif + +HEBI_API HEBI_NOTHROW +int +hebi_error_last(struct hebi_error *err) +{ + struct hebi_context *ctx; + +#if !defined USE_THREAD_LOCAL && defined USE_THREADS + struct lastarg larg; + larg.err = err; + if (UNLIKELY(setjmp(larg.env))) + return -1; + ctx = hebi_context_get__(&lasthandler, &larg); +#else + ctx = &hebi_context__; +#endif + + if (err) + *err = ctx->errlast; + return !ctx->errlast.he_code ? 0 : -1; +} diff --git a/pool/shard003/C/0067414_test_lyd.c b/pool/shard003/C/0067414_test_lyd.c new file mode 100644 index 0000000000000000000000000000000000000000..efaae2b6fa0388fa9b358f8566307c3b7d9aaea2 --- /dev/null +++ b/pool/shard003/C/0067414_test_lyd.c @@ -0,0 +1,70 @@ +/* + C -programmering, en innføring. + + Eksempel 35 + +*/ + +#include + +#include +#include + +#include "../logger.h" +#include "../lyd.h" +#include "test_lyd.h" + +extern Logger * logg; + +int test_lyd() { + + const char * sign = "test_lyd()"; + + Logger_log (logg, INFO, sign, "start"); + + + if (SDL_Init (SDL_INIT_AUDIO) == -1){ + + char melding[512]; + sprintf(melding,"SDL_Init Error: %s", SDL_GetError()); + Logger_log (logg, FEIL, sign, melding); + return 1; + + } + + Logger_log (logg, INFO, sign, "SDL_Init(SDL_INIT_AUDIO) ok"); + + + + if( Mix_OpenAudio( MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 1, 4096 ) < 0 ) { + + char melding[512]; + sprintf(melding,"Mix_OpenAudio Error: %s", Mix_GetError()); + Logger_log (logg, FEIL, sign, melding); + return 1; + + } + + Logger_log (logg, INFO, sign, "Mix_OpenAudio ok"); + + + + + Lyd *lyd = Lyd_opprett(); + Lyd_generer(lyd, 1); + + SDL_Delay(400); + + Lyd_slett(&lyd); + + + + Logger_log (logg, INFO, sign, "slutt"); + + return 0; + +} + + + + diff --git a/pool/shard003/C/0067442_exefixup.c b/pool/shard003/C/0067442_exefixup.c new file mode 100644 index 0000000000000000000000000000000000000000..c83754d7641fe7cd9febad475b46eb7e3171ec32 --- /dev/null +++ b/pool/shard003/C/0067442_exefixup.c @@ -0,0 +1,210 @@ +/* + * exefixup.c v0.02.1 Andrew Kieschnick + * (v0.02.1): Giuseppe Gatta + * + * v0.02.1 changes: removed warnings + * + * displays PS-X EXE header information + * offers to fix incorrect t_size + * offers to pad to 2048-byte boundary for cd-rom use + * + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + */ + +#include +#include +#include +#include + +unsigned int char2int(unsigned char *foo) +{ + return foo[3]*16777216 + foo[2]*65536 + foo[1]*256 + foo[0]; +} + +void int2char(unsigned int foo, unsigned char *bar) +{ + bar[3]=foo>>24; + bar[2]=foo>>16; + bar[1]=foo>>8; + bar[0]=foo; +} + +void usage(void) +{ + printf("Usage: exefixup \n\n"); + printf("\t\ta PS-X EXE file\n\n"); + printf("\tdisplays EXE header\n"); + printf("\toffers to correct a wrong t_size\n"); + printf("\toffers to pad to 2048-byte boundary\n\n"); + exit(0); +} + +int main(int argc, char *argv[]) +{ + FILE *exe; + FILE *out; + unsigned char data[8]; + char filename[256]; + int i; + unsigned int header_data[12]; + unsigned int size; + unsigned int padsize; + signed char yesno='Z'; + + printf("exefixup v0.02.1 Andrew Kieschnick \n\n"); + + if (argc!=2) + usage(); + + strncpy(filename,argv[1],256); + + exe=fopen(filename, "r"); + + strcat(filename, "-fixed"); /* output filename is same as input filename, but with -fix appended */ + + if (!exe) + { + printf("ERROR: Can't open %s\n",filename); + exit(-1); + } + + for(i=0;i<8;i++) + fscanf(exe, "%c", &data[i]); + data[8]=0; + + if (strncmp((char*)data, "PS-X EXE", 8)) + { + printf("ERROR: Not a PS-X EXE file\n"); + exit(-1); + } + + for(i=0;i<12;i++) + { + fscanf(exe, "%c", &data[0]); + fscanf(exe, "%c", &data[1]); + fscanf(exe, "%c", &data[2]); + fscanf(exe, "%c", &data[3]); + header_data[i]=char2int(data); + } + + printf("id\tPS-X EXE\n"); + printf("text\t0x%.8x\n", header_data[0]); + printf("data\t0x%.8x\n", header_data[1]); + printf("pc0\t0x%.8x\n", header_data[2]); + printf("gp0\t0x%.8x\n", header_data[3]); + printf("t_addr\t0x%.8x\n", header_data[4]); + printf("t_size\t0x%.8x\n", header_data[5]); + printf("d_addr\t0x%.8x\n", header_data[6]); + printf("d_size\t0x%.8x\n", header_data[7]); + printf("b_addr\t0x%.8x\n", header_data[8]); + printf("b_size\t0x%.8x\n", header_data[9]); + printf("s_addr\t0x%.8x\n", header_data[10]); + printf("s_size\t0x%.8x\n\n", header_data[11]); + + fseek(exe, 0, SEEK_END); + + size=ftell(exe)-2048; + + padsize=2048-(size%2048); + + if (padsize!=2048) + { + printf("WARNING: EXE size is not a multiple of 2048!\n"); + while ((yesno!='Y')&&(yesno!='N')) + { + printf("Write a padded EXE (to %s) ? ",filename); + scanf("%c%*c", &yesno); + yesno=toupper(yesno); + } + if (yesno=='Y') + { + out = fopen(filename, "w"); + + header_data[5]=size+padsize; + + fprintf(out, "PS-X EXE"); + for(i=0;i<12;i++) + { + int2char(header_data[i], data); + fprintf(out, "%c%c%c%c", data[0], data[1], data[2], data[3]); + } + + fseek(exe, 56, SEEK_SET); + + for(i=0;i +#include +#include +#include +#include +#include "sysdep/ptrace.h" +#include "sigcontext.h" +#include "ptrace_user.h" +#include "task.h" +#include "user_util.h" +#include "kern_util.h" +#include "syscall_user.h" +#include "tt.h" + + +void syscall_handler_tt(int sig, union uml_pt_regs *regs) +{ + void *sc; + long result; + int index, syscall; + + syscall = UPT_SYSCALL_NR(regs); + sc = UPT_SC(regs); + SC_START_SYSCALL(sc); + + index = record_syscall_start(syscall); + syscall_trace(regs, 0); + result = execute_syscall(regs); + + /* regs->sc may have changed while the system call ran (there may + * have been an interrupt or segfault), so it needs to be refreshed. + */ + UPT_SC(regs) = sc; + + SC_SET_SYSCALL_RETURN(sc, result); + + syscall_trace(regs, 1); + record_syscall_end(index, result); +} + +int do_syscall(void *task, int pid, int local_using_sysemu) +{ + unsigned long proc_regs[FRAME_SIZE]; + union uml_pt_regs *regs; + int syscall; + + if(ptrace_getregs(pid, proc_regs) < 0) + tracer_panic("Couldn't read registers"); + syscall = PT_SYSCALL_NR(proc_regs); + + regs = TASK_REGS(task); + UPT_SYSCALL_NR(regs) = syscall; + + if(syscall < 0) + return(0); + + if((syscall != __NR_sigreturn) && + ((unsigned long *) PT_IP(proc_regs) >= &_stext) && + ((unsigned long *) PT_IP(proc_regs) <= &_etext)) + tracer_panic("I'm tracing myself and I can't get out"); + + if(local_using_sysemu) + return(1); + + if(ptrace(PTRACE_POKEUSER, pid, PT_SYSCALL_NR_OFFSET, + __NR_getpid) < 0) + tracer_panic("do_syscall : Nullifying syscall failed, " + "errno = %d", errno); + return(1); +} + +/* + * Overrides for Emacs so that we follow Linus's tabbing style. + * Emacs will notice this stuff at the end of the file and automatically + * adjust the settings for this buffer only. This must remain at the end + * of the file. + * --------------------------------------------------------------------------- + * Local variables: + * c-file-style: "linux" + * End: + */ diff --git a/pool/shard003/C/0067521_main.c b/pool/shard003/C/0067521_main.c new file mode 100644 index 0000000000000000000000000000000000000000..4cb809e4ee40cbaa6f98d9008a746bcaa0def5dc --- /dev/null +++ b/pool/shard003/C/0067521_main.c @@ -0,0 +1,153 @@ +#include + +static Window *window; +static SimpleMenuLayer* menuLayer; + +typedef struct TGcString +{ + char* String; + struct TGcString* Next; +} TGcString; + +typedef struct +{ + char Departure[10]; + char Arrival[10]; + char Route[10]; +} TTrain; + +typedef struct +{ + TTrain Trains[10]; + int NumTrains; + const char* StationName; +} TTimetable; + +static TTimetable Timetable = { + .Trains = {{ + .Departure = "10:00", + .Arrival = "11:00", + .Route = "1234" + }, + { + .Departure = "12:14", + .Arrival = "13:07", + .Route = "3456" + }, + { + .Departure = "15:25", + .Arrival = "16:03", + .Route = "4567" + }, + { + .Departure = "21:01", + .Arrival = "22:11", + .Route = "6789" + }}, + .NumTrains = 4, + .StationName = "Екатеринбург-Пассажирский" +}; + +static SimpleMenuSection* StationMenu = NULL; +static TGcString* StationMenuStrings = NULL; + +char* AllocGcString(TGcString** where, size_t len) +{ + TGcString* next = NULL; + + if (*where != NULL) { + next = (*where)->Next; + } + *where = malloc(sizeof(TGcString)); + (*where)->Next = next; + char* result = malloc(len+1); + (*where)->String = result; + return result; +} + +void DestroyGcStrings(TGcString* which) +{ + TGcString* curr = which; + TGcString* next; + while (curr != NULL) { + next = curr->Next; + free(curr->String); + free(curr); + curr = next; + } +} + +static void GenerateStationMenu(TTimetable* timetable) +{ + int i; + + StationMenu = malloc(sizeof(SimpleMenuSection)); + memset(StationMenu, 0, sizeof(SimpleMenuSection)); + StationMenu->title = timetable->StationName; + + StationMenu->num_items = timetable->NumTrains; + SimpleMenuItem* items = malloc(sizeof(SimpleMenuItem)*timetable->NumTrains); + for (i = 0; i < timetable->NumTrains; ++i) { + SimpleMenuItem* item = &items[i]; + const TTrain* train = &timetable->Trains[i]; + + const char* titleFormat = "%s - %s"; + size_t titleLen = strlen(train->Departure) + strlen(train->Arrival) + strlen(titleFormat); + char* title = AllocGcString(&StationMenuStrings, titleLen); + snprintf(title, titleLen+1, titleFormat, train->Departure, train->Arrival); + + static const char* subtitleFormat = "поезд %s"; + size_t subtitleLen = strlen(train->Route) + strlen(subtitleFormat); + char* subtitle = AllocGcString(&StationMenuStrings, subtitleLen); + snprintf(subtitle, subtitleLen+1, subtitleFormat, train->Route); + + item->callback = NULL; + item->icon = NULL; + item->title = title; + item->subtitle = subtitle; + //item->subtitle="12345678901234567890"; + //item->title="12345678901234567890"; + } + StationMenu->items = items; +} + +static void DestroyStationMenu() +{ + free((SimpleMenuItem*)(StationMenu->items)); + free(StationMenu); + DestroyGcStrings(StationMenuStrings); + StationMenu = NULL; + StationMenuStrings = NULL; +} + +static void window_load(Window *window) { + Layer *windowLayer = window_get_root_layer(window); + GRect bounds = layer_get_frame(windowLayer); + GenerateStationMenu(&Timetable); + menuLayer = simple_menu_layer_create(bounds, window, StationMenu, 1, NULL); + layer_add_child(windowLayer, simple_menu_layer_get_layer(menuLayer)); +} + +static void window_unload(Window *window) { + simple_menu_layer_destroy(menuLayer); + DestroyStationMenu(); +} + +static void init(void) { + window = window_create(); + window_set_window_handlers(window, (WindowHandlers) { + .load = window_load, + .unload = window_unload, + }); + window_stack_push(window, true /* Animated */); +} + +static void deinit(void) { + window_destroy(window); +} + +int main(void) { + init(); + app_event_loop(); + deinit(); +} diff --git a/pool/shard003/C/0067536_arm_init.c b/pool/shard003/C/0067536_arm_init.c new file mode 100644 index 0000000000000000000000000000000000000000..271c6121d5b15001be1d45600618e4341be58b7a --- /dev/null +++ b/pool/shard003/C/0067536_arm_init.c @@ -0,0 +1,232 @@ + +/* arm_init.c - NEON optimised filter functions + * + * Copyright (c) 2013 Glenn Randers-Pehrson + * Written by Mans Rullgard, 2011. + * Last changed in libpng 1.6.6 [September 16, 2013] + * + * This code is released under the libpng license. + * For conditions of distribution and use, see the disclaimer + * and license in png.h + */ +/* Below, after checking __linux__, various non-C90 POSIX 1003.1 functions are + * called. + */ +#define _POSIX_SOURCE 1 + +#include "../pngpriv.h" + +#ifdef PNG_READ_SUPPORTED +#if PNG_ARM_NEON_OPT > 0 +#ifdef PNG_ARM_NEON_CHECK_SUPPORTED /* Do run-time checks */ +#include /* for sig_atomic_t */ + +#ifdef __ANDROID__ +/* Linux provides access to information about CPU capabilites via + * /proc/self/auxv, however Android blocks this while still claiming to be + * Linux. The Andoid NDK, however, provides appropriate support. + * + * Documentation: http://www.kandroid.org/ndk/docs/CPU-ARM-NEON.html + */ +#include + +static int +png_have_neon(png_structp png_ptr) +{ + /* This is a whole lot easier than the mess below, however it is probably + * implemented as below, therefore it is better to cache the result (these + * function calls may be slow!) + */ + PNG_UNUSED(png_ptr) + return android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM && + (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0; +} +#elif defined(__linux__) +/* The generic __linux__ implementation requires reading /proc/self/auxv and + * looking at each element for one that records NEON capabilities. + */ +#include /* for POSIX 1003.1 */ +#include /* for EINTR */ + +#include +#include +#include +#include +#include + +/* A read call may be interrupted, in which case it returns -1 and sets errno to + * EINTR if nothing was done, otherwise (if something was done) a partial read + * may result. + */ +static size_t +safe_read(png_structp png_ptr, int fd, void *buffer_in, size_t nbytes) +{ + size_t ntotal = 0; + char *buffer = png_voidcast(char*, buffer_in); + + while (nbytes > 0) + { + unsigned int nread; + int iread; + + /* Passing nread > INT_MAX to read is implementation defined in POSIX + * 1003.1, therefore despite the unsigned argument portable code must + * limit the value to INT_MAX! + */ + if (nbytes > INT_MAX) + nread = INT_MAX; + + else + nread = (unsigned int)/*SAFE*/nbytes; + + iread = read(fd, buffer, nread); + + if (iread == -1) + { + /* This is the devil in the details, a read can terminate early with 0 + * bytes read because of EINTR, yet it still returns -1 otherwise end + * of file cannot be distinguished. + */ + if (errno != EINTR) + { + png_warning(png_ptr, "/proc read failed"); + return 0; /* I.e., a permanent failure */ + } + } + + else if (iread < 0) + { + /* Not a valid 'read' result: */ + png_warning(png_ptr, "OS /proc read bug"); + return 0; + } + + else if (iread > 0) + { + /* Continue reading until a permanent failure, or EOF */ + buffer += iread; + nbytes -= (unsigned int)/*SAFE*/iread; + ntotal += (unsigned int)/*SAFE*/iread; + } + + else + return ntotal; + } + + return ntotal; /* nbytes == 0 */ +} + +static int +png_have_neon(png_structp png_ptr) +{ + int fd = open("/proc/self/auxv", O_RDONLY); + Elf32_auxv_t aux; + + /* Failsafe: failure to open means no NEON */ + if (fd == -1) + { + png_warning(png_ptr, "/proc/self/auxv open failed"); + return 0; + } + + while (safe_read(png_ptr, fd, &aux, sizeof aux) == sizeof aux) + { + if (aux.a_type == AT_HWCAP && (aux.a_un.a_val & HWCAP_NEON) != 0) + { + close(fd); + return 1; + } + } + + close(fd); + return 0; +} +#else + /* We don't know how to do a run-time check on this system */ +# error "no support for run-time ARM NEON checks" +#endif /* OS checks */ +#endif /* PNG_ARM_NEON_CHECK_SUPPORTED */ + +#ifndef PNG_ALIGNED_MEMORY_SUPPORTED +# error "ALIGNED_MEMORY is required; set: -DPNG_ALIGNED_MEMORY_SUPPORTED" +#endif + +void +png_init_filter_functions_neon(png_structp pp, unsigned int bpp) +{ + /* The switch statement is compiled in for ARM_NEON_API, the call to + * png_have_neon is compiled in for ARM_NEON_CHECK. If both are defined + * the check is only performed if the API has not set the NEON option on + * or off explicitly. In this case the check controls what happens. + * + * If the CHECK is not compiled in and the option is UNSET the behavior prior + * to 1.6.7 was to use the NEON code - this was a bug caused by having the + * wrong order of the 'ON' and 'default' cases. UNSET now defaults to OFF, + * as documented in png.h + */ +#ifdef PNG_ARM_NEON_API_SUPPORTED + switch ((pp->options >> PNG_ARM_NEON) & 3) + { + case PNG_OPTION_UNSET: + /* Allow the run-time check to execute if it has been enabled - + * thus both API and CHECK can be turned on. If it isn't supported + * this case will fall through to the 'default' below, which just + * returns. + */ +#endif /* PNG_ARM_NEON_API_SUPPORTED */ +#ifdef PNG_ARM_NEON_CHECK_SUPPORTED + { + static volatile sig_atomic_t no_neon = -1; /* not checked */ + + if (no_neon < 0) + no_neon = !png_have_neon(pp); + + if (no_neon) + return; + } +#ifdef PNG_ARM_NEON_API_SUPPORTED + break; +#endif +#endif /* PNG_ARM_NEON_CHECK_SUPPORTED */ + +#ifdef PNG_ARM_NEON_API_SUPPORTED + default: /* OFF or INVALID */ + return; + + case PNG_OPTION_ON: + /* Option turned on */ + break; + } +#endif + + /* IMPORTANT: any new external functions used here must be declared using + * PNG_INTERNAL_FUNCTION in ../pngpriv.h. This is required so that the + * 'prefix' option to configure works: + * + * ./configure --with-libpng-prefix=foobar_ + * + * Verify you have got this right by running the above command, doing a build + * and examining pngprefix.h; it must contain a #define for every external + * function you add. (Notice that this happens automatically for the + * initialization function.) + */ + pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up_neon; + + if (bpp == 3) + { + pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub3_neon; + pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg3_neon; + pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = + png_read_filter_row_paeth3_neon; + } + + else if (bpp == 4) + { + pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub4_neon; + pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg4_neon; + pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = + png_read_filter_row_paeth4_neon; + } +} +#endif /* PNG_ARM_NEON_OPT > 0 */ +#endif /* PNG_READ_SUPPORTED */ diff --git a/pool/shard003/C/0067538_emff.c b/pool/shard003/C/0067538_emff.c new file mode 100644 index 0000000000000000000000000000000000000000..0798ddfee17a7bc137f77b45f6055872237a1a6a --- /dev/null +++ b/pool/shard003/C/0067538_emff.c @@ -0,0 +1,179 @@ +#include "meta.h" +#include "../layout/layout.h" +#include "../util.h" + +/* EMFF - Eidos Music File Format (PS2), +Legacy of Kain - Defiance, possibly more... */ +VGMSTREAM * init_vgmstream_emff_ps2(STREAMFILE *streamFile) { + VGMSTREAM * vgmstream = NULL; + char filename[260]; + off_t start_offset; + int loop_flag = 0; + int channel_count; + int frequency; + int i; + + /* check extension, case insensitive */ + streamFile->get_name(streamFile,filename,sizeof(filename)); + if (strcasecmp("emff",filename_extension(filename))) goto fail; + + /* do some checks on the file, cause we have no magic words to check the header... + it seems if 0x800 and 0x804 = 0 then the file has only audio, if 0x800 = 1 + it has a text section, if both are 1 it's video with a text section included... */ + if (read_32bitBE(0x800,streamFile) == 0x01000000 || /* "0x01000000" */ + read_32bitBE(0x804,streamFile) == 0x01000000) /* "0x01000000" */ + goto fail; + + frequency = read_32bitLE(0x0,streamFile); + channel_count = read_32bitLE(0xC,streamFile); + + if (frequency > 48000 || + channel_count > 8) { + goto fail; + } + + loop_flag = (read_32bitLE(0x4,streamFile) != 0xFFFFFFFF); + + /* build the VGMSTREAM */ + vgmstream = allocate_vgmstream(channel_count,loop_flag); + if (!vgmstream) goto fail; + + /* fill in the vital statistics */ + start_offset = 0x800; + vgmstream->sample_rate = frequency; + vgmstream->channels = channel_count; + vgmstream->coding_type = coding_PSX; + + vgmstream->layout_type = layout_emff_ps2_blocked; + vgmstream->interleave_block_size = 0x10; + vgmstream->meta_type = meta_EMFF_PS2; + + /* open the file for reading */ + { + STREAMFILE * file; + file = streamFile->open(streamFile,filename,STREAMFILE_DEFAULT_BUFFER_SIZE); + if (!file) goto fail; + for (i=0;ich[i].streamfile = file; + } + } + + /* Calc num_samples */ + emff_ps2_block_update(start_offset,vgmstream); + vgmstream->num_samples = read_32bitLE(0x8,streamFile);; + if (loop_flag) { + vgmstream->loop_start_sample = (read_32bitLE(0x28,streamFile)-start_offset)*28/16/channel_count; + vgmstream->loop_end_sample = read_32bitLE(0x8,streamFile); + } + + return vgmstream; + +/* clean up anything we may have opened */ +fail: + if (vgmstream) close_vgmstream(vgmstream); + return NULL; +} + + +/* EMFF - Eidos Music File Format (NGC/WII), +found in Tomb Raider Legend/Anniversary/Underworld, possibly more... */ +VGMSTREAM * init_vgmstream_emff_ngc(STREAMFILE *streamFile) { + VGMSTREAM * vgmstream = NULL; + char filename[260]; + off_t start_offset; + int loop_flag = 0; + int channel_count; + int frequency; + int i; + int j; + + /* check extension, case insensitive */ + streamFile->get_name(streamFile,filename,sizeof(filename)); + if (strcasecmp("emff",filename_extension(filename))) goto fail; + + /* do some checks on the file, cause we have no magic words to check the header... + it seems if 0x800 and 0x804 = 0 then the file has only audio, if 0x800 = 1 + it has a text section, if both are 1 it's video with a text section included... */ + if (read_32bitBE(0x800,streamFile) == 0x00000001 || /* "0x00000001" */ + read_32bitBE(0x804,streamFile) == 0x00000001) /* "0x00000001" */ + goto fail; + + frequency = read_32bitBE(0x0,streamFile); + channel_count = read_32bitBE(0xC,streamFile); + + if (frequency > 48000 || + channel_count > 8) { + goto fail; + } + + loop_flag = (read_32bitBE(0x4,streamFile) != 0xFFFFFFFF); + + /* build the VGMSTREAM */ + vgmstream = allocate_vgmstream(channel_count,loop_flag); + if (!vgmstream) goto fail; + + /* fill in the vital statistics */ + start_offset = 0x800; + vgmstream->sample_rate = frequency; + vgmstream->channels = channel_count; + vgmstream->coding_type = coding_NGC_DSP; + + /* Retrieving coefs and loops, depending on the file layout... */ + /* Found in Tomb Raider - Legend for GameCube */ + if (read_32bitBE(0xC8,streamFile) > 0x0) { + off_t coef_table[8] = {0xC8,0xF6,0x124,0x152,0x180,0x1AE,0x1DC,0x20A}; + for (j=0;jchannels;j++) { + for (i=0;i<16;i++) { + vgmstream->ch[j].adpcm_coef[i] = read_16bitBE(coef_table[j]+i*2,streamFile); + } + } + /* Found in Tomb Raider - Anniversary for WII */ + } else if (read_32bitBE(0xCC,streamFile) > 0x0) { + off_t coef_table[8] = {0xCC,0xFA,0x128,0x156,0x184,0x1B2,0x1E0,0x20E}; + for (j=0;jchannels;j++) { + for (i=0;i<16;i++) { + vgmstream->ch[j].adpcm_coef[i] = read_16bitBE(coef_table[j]+i*2,streamFile); + } +} + /* Found in Tomb Raider - Underworld for WII */ + } else if (read_32bitBE(0x2D0,streamFile) > 0x0) { + off_t coef_table[8] = {0x2D0,0x2FE,0x32C,0x35A,0x388,0x3B6,0x3E4,0x412}; + for (j=0;jchannels;j++) { + for (i=0;i<16;i++) { + vgmstream->ch[j].adpcm_coef[i] = read_16bitBE(coef_table[j]+i*2,streamFile); + } +} + + } else { + goto fail; + } + + vgmstream->layout_type = layout_emff_ngc_blocked; + vgmstream->interleave_block_size = 0x10; + vgmstream->meta_type = meta_EMFF_NGC; + + /* open the file for reading */ + { + STREAMFILE * file; + file = streamFile->open(streamFile,filename,STREAMFILE_DEFAULT_BUFFER_SIZE); + if (!file) goto fail; + for (i=0;ich[i].streamfile = file; + } + } + + /* Calc num_samples */ + emff_ngc_block_update(start_offset,vgmstream); + vgmstream->num_samples = read_32bitBE(0x8,streamFile);; + if (loop_flag) { + vgmstream->loop_start_sample = (read_32bitBE(0x28,streamFile))*14/8/channel_count; + vgmstream->loop_end_sample = read_32bitBE(0x8,streamFile); + } + + return vgmstream; + +/* clean up anything we may have opened */ +fail: + if (vgmstream) close_vgmstream(vgmstream); + return NULL; +} diff --git a/pool/shard003/C/0067550_mainboard.c b/pool/shard003/C/0067550_mainboard.c new file mode 100644 index 0000000000000000000000000000000000000000..0362b90c1a79e181d40effe91829225e9aad5b8f --- /dev/null +++ b/pool/shard003/C/0067550_mainboard.c @@ -0,0 +1,257 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2008 Advanced Micro Devices, 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 +#include +#include +#include +#include "tn_post_code.h" +#include "vgabios.h" + +#define ADT7461_ADDRESS 0x4C +#define ARA_ADDRESS 0x0C /* Alert Response Address */ +#define SMBUS_IO_BASE 0x1000 + + +/* Video BIOS Function Extensions Specification + */ +//Callback Sub-Function 00h - Get LCD Panel ID +#define LCD_PANEL_ID_NO 0x00 /* No LCD */ +#define LCD_PANEL_ID_01 0x01 /* 1024x768, 24 bits, 1 channel */ +#define LCD_PANEL_ID_02 0x02 /* 1280x1024, 24 bits, 2 channels */ +#define LCD_PANEL_ID_03 0x03 /* 1440x900, 24 bits, 2 channels */ +#define LCD_PANEL_ID_04 0x04 /* 1680x1050, 24 bits, 2 channels */ +#define LCD_PANEL_ID_05 0x05 /* 1920x1200, 24 bits, 2 channels */ +#define LCD_PANEL_ID_06 0x06 /* 1920x1080, 24 bits, 2 channels */ +//Callback Sub-Function 05h – Select Boot-up TV Standard +#define TV_MODE_00 0x00 /* NTSC */ +#define TV_MODE_01 0x01 /* PAL */ +#define TV_MODE_02 0x02 /* PALM */ +#define TV_MODE_03 0x03 /* PAL60 */ +#define TV_MODE_04 0x04 /* NTSCJ */ +#define TV_MODE_05 0x05 /* PALCN */ +#define TV_MODE_06 0x06 /* PALN */ +#define TV_MODE_09 0x09 /* SCART-RGB */ +#define TV_MODE_NO 0xff /* No TV Support */ + +/* The base address is 0x2e or 0x4e, depending on config bytes. */ +#define SIO_BASE 0x2e +#define SIO_INDEX SIO_BASE +#define SIO_DATA SIO_BASE+1 + +/* Global configuration registers. */ +#define IT8712F_CONFIG_REG_CC 0x02 /* Configure Control (write-only). */ +#define IT8712F_CONFIG_REG_LDN 0x07 /* Logical Device Number. */ +#define IT8712F_CONFIG_REG_CONFIGSEL 0x22 /* Configuration Select. */ +#define IT8712F_CONFIG_REG_CLOCKSEL 0x23 /* Clock Selection. */ +#define IT8712F_CONFIG_REG_SWSUSP 0x24 /* Software Suspend, Flash I/F. */ +#define IT8712F_CONFIG_REG_MFC 0x2a /* Multi-function control */ +#define IT8712F_CONFIG_REG_WATCHDOG 0x72 /* Watchdog control. */ + +#define IT8712F_CONFIGURATION_PORT 0x2e /* Write-only. */ +#define IT8712F_SIMPLE_IO_BASE 0x200 /* Simple I/O base address */ + +int do_smbus_read_byte(u32 smbus_io_base, u32 device, u32 address); +int do_smbus_write_byte(u32 smbus_io_base, u32 device, u32 address, u8 val); +#define ADT7461_read_byte(address) \ + do_smbus_read_byte(SMBUS_IO_BASE, ADT7461_ADDRESS, address) +#define ARA_read_byte(address) \ + do_smbus_read_byte(SMBUS_IO_BASE, ARA_ADDRESS, address) +#define ADT7461_write_byte(address, val) \ + do_smbus_write_byte(SMBUS_IO_BASE, ADT7461_ADDRESS, address, val) + + +/* The content of IT8712F_CONFIG_REG_LDN (index 0x07) must be set to the + LDN the register belongs to, before you can access the register. */ +static void it8712f_sio_write(uint8_t ldn, uint8_t index, uint8_t value) +{ + outb(IT8712F_CONFIG_REG_LDN, SIO_BASE); + outb(ldn, SIO_DATA); + outb(index, SIO_BASE); + outb(value, SIO_DATA); +} + +static void it8712f_enter_conf(void) +{ + /* Enter the configuration state (MB PnP mode). */ + + /* Perform MB PnP setup to put the SIO chip at 0x2e. */ + /* Base address 0x2e: 0x87 0x01 0x55 0x55. */ + /* Base address 0x4e: 0x87 0x01 0x55 0xaa. */ + outb(0x87, IT8712F_CONFIGURATION_PORT); + outb(0x01, IT8712F_CONFIGURATION_PORT); + outb(0x55, IT8712F_CONFIGURATION_PORT); + outb(0x55, IT8712F_CONFIGURATION_PORT); +} + +static void it8712f_exit_conf(void) +{ + /* Exit the configuration state (MB PnP mode). */ + it8712f_sio_write(0x00, IT8712F_CONFIG_REG_CC, 0x02); +} + +/* set thermal config + */ +static void set_thermal_config(void) +{ + u8 byte; + u16 word; + device_t sm_dev; + + /* set ADT 7461 */ + ADT7461_write_byte(0x0B, 0x50); /* Local Temperature Hight limit */ + ADT7461_write_byte(0x0C, 0x00); /* Local Temperature Low limit */ + ADT7461_write_byte(0x0D, 0x50); /* External Temperature Hight limit High Byte */ + ADT7461_write_byte(0x0E, 0x00); /* External Temperature Low limit High Byte */ + + ADT7461_write_byte(0x19, 0x55); /* External THERM limit */ + ADT7461_write_byte(0x20, 0x55); /* Local THERM limit */ + + byte = ADT7461_read_byte(0x02); /* read status register to clear it */ + ARA_read_byte(0x05); /* A hardware alert can only be cleared by the master sending an ARA as a read command */ + printk(BIOS_INFO, "Init adt7461 end , status 0x02 %02x\n", byte); + + /* sb600 settings for thermal config */ + /* set SB600 GPIO 64 to GPIO with pull-up */ + byte = pm2_ioread(0x42); + byte &= 0x3f; + pm2_iowrite(0x42, byte); + + /* set GPIO 64 to input */ + sm_dev = dev_find_slot(0, PCI_DEVFN(0x14, 0)); + word = pci_read_config16(sm_dev, 0x56); + word |= 1 << 7; + pci_write_config16(sm_dev, 0x56, word); + + /* set GPIO 64 internal pull-up */ + byte = pm2_ioread(0xf0); + byte &= 0xee; + pm2_iowrite(0xf0, byte); + + /* set Talert to be active low */ + byte = pm_ioread(0x67); + byte &= ~(1 << 5); + pm_iowrite(0x67, byte); + + /* set Talert to generate ACPI event */ + byte = pm_ioread(0x3c); + byte &= 0xf3; + pm_iowrite(0x3c, byte); + + /* THERMTRIP pin */ + /* byte = pm_ioread(0x68); + * byte |= 1 << 3; + * pm_iowrite(0x68, byte); + * + * byte = pm_ioread(0x55); + * byte |= 1 << 0; + * pm_iowrite(0x55, byte); + * + * byte = pm_ioread(0x67); + * byte &= ~( 1 << 6); + * pm_iowrite(0x67, byte); + */ +} + +/* Mainboard specific GPIO setup. */ +static void mb_gpio_init(u16 *iobase) +{ + /* Init Super I/O GPIOs. */ + it8712f_enter_conf(); + outb(IT8712F_CONFIG_REG_LDN, SIO_INDEX); + outb(IT8712F_GPIO, SIO_DATA); + outb(0x62, SIO_INDEX); + outb((*iobase >> 8), SIO_DATA); + outb(0x63, SIO_INDEX); + outb((*iobase & 0xff), SIO_DATA); + it8712f_exit_conf(); +} + +#if CONFIG_VGA_ROM_RUN +/* The LCD's panel id seletion. */ +static void lcd_panel_id(rs690_vbios_regs *vbios_regs, u8 num_id) +{ + switch (num_id) { + case 0x1: + vbios_regs->int15_regs.fun00_panel_id = LCD_PANEL_ID_01; + break; + case 0x2: + vbios_regs->int15_regs.fun00_panel_id = LCD_PANEL_ID_02; + break; + case 0x3: + vbios_regs->int15_regs.fun00_panel_id = LCD_PANEL_ID_03; + break; + case 0x4: + vbios_regs->int15_regs.fun00_panel_id = LCD_PANEL_ID_04; + break; + case 0x5: + vbios_regs->int15_regs.fun00_panel_id = LCD_PANEL_ID_05; + break; + case 0x6: + vbios_regs->int15_regs.fun00_panel_id = LCD_PANEL_ID_06; + break; + default: + vbios_regs->int15_regs.fun00_panel_id = LCD_PANEL_ID_NO; + break; + } +} +#endif + +/************************************************* +* enable the dedicated function in tim5690 board. +* This function called early than rs690_enable. +*************************************************/ +static void mainboard_enable(device_t dev) +{ + u16 gpio_base = IT8712F_SIMPLE_IO_BASE; +#if CONFIG_VGA_ROM_RUN + rs690_vbios_regs vbios_regs; + u8 port2; +#endif + + printk(BIOS_INFO, "Mainboard tim5690 Enable. dev=0x%p\n", dev); + + mb_gpio_init(&gpio_base); + +#if CONFIG_VGA_ROM_RUN + /* The LCD's panel id seletion by switch. */ + port2 = inb(gpio_base+1); + lcd_panel_id(&vbios_regs, ((~port2) & 0xf)); + + /* No support TV */ + vbios_regs.int15_regs.fun05_tv_standard = TV_MODE_NO; + vgabios_init(&vbios_regs); +#endif + + set_thermal_config(); +} + +void mainboard_post(u8 value) +{ + switch (value) { + case POST_ENTER_ELF_BOOT: + technexion_post_code(LED_MESSAGE_FINISH); + break; + } +} + +struct chip_operations mainboard_ops = { + .enable_dev = mainboard_enable, +}; diff --git a/pool/shard003/C/0067557_gkd-dbus-secrets.c b/pool/shard003/C/0067557_gkd-dbus-secrets.c new file mode 100644 index 0000000000000000000000000000000000000000..313223c2adcb8826a6ecff6e5a620070b45cc200 --- /dev/null +++ b/pool/shard003/C/0067557_gkd-dbus-secrets.c @@ -0,0 +1,147 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* gkd-dbus-secrets.c - dbus secret service + + Copyright (C) 2009, Stefan Walter + + The Mate Keyring Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The Mate Keyring 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 + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the Mate Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + Boston, MA 02110-1301, USA. + + Author: Stef Walter +*/ + +#include "config.h" + +#include "gkd-dbus.h" +#include "gkd-dbus-private.h" +#include "gkd-secret-service.h" + +#include "daemon/gkd-pkcs11.h" + +#include "egg/egg-cleanup.h" +#include "egg/egg-error.h" + +#include "gck/gck.h" + +static DBusConnection *dbus_conn = NULL; +static GkdSecretService *secrets_service = NULL; + +static GckSlot* +calculate_secrets_slot (void) +{ + GckSlot *slot = NULL; + GckModule *module; + GList *modules; + GError *err = NULL; + + /* TODO: Should we be handling just one module here? */ + module = gck_module_new (gkd_pkcs11_get_functions (), 0); + g_return_val_if_fail (module, NULL); + + modules = g_list_prepend (NULL, module); + slot = gck_modules_token_for_uri (modules, "pkcs11:token=Secret%20Store", &err); + if (!slot && err) { + g_warning ("couldn't find secret store: %s", egg_error_message (err)); + g_clear_error (&err); + } + + gck_list_unref_free (modules); + return slot; +} + +gboolean +gkd_dbus_secrets_startup (void) +{ + DBusError error = DBUS_ERROR_INIT; + dbus_uint32_t result = 0; + const gchar *service = NULL; + unsigned int flags = 0; + GckSlot *slot; + + g_return_val_if_fail (dbus_conn, FALSE); + +#ifdef WITH_TESTS + service = g_getenv ("MATE_KEYRING_TEST_SERVICE"); + if (service && service[0]) + flags = DBUS_NAME_FLAG_ALLOW_REPLACEMENT | DBUS_NAME_FLAG_REPLACE_EXISTING; + else +#endif + service = SECRET_SERVICE; + + /* Figure out which slot to use */ + slot = calculate_secrets_slot (); + g_return_val_if_fail (slot, FALSE); + + /* Try and grab our name */ + result = dbus_bus_request_name (dbus_conn, service, flags, &error); + if (dbus_error_is_set (&error)) { + g_message ("couldn't request name '%s' on session bus: %s", + service, error.message); + dbus_error_free (&error); + + } else { + switch (result) { + + /* We acquired the service name */ + case DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER: + break; + + /* We already acquired the service name. */ + case DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER: + break; + + /* Another daemon is running */ + case DBUS_REQUEST_NAME_REPLY_IN_QUEUE: + case DBUS_REQUEST_NAME_REPLY_EXISTS: + g_message ("another secret service is running"); + break; + + default: + g_return_val_if_reached (FALSE); + break; + }; + } + + g_return_val_if_fail (!secrets_service, FALSE); + secrets_service = g_object_new (GKD_SECRET_TYPE_SERVICE, + "connection", dbus_conn, "pkcs11-slot", slot, NULL); + + g_object_unref (slot); + return TRUE; +} + +static void +cleanup_dbus_conn (gpointer unused) +{ + g_assert (dbus_conn); + dbus_connection_unref (dbus_conn); + dbus_conn = NULL; +} + +void +gkd_dbus_secrets_init (DBusConnection *conn) +{ + dbus_conn = dbus_connection_ref (conn); + egg_cleanup_register (cleanup_dbus_conn, NULL); +} + +void +gkd_dbus_secrets_cleanup (DBusConnection *conn) +{ + if (secrets_service) { + g_object_run_dispose (G_OBJECT (secrets_service)); + g_object_unref (secrets_service); + secrets_service = NULL; + } +} diff --git a/pool/shard003/C/0067558_CWE190_Integer_Overflow__unsigned_int_max_preinc_61a.c b/pool/shard003/C/0067558_CWE190_Integer_Overflow__unsigned_int_max_preinc_61a.c new file mode 100644 index 0000000000000000000000000000000000000000..1c63e9a9a845493bf8812561b50b6a2c0c7abddd --- /dev/null +++ b/pool/shard003/C/0067558_CWE190_Integer_Overflow__unsigned_int_max_preinc_61a.c @@ -0,0 +1,111 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE190_Integer_Overflow__unsigned_int_max_preinc_61a.c +Label Definition File: CWE190_Integer_Overflow.label.xml +Template File: sources-sinks-61a.tmpl.c +*/ +/* + * @description + * CWE: 190 Integer Overflow + * BadSource: max Set data to the max value for unsigned int + * GoodSource: Set data to a small, non-zero number (two) + * Sinks: increment + * GoodSink: Ensure there will not be an overflow before incrementing data + * BadSink : Increment data, which can cause an overflow + * Flow Variant: 61 Data flow: data returned from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#ifndef OMITBAD + +/* bad function declaration */ +unsigned int CWE190_Integer_Overflow__unsigned_int_max_preinc_61b_badSource(unsigned int data); + +void CWE190_Integer_Overflow__unsigned_int_max_preinc_61_bad() +{ + unsigned int data; + data = 0; + data = CWE190_Integer_Overflow__unsigned_int_max_preinc_61b_badSource(data); + { + /* POTENTIAL FLAW: Incrementing data could cause an overflow */ + ++data; + unsigned int result = data; + printUnsignedLine(result); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +unsigned int CWE190_Integer_Overflow__unsigned_int_max_preinc_61b_goodG2BSource(unsigned int data); + +static void goodG2B() +{ + unsigned int data; + data = 0; + data = CWE190_Integer_Overflow__unsigned_int_max_preinc_61b_goodG2BSource(data); + { + /* POTENTIAL FLAW: Incrementing data could cause an overflow */ + ++data; + unsigned int result = data; + printUnsignedLine(result); + } +} + +/* goodB2G uses the BadSource with the GoodSink */ +unsigned int CWE190_Integer_Overflow__unsigned_int_max_preinc_61b_goodB2GSource(unsigned int data); + +static void goodB2G() +{ + unsigned int data; + data = 0; + data = CWE190_Integer_Overflow__unsigned_int_max_preinc_61b_goodB2GSource(data); + /* FIX: Add a check to prevent an overflow from occurring */ + if (data < UINT_MAX) + { + ++data; + unsigned int result = data; + printUnsignedLine(result); + } + else + { + printLine("data value is too large to perform arithmetic safely."); + } +} + +void CWE190_Integer_Overflow__unsigned_int_max_preinc_61_good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE190_Integer_Overflow__unsigned_int_max_preinc_61_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE190_Integer_Overflow__unsigned_int_max_preinc_61_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard003/C/0067564_csps-cam-mod-DSIDE.c b/pool/shard003/C/0067564_csps-cam-mod-DSIDE.c new file mode 100644 index 0000000000000000000000000000000000000000..b2b8f3df8b5d741220b063595de9b92eae15f929 --- /dev/null +++ b/pool/shard003/C/0067564_csps-cam-mod-DSIDE.c @@ -0,0 +1,179 @@ +/* + * libcsps - Crossed-signal positioning system library + * + * Copyright (c) 2013-2015 FOXEL SA - http://foxel.ch + * Please read for more information. + * + * + * Author(s): + * + * Nils Hamel + * + * + * This file is part of the FOXEL project . + * + * 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 . + * + * + * Additional Terms: + * + * You are required to preserve legal notices and author attributions in + * that material or in the Appropriate Legal Notices displayed by works + * containing it. + * + * You are required to attribute the work as explained in the "Usage and + * Attribution" section of . + */ + + +/* + Source - Includes + */ + + # include "csps-cam-mod-DSIDE.h" + +/* + Source - Camera signal extraction switch + */ + + lp_Void_t lp_cam_mod_DSIDE( + + lp_Char_t const * const lpPath, + lp_Camera_t const lpCAM, + lp_Size_t const lpBlock + + ) { + + /* Select device */ + if ( strcmp( lpCAM.dvName, LP_DEVICE_EYESIS4PI ) == 0 ) { + + /* Eyesis4pi specific process */ + lp_cam_DSIDE_EYESIS4PI( lpPath, lpCAM, lpBlock ); + + } else if ( strcmp( lpCAM.dvName, LP_DEVICE_NC353L369IMUGPS ) == 0 ) { + + /* NC353L369 specific process (same as Eyesis4Pi) */ + lp_cam_DSIDE_EYESIS4PI( lpPath, lpCAM, lpBlock ); + + } + + } + +/* + Source - Camera Eyesis4pi specific extractor + */ + + lp_Void_t lp_cam_DSIDE_EYESIS4PI( + + lp_Char_t const * const lpPath, + lp_Camera_t const lpCAM, + lp_Size_t const lpBlock + + ) { + + /* FPGA record buffer variables */ + lp_Byte_t lpRec[LP_DEVICE_EYESIS4PI_RECLEN]; + + /* Reading variables */ + lp_Enum_t lpReading = LP_TRUE; + lp_Size_t lpIndex = lp_Size_s( 0 ); + lp_Size_t lpReaded = lp_Size_s( 0 ); + + /* Stream path variables */ + lp_Char_t lpDEVlogp[LP_STR_LEN] = LP_STR_INI; + lp_Char_t lpDEVmasp[LP_STR_LEN] = LP_STR_INI; + lp_Char_t lpDEVsynp[LP_STR_LEN] = LP_STR_INI; + + /* Stream file variables */ + lp_File_t lpDEVlogf = NULL; + lp_File_t lpDEVmasf = NULL; + lp_File_t lpDEVsynf = NULL; + + /* Stream memory variables */ + lp_Time_t * lpDEVmas = NULL; + lp_Time_t * lpDEVsyn = NULL; + + /* Build device log file paths */ + lp_path_dside( lpPath, LP_DEVICE_EYESIS4PI, LP_DEVICE_EYESIS4PI_LOG, lpDEVlogp ); + + /* Build stream file paths */ + lp_path_stream( lpPath, lpCAM.dvTag, LP_CAM_DSIDE_MOD, LP_STREAM_CPN_TAG, lpDEVmasp ); + lp_path_stream( lpPath, lpCAM.dvTag, LP_CAM_DSIDE_MOD, LP_STREAM_CPN_SYN, lpDEVsynp ); + + /* Open stream files */ + lpDEVlogf = fopen( lpDEVlogp, "rb" ); + lpDEVmasf = fopen( lpDEVmasp, "wb" ); + lpDEVsynf = fopen( lpDEVsynp, "wb" ); + + /* Create streams */ + lpDEVmas = ( lp_Time_t * ) lp_stream_create( sizeof( lp_Time_t ) * lpBlock ); + lpDEVsyn = ( lp_Time_t * ) lp_stream_create( sizeof( lp_Time_t ) * lpBlock ); + + /* FPGA records reading loop */ + while ( lpReading == LP_TRUE ) { + + /* Reset reading index */ + lpIndex = lp_Size_s( 0 ); + + /* Reading of FPGA record by block */ + while ( ( lpReading == LP_TRUE ) && ( lpIndex < lpBlock ) ) { + + /* Read and verify FPGA record */ + if ( ( lpReaded = fread( lpRec, 1, LP_DEVICE_EYESIS4PI_RECLEN, lpDEVlogf ) ) == LP_DEVICE_EYESIS4PI_RECLEN ) { + + /* Camera signal filter */ + if ( ( lpRec[3] & lp_Byte_s( 0x0F ) ) == LP_DEVICE_EYESIS4PI_MASEVT ) { + + /* Retrieve FPGA master timestamp */ + lpDEVmas[lpIndex] = lp_timestamp( ( lp_Void_t * ) ( lpRec + lp_Size_s( 8 ) ) ); + + /* Retrieve FPGA local timestamp */ + lpDEVsyn[lpIndex] = lp_timestamp( ( lp_Void_t * ) lpRec ); + + /* Update reading index */ + lpIndex += lp_Size_s( 1 ); + + } + + } else { + + /* Stop reading on EOF */ + lpReading = LP_FALSE; + + } + + } + + /* Verify that the current block is not empty */ + if ( lpIndex > lp_Size_s( 0 ) ) { + + /* Export block in output streams */ + fwrite( lpDEVmas, sizeof( lp_Time_t ) * lpIndex, 1, lpDEVmasf ); + fwrite( lpDEVsyn, sizeof( lp_Time_t ) * lpIndex, 1, lpDEVsynf ); + + } + + } + + /* Close stream files */ + fclose( lpDEVlogf ); + fclose( lpDEVmasf ); + fclose( lpDEVsynf ); + + /* Unallocate streams */ + free( lpDEVmas ); + free( lpDEVsyn ); + + } + diff --git a/pool/shard003/C/0067580_CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnlp_16.c b/pool/shard003/C/0067580_CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnlp_16.c new file mode 100644 index 0000000000000000000000000000000000000000..9b9e341caa3e5d13f3182648945614a0261111c0 --- /dev/null +++ b/pool/shard003/C/0067580_CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnlp_16.c @@ -0,0 +1,128 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnlp_16.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-16.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: environment Read input from an environment variable + * GoodSource: Fixed string + * Sink: w32_spawnlp + * BadSink : execute command with wspawnlp + * Flow Variant: 16 Control flow: while(1) + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir " +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"-c" +#define COMMAND_ARG2 L"ls " +#define COMMAND_ARG3 data +#endif + +#define ENV_VARIABLE L"ADD" + +#ifdef _WIN32 +#define GETENV _wgetenv +#else +#define GETENV getenv +#endif + +#include + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnlp_16_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + while(1) + { + { + /* Append input from an environment variable to data */ + size_t dataLen = wcslen(data); + wchar_t * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + wcsncat(data+dataLen, environment, 100-dataLen-1); + } + } + break; + } + /* wspawnlp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _wspawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by changing the conditions on the while statements */ +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + while(1) + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + break; + } + /* wspawnlp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _wspawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnlp_16_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnlp_16_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnlp_16_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard003/C/0067581_circuit.c b/pool/shard003/C/0067581_circuit.c new file mode 100644 index 0000000000000000000000000000000000000000..53b1c9d4134067f8be84c526b5412df65c8f0542 --- /dev/null +++ b/pool/shard003/C/0067581_circuit.c @@ -0,0 +1,320 @@ +/* circuit.c + * Routines for building lists of packets that are part of a "circuit" + * + * 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 "packet.h" +#include "circuit.h" + +/* + * Hash table for circuits. + */ +static GHashTable *circuit_hashtable = NULL; + +static guint32 new_index; + +/* + * Protocol-specific data attached to a circuit_t structure - protocol + * index and opaque pointer. + */ +typedef struct _circuit_proto_data { + int proto; + void *proto_data; +} circuit_proto_data; + +/* + * Compute the hash value for a circuit. + */ +static guint +circuit_hash(gconstpointer v) +{ + const circuit_key *key = (const circuit_key *)v; + + return key->ctype ^ key->circuit_id; +} + +/* + * Compare two circuit keys. + */ +static gint +circuit_match(gconstpointer v, gconstpointer w) +{ + const circuit_key *v1 = (const circuit_key *)v; + const circuit_key *v2 = (const circuit_key *)w; + + return v1->ctype == v2->ctype && v1->circuit_id == v2->circuit_id; +} + +/* + * Destroy all existing circuits. + */ +void +circuit_cleanup(void) +{ + /* + * Free up any space allocated for the circuit hashtable. + * + * We can free the hash as the structures pointed to in the + * hash are in "seasonal" memory which is freed separately. + * Note: circuit_cleanup() must be called only when + * seasonal memory is also freed. + */ + + if (circuit_hashtable != NULL) + g_hash_table_destroy(circuit_hashtable); + + circuit_hashtable = NULL; +} + +/* + * Initialize some variables every time a file is loaded or re-loaded. + * Create a new hash table for the circuits in the new file. + */ +void +circuit_init(void) +{ + g_assert(circuit_hashtable == NULL); + circuit_hashtable = g_hash_table_new(circuit_hash, circuit_match); + + /* + * Start the circuit indices over at 0. + */ + new_index = 0; +} + +/* + * Given a circuit type and circuit ID for a packet, create a new circuit + * to contain packets for that circuit. + */ +circuit_t * +circuit_new(circuit_type ctype, guint32 circuit_id, guint32 first_frame) +{ + circuit_t *circuit, *old_circuit; + circuit_key *new_key; + + new_key = wmem_new(wmem_file_scope(), struct circuit_key); + new_key->ctype = ctype; + new_key->circuit_id = circuit_id; + + circuit = wmem_new(wmem_file_scope(), circuit_t); + circuit->next = NULL; + circuit->first_frame = first_frame; + circuit->last_frame = 0; /* not known yet */ + circuit->index = new_index; + circuit->data_list = NULL; + circuit->dissector_handle = NULL; + circuit->key_ptr = new_key; + + new_index++; + + /* + * Is there already a circuit with this circuit ID? + */ + old_circuit = (circuit_t *)g_hash_table_lookup(circuit_hashtable, new_key); + if (old_circuit != NULL) { + /* + * Yes. Find the last circuit in the list of circuits + * with this circuit ID, and if its last frame isn't + * known, make it be the previous frame to this one. + */ + while (old_circuit->next != NULL) + old_circuit = old_circuit->next; + if (old_circuit->last_frame == 0) + old_circuit->last_frame = first_frame - 1; + + /* + * Now put the new circuit after the last one in the + * list. + */ + old_circuit->next = circuit; + } else { + /* + * No. This is the first one with this circuit ID; add + * it to the hash table. + */ + g_hash_table_insert(circuit_hashtable, new_key, circuit); + } + + return circuit; +} + +/* + * Given a circuit type and ID, and a frame number, search for a circuit with + * that type and ID whose range of frames includes that frame number. + * Returns NULL if not found. + */ +circuit_t * +find_circuit(circuit_type ctype, guint32 circuit_id, guint32 frame) +{ + circuit_key key; + circuit_t *circuit; + + key.ctype = ctype; + key.circuit_id = circuit_id; + + /* + * OK, search the list of circuits with that type and ID for + * a circuit whose range of frames includes that frame number. + */ + for (circuit = (circuit_t *)g_hash_table_lookup(circuit_hashtable, &key); + circuit != NULL; circuit = circuit->next) { + /* + * The circuit includes that frame number if: + * + * the circuit's first frame is unknown or is at or + * before that frame + * + * and + * + * the circuit's last frame is unknown or is at or + * after that frame. + */ + if ((circuit->first_frame == 0 || circuit->first_frame <= frame) + && (circuit->last_frame == 0 || circuit->last_frame >= frame)) + break; + } + return circuit; +} + +/* + * Set the last frame of a circuit, if it's not already known, + * "closing" the circuit. + */ +void +close_circuit(circuit_t *circuit, guint32 last_frame) +{ + if (circuit->last_frame == 0) + circuit->last_frame = last_frame; +} + +static gint +p_compare(gconstpointer a, gconstpointer b) +{ + const circuit_proto_data *ap = (const circuit_proto_data *)a; + const circuit_proto_data *bp = (const circuit_proto_data *)b; + + if (ap->proto > bp->proto) + return 1; + else if (ap->proto == bp->proto) + return 0; + else + return -1; +} + +void +circuit_add_proto_data(circuit_t *conv, int proto, void *proto_data) +{ + circuit_proto_data *p1 = wmem_new(wmem_file_scope(), circuit_proto_data); + + p1->proto = proto; + p1->proto_data = proto_data; + + /* Add it to the list of items for this circuit. */ + + conv->data_list = g_slist_insert_sorted(conv->data_list, (gpointer *)p1, + p_compare); +} + +void * +circuit_get_proto_data(circuit_t *conv, int proto) +{ + circuit_proto_data temp, *p1; + GSList *item; + + temp.proto = proto; + temp.proto_data = NULL; + + item = g_slist_find_custom(conv->data_list, (gpointer *)&temp, + p_compare); + + if (item != NULL) { + p1 = (circuit_proto_data *)item->data; + return p1->proto_data; + } + + return NULL; +} + +void +circuit_delete_proto_data(circuit_t *conv, int proto) +{ + circuit_proto_data temp; + GSList *item; + + temp.proto = proto; + temp.proto_data = NULL; + + item = g_slist_find_custom(conv->data_list, (gpointer *)&temp, + p_compare); + + if (item != NULL) + conv->data_list = g_slist_remove(conv->data_list, item); +} + +void +circuit_set_dissector(circuit_t *circuit, dissector_handle_t handle) +{ + circuit->dissector_handle = handle; +} + +dissector_handle_t +circuit_get_dissector(circuit_t *circuit) +{ + return circuit->dissector_handle; +} + +/* + * Given a circuit type and ID for a packet, search for a matching + * circuit and, if found and it has a circuit dissector, + * call that dissector and return TRUE, otherwise return FALSE. + */ +gboolean +try_circuit_dissector(circuit_type ctype, guint32 circuit_id, guint32 frame, + tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data) +{ + circuit_t *circuit; + + circuit = find_circuit(ctype, circuit_id, frame); + + if (circuit != NULL) { + if (circuit->dissector_handle == NULL) + return FALSE; + call_dissector_with_data(circuit->dissector_handle, tvb, pinfo, + tree, data); + return TRUE; + } + return FALSE; +} + +/* + * Editor modelines - http://www.wireshark.org/tools/modelines.html + * + * Local variables: + * c-basic-offset: 8 + * tab-width: 8 + * indent-tabs-mode: t + * End: + * + * vi: set shiftwidth=8 tabstop=8 noexpandtab: + * :indentSize=8:tabSize=8:noTabs=false: + */ diff --git a/pool/shard003/C/0067583_rmdir.c b/pool/shard003/C/0067583_rmdir.c new file mode 100644 index 0000000000000000000000000000000000000000..280b646287ae79b60b1a0ff531f800e24ae504e3 --- /dev/null +++ b/pool/shard003/C/0067583_rmdir.c @@ -0,0 +1,192 @@ +/* + Authors: Paul Turchinetz and Tyler Van Ollefen + Class: CSI-385-01 + Assignment: FAT + Due Date: 6 December 2016, 11:59PM + Description: rmdir deletes a directory if it is empty + Certification of Authenticity: + I certify that this assignment is entirely our own work unless cited otherwise. +*/ + + +#include +#include +#include + +#include "utilities.h" +#include "sharedMemory.h" + +FILE* FILE_SYSTEM_ID; + +void usage() +{ + printf("Please enter only 1 argument.\n"); +} + +int main(int argc, char **argv) +{ + //https://beej.us/guide/bgipc/output/html/multipage/shm.html + //Thanks Alex Apmann + int shmId = shmget((key_t) 8888888, sizeof(char), 0666 | IPC_CREAT); + + SharedMemory *sharedMemory = (SharedMemory *)shmat(shmId, (void *) 0, 0); + + FILE_SYSTEM_ID = fopen(sharedMemory->floppyImgName, "r+"); + + if (FILE_SYSTEM_ID == NULL) + { + printf("Could not open the floppy drive or image.\n"); + exit(1); + } + + int i; + short FLC = 0; + short oldFLC = 0; + int deletable = 0; + int realCluster; + short oldCluster = sharedMemory->firstCluster; + DirectoryOrFile *infoAtCluster; + DirectoryOrFile *infoAtOldCluster; + + unsigned char *data = malloc(BYTES_PER_SECTOR); + unsigned char *oldData = malloc(BYTES_PER_SECTOR); + + if (argc != 2) + { + usage(); + } + else + { + //if we only have . or .. we're not looking for files + if ((argv[1][0] == '.' && strlen(argv[1]) == 1)) + { + printf("You can't delete the folder you're in.\n"); + return 1; + } + + if (argv[1][0] == '.' && argv[1][1] == '.' && strlen(argv[1]) == 2) + { + if (sharedMemory->firstCluster == 0) + printf("Fam, this directory is the root.\nIt doesn't have a parent.\nAnd even if it did, it wouldn't be empty.\nSilly goose.\n"); + else + printf("You're trying to delete this directory's parent directory...\nHow silly is that?\nIt's obviously not empty.\n"); + } + + //i is either the location of the file in the cluster or the FLC of the directory. yeah, weird, I know. + if (argv[1][0] == '/') + i = search(0, argv[1], 0, &sharedMemory->firstCluster, &infoAtCluster); + else + i = search(sharedMemory->firstCluster, argv[1], 0, &sharedMemory->firstCluster, &infoAtCluster); + + + if (i >= 0) + { + if (i == 0) + realCluster = 19; + else + realCluster = 31 + i; + + read_sector(realCluster, data); + infoAtCluster = (DirectoryOrFile*) data; + + int j; + for (j = 0; j < 16; j++) + { + //if there's something inside the directory it can't be deleted + if (infoAtCluster[i].filename[0] != 0x00 && + infoAtCluster[i].filename[0] != 0xE5 && + infoAtCluster[i].filename[0] != 0xffffffe5 && + infoAtCluster[i].filename[0] != '.') + { + deletable = 1; + break; + } + } + if (deletable == 0) + { + //q is for the directory above + int q; + + q = search(sharedMemory->firstCluster, "..", 0, &sharedMemory->firstCluster, &infoAtCluster); + //printf("q after searching is %d\n", q); + + int newCluster; + if (q == 0) + newCluster = 19; + else + newCluster = 31 + q; + read_sector(newCluster, oldData); + infoAtOldCluster = (DirectoryOrFile*) oldData; + + //printf("our argument has changed maybe i hope please and it is now %s\n", argv[1]); + //strcat(argv[1], "\0"); + + for (q = 0; q < 16; q++) + { + //printf("We're gonna compare %s and %s\n", infoAtOldCluster[q].filename, argv[1]); + char* fixedName = malloc(8); + int g; + for (g = 0; g < 8; g++) + { + if(infoAtOldCluster[q].filename[g] != ' ') + fixedName[g] = infoAtOldCluster[q].filename[g]; + else + break; + } + //printf("fixedName is %s, and argv is %s,\n", fixedName, argv[1]); + + if (strcmp(fixedName, argv[1]) == 0) + break; + } + + //printf ("q is %d\n", q); + + char* deletionBuffer = malloc(BYTES_PER_SECTOR); + char* deleteFromAboveBuffer = malloc(BYTES_PER_SECTOR); + int k; + for (k = 0; k <= BYTES_PER_SECTOR; k++) + { + if (k == 0) + deletionBuffer[k] = 0xE5; + else + deletionBuffer[k] = 0; + } + + read_sector(newCluster, deleteFromAboveBuffer); + //32 bytes per file/directory info + deleteFromAboveBuffer[q * 32] = 0xE5; + + + + write_sector(realCluster, deletionBuffer); + write_sector(newCluster, deleteFromAboveBuffer); + + //FLC will never be 0 because the file can't actually be the root directory + FLC = infoAtOldCluster[q].firstLogicalCluster; + char* fatEntryBuffer = readFAT12Table(); + + while (FLC != 0 && FLC != 4095) //FFF -> decimal = 4095 + { + oldFLC = get_fat_entry(FLC,fatEntryBuffer); + set_fat_entry(FLC, 0, fatEntryBuffer); + FLC = oldFLC; + } + + writeFAT12Table(fatEntryBuffer); + + printf("Directory successfully deleted!\n"); + } + else + { + printf("The directory is not empty so we can't delete it.\n"); + sharedMemory->firstCluster = oldCluster; + return 1; + } + //print(infoAtCluster); + sharedMemory->firstCluster = oldCluster; + } + } + + free(data); + return 0; +} diff --git a/pool/shard003/C/0067586_papi_csr_fal.c b/pool/shard003/C/0067586_papi_csr_fal.c new file mode 100644 index 0000000000000000000000000000000000000000..06c1e6b4bb7633e53756e46acf29e32b67672da0 --- /dev/null +++ b/pool/shard003/C/0067586_papi_csr_fal.c @@ -0,0 +1,53 @@ +/* This code runs some sanity checks on the PAPI_CSR_FAL */ +/* (Failed Store Conditional) event. */ + +/* by Vince Weaver, vweaver1 _at_ eecs.utk.edu */ + +#include +#include +#include + +#include "papi.h" + +#include "test_utils.h" + +int main(int argc, char **argv) { + + int events[1]; + long long counts[1]; + + int retval,quiet; + + char test_string[]="Testing PAPI_CSR_FAL predefined event..."; + + quiet=test_quiet(); + + retval = PAPI_library_init(PAPI_VER_CURRENT); + if (retval != PAPI_VER_CURRENT) { + if (!quiet) printf("Error! PAPI_library_init %d\n",retval); + test_fail(test_string); + } + + retval = PAPI_query_event(PAPI_CSR_FAL); + if (retval != PAPI_OK) { + if (!quiet) printf("PAPI_CSR_FAL not available\n"); + test_skip(test_string); + } + + events[0]=PAPI_CSR_FAL; + + PAPI_start_counters(events,1); + + PAPI_stop_counters(counts,1); + + if (counts[0]<1) { + if (!quiet) printf("Error! Count too low\n"); + test_fail(test_string); + } + + PAPI_shutdown(); + + test_unimplemented(test_string); + + return 0; +} diff --git a/pool/shard003/C/0067598_div_2exp.c b/pool/shard003/C/0067598_div_2exp.c new file mode 100644 index 0000000000000000000000000000000000000000..ad552c115cac016d443e3ced22129c723bd76093 --- /dev/null +++ b/pool/shard003/C/0067598_div_2exp.c @@ -0,0 +1,138 @@ +/* mpf_div_2exp -- Divide a float by 2^n. + +Copyright 1993, 1994, 1996, 2000-2002, 2004 Free Software Foundation, Inc. + +This file is part of the GNU MP Library. + +The GNU MP Library is free software; you can redistribute it and/or modify +it under the terms of either: + + * 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. + +or + + * 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. + +or both in parallel, as here. + +The GNU MP Library is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received copies of the GNU General Public License and the +GNU Lesser General Public License along with the GNU MP Library. If not, +see https://www.gnu.org/licenses/. */ + +#include "gmp-impl.h" + + +/* Multiples of GMP_NUMB_BITS in exp simply mean an amount subtracted from + EXP(u) to set EXP(r). The remainder exp%GMP_NUMB_BITS is then a right + shift for the limb data. + + If exp%GMP_NUMB_BITS == 0 then there's no shifting, we effectively just + do an mpz_set with changed EXP(r). Like mpz_set we take prec+1 limbs in + this case. Although just prec would suffice, it's nice to have + mpf_div_2exp with exp==0 come out the same as mpz_set. + + When shifting we take up to prec many limbs from the input. Our shift is + cy = mpn_rshift (PTR(r)+1, PTR(u)+k, ...), where k is the number of low + limbs dropped from u, and the carry out is stored to PTR(r)[0]. We don't + try to work extra bits from PTR(u)[k-1] (when k>=1 makes it available) + into that low carry limb. Just prec limbs (with the high non-zero) from + the input is enough bits for the application requested precision, no need + to do extra work. + + If r==u the shift will have overlapping operands. When k>=1 (ie. when + usize > prec), the overlap is in the style supported by rshift (ie. dst + <= src). + + But when r==u and k==0 (ie. usize <= prec), we would have an invalid + overlap (mpn_rshift (rp+1, rp, ...)). In this case we must instead use + mpn_lshift (PTR(r), PTR(u), size, NUMB-shift). An lshift by NUMB-shift + bits gives identical data of course, it's just its overlap restrictions + which differ. + + In both shift cases, the resulting data is abs_usize+1 limbs. "adj" is + used to add +1 to that size if the high is non-zero (it may of course + have become zero by the shifting). EXP(u) is the exponent just above + those abs_usize+1 limbs, so it gets -1+adj, which means -1 if the high is + zero, or no change if the high is non-zero. + + Enhancements: + + The way mpn_lshift is used means successive mpf_div_2exp calls on the + same operand will accumulate low zero limbs, until prec+1 limbs is + reached. This is wasteful for subsequent operations. When abs_usize <= + prec, we should test the low exp%GMP_NUMB_BITS many bits of PTR(u)[0], + ie. those which would be shifted out by an mpn_rshift. If they're zero + then use that mpn_rshift. */ + +void +mpf_div_2exp (mpf_ptr r, mpf_srcptr u, mp_bitcnt_t exp) +{ + mp_srcptr up; + mp_ptr rp = r->_mp_d; + mp_size_t usize; + mp_size_t abs_usize; + mp_size_t prec = r->_mp_prec; + mp_exp_t uexp = u->_mp_exp; + + usize = u->_mp_size; + + if (UNLIKELY (usize == 0)) + { + r->_mp_size = 0; + r->_mp_exp = 0; + return; + } + + abs_usize = ABS (usize); + up = u->_mp_d; + + if (exp % GMP_NUMB_BITS == 0) + { + prec++; /* retain more precision here as we don't need + to account for carry-out here */ + if (abs_usize > prec) + { + up += abs_usize - prec; + abs_usize = prec; + } + if (rp != up) + MPN_COPY_INCR (rp, up, abs_usize); + r->_mp_exp = uexp - exp / GMP_NUMB_BITS; + } + else + { + mp_limb_t cy_limb; + mp_size_t adj; + if (abs_usize > prec) + { + up += abs_usize - prec; + abs_usize = prec; + /* Use mpn_rshift since mpn_lshift operates downwards, and we + therefore would clobber part of U before using that part, in case + R is the same variable as U. */ + cy_limb = mpn_rshift (rp + 1, up, abs_usize, exp % GMP_NUMB_BITS); + rp[0] = cy_limb; + adj = rp[abs_usize] != 0; + } + else + { + cy_limb = mpn_lshift (rp, up, abs_usize, + GMP_NUMB_BITS - exp % GMP_NUMB_BITS); + rp[abs_usize] = cy_limb; + adj = cy_limb != 0; + } + + abs_usize += adj; + r->_mp_exp = uexp - exp / GMP_NUMB_BITS - 1 + adj; + } + r->_mp_size = usize >= 0 ? abs_usize : -abs_usize; +} diff --git a/pool/shard003/C/0067600_pwmout_api.c b/pool/shard003/C/0067600_pwmout_api.c new file mode 100644 index 0000000000000000000000000000000000000000..1a412248de50012cb5cf10ba98db479ba4bf04ae --- /dev/null +++ b/pool/shard003/C/0067600_pwmout_api.c @@ -0,0 +1,234 @@ +/******************************************************************************* + * Copyright (C) 2015 Maxim Integrated Products, Inc., 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 MAXIM INTEGRATED 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. + * + * Except as contained in this notice, the name of Maxim Integrated + * Products, Inc. shall not be used except as stated in the Maxim Integrated + * Products, Inc. Branding Policy. + * + * The mere transfer of this software does not imply any licenses + * of trade secrets, proprietary technology, copyrights, patents, + * trademarks, maskwork rights, or any other form of intellectual + * property whatsoever. Maxim Integrated Products, Inc. retains all + * ownership rights. + ******************************************************************************* + */ + +#include "mbed_assert.h" +#include "cmsis.h" +#include "pwmout_api.h" +#include "pinmap.h" +#include "ioman_regs.h" +#include "clkman_regs.h" +#include "PeripheralPins.h" + +//****************************************************************************** +void pwmout_init(pwmout_t* obj, PinName pin) +{ + // Make sure the pin is free for GPIO use + unsigned int port = (unsigned int)pin >> PORT_SHIFT; + unsigned int port_pin = (unsigned int)pin & ~(0xFFFFFFFF << PORT_SHIFT); + MBED_ASSERT(MXC_GPIO->free[port] & (0x1 << port_pin)); + + int i = 0; + PinMap pwm = PinMap_PWM[0]; + + // Check if there is a pulse train already active on this port + int pin_func = (MXC_GPIO->func_sel[port] & (0xF << (port_pin*4))) >> (port_pin*4); + if((pin_func > 0) && (pin_func < 4)) { + // Search through PinMap_PWM to find the active PT + while(pwm.pin != (PinName)NC) { + if((pwm.pin == pin) && (pwm.function == pin_func)) { + break; + } + pwm = PinMap_PWM[++i]; + } + + } else { + // Search through PinMap_PWM to find an available PT + int i = 0; + while(pwm.pin != (PinName)NC && (i > -1)) { + pwm = PinMap_PWM[i++]; + if(pwm.pin == pin) { + // Check each instance of PT + while(1) { + // Check to see if this PT instance is already in use + if((((mxc_pt_regs_t*)pwm.peripheral)->rate_length & + MXC_F_PT_RATE_LENGTH_MODE)) { + i = -1; + break; + } + + // If all instances are in use, overwrite the last + pwm = PinMap_PWM[++i]; + if(pwm.pin != pin) { + pwm = PinMap_PWM[--i]; + i = -1; + break; + } + + } + } + } + } + + // Make sure we found an available PWM generator + MBED_ASSERT(pwm.pin != (PinName)NC); + + // Disable all pwm output + MXC_PTG->ctrl = 0; + + // Enable the clock + MXC_CLKMAN->clk_ctrl_2_pt = MXC_E_CLKMAN_CLK_SCALE_ENABLED; + + // Set the drive mode to normal + MXC_SET_FIELD(&MXC_GPIO->out_mode[port], (0x7 << (port_pin*4)), (MXC_V_GPIO_OUT_MODE_NORMAL_DRIVE << (port_pin*4))); + + // Set the obj pointer to the propper PWM instance + obj->pwm = (mxc_pt_regs_t*)pwm.peripheral; + + // Initialize object period and pulse width + obj->period = -1; + obj->pulse_width = -1; + + // Disable the output + obj->pwm->train = 0x0; + obj->pwm->rate_length = 0x0; + + // Configure the pin + pin_mode(pin, (PinMode)PullNone); + pin_function(pin, pwm.function); + + // default to 20ms: standard for servos, and fine for e.g. brightness control + pwmout_period_us(obj, 20000); + pwmout_write (obj, 0); + + // Enable the global pwm + MXC_PTG->ctrl = MXC_F_PT_CTRL_ENABLE_ALL; +} + +//****************************************************************************** +void pwmout_free(pwmout_t* obj) +{ + // Set the registers to the reset value + obj->pwm->train = 0; + obj->pwm->rate_length = 0x08000000; +} + +//****************************************************************************** +static void pwmout_update(pwmout_t* obj) +{ + // Calculate and set the divider ratio + int div = (obj->period * (SystemCoreClock/1000000))/32; + if (div < 2){ + div = 2; + } + MXC_SET_FIELD(&obj->pwm->rate_length, MXC_F_PT_RATE_LENGTH_RATE_CONTROL, div); + + // Change the duty cycle to adjust the pulse width + obj->pwm->train = (0xFFFFFFFF << (32-((32*obj->pulse_width)/obj->period))); +} + + +//****************************************************************************** +void pwmout_write(pwmout_t* obj, float percent) +{ + // Saturate percent if outside of range + if(percent < 0.0) { + percent = 0.0; + } else if(percent > 1.0) { + percent = 1.0; + } + + // Resize the pulse width to set the duty cycle + pwmout_pulsewidth_us(obj, (int)(percent*obj->period)); +} + +//****************************************************************************** +float pwmout_read(pwmout_t* obj) +{ + // Check for when pulsewidth or period equals 0 + if((obj->pulse_width == 0) || (obj->period == 0)){ + return 0; + } + + // Return the duty cycle + return ((float)obj->pulse_width / (float)obj->period); +} + +//****************************************************************************** +void pwmout_period(pwmout_t* obj, float seconds) +{ + pwmout_period_us(obj, (int)(seconds * 1000000.0)); +} + +//****************************************************************************** +void pwmout_period_ms(pwmout_t* obj, int ms) +{ + pwmout_period_us(obj, ms*1000); +} + +//****************************************************************************** +void pwmout_period_us(pwmout_t* obj, int us) +{ + // Check the range of the period + MBED_ASSERT((us >= 0) && (us <= (int)(SystemCoreClock/32))); + + // Set pulse width to half the period if uninitialized + if(obj->pulse_width == -1){ + obj->pulse_width = us/2; + } + + // Save the period + obj->period = us; + + // Update the registers + pwmout_update(obj); +} + +//****************************************************************************** +void pwmout_pulsewidth(pwmout_t* obj, float seconds) +{ + pwmout_pulsewidth_us(obj, (int)(seconds * 1000000.0)); +} + +//****************************************************************************** +void pwmout_pulsewidth_ms(pwmout_t* obj, int ms) +{ + pwmout_pulsewidth_us(obj, ms*1000); +} + +//****************************************************************************** +void pwmout_pulsewidth_us(pwmout_t* obj, int us) +{ + // Check the range of the pulsewidth + MBED_ASSERT((us >= 0) && (us <= (int)(SystemCoreClock/32))); + + // Initialize period to double the pulsewidth if uninitialized + if(obj->period == -1){ + obj->period = 2*us; + } + + // Save the pulsewidth + obj->pulse_width = us; + + // Update the register + pwmout_update(obj); +} diff --git a/pool/shard003/C/0067601_board.c b/pool/shard003/C/0067601_board.c new file mode 100644 index 0000000000000000000000000000000000000000..513d45d9a7cfa76baa97ddd7afe6657ce2f7e451 --- /dev/null +++ b/pool/shard003/C/0067601_board.c @@ -0,0 +1,82 @@ +/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ +/* Twinkie dongle configuration */ + +#include "adc.h" +#include "adc_chip.h" +#include "common.h" +#include "console.h" +#include "ec_version.h" +#include "gpio.h" +#include "hooks.h" +#include "i2c.h" +#include "ina2xx.h" +#include "registers.h" +#include "task.h" +#include "usb_descriptor.h" +#include "util.h" + +void cc2_event(enum gpio_signal signal) +{ + ccprintf("INA!\n"); +} + +void vbus_event(enum gpio_signal signal) +{ + ccprintf("INA!\n"); +} + +#include "gpio_list.h" + +/* Initialize board. */ +void board_config_pre_init(void) +{ + /* enable SYSCFG clock */ + STM32_RCC_APB2ENR |= 1 << 0; + /* Remap USART DMA to match the USART driver and TIM2 DMA */ + STM32_SYSCFG_CFGR1 |= (1 << 9) | (1 << 10) /* Remap USART1 RX/TX DMA */ + | (1 << 29);/* Remap TIM2 DMA */ + /* 40 MHz pin speed on UART PA9/PA10 */ + STM32_GPIO_OSPEEDR(GPIO_A) |= 0x003C0000; + /* 40 MHz pin speed on TX clock out PB9 */ + STM32_GPIO_OSPEEDR(GPIO_B) |= 0x000C0000; +} + +static void board_init(void) +{ + /* Enable interrupts for INAs. */ + gpio_enable_interrupt(GPIO_CC2_ALERT_L); + gpio_enable_interrupt(GPIO_VBUS_ALERT_L); + + /* Calibrate INA0 (VBUS) with 1mA/LSB scale */ + ina2xx_init(0, 0x8000, INA2XX_CALIB_1MA(15 /*mOhm*/)); + /* Disable INA1 (VCONN2) to avoid leaking current */ + ina2xx_init(1, 0, INA2XX_CALIB_1MA(15 /*mOhm*/)); +} +DECLARE_HOOK(HOOK_INIT, board_init, HOOK_PRIO_DEFAULT); + +/* ADC channels */ +const struct adc_t adc_channels[] = { + /* USB PD CC lines sensing. Converted to mV (3300mV/4096). */ + [ADC_CH_CC1_PD] = {"CC1_PD", 3300, 4096, 0, STM32_AIN(1)}, + [ADC_CH_CC2_PD] = {"CC2_PD", 3300, 4096, 0, STM32_AIN(3)}, +}; +BUILD_ASSERT(ARRAY_SIZE(adc_channels) == ADC_CH_COUNT); + +/* I2C ports */ +const struct i2c_port_t i2c_ports[] = { + {"master", I2C_PORT_MASTER, 100, GPIO_I2C_SCL, GPIO_I2C_SDA}, +}; +const unsigned int i2c_ports_used = ARRAY_SIZE(i2c_ports); + +const void * const usb_strings[] = { + [USB_STR_DESC] = usb_string_desc, + [USB_STR_VENDOR] = USB_STRING_DESC("Google Inc."), + [USB_STR_PRODUCT] = USB_STRING_DESC("Twinkie"), + [USB_STR_VERSION] = USB_STRING_DESC(CROS_EC_VERSION32), + [USB_STR_SNIFFER] = USB_STRING_DESC("USB-PD Sniffer"), + [USB_STR_CONSOLE_NAME] = USB_STRING_DESC("Shell"), +}; +BUILD_ASSERT(ARRAY_SIZE(usb_strings) == USB_STR_COUNT); diff --git a/pool/shard003/C/0067602_lb-mpi-utils.c b/pool/shard003/C/0067602_lb-mpi-utils.c new file mode 100644 index 0000000000000000000000000000000000000000..b7f69b2dc561333669700d600f29040d8b1162fb --- /dev/null +++ b/pool/shard003/C/0067602_lb-mpi-utils.c @@ -0,0 +1,231 @@ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif /* HAVE_CONFIG_H */ + +#include +#include +#include + +#include "lb-memory.h" +#include "lb-mpi-utils.h" +#include "lb-cart-partition.h" + +int +lb_mpi_comm_size(MPI_Comm comm) +{ + int size; + LB_CALL_MPI(MPI_Comm_size(comm, &size)); + return size; +} + +int +lb_mpi_comm_rank(MPI_Comm comm) +{ + int rank; + LB_CALL_MPI(MPI_Comm_rank(comm, &rank)); + return rank; +} + +static void +print_line(void) +{ + int i; + + for (i = 0; i < 64; ++i) + putchar('='); + + putchar('\n'); +} + +static void +print_int_array(int n, const int* x, + const char* start, const char* separator, const char* end) +{ + int i; + + lb_assert(n > 0); + lb_assert(x != NULL); + + if (start != NULL) + fputs(start, stdout); + + for (i = 0; i < n - 1; ++i) + printf("%d%s", x[i], (separator == NULL ? ", " : separator)); + + printf("%d", x[n - 1]); + + if (end != NULL) + fputs(end, stdout); +} + +static void +print_cart_info_one(int rank, const char* name, int pid, + int ndims, + const int* coords, + const int* size, + const int* origin) +{ + print_line(); + printf("<>> process rank : %d\n" + "<>> machine : '%s', pid : %d\n", + rank, name, pid); + + print_int_array(ndims, coords, + "<>> coordinates = (", ", ", ")\n"); + print_int_array(ndims, size, + "<>> brick size = ", " x ", "\n"); + print_int_array(ndims, origin, + "<>> origin = (", ", ", ")\n"); + fflush(stdout); +} + +static void +print_cart_info(MPI_Comm comm, int ndims, + const int* coords, const int* size, const int* origin) +{ + int rank = lb_mpi_comm_rank(comm); + + int tmp, data_size; + char* data; + + data_size = MPI_MAX_PROCESSOR_NAME + sizeof(int) + 3*ndims*sizeof(int); + data = lb_newa(char, data_size); + + MPI_Get_processor_name(data, &tmp); + tmp = ndims*sizeof(int); + + if (rank) { + int pid; + + pid = getpid(); + + memcpy(data + MPI_MAX_PROCESSOR_NAME, + &pid, sizeof(int)); + + memcpy(data + MPI_MAX_PROCESSOR_NAME + sizeof(pid), + coords, tmp); + + memcpy(data + MPI_MAX_PROCESSOR_NAME + sizeof(pid) + tmp, + size, tmp); + + memcpy(data + MPI_MAX_PROCESSOR_NAME + sizeof(pid) + 2*tmp, + origin, tmp); + + MPI_Send(data, data_size, MPI_CHAR, 0, 0, comm); + } else { + int i; + + print_cart_info_one(0, data, getpid(), ndims, + coords, size, origin); + + for (i = 1; i < lb_mpi_comm_size(comm); ++i) { + MPI_Status status; + + MPI_Recv(data, data_size, MPI_CHAR, i, 0, comm, &status); + + print_cart_info_one(i, data, + *((int *) (data + MPI_MAX_PROCESSOR_NAME)), ndims, + (int *) (data + MPI_MAX_PROCESSOR_NAME + sizeof(int)), + (int *) (data + MPI_MAX_PROCESSOR_NAME + sizeof(int) + tmp), + (int *) (data + MPI_MAX_PROCESSOR_NAME + sizeof(int) + 2*tmp)); + } + + print_line(); + fflush(stdout); + } +} + +void +lb_mpi_cart_create(MPI_Comm comm, int n_dimensions, + const int* global_size, + const int* global_periods, + int* partition_dims, + int* processor_coords, + int* local_size, + int* local_origin, + MPI_Comm* cart_comm) +{ + lb_assert(comm != MPI_COMM_NULL); + lb_assert(n_dimensions > 0); + lb_assert(global_size && global_periods); + lb_assert(partition_dims && processor_coords); + lb_assert(local_size && local_origin); + lb_assert(cart_comm != NULL); + + /* + * look for optimal domain partition + */ + + lb_cart_partition(n_dimensions, global_size, global_periods, + lb_mpi_comm_size(comm), partition_dims); + + /* + * create communicator + */ + + LB_CALL_MPI(MPI_Cart_create(comm, n_dimensions, partition_dims, + (int*) global_periods, 0, cart_comm)) + + /* + * ask for our coordinates within processors grid + */ + + LB_CALL_MPI(MPI_Cart_coords(*cart_comm, lb_mpi_comm_rank(*cart_comm), + n_dimensions, processor_coords)) + + /* + * setup local size/origin + */ + + lb_cart_partition_size(n_dimensions, partition_dims, global_size, + processor_coords, local_size); + + lb_cart_partition_origin(n_dimensions, partition_dims, global_size, + processor_coords, local_origin); + + if (lb_info_enabled()) + print_cart_info(*cart_comm, n_dimensions, processor_coords, + local_size, local_origin); +} + +int +lb_mpi_neighbor_rank(MPI_Comm comm, const int* shift) +{ + int ndims, i; + int* dims; + int* pers; + int* coords; + int ok, rank = MPI_PROC_NULL; + + lb_assert(comm != MPI_COMM_NULL); + lb_assert(shift != NULL); + + LB_CALL_MPI(MPI_Cartdim_get(comm, &ndims)) + lb_assert(ndims > 0); + + dims = lb_newa(int, ndims); + pers = lb_newa(int, ndims); + coords = lb_newa(int, ndims); + + LB_CALL_MPI(MPI_Cart_get(comm, ndims, dims, pers, coords)) + + for (i = 0, ok = TRUE; i < ndims; ++i) { + coords[i] += shift[i]; + ok = ok && (pers[i] || (coords[i] >= 0 && coords[i] < dims[i])); + } + + if (ok) + LB_CALL_MPI(MPI_Cart_rank(comm, coords, &rank)) + + return rank; +} + +void +lb_mpi_barrier(void) +{ + +#ifdef LB_ENABLE_MPI + LB_CALL_MPI(MPI_Barrier(MPI_COMM_WORLD)) +#endif /* LB_ENABLE_MPI */ + +} diff --git a/pool/shard003/C/0067605_bitboard.c b/pool/shard003/C/0067605_bitboard.c new file mode 100644 index 0000000000000000000000000000000000000000..a5ff709b600c945d2f4ef99ed5cdfa20dd1af3e8 --- /dev/null +++ b/pool/shard003/C/0067605_bitboard.c @@ -0,0 +1,145 @@ +/* + File: bitboard.c + + Created: November 21, 1999 + + Modified: November 24, 2005 + + Authors: Gunnar Andersson (gunnar@radagast.se) + Toshihiko Okuhara + + Contents: Basic bitboard manipulations +*/ + + + +#include "bitboard.h" +#include "constant.h" +#include "macros.h" + + + +BitBoard square_mask[100]; + + + +/* + NON_ITERATIVE_POPCOUNT + Counts the number of bits set in a 64-bit integer. + This is done using some bitfiddling tricks. +*/ + +INLINE unsigned int REGPARM(2) +non_iterative_popcount( unsigned int n1, unsigned int n2 ) { + n1 = n1 - ((n1 >> 1) & 0x55555555u); + n2 = n2 - ((n2 >> 1) & 0x55555555u); + n1 = (n1 & 0x33333333u) + ((n1 >> 2) & 0x33333333u); + n2 = (n2 & 0x33333333u) + ((n2 >> 2) & 0x33333333u); + n1 = (n1 + (n1 >> 4)) & 0x0F0F0F0Fu; + n2 = (n2 + (n2 >> 4)) & 0x0F0F0F0Fu; + return ((n1 + n2) * 0x01010101u) >> 24; +} + + +/* + ITERATIVE_POPCOUNT + Counts the number of bits set in a 64-bit integer. + This is done using an iterative procedure which loops + a number of times equal to the number of bits set, + hence this function is fast when the number of bits + set is low. +*/ + +INLINE unsigned int REGPARM(2) +iterative_popcount( unsigned int n1, unsigned int n2 ) { + unsigned int n; + n = 0; + for ( ; n1 != 0; n++, n1 &= (n1 - 1) ) + ; + for ( ; n2 != 0; n++, n2 &= (n2 - 1) ) + ; + + return n; +} + + + +/* + BIT_REVERSE_32 + Returns the bit-reverse of a 32-bit integer. +*/ + +unsigned int REGPARM(1) +bit_reverse_32( unsigned int val ) { + val = ((val >> 1) & 0x55555555) | ((val << 1) & 0xAAAAAAAA); + val = ((val >> 2) & 0x33333333) | ((val << 2) & 0xCCCCCCCC); + val = ((val >> 4) & 0x0F0F0F0F) | ((val << 4) & 0xF0F0F0F0); + val = ((val >> 8) & 0x00FF00FF) | ((val << 8) & 0xFF00FF00); + val = ((val >> 16) & 0x0000FFFF) | ((val << 16) & 0xFFFF0000); + + return val; +} + + +/* + SET_BITBOARDS + Converts the vector board representation to the bitboard representation. +*/ + +void +set_bitboards( int *board, int side_to_move, + BitBoard *my_out, BitBoard *opp_out ) { + int i, j; + int pos; + unsigned int mask; + BitBoard my_bits, opp_bits; + + my_bits.high = 0; + my_bits.low = 0; + opp_bits.high = 0; + opp_bits.low = 0; + + mask = 1; + for ( i = 1; i <= 4; i++ ) + for ( j = 1; j <= 8; j++, mask <<= 1 ) { + pos = 10 * i + j; + if ( board[pos] == side_to_move ) + my_bits.low |= mask; + else if ( board[pos] == OPP( side_to_move ) ) + opp_bits.low |= mask; + } + + mask = 1; + for ( i = 5; i <= 8; i++ ) + for ( j = 1; j <= 8; j++, mask <<= 1 ) { + pos = 10 * i + j; + if ( board[pos] == side_to_move ) + my_bits.high |= mask; + else if ( board[pos] == OPP( side_to_move ) ) + opp_bits.high |= mask; + } + + *my_out = my_bits; + *opp_out = opp_bits; +} + + + +void +init_bitboard( void ) { + int i, j; + + for ( i = 1; i <= 8; i++ ) + for ( j = 1; j <= 8; j++ ) { + int pos = 10 * i + j; + unsigned shift = 8 * (i - 1) + (j - 1); + if ( shift < 32 ) { + square_mask[pos].low = 1ul << shift; + square_mask[pos].high = 0; + } + else { + square_mask[pos].low = 0; + square_mask[pos].high = 1ul << (shift - 32); + } + } +} diff --git a/pool/shard003/C/0067622_xm_vector.c b/pool/shard003/C/0067622_xm_vector.c new file mode 100644 index 0000000000000000000000000000000000000000..6d05bc54f8e535d74f9192278350721989919d44 --- /dev/null +++ b/pool/shard003/C/0067622_xm_vector.c @@ -0,0 +1,164 @@ +/* -------------------------------------------------------------------------- + * + * File xm_vector.c + * Description Vector calculation function. + * Author Y.H Mun + * + * -------------------------------------------------------------------------- + * + * Copyright (C) 2010-2012 XMSoft. All rights reserved. + * + * Contact Email: xmsoft77@gmail.com + * + * -------------------------------------------------------------------------- + * + * 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 in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- */ + +#include "kd_library.h" + +KD_API XMVectorf KD_APIENTRY xmVectorCastFloat ( const XMVectorx* v ) +{ + XMVectorf vr; + + vr.x = KD_X2F ( v->x ); + vr.y = KD_X2F ( v->y ); + vr.z = KD_X2F ( v->z ); + + return vr; +} + +KD_API XMVectorx KD_APIENTRY xmVectorCastFixed ( const XMVectorf* v ) +{ + XMVectorx vr; + + vr.x = KD_F2X ( v->x ); + vr.y = KD_F2X ( v->y ); + vr.z = KD_F2X ( v->z ); + + return vr; +} + +KD_API KDfloat KD_APIENTRY xmVectorLength ( const XMVectorf* v ) +{ + return kdSqrtf ( v->x * v->x + v->y * v->y + v->z * v->z ); +} + +KD_API XMVectorf KD_APIENTRY xmVectorNormalize ( const XMVectorf* v ) +{ + XMVectorf vr; + KDfloat l = xmVectorLength ( v ); + + if ( l > -KD_FLT_EPSILON && l < KD_FLT_EPSILON ) + { + kdLogMessage ( "xmVectorNormalize failed." ); + + vr.x = 0; + vr.y = 0; + vr.z = 0; + } + else + { + vr.x = v->x / l; + vr.y = v->y / l; + vr.z = v->z / l; + } + + return vr; +} + +KD_API KDfloat KD_APIENTRY xmVectorDot ( const XMVectorf* v1, const XMVectorf* v2 ) +{ + return ( v1->x * v2->x + v1->y * v2->y + v1->z * v2->z ); +} + +KD_API XMVectorf KD_APIENTRY xmVectorCross ( const XMVectorf* v1, const XMVectorf* v2 ) +{ + XMVectorf vr; + + vr.x = v1->y * v2->z - v1->z * v2->y; + vr.y = v1->z * v2->x - v1->x * v2->z; + vr.z = v1->x * v2->y - v1->y * v2->x; + + return vr; +} + +KD_API XMVectorf KD_APIENTRY xmVectorAdd ( const XMVectorf* v1, const XMVectorf* v2 ) +{ + XMVectorf vr; + + vr.x = v1->x + v2->x; + vr.y = v1->y + v2->y; + vr.z = v1->z + v2->z; + + return vr; +} + +KD_API XMVectorf KD_APIENTRY xmVectorSubstract ( const XMVectorf* v1, const XMVectorf* v2 ) +{ + XMVectorf vr; + + vr.x = v1->x - v2->x; + vr.y = v1->y - v2->y; + vr.z = v1->z - v2->z; + + return vr; +} + +KD_API XMVectorf KD_APIENTRY xmVectorMultiply ( const XMVectorf* v, KDfloat s ) +{ + XMVectorf vr; + + vr.x = v->x * s; + vr.y = v->y * s; + vr.z = v->z * s; + + return vr; +} + +KD_API XMVectorf KD_APIENTRY xmVectorDivide ( const XMVectorf* v, KDfloat s ) +{ + XMVectorf vr; + + if ( s == 0 ) + { + kdLogMessage ( "xmVectorDivide failed." ); + + vr.x = 0; + vr.y = 0; + vr.z = 0; + } + else + { + vr.x = v->x / s; + vr.y = v->y / s; + vr.z = v->z / s; + } + + return vr; +} + +KD_API XMVectorf KD_APIENTRY xmVectorTranform ( const KDfloat* m, const XMVectorf* v ) +{ + XMVectorf vr; + + vr.x = v->x * m[0] + v->y * m[4] + v->z * m[8]; + vr.y = v->x * m[1] + v->y * m[5] + v->z * m[9]; + vr.z = v->x * m[2] + v->y * m[6] + v->z * m[10]; + + return vr; +} diff --git a/pool/shard003/C/0067631_dwmstatus.c b/pool/shard003/C/0067631_dwmstatus.c new file mode 100644 index 0000000000000000000000000000000000000000..d0ca83415303d4162a113530b9232f0637091df6 --- /dev/null +++ b/pool/shard003/C/0067631_dwmstatus.c @@ -0,0 +1,132 @@ +#define _DEFAULT_SOURCE +#include /* sleep() */ +#include +#include +#include +#include +#include +#include + +const char *tmfmt = "%Y-%m-%d %H:%M"; +const char *tzmtl = "America/Montreal"; +const char *tzgva = "Europe/Paris"; + +static Display *dpy; + +char *smprintf(const char *fmt, ...) +{ + va_list fmtargs; + char *ret; + int len; + + va_start(fmtargs, fmt); + len = vsnprintf(NULL, 0, fmt, fmtargs); + va_end(fmtargs); + + ret = malloc(++len); + if (ret == NULL) { + perror("malloc"); + exit(1); + } + + va_start(fmtargs, fmt); + vsnprintf(ret, len, fmt, fmtargs); + va_end(fmtargs); + + return ret; +} + +void settz(const char *tzname) +{ + setenv("TZ", tzname, 1); +} + +char* mktimes(const char *fmt, const char *tzname) +{ + char buf[129]; + time_t tim; + struct tm *timtm; + + memset(buf, 0, sizeof(buf)); + settz(tzname); + tim = time(NULL); + timtm = localtime(&tim); + if (timtm == NULL) { + perror("localtime"); + exit(1); + } + + if (!strftime(buf, sizeof(buf)-1, fmt, timtm)) { + fprintf(stderr, "strftime == 0\n"); + exit(1); + } + + return smprintf("%s", buf); +} + +void setstatus(const char *str) +{ + XStoreName(dpy, DefaultRootWindow(dpy), str); + XSync(dpy, False); +} + +char* battery(void) +{ + int nmarks,full,now; + char *bar; + + FILE *battinfo = fopen("/sys/class/power_supply/BAT1/energy_full","r"); + fscanf(battinfo,"%d",&full); + fclose(battinfo); + battinfo = fopen("/sys/class/power_supply/BAT1/energy_now","r"); + fscanf(battinfo,"%d",&now); + fclose(battinfo); + + bar = (char*)malloc(sizeof(char) * 25); + nmarks = 10*now/full; + + if((double)now/full <= 0.05) { + strcpy(bar,"*** BATTERIE < 5% ***"); + } else { + strcpy(bar,"["); + for(int i = 1; i < 11; i++) { + if(i <= nmarks) + strcat(bar,"#"); + else + strcat(bar," "); + } + strcat(bar,"]"); + } + return bar; +} + +int main(void) +{ + char *status; + char *batt; + char *tmmtl; + char *tmgva; + + if (!(dpy = XOpenDisplay(NULL))) { + fprintf(stderr, "dwmstatus: cannot open display.\n"); + return 1; + } + + for (;;sleep(1)) { + batt = battery(); + tmmtl = mktimes(tmfmt, tzmtl); + tmgva = mktimes(tmfmt, tzgva); + + status = smprintf("%s | mtl: %s gva: %s", + batt,tmmtl,tmgva); + setstatus(status); + free(batt); + free(tmmtl); + free(status); + } + + XCloseDisplay(dpy); + + return 0; +} + diff --git a/pool/shard003/C/0067649_S+PPO846.c b/pool/shard003/C/0067649_S+PPO846.c new file mode 100644 index 0000000000000000000000000000000000000000..ac7121f7e98e2fd42acbfec1e280b7f9897456b1 --- /dev/null +++ b/pool/shard003/C/0067649_S+PPO846.c @@ -0,0 +1,64 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[3]; +atomic_int atom_1_r1_1; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); + + atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v3_cmpeq = (v2_r1 == v2_r1); + if (v3_cmpeq) goto lbl_LC00; else goto lbl_LC00; +lbl_LC00:; + atomic_store_explicit(&vars[2], 1, memory_order_seq_cst); + int v5_r5 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + atomic_store_explicit(&vars[2], 2, memory_order_seq_cst); + int v7_r7 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v9_r8 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v10_cmpeq = (v9_r8 == v9_r8); + if (v10_cmpeq) goto lbl_LC01; else goto lbl_LC01; +lbl_LC01:; + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + int v18 = (v2_r1 == 1); + atomic_store_explicit(&atom_1_r1_1, v18, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + + atomic_init(&vars[1], 0); + atomic_init(&vars[0], 0); + atomic_init(&vars[2], 0); + atomic_init(&atom_1_r1_1, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + + int v11 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v12 = (v11 == 2); + int v13 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v14 = (v13 == 2); + int v15 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v16_conj = v14 & v15; + int v17_conj = v12 & v16_conj; + if (v17_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard003/C/0067666_xanimjpeg.c b/pool/shard003/C/0067666_xanimjpeg.c new file mode 100644 index 0000000000000000000000000000000000000000..55736c6d822ce6d2ace5f5b336e18154657dd77e --- /dev/null +++ b/pool/shard003/C/0067666_xanimjpeg.c @@ -0,0 +1,154 @@ +#include "quicktime.h" +#include "jpeglib.h" +#include + +/* Attempt to use JPEG code from XAnim. */ +/* Ended up 10% slower than libjpeg. */ + +struct my_error_mgr { + struct jpeg_error_mgr pub; /* "public" fields */ + + jmp_buf setjmp_buffer; /* for return to caller */ +}; + +typedef struct my_error_mgr* my_error_ptr; + +METHODDEF(void) +my_error_exit (j_common_ptr cinfo) +{ + /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */ + my_error_ptr myerr = (my_error_ptr) cinfo->err; + + /* Always display the message. */ + /* We could postpone this until after returning, if we chose. */ + (*cinfo->err->output_message) (cinfo); + + /* Return control to the setjmp point */ + longjmp(myerr->setjmp_buffer, 1); +} + +int quicktime_init_codec_jpeg(quicktime_video_map_t *vtrack) +{ + vtrack->codecs.jpeg_codec.quality = 100; + vtrack->codecs.jpeg_codec.use_float = 0; + vtrack->codecs.jpeg_codec.chunk_buffer = 0; + vtrack->codecs.jpeg_codec.chunk_buffer_len = 0; + quicktime_fastjpg_init(&(vtrack->codecs.jpeg_codec.fastjpg)); +} + +int quicktime_delete_codec_jpeg(quicktime_video_map_t *vtrack) +{ + if(vtrack->codecs.jpeg_codec.chunk_buffer) + { + free(vtrack->codecs.jpeg_codec.chunk_buffer); + } + quicktime_fastjpg_delete(&(vtrack->codecs.jpeg_codec.fastjpg)); +} + +int quicktime_set_jpeg(quicktime_t *file, int quality, int use_float) +{ + int i; + char *compressor; + + for(i = 0; i < file->total_vtracks; i++) + { + if(quicktime_match_32(quicktime_video_compressor(file, i), QUICKTIME_JPEG)) + { + quicktime_jpeg_codec_t *codec = &(file->vtracks[i].codecs.jpeg_codec); + codec->quality = quality; + codec->use_float = use_float; + } + } +} + +int quicktime_decode_jpeg(quicktime_t *file, unsigned char **row_pointers, int track) +{ + int result = 0; + long i, chunk_size; + quicktime_trak_t *trak = file->vtracks[track].track; + char *chunk; + + if(file->vtracks[track].frames_cached) + { + chunk = file->vtracks[track].frame_cache[file->vtracks[track].current_position]; + chunk_size = quicktime_frame_size(file, file->vtracks[track].current_position, track); + } + else + { + chunk_size = quicktime_frame_size(file, file->vtracks[track].current_position, track); + if(file->vtracks[track].codecs.jpeg_codec.chunk_buffer) + { + if(file->vtracks[track].codecs.jpeg_codec.chunk_buffer_len < chunk_size) + { + free(file->vtracks[track].codecs.jpeg_codec.chunk_buffer); + file->vtracks[track].codecs.jpeg_codec.chunk_buffer = 0; + } + } + if(!file->vtracks[track].codecs.jpeg_codec.chunk_buffer) + { + file->vtracks[track].codecs.jpeg_codec.chunk_buffer = malloc(chunk_size); + file->vtracks[track].codecs.jpeg_codec.chunk_buffer_len = chunk_size; + } + chunk = file->vtracks[track].codecs.jpeg_codec.chunk_buffer; + quicktime_set_video_position(file, file->vtracks[track].current_position, track); + result = quicktime_read_data(file, chunk, chunk_size); + if(result) result = 0; else result = 1; + } + + result = quicktime_fastjpg_decode(chunk, + chunk_size, + row_pointers, + &(file->vtracks[track].codecs.jpeg_codec.fastjpg), + (int)trak->tkhd.track_width, + (int)trak->tkhd.track_height, + 0); + + return result; +} + +int quicktime_encode_jpeg(quicktime_t *file, unsigned char **row_pointers, int track) +{ + long offset = quicktime_position(file); + int result = 0; + int i; + quicktime_trak_t *trak = file->vtracks[track].track; + int height = trak->tkhd.track_height; + int width = trak->tkhd.track_width; + struct jpeg_compress_struct jpeg_compress; + struct jpeg_error_mgr jpeg_error; + JSAMPROW row_pointer[1]; + long bytes; + + jpeg_compress.err = jpeg_std_error(&jpeg_error); + jpeg_create_compress(&jpeg_compress); + jpeg_stdio_dest(&jpeg_compress, quicktime_get_fd(file)); + jpeg_compress.image_width = width; + jpeg_compress.image_height = height; + jpeg_compress.input_components = 3; + jpeg_compress.in_color_space = JCS_RGB; + jpeg_set_defaults(&jpeg_compress); + jpeg_set_quality(&jpeg_compress, file->vtracks[track].codecs.jpeg_codec.quality, 0); + if(file->vtracks[track].codecs.jpeg_codec.use_float) + jpeg_compress.dct_method = JDCT_FLOAT; + + jpeg_start_compress(&jpeg_compress, TRUE); + while(jpeg_compress.next_scanline < jpeg_compress.image_height) + { + row_pointer[0] = row_pointers[jpeg_compress.next_scanline]; + jpeg_write_scanlines(&jpeg_compress, row_pointer, 1); + } + jpeg_finish_compress(&jpeg_compress); + jpeg_destroy((j_common_ptr)&jpeg_compress); + + bytes = quicktime_position(file) - offset; + quicktime_update_tables(file, + file->vtracks[track].track, + offset, + file->vtracks[track].current_chunk, + file->vtracks[track].current_position, + 1, + bytes); + + file->vtracks[track].current_chunk++; + return result; +} diff --git a/pool/shard003/C/0067671_state.c b/pool/shard003/C/0067671_state.c new file mode 100644 index 0000000000000000000000000000000000000000..db833b0742a15a27fe72b4f80d0f9115b594268a --- /dev/null +++ b/pool/shard003/C/0067671_state.c @@ -0,0 +1,197 @@ +/* + * lxc: linux Container library + * + * (C) Copyright IBM Corp. 2007, 2008 + * + * Authors: + * Daniel Lezcano + * + * 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 + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "lxc.h" +#include "log.h" +#include "start.h" +#include "cgroup.h" +#include "monitor.h" +#include "commands.h" +#include "config.h" + +lxc_log_define(lxc_state, lxc); + +static const char * const strstate[] = { + "STOPPED", "STARTING", "RUNNING", "STOPPING", + "ABORTING", "FREEZING", "FROZEN", "THAWED", +}; + +const char *lxc_state2str(lxc_state_t state) +{ + if (state < STOPPED || state > MAX_STATE - 1) + return NULL; + return strstate[state]; +} + +lxc_state_t lxc_str2state(const char *state) +{ + size_t len; + lxc_state_t i; + len = sizeof(strstate)/sizeof(strstate[0]); + for (i = 0; i < len; i++) + if (!strcmp(strstate[i], state)) + return i; + + ERROR("invalid state '%s'", state); + return -1; +} + +lxc_state_t lxc_getstate(const char *name, const char *lxcpath) +{ + extern lxc_state_t freezer_state(const char *name, const char *lxcpath); + + lxc_state_t state = freezer_state(name, lxcpath); + if (state != FROZEN && state != FREEZING) + state = lxc_cmd_get_state(name, lxcpath); + return state; +} + +static int fillwaitedstates(const char *strstates, int *states) +{ + char *token, *saveptr = NULL; + char *strstates_dup = strdup(strstates); + int state; + + if (!strstates_dup) + return -1; + + token = strtok_r(strstates_dup, "|", &saveptr); + while (token) { + + state = lxc_str2state(token); + if (state < 0) { + free(strstates_dup); + return -1; + } + + states[state] = 1; + + token = strtok_r(NULL, "|", &saveptr); + } + free(strstates_dup); + return 0; +} + +extern int lxc_wait(const char *lxcname, const char *states, int timeout, const char *lxcpath) +{ + struct lxc_msg msg; + int state, ret; + int s[MAX_STATE] = { }, fd; + + if (fillwaitedstates(states, s)) + return -1; + + if (lxc_monitord_spawn(lxcpath)) + return -1; + + fd = lxc_monitor_open(lxcpath); + if (fd < 0) + return -1; + + /* + * if container present, + * then check if already in requested state + */ + ret = -1; + state = lxc_getstate(lxcname, lxcpath); + if (state < 0) { + goto out_close; + } else if ((state >= 0) && (s[state])) { + ret = 0; + goto out_close; + } + + for (;;) { + int elapsed_time, curtime = 0; + struct timeval tv; + int stop = 0; + int retval; + + if (timeout != -1) { + retval = gettimeofday(&tv, NULL); + if (retval) + goto out_close; + curtime = tv.tv_sec; + } + if (lxc_monitor_read_timeout(fd, &msg, timeout) < 0) { + /* try again if select interrupted by signal */ + if (errno != EINTR) + goto out_close; + } + + if (timeout != -1) { + retval = gettimeofday(&tv, NULL); + if (retval) + goto out_close; + elapsed_time = tv.tv_sec - curtime; + if (timeout - elapsed_time <= 0) + stop = 1; + timeout -= elapsed_time; + } + + if (strcmp(lxcname, msg.name)) { + if (stop) { + ret = -2; + goto out_close; + } + continue; + } + + switch (msg.type) { + case lxc_msg_state: + if (msg.value < 0 || msg.value >= MAX_STATE) { + ERROR("Receive an invalid state number '%d'", + msg.value); + goto out_close; + } + + if (s[msg.value]) { + ret = 0; + goto out_close; + } + break; + default: + if (stop) { + ret = -2; + goto out_close; + } + /* just ignore garbage */ + break; + } + } + +out_close: + lxc_monitor_close(fd); + return ret; +} diff --git a/pool/shard003/C/0067676_BigIntegerTest.c b/pool/shard003/C/0067676_BigIntegerTest.c new file mode 100644 index 0000000000000000000000000000000000000000..ef8ffd5b632b1c4be24b8cae2cf4563499a33308 --- /dev/null +++ b/pool/shard003/C/0067676_BigIntegerTest.c @@ -0,0 +1,132 @@ +#include +#include +#include "../BigIntegerOps.h" + +void setup(void) +{} + +void teardown(void) +{ +} + +START_TEST(test_isInteger) +{ + char* a = "12"; + char* b = "+1"; + char* c = "00"; + char* d = "-1"; + fail_unless(isInteger(a, 2) == 0, "12 should be an interger"); + fail_unless(isInteger(b, 2) == 0, "+1 should be an interger"); + fail_unless(isInteger(c, 2) == 0, "00 should be an interger"); + fail_unless(isInteger(d, 2) == 0, "-1 should be an interger"); +} +END_TEST + +START_TEST(test_integerMutiTenPow) +{ + char* a = "12"; + char* b = "-1"; + + int len = 0; + char* res1 = bigIntMutiTenPow(a, strlen(a), 2, &len); + fail_unless(res1 != NULL, "result should not null"); + fail_unless(strcmp(res1, "1200") == 0, "result should == 1200"); + free(res1); + + char* res2 = bigIntMutiTenPow(b, strlen(b), 2, &len); + fail_unless(res2 != NULL, "result should == -100"); + fail_unless(strcmp(res2, "-100") == 0, "result should == -100"); + free(res2); + + char* res3 = bigIntMutiTenPow(a, strlen(b), 0, &len); + fail_unless(res3 != NULL, "result should == 12"); + fail_unless(strcmp(res3, "12") == 0, "result should == 12"); + free(res3); +} +END_TEST + +START_TEST(test_integerMutiN) +{ + char *a = "12"; + int len = 0; + char* res1 = bigIntMultipleN(a, strlen(a), 9, &len); + fail_unless(res1 != NULL, "result should not null"); + fail_unless(strcmp(res1, "108") == 0, "result should == 108"); + free(res1); + + char* res2 = bigIntMultipleN(a, strlen(a), 0, &len); + fail_unless(res2 != NULL, "result should not null"); + fail_unless(strcmp(res2, "0") == 0, "result should == 0"); + free(res2); + +} +END_TEST + +START_TEST(test_integerMuti) +{ + char* a = "12"; + char* b = "12"; + char* c = "0"; + int len = 0; + char* res1 = bigIntMultiple(a, strlen(a), b, strlen(b), &len); + fail_unless(res1 != NULL, "result should not null"); + fail_unless(strcmp(res1, "144") == 0, "result should == 144"); + free(res1); + + char* res2 = bigIntMultiple(a, strlen(a), c, strlen(c), &len); + fail_unless(res2 != NULL, "result should not null"); + fail_unless(strcmp(res2, "0") == 0, "result should == 0"); + free(res2); +} +END_TEST + +START_TEST(test_integerDivide) +{ + char* a = "12345"; + char* b = "12"; + char* c = NULL; + int len = 0; + int modLen = 0; + char* res1 = bigIntDevide(a, strlen(a), b, strlen(b), &len, &c, &modLen); + fail_unless(res1 != NULL, "result should not null"); + fail_unless(strcmp(res1, "1028") == 0, "result should == 1028"); + fail_unless(c != NULL, "mod result should not null"); + fail_unless(strcmp(c, "9")== 0, "mod result should == 9"); + free(res1); + free(c); +} +END_TEST + +Suite* bigInteger_suit(void) +{ + Suite *s = suite_create("Test_BigInteger"); + + /* core test cases*/ + TCase *tc_core = tcase_create("Core"); + tcase_add_checked_fixture(tc_core, setup, teardown); + tcase_add_test(tc_core, test_isInteger); + + TCase *tc_calc = tcase_create("Calc"); + tcase_add_test(tc_calc, test_integerMutiTenPow); + tcase_add_test(tc_calc, test_integerMutiN); + tcase_add_test(tc_calc, test_integerMuti); + tcase_add_test(tc_calc, test_integerDivide); + + suite_add_tcase(s, tc_core); + suite_add_tcase(s, tc_calc); + + return s; +} + +int main(void) +{ + int number_failed = 0; + Suite*s = bigInteger_suit(); + SRunner* sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; +} + + diff --git a/pool/shard003/C/0067687_console-linux.c b/pool/shard003/C/0067687_console-linux.c new file mode 100644 index 0000000000000000000000000000000000000000..b02810ac105805ea3de7c1a2fd1973e19d893774 --- /dev/null +++ b/pool/shard003/C/0067687_console-linux.c @@ -0,0 +1,137 @@ +/** +******************************************************************************** +\file console-linux.c + +\brief Console input/output implementation for Linux + +This file contains the console input/output implementation for Linux. + +\ingroup module_console +*******************************************************************************/ + +/*------------------------------------------------------------------------------ +Copyright (c) 2014, Bernecker+Rainer Industrie-Elektronik Ges.m.b.H. (B&R) +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 COPYRIGHT HOLDERS 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 + +//============================================================================// +// P U B L I C F U N C T I O N S // +//============================================================================// + +//------------------------------------------------------------------------------ +/** +\brief Get character from console + +This function reads a character from the console input. It uses the +termios library. + +\return The function returns the read character. + +\ingroup module_console +*/ +//------------------------------------------------------------------------------ +int console_getch(void) +{ + struct termios oldt; + struct termios newt; + int ch; + + // Save old attributes + tcgetattr(STDIN_FILENO, &oldt); + + // Calculate and set new attributes + // ECHO ..... echo input key on/off + // ICANON ... line buffering on/off + newt = oldt; + newt.c_lflag &= ~(ICANON | ECHO); + tcsetattr(STDIN_FILENO, TCSANOW, &newt); + + // Read input key + ch = getchar(); + + // Restore old attributes + tcsetattr(STDIN_FILENO, TCSANOW, &oldt); + + return ch; +} + +//------------------------------------------------------------------------------ +/** +\brief Detecting a keystroke + +The function checks the console for a keystroke. + +\return The function returns 0 if no key has been pressed or 1 if a key has + been pressed. + +\ingroup module_console +*/ +//------------------------------------------------------------------------------ +int console_kbhit(void) +{ + struct termios oldt; + struct termios newt; + int oldf; + int newf; + int ch; + + // Save current attributes and file status + tcgetattr(STDIN_FILENO, &oldt); + oldf = fcntl(STDIN_FILENO, F_GETFL, 0); + + // Calculate new attributes and file status + newt = oldt; + newt.c_lflag &= ~(ICANON | ECHO); + newf = oldf | O_NONBLOCK; + + // Set new attributes and file status + tcsetattr(STDIN_FILENO, TCSANOW, &newt); + fcntl(STDIN_FILENO, F_SETFL, newf); + + // Read input + ch = getchar(); + + // Restore save attributes and file status + tcsetattr(STDIN_FILENO, TCSANOW, &oldt); + fcntl(STDIN_FILENO, F_SETFL, oldf); + + // Put read character back where it was taken + if (ch != EOF) + { + ungetc(ch, stdin); + return 1; + } + + return 0; +} + diff --git a/pool/shard003/C/0067702_lgwt_test.c b/pool/shard003/C/0067702_lgwt_test.c new file mode 100644 index 0000000000000000000000000000000000000000..a97e401a5da72f16f9adc2482c05a4da6fbe77ac --- /dev/null +++ b/pool/shard003/C/0067702_lgwt_test.c @@ -0,0 +1,83 @@ +// Test file for constructing a Legendre-Gauss quadrature rule +// +// Copyright (c) 2014, Christian B. Mendl +// All rights reserved. +// http://christian.mendl.net +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the Simplified BSD License +// http://www.opensource.org/licenses/bsd-license.php +// +// References: +// - Jianfeng Lu, Christian B. Mendl +// Numerical scheme for a spatially inhomogeneous matrix-valued quantum Boltzmann equation +// Journal of Computational Physics 291, 303-316 (2015) +// (arXiv:1408.1782) +// +// - Martin L.R. F"urst, Christian B. Mendl, Herbert Spohn +// Matrix-valued Boltzmann equation for the Hubbard chain +// Physical Review E 86, 031122 (2012) +// (arXiv:1207.6926) +//_______________________________________________________________________________________________________________________ +// + +#include "quadrature.h" +#include "util.h" +#include +#include + + +#if defined(_WIN32) & (defined(DEBUG) | defined(_DEBUG)) +#include +#endif + +#define V_RETURN(x) { hr = (x); if (hr < 0) { fprintf(stderr, "%s, line %d: command '%s' failed, return value: %d\n", __FILE__, __LINE__, #x, hr); return hr; } } + + +void LegendreGaussQuad(const unsigned int M, const double a, const double b, double *x, double *w); + + +int main() +{ + const unsigned int M = 15; + const double a = 0.5; + const double b = 2; + + unsigned int i; + int hr; + + // enable run-time memory check for debug builds + #if defined(_WIN32) & (defined(DEBUG) | defined(_DEBUG)) + _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); + #endif + + double *x = malloc(M * sizeof(double)); + double *w = malloc(M * sizeof(double)); + + printf("constructing a Legendre-Gauss quadrature rule...\n"); + LegendreGaussQuad(M, a, b, x, w); + + // load reference data from disk + double *x_ref = malloc(M * sizeof(double)); + double *w_ref = malloc(M * sizeof(double)); + V_RETURN(ReadData("../test/data/x_ref.dat", x_ref, sizeof(double), M)); + V_RETURN(ReadData("../test/data/w_ref.dat", w_ref, sizeof(double), M)); + + // compare with reference + double err = 0; + for (i = 0; i < M; i++) + { + err += fabs(x[i] - x_ref[i]) + fabs(w[i] - w_ref[i]); + } + printf("total error compared to reference: %g\n", err); + + // clean up + + free(w_ref); + free(x_ref); + + free(w); + free(x); + + return 0; +} \ No newline at end of file diff --git a/pool/shard003/C/0067710_err_disable3.c b/pool/shard003/C/0067710_err_disable3.c new file mode 100644 index 0000000000000000000000000000000000000000..53e335b9983164c9591ce21942eb6d0a77fd2ba4 --- /dev/null +++ b/pool/shard003/C/0067710_err_disable3.c @@ -0,0 +1,63 @@ + +/* Check that a child thread doesn't inherit its parent's disablement + status. */ + +#include +#include +#include +#include +#include // sleep + +#include "../include/valgrind.h" + +char* block = NULL; + +__attribute__((noinline)) void usechar ( char c ) +{ + // Spook gcc into believing mysterious bad things are + // happening behind its back, and that 'c' is definitely + // used in some (unknown) way. + __asm__ __volatile__("" : : "r"(c) : "memory","cc"); +} + +__attribute__((noinline)) void err ( void ) +{ + usechar( block[5] ); +} + +void* child_fn ( void* arg ) +{ + fprintf(stderr, "\n--------- c: start (expect 1) ---------\n\n"); + err(); + fprintf(stderr, "\n--------- c: end ---------\n\n"); + return NULL; +} + +int main ( void ) +{ + int r; + pthread_t child; + + block = malloc(10); + free(block); + + fprintf(stderr, "\n--------- p: disabling errors (expect 0) ---------\n\n"); + + VALGRIND_DISABLE_ERROR_REPORTING; + err(); + + fprintf(stderr, "\n--------- p: creating child ---------\n\n"); + + r = pthread_create(&child, NULL, child_fn, NULL); + assert(!r); + sleep(1); // let the child run first (determinism fix) + fprintf(stderr, "\n--------- p: join child ---------\n\n"); + r = pthread_join(child, NULL); + assert(!r); + + fprintf(stderr, "\n--------- p: re_enabled (expect 1) ---------\n\n"); + VALGRIND_ENABLE_ERROR_REPORTING; + err(); + + return 0; +} diff --git a/pool/shard003/C/0067726_main.c b/pool/shard003/C/0067726_main.c new file mode 100644 index 0000000000000000000000000000000000000000..cf16beb6d14c9191cacff77633945c5bebdf538b --- /dev/null +++ b/pool/shard003/C/0067726_main.c @@ -0,0 +1,124 @@ +#include +#include +#include +#include "binarytree.h" +#include "linkedlist.h" + +#define INPUT_ARG 1 +#define FILE_READ_ONLY "r" + +typedef int bool; +#define true 1 +#define false 0 + +static inline int char_to_num(int n); +static linked_list* build_list_from_file(FILE* file, bool reverse); + +int main(int argc, char** argv) { + if (argc < (INPUT_ARG + 1)) { + printf("***Missing input argument\n"); + return EXIT_FAILURE; + } + + FILE* file = fopen(argv[INPUT_ARG], FILE_READ_ONLY); + if (!file) { + printf("***File \"%s\" could not be found\n", argv[INPUT_ARG]); + fclose(file); + return EXIT_FAILURE; + } + + linked_list* in_order_list = build_list_from_file(file, false); + linked_list* post_order_list = build_list_from_file(file, true); + if (in_order_list->size != post_order_list->size || + in_order_list->size == 0 || post_order_list->size == 0) { + ll_delete(in_order_list); + ll_delete(post_order_list); + fclose(file); + printf("***the length of the inorder and post order traversal" + " in the input must be nonzero and equal."); + return EXIT_FAILURE; + } + + printf("inorder: "); + ll_print(in_order_list); + printf("postorder: "); + ll_print(post_order_list); + + binary_tree* btree = new_binary_tree(in_order_list, post_order_list); + bt_print(btree); + + fclose(file); + ll_delete(in_order_list); + free(in_order_list); + ll_delete(post_order_list); + free(post_order_list); + bt_delete(btree); + free(btree); + return EXIT_SUCCESS; +} + +int char_to_num(int n) { + assert(n >= 48 && n <= 57); + return n - 48; +} + +#define COMMA 44 +#define SPACE 32 +#define NEWLINE 10 +#define RETURN 13 +linked_list* build_list_from_file(FILE* file, bool reverse) { + linked_list* new_list = new_linked_list(); + int ch; + bool still_reading = true; + bool first_val_read = false; + int number = 0; + while (!first_val_read && still_reading && (ch = getc(file)) != EOF) { + switch(ch) { + case SPACE: + break; // ignore spaces + case RETURN: + case NEWLINE: + still_reading = false; + break; + case COMMA: + ll_init_add(new_list, number); + number = 0; + first_val_read = true; + break; + + // NUMBER ENCOUNTERED + default: + number = number*10 + char_to_num(ch); + } + } + while (still_reading && (ch = getc(file)) != EOF) { + switch(ch) { + case SPACE: + break; // ignore spaces + case RETURN: + case NEWLINE: + still_reading = false; + break; + case COMMA: + if (reverse) { + ll_add_to_head(new_list, number); + } + else { + ll_add_to_tail(new_list, number); + } + number = 0; + break; + + // NUMBER ENCOUNTERED + default: + number = number*10 + char_to_num(ch); + } + } + if (reverse) { + ll_add_to_head(new_list, number); + } + else { + ll_add_to_tail(new_list, number); + } + return new_list; +} diff --git a/pool/shard003/C/0067727_timidity.c b/pool/shard003/C/0067727_timidity.c new file mode 100644 index 0000000000000000000000000000000000000000..4f9178ed1e6ca1e2885df5508512504cf5821d47 --- /dev/null +++ b/pool/shard003/C/0067727_timidity.c @@ -0,0 +1,238 @@ +/* + * MOC - music on console + * Copyright (C) 2004 Damian Pietras + * + * libTiMidity-plugin Copyright (C) 2007 Hendrik Iben + * The hard work is done by the libTiMidity-Library written by + * Konstantin Korikov (http://libtimidity.sourceforge.net). + * I have merely hacked together a wrapper... + * + * 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. + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include // for toupper +#include +#include +#include + +#define DEBUG + +#include "common.h" +#include "io.h" +#include "decoder.h" +#include "log.h" +#include "files.h" +#include "options.h" + +MidSongOptions midioptions; + +struct timidity_data +{ + MidSong *midisong; + int length; + struct decoder_error error; +}; + +static struct timidity_data *make_timidity_data(const char *file) { + struct timidity_data *data; + + data = (struct timidity_data *)xmalloc (sizeof(struct timidity_data)); + + data->midisong = NULL; + decoder_error_init (&data->error); + + MidIStream *midistream = mid_istream_open_file(file); + + if(midistream==NULL) { + decoder_error(&data->error, ERROR_FATAL, 0, "Can't open midifile: %s", file); + return data; + } + + data->midisong = mid_song_load(midistream, &midioptions); + mid_istream_close(midistream); + + if(data->midisong==NULL) { + decoder_error(&data->error, ERROR_FATAL, 0, "Can't load midifile: %s", file); + return data; + } + + return data; +} + +static void *timidity_open (const char *file) +{ + struct timidity_data *data = make_timidity_data(file); + + if(data->midisong) { + data->length = mid_song_get_total_time(data->midisong); + } + + + if(data->midisong) { + debug ("Opened file %s", file); + + mid_song_set_volume(data->midisong, options_get_int("TiMidity_Volume")); + mid_song_start(data->midisong); + } + + return data; +} + +static void timidity_close (void *void_data) +{ + struct timidity_data *data = (struct timidity_data *)void_data; + + if (data->midisong) { + mid_song_free(data->midisong); + } + + decoder_error_clear (&data->error); + free (data); +} + +static void timidity_info (const char *file_name, struct file_tags *info, + const int tags_sel) +{ + struct timidity_data *data = make_timidity_data(file_name); + + if(data->midisong==NULL) { + free (data); + return; + } + + if(tags_sel & TAGS_TIME) { + info->time = mid_song_get_total_time(data->midisong) / 1000; + info->filled |= TAGS_TIME; + } + + timidity_close(data); +} + +static int timidity_seek (void *void_data, int sec) +{ + struct timidity_data *data = (struct timidity_data *)void_data; + + assert (sec >= 0); + + int ms = sec*1000; + + ms = MIN(ms,data->length); + + mid_song_seek(data->midisong, ms); + + return ms/1000; +} + +static int timidity_decode (void *void_data, char *buf, int buf_len, + struct sound_params *sound_params) +{ + struct timidity_data *data = (struct timidity_data *)void_data; + + sound_params->channels = midioptions.channels; + sound_params->rate = midioptions.rate; + sound_params->fmt = (midioptions.format==MID_AUDIO_S16LSB)?(SFMT_S16 | SFMT_LE):SFMT_S8; + + return mid_song_read_wave(data->midisong, buf, buf_len); +} + +static int timidity_get_bitrate (void *void_data ATTR_UNUSED) +{ + return -1; +} + +static int timidity_get_duration (void *void_data) +{ + struct timidity_data *data = (struct timidity_data *)void_data; + return data->length/1000; +} + +static void timidity_get_name (const char *file ATTR_UNUSED, char buf[4]) +{ + strcpy (buf, "MID"); +} + +static int timidity_our_format_ext(const char *ext) +{ + return !strcasecmp (ext, "MID"); +} + +static int timidity_our_format_mime (const char *mime) +{ + return !strcasecmp(mime, "audio/midi") + || !strncasecmp(mime, "audio/midi;", 10); +} + +static void timidity_get_error (void *prv_data, struct decoder_error *error) +{ + struct timidity_data *data = (struct timidity_data *)prv_data; + + decoder_error_copy (error, &data->error); +} + +static void timidity_destroy() +{ + mid_exit(); +} + +static struct decoder timidity_decoder = +{ + DECODER_API_VERSION, + NULL, + timidity_destroy, + timidity_open, + NULL, + NULL, + timidity_close, + timidity_decode, + timidity_seek, + timidity_info, + timidity_get_bitrate, + timidity_get_duration, + timidity_get_error, + timidity_our_format_ext, + timidity_our_format_mime, + timidity_get_name, + NULL, + NULL, + NULL +}; + +struct decoder *plugin_init () +{ + char *config; + int initresult; + + config = options_get_str("TiMidity_Config"); + if (config == NULL || strcasecmp(config, "yes") == 0) + initresult = mid_init(NULL); + else if (strcasecmp(config, "no") == 0) + initresult = mid_init_no_config(); + else + initresult = mid_init(config); + + // Is there a better way to signal failed init? + // The decoder-init-function may not return errors AFAIK... + if(initresult < 0) + { + if (config == NULL || strcasecmp(config, "yes") == 0) + config = ""; + fatal("TiMidity-Plugin: Error processing TiMidity-Configuration!\n" + " Configuration file is: %s", config); + return NULL; + } + + midioptions.rate = options_get_int("TiMidity_Rate"); + midioptions.format = (options_get_int("TiMidity_Bits")==16)?MID_AUDIO_S16LSB:MID_AUDIO_S8; + midioptions.channels = options_get_int("TiMidity_Channels"); + midioptions.buffer_size = midioptions.rate; + + return &timidity_decoder; +} diff --git a/pool/shard003/C/0067743_rwmdn.c b/pool/shard003/C/0067743_rwmdn.c new file mode 100644 index 0000000000000000000000000000000000000000..eebfed6df71894b52d99c4ea698d9da78bde8c0c --- /dev/null +++ b/pool/shard003/C/0067743_rwmdn.c @@ -0,0 +1,217 @@ +/* $NetBSD: rwmdn.c,v 1.1.1.4 2014/05/28 09:58:52 tron Exp $ */ + +/* rwmdn.c - massages dns */ +/* $OpenLDAP$ */ +/* This work is part of OpenLDAP Software . + * + * Copyright 1999-2014 The OpenLDAP Foundation. + * Portions Copyright 1999-2003 Howard Chu. + * Portions Copyright 2000-2003 Pierangelo Masarati. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted only as authorized by the OpenLDAP + * Public License. + * + * A copy of this license is available in the file LICENSE in the + * top-level directory of the distribution or, alternatively, at + * . + */ +/* ACKNOWLEDGEMENTS: + * This work was initially developed by Howard Chu for inclusion + * in OpenLDAP Software and subsequently enhanced by Pierangelo + * Masarati. + */ + + +#include "portable.h" + +#ifdef SLAPD_OVER_RWM + +#include + +#include +#include + +#include "slap.h" +#include "rwm.h" + +/* FIXME: after rewriting, we should also remap attributes ... */ + +/* + * massages "in" and normalizes it into "ndn" + * + * "ndn" may be untouched if no massaging occurred and its value was not null + */ +int +rwm_dn_massage_normalize( + dncookie *dc, + struct berval *in, + struct berval *ndn ) +{ + int rc; + struct berval mdn = BER_BVNULL; + + /* massage and normalize a DN */ + rc = rwm_dn_massage( dc, in, &mdn ); + if ( rc != LDAP_SUCCESS ) { + return rc; + } + + if ( mdn.bv_val == in->bv_val && !BER_BVISNULL( ndn ) ) { + return rc; + } + + rc = dnNormalize( 0, NULL, NULL, &mdn, ndn, NULL ); + + if ( mdn.bv_val != in->bv_val ) { + ch_free( mdn.bv_val ); + } + + return rc; +} + +/* + * massages "in" and prettifies it into "pdn" + * + * "pdn" may be untouched if no massaging occurred and its value was not null + */ +int +rwm_dn_massage_pretty( + dncookie *dc, + struct berval *in, + struct berval *pdn ) +{ + int rc; + struct berval mdn = BER_BVNULL; + + /* massage and pretty a DN */ + rc = rwm_dn_massage( dc, in, &mdn ); + if ( rc != LDAP_SUCCESS ) { + return rc; + } + + if ( mdn.bv_val == in->bv_val && !BER_BVISNULL( pdn ) ) { + return rc; + } + + rc = dnPretty( NULL, &mdn, pdn, NULL ); + + if ( mdn.bv_val != in->bv_val ) { + ch_free( mdn.bv_val ); + } + + return rc; +} + +/* + * massages "in" and prettifies and normalizes it into "pdn" and "ndn" + * + * "pdn" may be untouched if no massaging occurred and its value was not null; + * "ndn" may be untouched if no massaging occurred and its value was not null; + * if no massage occurred and "ndn" value was not null, it is filled + * with the normaized value of "pdn", much like ndn = dnNormalize( pdn ) + */ +int +rwm_dn_massage_pretty_normalize( + dncookie *dc, + struct berval *in, + struct berval *pdn, + struct berval *ndn ) +{ + int rc; + struct berval mdn = BER_BVNULL; + + /* massage, pretty and normalize a DN */ + rc = rwm_dn_massage( dc, in, &mdn ); + if ( rc != LDAP_SUCCESS ) { + return rc; + } + + if ( mdn.bv_val == in->bv_val && !BER_BVISNULL( pdn ) ) { + if ( BER_BVISNULL( ndn ) ) { + rc = dnNormalize( 0, NULL, NULL, &mdn, ndn, NULL ); + } + return rc; + } + + rc = dnPrettyNormal( NULL, &mdn, pdn, ndn, NULL ); + + if ( mdn.bv_val != in->bv_val ) { + ch_free( mdn.bv_val ); + } + + return rc; +} + +/* + * massages "in" into "dn" + * + * "dn" may contain the value of "in" if no massage occurred + */ +int +rwm_dn_massage( + dncookie *dc, + struct berval *in, + struct berval *dn +) +{ + int rc = 0; + struct berval mdn; + static char *dmy = ""; + char *in_val; + + assert( dc != NULL ); + assert( in != NULL ); + assert( dn != NULL ); + + /* protect from NULL berval */ + in_val = in->bv_val ? in->bv_val : dmy; + + rc = rewrite_session( dc->rwmap->rwm_rw, dc->ctx, + in_val, dc->conn, &mdn.bv_val ); + switch ( rc ) { + case REWRITE_REGEXEC_OK: + if ( !BER_BVISNULL( &mdn ) && mdn.bv_val != in_val ) { + mdn.bv_len = strlen( mdn.bv_val ); + *dn = mdn; + } else { + dn->bv_len = in->bv_len; + dn->bv_val = in_val; + } + rc = LDAP_SUCCESS; + + Debug( LDAP_DEBUG_ARGS, + "[rw] %s: \"%s\" -> \"%s\"\n", + dc->ctx, in_val, dn->bv_val ); + break; + + case REWRITE_REGEXEC_UNWILLING: + if ( dc->rs ) { + dc->rs->sr_err = LDAP_UNWILLING_TO_PERFORM; + dc->rs->sr_text = "Operation not allowed"; + } + rc = LDAP_UNWILLING_TO_PERFORM; + break; + + case REWRITE_REGEXEC_ERR: + if ( dc->rs ) { + dc->rs->sr_err = LDAP_OTHER; + dc->rs->sr_text = "Rewrite error"; + } + rc = LDAP_OTHER; + break; + } + + if ( mdn.bv_val == dmy ) { + BER_BVZERO( &mdn ); + } + + if ( dn->bv_val == dmy ) { + BER_BVZERO( dn ); + } + + return rc; +} + +#endif /* SLAPD_OVER_RWM */ diff --git a/pool/shard003/C/0067753_u_basic.c b/pool/shard003/C/0067753_u_basic.c new file mode 100644 index 0000000000000000000000000000000000000000..5ec108fd1e9fe0b7bce58e0ab7ba84beda46da93 --- /dev/null +++ b/pool/shard003/C/0067753_u_basic.c @@ -0,0 +1,93 @@ +/* gEDA - GPL Electronic Design Automation + * libgeda - gEDA's library + * Copyright (C) 1998, 1999, 2000 Kazu Hirata / Ales Hvezda + * Copyright (C) 1998-2010 Ales Hvezda + * Copyright (C) 1998-2010 gEDA Contributors (see ChangeLog for details) + * + * 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 +#ifdef HAVE_STRING_H +#include +#endif +#ifdef HAVE_STDLIB_H +#include +#endif + +#include "libgeda_priv.h" + +/*! \todo Finish function documentation!!! + * \brief + * \par Function Description + * + */ +/* the delimiter is what is passed in or spaces */ +/* count starts at zero */ +char *u_basic_breakup_string(char *string, char delimiter, int count) +{ + int i=0, j=0; + int internal_counter=0; + int done=FALSE; + char *return_value; + + g_return_val_if_fail ((string != NULL), + NULL); + + /* skip over any leading white space */ + while(string[i] == ' ' && !string[i]) { + i++; + } + + /* Allocate space for temp string storage (+1 for null character) */ + return_value = g_malloc(sizeof(char)*(strlen(string) + 1)); + + while(!done) { + + /* oops, ran out of string before we found what we were */ + /* looking for */ + if (i > strlen(string)) { + g_free(return_value); + return(NULL); + } + + /* skip over any leading white space */ + while(string[i] == ' ' && string[i] != '\0') { + i++; + } + + j = 0; + + /* Old forgiving parsing */ + /* while(string[i] != ',' && string[i] != ';' && */ + /* string[i] != ' ' && string[i] != '\0') {*/ + + while(string[i] != delimiter && string[i] != '\0') { + return_value[j] = string[i]; + i++; j++; + } + + if (internal_counter == count) { + done = TRUE; + } else { + internal_counter++; + i++; /* skip the offending character */ + } + } + + return_value[j] = '\0'; + return(return_value); +} diff --git a/pool/shard003/C/0067760_init.c b/pool/shard003/C/0067760_init.c new file mode 100644 index 0000000000000000000000000000000000000000..14c1e541451cad3cf23620a05b59afd3825856d3 --- /dev/null +++ b/pool/shard003/C/0067760_init.c @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * linux/arch/m68k/mm/init.c + * + * Copyright (C) 1995 Hamish Macdonald + * + * Contains common initialization routines, specific init code moved + * to motorola.c and sun3mmu.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#ifdef CONFIG_ATARI +#include +#endif +#include +#include + +/* + * ZERO_PAGE is a special page that is used for zero-initialized + * data and COW. + */ +void *empty_zero_page; +EXPORT_SYMBOL(empty_zero_page); + +#ifdef CONFIG_MMU + +int m68k_virt_to_node_shift; + +#ifdef CONFIG_DISCONTIGMEM +pg_data_t pg_data_map[MAX_NUMNODES]; +EXPORT_SYMBOL(pg_data_map); + +pg_data_t *pg_data_table[65]; +EXPORT_SYMBOL(pg_data_table); +#endif + +void __init m68k_setup_node(int node) +{ +#ifdef CONFIG_DISCONTIGMEM + struct m68k_mem_info *info = m68k_memory + node; + int i, end; + + i = (unsigned long)phys_to_virt(info->addr) >> __virt_to_node_shift(); + end = (unsigned long)phys_to_virt(info->addr + info->size - 1) >> __virt_to_node_shift(); + for (; i <= end; i++) { + if (pg_data_table[i]) + pr_warn("overlap at %u for chunk %u\n", i, node); + pg_data_table[i] = pg_data_map + node; + } +#endif + node_set_online(node); +} + +#else /* CONFIG_MMU */ + +/* + * paging_init() continues the virtual memory environment setup which + * was begun by the code in arch/head.S. + * The parameters are pointers to where to stick the starting and ending + * addresses of available kernel virtual memory. + */ +void __init paging_init(void) +{ + /* + * Make sure start_mem is page aligned, otherwise bootmem and + * page_alloc get different views of the world. + */ + unsigned long end_mem = memory_end & PAGE_MASK; + unsigned long max_zone_pfn[MAX_NR_ZONES] = { 0, }; + + high_memory = (void *) end_mem; + + empty_zero_page = memblock_alloc(PAGE_SIZE, PAGE_SIZE); + if (!empty_zero_page) + panic("%s: Failed to allocate %lu bytes align=0x%lx\n", + __func__, PAGE_SIZE, PAGE_SIZE); + + /* + * Set up SFC/DFC registers (user data space). + */ + set_fs (USER_DS); + + max_zone_pfn[ZONE_DMA] = end_mem >> PAGE_SHIFT; + free_area_init(max_zone_pfn); +} + +#endif /* CONFIG_MMU */ + +void free_initmem(void) +{ +#ifndef CONFIG_MMU_SUN3 + free_initmem_default(-1); +#endif /* CONFIG_MMU_SUN3 */ +} + +#if defined(CONFIG_MMU) && !defined(CONFIG_COLDFIRE) +#define VECTORS &vectors[0] +#else +#define VECTORS _ramvec +#endif + +static inline void init_pointer_tables(void) +{ +#if defined(CONFIG_MMU) && !defined(CONFIG_SUN3) && !defined(CONFIG_COLDFIRE) + int i, j; + + /* insert pointer tables allocated so far into the tablelist */ + init_pointer_table(kernel_pg_dir, TABLE_PGD); + for (i = 0; i < PTRS_PER_PGD; i++) { + pud_t *pud = (pud_t *)&kernel_pg_dir[i]; + pmd_t *pmd_dir; + + if (!pud_present(*pud)) + continue; + + pmd_dir = (pmd_t *)pgd_page_vaddr(kernel_pg_dir[i]); + init_pointer_table(pmd_dir, TABLE_PMD); + + for (j = 0; j < PTRS_PER_PMD; j++) { + pmd_t *pmd = &pmd_dir[j]; + pte_t *pte_dir; + + if (!pmd_present(*pmd)) + continue; + + pte_dir = (pte_t *)pmd_page_vaddr(*pmd); + init_pointer_table(pte_dir, TABLE_PTE); + } + } +#endif +} + +void __init mem_init(void) +{ + /* this will put all memory onto the freelists */ + memblock_free_all(); + init_pointer_tables(); + mem_init_print_info(NULL); +} diff --git a/pool/shard003/C/0067767_sigprocmask.c b/pool/shard003/C/0067767_sigprocmask.c new file mode 100644 index 0000000000000000000000000000000000000000..03db4dafbe4660bba8a572dce9d15a1e8267f12e --- /dev/null +++ b/pool/shard003/C/0067767_sigprocmask.c @@ -0,0 +1,86 @@ +/* Copyright (C) 1991-2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C 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. + + The GNU C 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 the GNU C Library; if not, see + . */ + +#include +#include +#include +#include +#include + +/* If SET is not NULL, modify the current set of blocked signals + according to HOW, which may be SIG_BLOCK, SIG_UNBLOCK or SIG_SETMASK. + If OSET is not NULL, store the old set of blocked signals in *OSET. */ +int +__sigprocmask (how, set, oset) + int how; + const sigset_t *set; + sigset_t *oset; +{ + struct hurd_sigstate *ss; + sigset_t old, new; + sigset_t pending; + + if (set != NULL) + new = *set; + + ss = _hurd_self_sigstate (); + + _hurd_sigstate_lock (ss); + + old = ss->blocked; + + if (set != NULL) + { + switch (how) + { + case SIG_BLOCK: + __sigorset (&ss->blocked, &ss->blocked, &new); + break; + + case SIG_UNBLOCK: + ss->blocked &= ~new; + break; + + case SIG_SETMASK: + ss->blocked = new; + break; + + default: + _hurd_sigstate_unlock (ss); + errno = EINVAL; + return -1; + } + + ss->blocked &= ~_SIG_CANT_MASK; + } + + pending = _hurd_sigstate_pending (ss) & ~ss->blocked; + + _hurd_sigstate_unlock (ss); + + if (oset != NULL) + *oset = old; + + if (pending) + /* Send a message to the signal thread so it + will wake up and check for pending signals. */ + __msg_sig_post (_hurd_msgport, 0, 0, __mach_task_self ()); + + return 0; +} + +weak_alias (__sigprocmask, sigprocmask) diff --git a/pool/shard003/C/0067773_CWE690_NULL_Deref_From_Return__struct_malloc_42.c b/pool/shard003/C/0067773_CWE690_NULL_Deref_From_Return__struct_malloc_42.c new file mode 100644 index 0000000000000000000000000000000000000000..c561987566ad5d335bbbf61a5ab1cdbd40f9b309 --- /dev/null +++ b/pool/shard003/C/0067773_CWE690_NULL_Deref_From_Return__struct_malloc_42.c @@ -0,0 +1,100 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE690_NULL_Deref_From_Return__struct_malloc_42.c +Label Definition File: CWE690_NULL_Deref_From_Return.free.label.xml +Template File: source-sinks-42.tmpl.c +*/ +/* + * @description + * CWE: 690 Unchecked Return Value To NULL Pointer + * BadSource: malloc Allocate data using malloc() + * Sinks: + * GoodSink: Check to see if the data allocation failed and if not, use data + * BadSink : Don't check for NULL and use data + * Flow Variant: 42 Data flow: data returned from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +static twoIntsStruct * badSource(twoIntsStruct * data) +{ + /* POTENTIAL FLAW: Allocate memory without checking if the memory allocation function failed */ + data = (twoIntsStruct *)malloc(1*sizeof(twoIntsStruct)); + return data; +} + +void CWE690_NULL_Deref_From_Return__struct_malloc_42_bad() +{ + twoIntsStruct * data; + data = NULL; /* Initialize data */ + data = badSource(data); + /* FLAW: Initialize memory buffer without checking to see if the memory allocation function failed */ + data[0].intOne = 1; + data[0].intTwo = 1; + printStructLine(&data[0]); + free(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +static twoIntsStruct * goodB2GSource(twoIntsStruct * data) +{ + /* POTENTIAL FLAW: Allocate memory without checking if the memory allocation function failed */ + data = (twoIntsStruct *)malloc(1*sizeof(twoIntsStruct)); + return data; +} + +/* goodB2G uses the BadSource with the GoodSink */ +static void goodB2G() +{ + twoIntsStruct * data; + data = NULL; /* Initialize data */ + data = goodB2GSource(data); + /* FIX: Check to see if the memory allocation function was successful before initializing the memory buffer */ + if (data != NULL) + { + data[0].intOne = 1; + data[0].intTwo = 1; + printStructLine(&data[0]); + free(data); + } +} + +void CWE690_NULL_Deref_From_Return__struct_malloc_42_good() +{ + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE690_NULL_Deref_From_Return__struct_malloc_42_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE690_NULL_Deref_From_Return__struct_malloc_42_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard003/C/0067775_tinytest_demo.c b/pool/shard003/C/0067775_tinytest_demo.c new file mode 100644 index 0000000000000000000000000000000000000000..c07f099791e8c409df51d4e86276beac2299af73 --- /dev/null +++ b/pool/shard003/C/0067775_tinytest_demo.c @@ -0,0 +1,264 @@ +/* tinytest_demo.c -- Copyright 2009-2012 Nick Mathewson + * + * 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 ``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 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. + */ + + +/* Welcome to the example file for tinytest! I'll show you how to set up + * some simple and not-so-simple testcases. */ + +/* Make sure you include these headers. */ +#include "tinytest.h" +#include "tinytest_macros.h" + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +/* ============================================================ */ + +/* First, let's see if strcmp is working. (All your test cases should be + * functions declared to take a single void * as an argument.) */ +void +test_strcmp(void *data) +{ + (void)data; /* This testcase takes no data. */ + + /* Let's make sure the empty string is equal to itself */ + if (strcmp("","")) { + /* This macro tells tinytest to stop the current test + * and go straight to the "end" label. */ + tt_abort_msg("The empty string was not equal to itself"); + } + + /* Pretty often, calling tt_abort_msg to indicate failure is more + heavy-weight than you want. Instead, just say: */ + tt_assert(strcmp("testcase", "testcase") == 0); + + /* Occasionally, you don't want to stop the current testcase just + because a single assertion has failed. In that case, use + tt_want: */ + tt_want(strcmp("tinytest", "testcase") > 0); + + /* You can use the tt_*_op family of macros to compare values and to + fail unless they have the relationship you want. They produce + more useful output than tt_assert, since they display the actual + values of the failing things. + + Fail unless strcmp("abc, "abc") == 0 */ + tt_int_op(strcmp("abc", "abc"), OP_EQ, 0); + + /* Fail unless strcmp("abc, "abcd") is less than 0 */ + tt_int_op(strcmp("abc", "abcd"), OP_LT, 0); + + /* Incidentally, there's a test_str_op that uses strcmp internally. */ + tt_str_op("abc", OP_LT, "abcd"); + + + /* Every test-case function needs to finish with an "end:" + label and (optionally) code to clean up local variables. */ + end: + ; +} + +/* ============================================================ */ + +/* Now let's mess with setup and teardown functions! These are handy if + you have a bunch of tests that all need a similar environment, and you + want to reconstruct that environment freshly for each one. */ + +/* First you declare a type to hold the environment info, and functions to + set it up and tear it down. */ +struct data_buffer { + /* We're just going to have couple of character buffer. Using + setup/teardown functions is probably overkill for this case. + + You could also do file descriptors, complicated handles, temporary + files, etc. */ + char buffer1[512]; + char buffer2[512]; +}; +/* The setup function needs to take a const struct testcase_t and return + void* */ +void * +setup_data_buffer(const struct testcase_t *testcase) +{ + struct data_buffer *db = malloc(sizeof(struct data_buffer)); + + /* If you had a complicated set of setup rules, you might behave + differently here depending on testcase->flags or + testcase->setup_data or even or testcase->name. */ + + /* Returning a NULL here would mean that we couldn't set up for this + test, so we don't need to test db for null. */ + return db; +} +/* The clean function deallocates storage carefully and returns true on + success. */ +int +clean_data_buffer(const struct testcase_t *testcase, void *ptr) +{ + struct data_buffer *db = ptr; + + if (db) { + free(db); + return 1; + } + return 0; +} +/* Finally, declare a testcase_setup_t with these functions. */ +struct testcase_setup_t data_buffer_setup = { + setup_data_buffer, clean_data_buffer +}; + + +/* Now let's write our test. */ +void +test_memcpy(void *ptr) +{ + /* This time, we use the argument. */ + struct data_buffer *db = ptr; + + /* We'll also introduce a local variable that might need cleaning up. */ + char *mem = NULL; + + /* Let's make sure that memcpy does what we'd like. */ + strcpy(db->buffer1, "String 0"); + memcpy(db->buffer2, db->buffer1, sizeof(db->buffer1)); + tt_str_op(db->buffer1, OP_EQ, db->buffer2); + + /* tt_mem_op() does a memcmp, as opposed to the strcmp in tt_str_op() */ + db->buffer2[100] = 3; /* Make the buffers unequal */ + tt_mem_op(db->buffer1, OP_LT, db->buffer2, sizeof(db->buffer1)); + + /* Now we've allocated memory that's referenced by a local variable. + The end block of the function will clean it up. */ + mem = strdup("Hello world."); + tt_assert(mem); + + /* Another rather trivial test. */ + tt_str_op(db->buffer1, OP_NE, mem); + + end: + /* This time our end block has something to do. */ + if (mem) + free(mem); +} + +void +test_timeout(void *ptr) +{ + time_t t1, t2; + (void)ptr; + t1 = time(NULL); +#ifdef _WIN32 + Sleep(5000); +#else + sleep(5); +#endif + t2 = time(NULL); + + tt_int_op(t2-t1, OP_GE, 4); + + tt_int_op(t2-t1, OP_LE, 6); + + end: + ; +} + +/* ============================================================ */ + +/* Now we need to make sure that our tests get invoked. First, you take + a bunch of related tests and put them into an array of struct testcase_t. +*/ + +struct testcase_t demo_tests[] = { + /* Here's a really simple test: it has a name you can refer to it + with, and a function to invoke it. */ + { "strcmp", test_strcmp, }, + + /* The second test has a flag, "TT_FORK", to make it run in a + subprocess, and a pointer to the testcase_setup_t that configures + its environment. */ + { "memcpy", test_memcpy, TT_FORK, &data_buffer_setup }, + + /* This flag is off-by-default, since it takes a while to run. You + * can enable it manually by passing +demo/timeout at the command line.*/ + { "timeout", test_timeout, TT_OFF_BY_DEFAULT }, + + /* The array has to end with END_OF_TESTCASES. */ + END_OF_TESTCASES +}; + +/* Next, we make an array of testgroups. This is mandatory. Unlike more + heavy-duty testing frameworks, groups can't nest. */ +struct testgroup_t groups[] = { + + /* Every group has a 'prefix', and an array of tests. That's it. */ + { "demo/", demo_tests }, + + END_OF_GROUPS +}; + +/* We can also define test aliases. These can be used for types of tests that + * cut across groups. */ +const char *alltests[] = { "+..", NULL }; +const char *slowtests[] = { "+demo/timeout", NULL }; +struct testlist_alias_t aliases[] = { + + { "ALL", alltests }, + { "SLOW", slowtests }, + + END_OF_ALIASES +}; + + +int +main(int c, const char **v) +{ + /* Finally, just call tinytest_main(). It lets you specify verbose + or quiet output with --verbose and --quiet. You can list + specific tests: + + tinytest-demo demo/memcpy + + or use a ..-wildcard to select multiple tests with a common + prefix: + + tinytest-demo demo/.. + + If you list no tests, you get them all by default, so that + "tinytest-demo" and "tinytest-demo .." mean the same thing. + + */ + tinytest_set_aliases(aliases); + return tinytest_main(c, v, groups); +} diff --git a/pool/shard003/C/0067777_bug3564104.c b/pool/shard003/C/0067777_bug3564104.c new file mode 100644 index 0000000000000000000000000000000000000000..494f8e41813b7d5f22abcfae3919425a1e9eac9c --- /dev/null +++ b/pool/shard003/C/0067777_bug3564104.c @@ -0,0 +1,57 @@ +/* + bug3564104.c +*/ + +#include + +#include + +#ifdef __SDCC +#pragma disable_warning 127 +#endif + +uintptr_t array[4]; + +int i; + +void g(const void *p) +{ + array[i++] = (uintptr_t)(p); +} + +void f1(uintptr_t base, const char *message) +{ + for(; *message; message++) + g((const void *)(base + *message * 8)); +} + +void f2(uintptr_t base, const char *message) +{ + for(; *message; message++) + { + volatile uintptr_t tmp = base + *message * 8; + g((const void *)(tmp)); + } +} + +void testBug(void) +{ + char a[] = {10, 20, 30, 40, 0}; + + i = 0; + f1(0, a); + + ASSERT(array[0] == 10 * 8); + ASSERT(array[1] == 20 * 8); + ASSERT(array[2] == 30 * 8); + ASSERT(array[3] == 40 * 8); + + i = 0; + f2(0, a); + + ASSERT(array[0] == 10 * 8); + ASSERT(array[1] == 20 * 8); + ASSERT(array[2] == 30 * 8); + ASSERT(array[3] == 40 * 8); +} + diff --git a/pool/shard003/C/0067782_gimpoperationscreenmode.c b/pool/shard003/C/0067782_gimpoperationscreenmode.c new file mode 100644 index 0000000000000000000000000000000000000000..54cf8d6d759bd305ba533053478d88c689680c99 --- /dev/null +++ b/pool/shard003/C/0067782_gimpoperationscreenmode.c @@ -0,0 +1,141 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995 Spencer Kimball and Peter Mattis + * + * gimpoperationscreenmode.c + * Copyright (C) 2008 Michael Natterer + * 2012 Ville Sokk + * + * 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 "config.h" + +#include + +#include "operations-types.h" + +#include "gimpoperationscreenmode.h" + + +static void gimp_operation_screen_mode_prepare (GeglOperation *operation); +static gboolean gimp_operation_screen_mode_process (GeglOperation *operation, + void *in_buf, + void *aux_buf, + void *aux2_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi, + gint level); + + +G_DEFINE_TYPE (GimpOperationScreenMode, gimp_operation_screen_mode, + GIMP_TYPE_OPERATION_POINT_LAYER_MODE) + + +static void +gimp_operation_screen_mode_class_init (GimpOperationScreenModeClass *klass) +{ + GeglOperationClass *operation_class; + GeglOperationPointComposer3Class *point_class; + + operation_class = GEGL_OPERATION_CLASS (klass); + point_class = GEGL_OPERATION_POINT_COMPOSER3_CLASS (klass); + + gegl_operation_class_set_keys (operation_class, + "name", "gimp:screen-mode", + "description", "GIMP screen mode operation", + NULL); + + operation_class->prepare = gimp_operation_screen_mode_prepare; + point_class->process = gimp_operation_screen_mode_process; +} + +static void +gimp_operation_screen_mode_init (GimpOperationScreenMode *self) +{ +} + +static void +gimp_operation_screen_mode_prepare (GeglOperation *operation) +{ + const Babl *format = babl_format ("R'G'B'A float"); + + gegl_operation_set_format (operation, "input", format); + gegl_operation_set_format (operation, "aux", format); + gegl_operation_set_format (operation, "aux2", babl_format ("Y float")); + gegl_operation_set_format (operation, "output", format); +} + +static gboolean +gimp_operation_screen_mode_process (GeglOperation *operation, + void *in_buf, + void *aux_buf, + void *aux2_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi, + gint level) +{ + gdouble opacity = GIMP_OPERATION_POINT_LAYER_MODE (operation)->opacity; + gfloat *in = in_buf; + gfloat *layer = aux_buf; + gfloat *mask = aux2_buf; + gfloat *out = out_buf; + const gboolean has_mask = mask != NULL; + + while (samples--) + { + gfloat comp_alpha, new_alpha; + + comp_alpha = MIN (in[ALPHA], layer[ALPHA]) * opacity; + if (has_mask) + comp_alpha *= *mask; + + new_alpha = in[ALPHA] + (1.0 - in[ALPHA]) * comp_alpha; + + if (comp_alpha && new_alpha) + { + gfloat ratio = comp_alpha / new_alpha; + gint b; + + for (b = RED; b < ALPHA; b++) + { + gfloat comp = 1.0 - (1.0 - in[b]) * (1.0 - layer[b]); + + out[b] = comp * ratio + in[b] * (1.0 - ratio); + } + } + else + { + gint b; + + for (b = RED; b < ALPHA; b++) + { + out[b] = in[b]; + } + } + + out[ALPHA] = in[ALPHA]; + + in += 4; + layer += 4; + out += 4; + + if (has_mask) + mask++; + } + + return TRUE; +} diff --git a/pool/shard003/C/0067790_news-source-soup.c b/pool/shard003/C/0067790_news-source-soup.c new file mode 100644 index 0000000000000000000000000000000000000000..fe362dc232344510add8b5f331ab97f78a118f94 --- /dev/null +++ b/pool/shard003/C/0067790_news-source-soup.c @@ -0,0 +1,225 @@ +/* news-source-soup.c + * + * Copyright (C) 2011 Christian Hergert + * + * 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 "news-debug.h" +#include "news-source-soup.h" + +G_DEFINE_TYPE(NewsSourceSoup, news_source_soup, NEWS_TYPE_SOURCE) + +struct _NewsSourceSoupPrivate +{ + SoupSession *session; + gchar *uri; +}; + +enum +{ + PROP_0, + PROP_URI, + LAST_PROP +}; + +static GParamSpec *gParamSpecs[LAST_PROP]; + +/* + * TODO: We need to make this use chunked reading so that we don't copy + * the buffer (nor need it fully in memory ever). + */ + +static void +message_cb (SoupSession *session, + SoupMessage *message, + gpointer user_data) +{ + GSimpleAsyncResult *simple = (GSimpleAsyncResult *)user_data; + GInputStream *memory; + gpointer data; + gsize len; + + ENTRY; + + g_assert(SOUP_IS_SESSION(session)); + g_assert(SOUP_IS_MESSAGE(message)); + g_assert(G_IS_SIMPLE_ASYNC_RESULT(simple)); + + if (SOUP_STATUS_IS_SUCCESSFUL(message->status_code)) { + len = message->response_body->length; + data = g_malloc(len); + memcpy(data, message->response_body->data, len); + memory = g_memory_input_stream_new_from_data(data, len, g_free); + g_simple_async_result_set_op_res_gpointer(simple, memory, NULL); + } + + g_simple_async_result_complete_in_idle(simple); + g_object_unref(simple); + + EXIT; +} + +static void +news_source_soup_fetch_async (NewsSource *source, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + NewsSourceSoup *soup = (NewsSourceSoup *)source; + GSimpleAsyncResult *simple; + NewsSourceSoupPrivate *priv; + SoupMessage *message; + + ENTRY; + + g_return_if_fail(NEWS_IS_SOURCE_SOUP(soup)); + + priv = soup->priv; + + simple = g_simple_async_result_new(G_OBJECT(source), callback, user_data, + news_source_soup_fetch_async); + message = soup_message_new("GET", priv->uri); + soup_session_queue_message(priv->session, message, message_cb, simple); + + EXIT; +} + +static GInputStream * +news_source_soup_fetch_finish (NewsSource *source, + GAsyncResult *result, + GError **error) +{ + NewsSourceSoup *soup = (NewsSourceSoup *)source; + GSimpleAsyncResult *simple = (GSimpleAsyncResult *)result; + GInputStream *stream; + + ENTRY; + + g_return_val_if_fail(NEWS_IS_SOURCE_SOUP(soup), FALSE); + g_return_val_if_fail(G_IS_SIMPLE_ASYNC_RESULT(simple), FALSE); + + stream = g_simple_async_result_get_op_res_gpointer(simple); + g_assert(!stream || G_IS_INPUT_STREAM(stream)); + + if (!stream) { + g_simple_async_result_propagate_error(simple, error); + } + + RETURN(stream); +} + +static void +news_source_soup_set_uri (NewsSourceSoup *soup, + const gchar *uri) +{ + NewsSourceSoupPrivate *priv; + + g_return_if_fail(NEWS_IS_SOURCE_SOUP(soup)); + + priv = soup->priv; + + g_free(priv->uri); + priv->uri = g_strdup(uri); + g_object_notify_by_pspec(G_OBJECT(soup), gParamSpecs[PROP_URI]); +} + +static void +news_source_soup_finalize (GObject *object) +{ + NewsSourceSoupPrivate *priv = NEWS_SOURCE_SOUP(object)->priv; + + ENTRY; + + g_free(priv->uri); + g_clear_object(&priv->session); + + G_OBJECT_CLASS(news_source_soup_parent_class)->finalize(object); + + EXIT; +} + +static void +news_source_soup_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec) +{ + NewsSourceSoup *soup = NEWS_SOURCE_SOUP(object); + + switch (prop_id) { + case PROP_URI: + g_value_set_string(value, soup->priv->uri); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); + } +} + +static void +news_source_soup_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec) +{ + NewsSourceSoup *soup = NEWS_SOURCE_SOUP(object); + + switch (prop_id) { + case PROP_URI: + news_source_soup_set_uri(soup, g_value_get_string(value)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); + } +} + +static void +news_source_soup_class_init (NewsSourceSoupClass *klass) +{ + GObjectClass *object_class; + NewsSourceClass *source_class; + + object_class = G_OBJECT_CLASS(klass); + object_class->finalize = news_source_soup_finalize; + object_class->get_property = news_source_soup_get_property; + object_class->set_property = news_source_soup_set_property; + g_type_class_add_private(object_class, sizeof(NewsSourceSoupPrivate)); + + source_class = NEWS_SOURCE_CLASS(klass); + source_class->fetch_async = news_source_soup_fetch_async; + source_class->fetch_finish = news_source_soup_fetch_finish; + + gParamSpecs[PROP_URI] = + g_param_spec_string("uri", + _("URI"), + _("The URI of the source."), + NULL, + G_PARAM_READWRITE); + g_object_class_install_property(object_class, PROP_URI, + gParamSpecs[PROP_URI]); +} + +static void +news_source_soup_init (NewsSourceSoup *soup) +{ + soup->priv = + G_TYPE_INSTANCE_GET_PRIVATE(soup, + NEWS_TYPE_SOURCE_SOUP, + NewsSourceSoupPrivate); + soup->priv->session = soup_session_async_new(); +} diff --git a/pool/shard003/C/0067791_camd-midi.c b/pool/shard003/C/0067791_camd-midi.c new file mode 100644 index 0000000000000000000000000000000000000000..5249f2116bcf0c373e31c4e2d69a76f22f72d717 --- /dev/null +++ b/pool/shard003/C/0067791_camd-midi.c @@ -0,0 +1,161 @@ +/*************************************************************************** + camd-midi.c Copyright (C) 2005--08 Walter van Niftrik, Christoph Reichenbach + + + This program may be modified and copied freely according to the terms of + the GNU general public license (GPL), as long as the above copyright + notice and the licensing information contained herein are preserved. + + Please refer to www.gnu.org for licensing details. + + This work is provided AS IS, without warranty of any kind, expressed or + implied, including but not limited to the warranties of merchantibility, + noninfringement, and fitness for a specific purpose. The author will not + be held liable for any damage caused by this work or derivatives of it. + + By using this source code, you agree to the licensing terms as stated + above. + + + Please contact the maintainer for bug reports or inquiries. + + Current Maintainer: + + Walter van Niftrik + +***************************************************************************/ + +#ifdef HAVE_CONFIG_H +# include +#endif +#ifdef HAVE_PROTO_CAMD_H + +#include "sfx_engine.h" +#include "sfx_device.h" + +#include +#include +#include +#include +#include + + +#define SWAP_BYTES +#define FILL_BYTES + +#define SCI_CAMD_MIDI_VERSION "0.1" +#define SYSEX_PREFIX 0xf0 + +static const char *devicename = "via686.out.0"; + +struct Library *CamdBase = NULL; +struct CamdIFace *ICamd = NULL; +static struct MidiLink *midi_link = NULL; +static struct MidiNode *midi_node = NULL; + +#define ABORT(m) { \ + if (CamdBase) \ + IExec->CloseLibrary(CamdBase); \ + sciprintf("[SFX] CAMD driver: "); \ + sciprintf(m); \ + sciprintf("\n"); \ + return SFX_ERROR; \ + } + +static int +camd_init(midi_writer_t *self) +{ + sciprintf("[SFX] Initialising CAMD raw MIDI backend, v%s\n", SCI_CAMD_MIDI_VERSION); + + CamdBase = IExec->OpenLibrary("camd.library", 36L); + if (!CamdBase) + ABORT("Could not open 'camd.library'"); + + ICamd = (struct CamdIFace *) IExec->GetInterface(CamdBase, "main", 1, NULL); + if (!ICamd) + ABORT("Error while retrieving CAMD interface\n"); + + midi_node = ICamd->CreateMidi(MIDI_MsgQueue, 0L, MIDI_SysExSize, 4096L, MIDI_Name, "freesci", TAG_END); + if (!midi_node) + ABORT("Could not create CAMD MIDI node"); + + midi_link = ICamd->AddMidiLink(midi_node, MLTYPE_Sender, MLINK_Location, devicename, TAG_END); + if (!midi_link) + ABORT(("Could not create CAMD MIDI link to '%s'", devicename)); + + sciprintf("[SFX] CAMD initialisation completed\n"); + + return SFX_OK; +} + +static int +camd_set_option(midi_writer_t *self, char *name, char *value) +{ + return SFX_ERROR; +} + +#define MAX_MIDI_LEN 3 + +static int +camd_write(midi_writer_t *self, unsigned char *buffer, int len) +{ + if (len == 0) + return SFX_OK; + + if (buffer[0] == SYSEX_PREFIX) { + /* Must send this as a SysEx */ + ICamd->PutSysEx(midi_link, buffer); + } else { + ULONG data = 0l; + int i; + int readlen = (len > MAX_MIDI_LEN) ? MAX_MIDI_LEN : len; + + for (i = 0; i < readlen; i++) + if (len >= i) { + data <<= 8; + data |= buffer[i]; + } + data <<= (8 * (sizeof(ULONG) - readlen)); + + if (len > MAX_MIDI_LEN) + sciprintf("[SFX] Warning: Truncated MIDI message to fit CAMD format (sent %d: %02x %02x %02x, real length %d)\n", + MAX_MIDI_LEN, buffer[0], buffer[1], buffer[2], len); + + ICamd->PutMidi(midi_link, data); + } + + return SFX_OK; +} + +static void +camd_delay(midi_writer_t *self, int ticks) +{ +} + +static void +camd_reset_timer(midi_writer_t *self) +{ +} + +static void +camd_close(midi_writer_t *self) +{ +#ifdef NO_OP + return; +#endif + if (CamdBase) + IExec->CloseLibrary(CamdBase); +} + +midi_writer_t sfx_device_midi_camd = { + "camd-midi", + &camd_init, + &camd_set_option, + &camd_write, + &camd_delay, + NULL, + &camd_reset_timer, + &camd_close +}; + +#endif /* HAVE_PROTO_CAMD_H */ diff --git a/pool/shard003/C/0067848_weightfunc.c b/pool/shard003/C/0067848_weightfunc.c new file mode 100644 index 0000000000000000000000000000000000000000..d7dbea3fb9f687fbefd7bf4086dbd3596815759c --- /dev/null +++ b/pool/shard003/C/0067848_weightfunc.c @@ -0,0 +1,264 @@ +/* + * engrave --- preparation of image files for adaptive screening + * in a conventional RIP (Raster Image Processor). + * + * Copyright (C) 2018 Yuri V. Kouznetsov, Paul A. Wolneykien. + * + * 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 + * . + * + * Contact information: + * + * The High Definition Screening project: + * . + * + * Yuri Kuznetsov +#include +#include "weightfunc.h" + +/** + * ÷ÅÓÏ×ÁÑ ÆÕÎËÃÉÑ ×ÅÒÔÉËÁÌØÎÏÊ ÌÉÎÉÉ. + */ +const unsigned char ortline[WEIGHTFUNC_LEN] = { + 0xdc, 0x87, 0x32, 0x07, 0x5c, 0xb2, + + 0xf2, 0x9c, 0x47, 0x1c, 0x72, 0xc7, + + 0xe4, 0x8e, 0x39, 0x0e, 0x64, 0xb9, + + 0xf9, 0xa4, 0x4e, 0x24, 0x79, 0xce, + + 0xeb, 0x95, 0x40, 0x15, 0x6b, 0xc0, + + 0xff, 0xab, 0x55, 0x2b, 0x80, 0xd5 +}; + +/** + * ÷ÅÓÏ×ÁÑ ÆÕÎËÃÉÑ ÄÉÁÇÏÎÁÌØÎÏÊ ÌÉÎÉÉ (NW--SE). + */ +const unsigned char dialine[WEIGHTFUNC_LEN] = { + 0x07, 0x55, 0x95, 0xc7, 0xeb, 0xff, + + 0x32, 0x1c, 0x6b, 0xa4, 0xd5, 0xf2, + + 0x79, 0x47, 0x0e, 0x5c, 0x9c, 0xce, + + 0xb2, 0x87, 0x39, 0x24, 0x72, 0xab, + + 0xdc, 0xc0, 0x80, 0x4e, 0x15, 0x64, + + 0xf9, 0xe4, 0xb9, 0x8e, 0x40, 0x2b +}; + +/** + * ÷ÅÒÔÉËÁÌØÎÙÊ ËÏÎÔÕÒ (W). + */ +const unsigned char ortcontour[WEIGHTFUNC_LEN] = { + 0x07, 0x32, 0x5c, 0x87, 0xb2, 0xdc, + + 0x1c, 0x47, 0x72, 0x9c, 0xc7, 0xf2, + + 0x0e, 0x39, 0x64, 0x8e, 0xb9, 0xe4, + + 0x24, 0x4e, 0x79, 0xa4, 0xce, 0xf9, + + 0x15, 0x40, 0x6b, 0x95, 0xc0, 0xeb, + + 0x2b, 0x55, 0x80, 0xab, 0xd5, 0xff +}; + +/** + * äÉÁÇÏÎÁÌØÎÙÊ ËÏÎÔÕÒ (SW). + */ +const unsigned char diacontour[WEIGHTFUNC_LEN] = { + 0x72, 0x9c, 0xc0, 0xdc, 0xf2, 0xff, + + 0x4e, 0x87, 0xb2, 0xce, 0xeb, 0xf9, + + 0x32, 0x64, 0x79, 0xa4, 0xc7, 0xe4, + + 0x1c, 0x40, 0x55, 0x8e, 0xb9, 0xd5, + + 0x0e, 0x2b, 0x39, 0x6b, 0x80, 0xab, + + 0x07, 0x15, 0x24, 0x47, 0x5c, 0x95 +}; + +/** + * äÉÁÇÏÎÁÌØÎÙÊ ÕÇÏÌ (NW). + */ +const unsigned char ortcorner[WEIGHTFUNC_LEN] = { + 0x07, 0x0e, 0x24, 0x47, 0x79, 0xb9, + + 0x15, 0x1c, 0x32, 0x64, 0xa4, 0xe4, + + 0x2b, 0x39, 0x40, 0x55, 0x87, 0xc7, + + 0x4e, 0x6b, 0x5c, 0x72, 0xb2, 0xf2, + + 0x80, 0x9c, 0x8e, 0xab, 0x95, 0xd5, + + 0xc0, 0xeb, 0xce, 0xf9, 0xdc, 0xff +}; + +/** + * âÏËÏ×ÏÊ ÕÇÏÌ (W). + */ +const unsigned char diacorner[WEIGHTFUNC_LEN] = { + 0x32, 0x64, 0x8e, 0xb9, 0xdc, 0xf9, + + 0x1c, 0x47, 0x72, 0x9c, 0xc7, 0xeb, + + 0x07, 0x15, 0x55, 0x80, 0xab, 0xd5, + + 0x0e, 0x2b, 0x39, 0x5c, 0x87, 0xb2, + + 0x24, 0x4e, 0x79, 0xa4, 0xce, 0xf2, + + 0x40, 0x6b, 0x95, 0xc0, 0xe4, 0xff +}; + +/** + * âÉÂÌÉÏÔÅËÁ ×ÅÓÏ×ÙÈ ÆÕÎËÃÉÊ ÔÁÊÌÏ×. + */ +unsigned char weightfuncs[WEIGHTFUNCS_COUNT][WEIGHTFUNC_LEN]; + + +static void copyweightfunc( unsigned char *dest, + const unsigned char *src, + int rotation ); + +/** + * éÎÉÃÉÁÌÉÚÉÒÕÅÔ ÂÉÂÌÉÏÔÅËÕ ×ÅÓÏ×ÙÈ ÆÕÎËÃÉÊ. + */ +void +weightfuncs_init () +{ + static int initialized = 0; + + if ( initialized ) return; + + copyweightfunc( weightfuncs[TILE_NL - 1], ortline, 0 ); + copyweightfunc( weightfuncs[TILE_WL - 1], ortline, -90 ); + copyweightfunc( weightfuncs[TILE_NWL - 1], dialine, 0 ); + copyweightfunc( weightfuncs[TILE_NEL - 1], dialine, -90 ); + copyweightfunc( weightfuncs[TILE_WS - 1], ortcontour, 0 ); + copyweightfunc( weightfuncs[TILE_NS - 1], ortcontour, -90 ); + copyweightfunc( weightfuncs[TILE_ES - 1], ortcontour, 180 ); + copyweightfunc( weightfuncs[TILE_SS - 1], ortcontour, 90 ); + copyweightfunc( weightfuncs[TILE_NES - 1], diacontour, 180 ); + copyweightfunc( weightfuncs[TILE_SES - 1], diacontour, 90 ); + copyweightfunc( weightfuncs[TILE_SWS - 1], diacontour, 0 ); + copyweightfunc( weightfuncs[TILE_NWS - 1], diacontour, -90 ); + copyweightfunc( weightfuncs[TILE_WC - 1], diacorner, 0 ); + copyweightfunc( weightfuncs[TILE_NC - 1], diacorner, -90 ); + copyweightfunc( weightfuncs[TILE_EC - 1], diacorner, 180 ); + copyweightfunc( weightfuncs[TILE_SC - 1], diacorner, 90 ); + copyweightfunc( weightfuncs[TILE_NWC - 1], ortcorner, 0 ); + copyweightfunc( weightfuncs[TILE_NEC - 1], ortcorner, -90 ); + copyweightfunc( weightfuncs[TILE_SEC - 1], ortcorner, 180 ); + copyweightfunc( weightfuncs[TILE_SWC - 1], ortcorner, 90 ); + + initialized = 1; +} + +/** + * ÷ÏÚ×ÒÁÝÁÅÔ ÍÁÓÓÉ× ×ÅÓÏ×ÙÈ ÚÎÁÞÅÎÉÊ ÐÏ ÎÏÍÅÒÕ ÔÁÊÌÁ. + */ +const unsigned char * +get_weight_func( unsigned char tile_index ) +{ + if ( tile_index <= WEIGHTFUNCS_COUNT ) { + return weightfuncs[tile_index - 1]; + } +} + +/** + * äÅÌÁÅÔ ÓÒÅÚ ×ÅÓÏ×ÏÊ ÆÕÎËÃÉÉ #tile_index ÐÏ ÕÒÏ×ÎÀ ÔÏÎÁ #tile_area + * É ÐÏÍÅÝÁÅÔ ÒÅÚÕÌØÔÁÔ × #tilebuf. + */ +void weight_func_apply( unsigned char *tilebuf, + unsigned char tile_index, + unsigned char tile_area ) +{ + if ( 0 == tile_area || TILE_EMPTY == tile_index ) { + memset( tilebuf, 0, WEIGHTFUNC_LEN ); + } else { + const unsigned char *weight_func = get_weight_func( tile_index ); + if ( !weight_func ) { + fprintf( stderr, "Error: Unable to get the weight function " + "of tile %d\n", tile_index ); + return; + } + + int x; + for ( x = 0; x < WEIGHTFUNC_LEN; x++ ) { + if ( weight_func[x] <= tile_area ) { + tilebuf[x] = 0xff; + } else { + tilebuf[x] = 0x00; + } + } + } +} + +static void +copyweightfunc( unsigned char *dest, const unsigned char *src, + int rotation ) +{ + int i, i0, j, j0; + + for (j = 0; j < TILEHEIGHT; j++) { + for (i = 0; i < TILEWIDTH; i++) { + switch ( rotation ) { + case 0: + j0 = j; + i0 = i; + break; + case 90: + j0 = i; + i0 = TILEWIDTH - j - 1; + break; + case 180: + case -180: + j0 = TILEHEIGHT - j - 1; + i0 = TILEWIDTH - i - 1; + break; + case -90: + j0 = TILEHEIGHT - i - 1; + i0 = j; + break; + default: + fprintf( stderr, "BUG: Illegal rotation: %i\n", + rotation ); + return; + } + dest[ j * TILEWIDTH + i ] = src[ j0 * TILEWIDTH + i0 ]; + } + } +} diff --git a/pool/shard003/C/0067852_duda_queue.c b/pool/shard003/C/0067852_duda_queue.c new file mode 100644 index 0000000000000000000000000000000000000000..a4f079b9672274845097b396bad531a3557cf381 --- /dev/null +++ b/pool/shard003/C/0067852_duda_queue.c @@ -0,0 +1,229 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + +/* Monkey HTTP Daemon + * ------------------ + * Copyright (C) 2001-2012, Eduardo Silva P. + * + * 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 Library 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 "MKPlugin.h" + +#include "duda.h" +#include "duda_event.h" +#include "duda_queue.h" +#include "duda_sendfile.h" +#include "duda_body_buffer.h" + +struct duda_queue_item *duda_queue_item_new(short int type) +{ + struct duda_queue_item *item; + + item = mk_api->mem_alloc(sizeof(struct duda_queue_item)); + if (!item) { + return NULL; + } + + item->type = type; + item->status = DUDA_QSTATUS_ACTIVE; + + return item; +} + +int duda_queue_add(struct duda_queue_item *item, struct mk_list *queue) +{ + mk_list_add(&item->_head, queue); + return 0; +} + +struct duda_queue_item *duda_queue_last(struct mk_list *queue) +{ + struct duda_queue_item *item; + + item = mk_list_entry_last(queue, struct duda_queue_item, _head); + return item; +} + +unsigned long duda_queue_length(struct mk_list *queue) +{ + long int length = 0; + struct mk_list *head; + struct duda_queue_item *entry; + struct duda_sendfile *entry_sf; + struct duda_body_buffer *entry_bb; + + mk_list_foreach(head, queue) { + entry = mk_list_entry(head, struct duda_queue_item, _head); + if (entry->type == DUDA_QTYPE_BODY_BUFFER) { + entry_bb = (struct duda_body_buffer *) entry->data; + length += entry_bb->buf->total_len; + } + else if(entry->type == DUDA_QTYPE_SENDFILE) { + entry_sf = (struct duda_sendfile *) entry->data; + length += entry_sf->pending_bytes; + } + } + + return length; +} + +int duda_queue_flush(duda_request_t *dr) +{ + int ret = -1; + int socket = dr->cs->socket; + short int is_registered; + unsigned long queue_len=0; + struct mk_list *head; + struct duda_queue_item *item; + + mk_list_foreach(head, &dr->queue_out) { + item = mk_list_entry(head, struct duda_queue_item, _head); + if (item->status == DUDA_QSTATUS_INACTIVE) { + continue; + } + + switch (item->type) { + case DUDA_QTYPE_BODY_BUFFER: + ret = duda_body_buffer_flush(socket, item->data); + break; + case DUDA_QTYPE_SENDFILE: + ret = duda_sendfile_flush(socket, item->data); + break; + } + + if (ret == 0) { + item->status = DUDA_QSTATUS_INACTIVE; + } + + is_registered = duda_queue_event_is_registered_write(dr); + queue_len = duda_queue_length(&dr->queue_out); + + if (queue_len > 0 && is_registered == MK_FALSE) { + duda_queue_event_register_write(dr); + } + else if (queue_len == 0 && is_registered == MK_TRUE) { + duda_queue_event_unregister_write(dr); + } + break; + } + + return queue_len; +} + +int duda_queue_free(struct mk_list *queue) +{ + struct mk_list *head, *temp; + struct duda_queue_item *item; + struct duda_sendfile *sf; + struct duda_body_buffer *bb; + + mk_list_foreach_safe(head, temp, queue) { + item = mk_list_entry(head, struct duda_queue_item, _head); + if (item->type == DUDA_QTYPE_BODY_BUFFER) { + bb = (struct duda_body_buffer *) item->data; + mk_api->iov_free(bb->buf); + mk_api->mem_free(bb); + } + else if(item->type == DUDA_QTYPE_SENDFILE) { + sf = (struct duda_sendfile *) item->data; + close(sf->fd); + mk_api->mem_free(sf); + } + item->data = NULL; + mk_list_del(head); + mk_api->mem_free(item); + } + + return 0; +} + + +int duda_queue_event_register_write(duda_request_t *dr) +{ + struct mk_list *list; + + list = pthread_getspecific(duda_global_events_write); + if (!list) { + return -1; + } + + mk_list_add(&dr->_head_events_write, list); + return 0; +} + +int duda_queue_event_unregister_write(duda_request_t *dr) +{ + struct mk_list *list, *head, *temp; + duda_request_t *entry; + + list = pthread_getspecific(duda_global_events_write); + mk_list_foreach_safe(head, temp, list) { + entry = mk_list_entry(head, duda_request_t, _head_events_write); + if (entry == dr) { + mk_list_del(&entry->_head_events_write); + pthread_setspecific(duda_global_events_write, list); + return 0; + } + } + + return -1; +} + +int duda_queue_event_is_registered_write(duda_request_t *dr) +{ + struct mk_list *list; + struct mk_list *head; + duda_request_t *entry; + + list = pthread_getspecific(duda_global_events_write); + mk_list_foreach(head, list) { + entry = mk_list_entry(head, duda_request_t, _head_events_write); + if (entry == dr) { + return MK_TRUE; + } + } + + return MK_FALSE; +} + +int duda_queue_event_write_callback(int sockfd) +{ + int ret = MK_PLUGIN_RET_CONTINUE; + struct mk_list *list, *temp, *head; + duda_request_t *entry; + + list = pthread_getspecific(duda_global_events_write); + mk_list_foreach_safe(head, temp, list) { + entry = mk_list_entry(head, duda_request_t, _head_events_write); + if (entry->cs->socket == sockfd) { + ret = duda_queue_flush(entry); + + if (ret > 0) { + return MK_PLUGIN_RET_EVENT_OWNED; + } + + if (duda_service_end(entry) == -1) { + return MK_PLUGIN_RET_EVENT_CLOSE; + } + else { + return MK_PLUGIN_RET_EVENT_OWNED; + } + + break; + } + } + + return MK_PLUGIN_RET_EVENT_CONTINUE; +} diff --git a/pool/shard003/C/0067858_lock.c b/pool/shard003/C/0067858_lock.c new file mode 100644 index 0000000000000000000000000000000000000000..098cde8df2bf2fa909f3889b7952d93898104a53 --- /dev/null +++ b/pool/shard003/C/0067858_lock.c @@ -0,0 +1,77 @@ +/* sdb - LGPLv3 - Copyright 2012-2014 - pancake */ + +#include +#include +#include +#include +#include "sdb.h" +#if WINDOWS +#include +#endif + +SDB_API const char *sdb_lock_file(const char *f) { + static char buf[128]; + size_t len; + if (!f || !*f) + return NULL; + len = strlen (f); + if (len+10>sizeof buf) + return NULL; + memcpy (buf, f, len); + strcpy (buf+len, ".lock"); + return buf; +} + +#define os_getpid() getpid() + +SDB_API int sdb_lock(const char *s) { + int fd; + char *pid, pidstr[64]; + if (!s) return 0; + fd = open (s, O_CREAT | O_TRUNC | O_WRONLY | O_EXCL, SDB_MODE); + if (fd==-1) + return 0; + pid = sdb_itoa (getpid(), pidstr, 10); + if (pid) { + if ((write (fd, pid, strlen (pid)) < 0) + || (write (fd, "\n", 1) < 0)) { + close (fd); + return 0; + } + } + close (fd); + return 1; +} + +SDB_API int sdb_lock_wait(const char *s) { + // TODO use flock() here + // wait forever here? + while (!sdb_lock (s)) { + // TODO: if waiting too much return 0 +#if WINDOWS + Sleep (500); // hack +#else + // TODO use lockf() here .. flock is not much useful (fd, LOCK_EX); + sleep (1); // hack +#endif + } + return 1; +} + +SDB_API void sdb_unlock(const char *s) { + //flock (fd, LOCK_UN); + unlink (s); +} + +#if TEST +main () { + int r; + r = sdb_lock (".lock"); + printf ("%d\n", r); + r = sdb_lock (".lock"); + printf ("%d\n", r); + sdb_unlock (".lock"); + r = sdb_lock (".lock"); + printf ("%d\n", r); +} +#endif diff --git a/pool/shard003/C/0067873_pattern_manager.c b/pool/shard003/C/0067873_pattern_manager.c new file mode 100644 index 0000000000000000000000000000000000000000..d90a801ec1a382ebe20c4a21b40b851f8f0fe7bf --- /dev/null +++ b/pool/shard003/C/0067873_pattern_manager.c @@ -0,0 +1,78 @@ + +static void touch_simple(char *addr) +{ + /* Notice the function reads and then writes*/ + if(*addr != 0xf) { + *addr = 0xf; + } + else { + *addr = 0x00; + } +} + +/* + * For FIX to work we need a static structure + * that book keeps the same element within + * the addr range. + * + * Following is a simple disjoint linear list that + * keeps track of the previous access point. + * TODO: Make it a self balancing tree eg: AVL. + */ +typedef struct __fix_bookeeper_node { + char *addr; + lt_t loc; +}fix_bk_node; +typedef struct __fix_bookeeper { + fix_bk_node node; + struct __fix_bookeeper *nxt; +}fix_bookeeper; + +static fix_bookeeper *fix_head = NULL; + +static fix_bk_node* fix_exists(char *const addr) +{ + fix_bookeeper *iter = fix_head; + + while(iter) { + if(addr == iter->node.addr) + break; + iter = iter->nxt; + } + + if(iter) { + return &(iter->node); + } + return NULL; +} + +static fix_bk_node* fix_alloc_node(char *addr) +{ + fix_bookeeper *b = malloc(sizeof(*b)); + if(b) { + b->node.addr = addr; + b->node.loc = 0; + b->nxt = fix_head; + fix_head = b; + } + return &(b->node); +} + +void pattern_fix(char *addr1, lt_t len) +{ + char *addr = (char*)addr1; + fix_bk_node *node; + + if(!addr || !len) { + PR_ERROR("%s: addr: %p len: %lld\n", addr, len); + goto fin; + } + + if(!(node = fix_exists(addr))) { + node = fix_alloc_node(addr) + } + touch_simple(node->addr); +fin: + return; +} + diff --git a/pool/shard003/C/0067891_idt.c b/pool/shard003/C/0067891_idt.c new file mode 100644 index 0000000000000000000000000000000000000000..26e80449c5050c56ad5b0f52c68845117f8c98fe --- /dev/null +++ b/pool/shard003/C/0067891_idt.c @@ -0,0 +1,51 @@ +#include +#include +#include +/* Declare an IDT of 256 entries. Although we will only use the +* first 32 entries in this tutorial, the rest exists as a bit +* of a trap. If any undefined IDT entry is hit, it normally +* will cause an "Unhandled Interrupt" exception. Any descriptor +* for which the 'presence' bit is cleared (0) will generate an +* "Unhandled Interrupt" exception */ +idt_entry idt[256]; +idt_ptr idtp; + +/* This exists in 'start.asm', and is used to load our IDT */ +extern "C" void idt_load(); + +/* Use this function to set an entry in the IDT. Alot simpler +* than twiddling with the GDT ;) */ +void idt_set_gate(unsigned char num, unsigned long base, unsigned short sel, unsigned char flags) +{ + /* We'll leave you to try and code this function: take the + * argument 'base' and split it up into a high and low 16-bits, + * storing them in idt[num].base_hi and base_lo. The rest of the + * fields that you must set in idt[num] are fairly self- + * explanatory when it comes to setup */ + /* The interrupt routine's base address */ + idt[num].base_lo = (base & 0xFFFF); + idt[num].base_hi = (base >> 16) & 0xFFFF; + + /* The segment or 'selector' that this IDT entry will use + * is set here, along with any access flags */ + idt[num].sel = sel; + idt[num].always0 = 0; + idt[num].flags = flags; +} + +/* Installs the IDT */ +void idt_install() +{ + /* Sets the special IDT pointer up, just like in 'gdt.c' */ + idtp.limit = (sizeof (struct idt_entry) * 256) - 1; + idtp.base = (unsigned int)&idt; + + /* Clear out the entire IDT, initializing it to zeros */ + memset(&idt, 0, sizeof(struct idt_entry) * 256); + idt_set_gate(0, (unsigned int)isr0, 0x08, 0x8e) ; + idt_set_gate(0, (unsigned int)isr8, 0x08, 0x8e) ; + /* Add any new ISRs to the IDT here using idt_set_gate */ + + /* Points the processor's internal register to the new IDT */ + idt_load(); +} diff --git a/pool/shard003/C/0067916_impath.c b/pool/shard003/C/0067916_impath.c new file mode 100644 index 0000000000000000000000000000000000000000..368d6f04fc56ffdced3d504e683b46d83da6b53e --- /dev/null +++ b/pool/shard003/C/0067916_impath.c @@ -0,0 +1,75 @@ +/**@file impath.c + * @brief >> shortest path for stack + * @author Ting Zhao + * @date 25-Nov-2008 + */ + +#include +#include +#include +#include "tz_utilities.h" +#include "tz_darray.h" +#include "tz_iarray.h" +#include "tz_graph.h" +#include "tz_arrayqueue.h" +#include "tz_graph_utils.h" +#include "tz_unipointer_linked_list.h" +#include "tz_stack_graph.h" +#include "tz_stack_utils.h" +#include "tz_image_lib_defs.h" +#include "tz_stack_lib.h" +#include "tz_utilities.h" + +/* + * impath from to imagefile -o out + */ + +int main(int argc, char *argv[]) +{ + static char *Spec[] = {"-from -to ", + " -o ", + NULL}; + Process_Arguments(argc, argv, Spec, 1); + + int start[3]; + int end[3]; + start[0] = Get_Int_Arg("-from", 1); + start[1] = Get_Int_Arg("-from", 2); + start[2] = Get_Int_Arg("-from", 3); + + end[0] = Get_Int_Arg("-to", 1); + end[1] = Get_Int_Arg("-to", 2); + end[2] = Get_Int_Arg("-to", 3); + + Stack *stack = Read_Stack(Get_String_Arg("image")); + Stack *stack2 = Copy_Stack(stack); + + Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace(); + sgw->conn = 26; + sgw->wf = Stack_Voxel_Weight_R; + + Stack_Graph_Workspace_Set_Range_M(sgw, start[0], end[0], start[1], end[1], + start[2], end[2], 10, 10, 10, 10, 10, 10); + + Int_Arraylist *offset_path = + Stack_Route(stack, start, end, sgw); + + Stack *canvas = Translate_Stack(stack2, COLOR, 0); + Image_Array ima; + ima.array = canvas->array; + + int i; + for (i = 0; i < offset_path->length; i++) { + int index = offset_path->array[i]; + ima.arrayc[index][0] = 255; + ima.arrayc[index][1] = 0; + ima.arrayc[index][2] = 0; + } + + Kill_Stack_Graph_Workspace(sgw); + Kill_Int_Arraylist(offset_path); + + Write_Stack("../data/test.tif", canvas); + + return 0; +} diff --git a/pool/shard003/C/0067942_basics_mem.c b/pool/shard003/C/0067942_basics_mem.c new file mode 100644 index 0000000000000000000000000000000000000000..6e638ff35ef8ff36c527fd39ca97419cbf642b41 --- /dev/null +++ b/pool/shard003/C/0067942_basics_mem.c @@ -0,0 +1,84 @@ +/* C example that opens a game music file and records 10 seconds to "out.wav" */ + +#include "gme/gme.h" + +#include "Wave_Writer.h" /* wave_ functions for writing sound file */ +#include +#include + +void handle_error( const char* str ); + +char * dump_file(const char*file_path, size_t *size) +{ + FILE *in = fopen(file_path, "rb"); + char *buffer = NULL; + if (!in) + return NULL; + fseek(in, 0, SEEK_END); + (*size) = (size_t)ftell(in); + fseek(in, 0, SEEK_SET); + buffer = (char*)malloc(*size); + fread(buffer, 1, *size, in); + return buffer; +} + +int main(int argc, char *argv[]) +{ + const char *filename = "test.vgz"; /* Default file to open */ + if ( argc >= 2 ) + filename = argv[1]; + + int sample_rate = 44100; /* number of samples per second */ + /* index of track to play (0 = first) */ + int track = argc >= 3 ? atoi(argv[2]) : 0; + + size_t file_size = 0; + char *file_data = dump_file(filename, &file_size); + if (!file_data) + { + printf( "Error: Can't dump %s!\n", filename ); + exit( EXIT_FAILURE ); + } + + /* Open music file in new emulator */ + Music_Emu* emu; + handle_error( gme_open_data(file_data, (long)file_size, &emu, sample_rate) ); + /* File dump is no more needed */ + free(file_data); + + /* Start track */ + handle_error( gme_start_track( emu, track ) ); + + /* Begin writing to wave file */ + wave_open( sample_rate, "out.wav" ); + wave_enable_stereo(); + + /* Record 10 seconds of track */ + while ( gme_tell( emu ) < 10 * 1000L ) + { + /* Sample buffer */ + #define buf_size 1024 /* can be any multiple of 2 */ + short buf [buf_size]; + + /* Fill sample buffer */ + handle_error( gme_play( emu, buf_size, buf ) ); + + /* Write samples to wave file */ + wave_write( buf, buf_size ); + } + + /* Cleanup */ + gme_delete( emu ); + wave_close(); + + return 0; +} + +void handle_error( const char* str ) +{ + if ( str ) + { + printf( "Error: %s\n", str ); getchar(); + exit( EXIT_FAILURE ); + } +} diff --git a/pool/shard003/C/0067963_testmessage.c b/pool/shard003/C/0067963_testmessage.c new file mode 100644 index 0000000000000000000000000000000000000000..33046236263cb4c6d50df8099fcfb98dabd7ca6d --- /dev/null +++ b/pool/shard003/C/0067963_testmessage.c @@ -0,0 +1,186 @@ +/* + Copyright (C) 1997-2013 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely. +*/ + +/* Simple test of the SDL MessageBox API*/ + +#include +#include +#include + +#include "SDL.h" +#include "SDL_thread.h" + +static int alive = 0; + +/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */ +static void +quit(int rc) +{ + SDL_Quit(); + exit(rc); +} + +static int +button_messagebox(void *eventNumber) +{ + const SDL_MessageBoxButtonData buttons[] = { + { + SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, + 0, + "OK" + },{ + SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, + 1, + "Cancel" + }, + }; + + SDL_MessageBoxData data = { + SDL_MESSAGEBOX_INFORMATION, + NULL, // no parent window + "Custom MessageBox", + "This is a custom messagebox", + 2, + buttons, + NULL // Default color scheme + }; + + int button = -1; + int success = 0; + if (eventNumber) { + data.message = "This is a custom messagebox from a background thread."; + } + + success = SDL_ShowMessageBox(&data, &button); + if (success == -1) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError()); + if (eventNumber) { + SDL_UserEvent event; + event.type = (intptr_t)eventNumber; + SDL_PushEvent((SDL_Event*)&event); + return 1; + } else { + quit(2); + } + } + SDL_Log("Pressed button: %d, %s\n", button, button == 1 ? "Cancel" : "OK"); + + if (eventNumber) { + SDL_UserEvent event; + event.type = (intptr_t)eventNumber; + SDL_PushEvent((SDL_Event*)&event); + } + + return 0; +} + +int +main(int argc, char *argv[]) +{ + int success; + + /* Enable standard application logging */ + SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); + + success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, + "Simple MessageBox", + "This is a simple error MessageBox", + NULL); + if (success == -1) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError()); + quit(1); + } + + success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, + "Simple MessageBox", + "This is a simple MessageBox with a newline:\r\nHello world!", + NULL); + if (success == -1) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError()); + quit(1); + } + + /* Google says this is Traditional Chinese for "beef with broccoli" */ + success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, + "UTF-8 Simple MessageBox", + "Unicode text: '牛肉西蘭花' ...", + NULL); + if (success == -1) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError()); + quit(1); + } + + /* Google says this is Traditional Chinese for "beef with broccoli" */ + success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, + "UTF-8 Simple MessageBox", + "Unicode text and newline:\r\n'牛肉西蘭花'\n'牛肉西蘭花'", + NULL); + if (success == -1) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError()); + quit(1); + } + + button_messagebox(NULL); + + /* Test showing a message box from a background thread. + + On Mac OS X, the video subsystem needs to be initialized for this + to work, since the message box events are dispatched by the Cocoa + subsystem on the main thread. + */ + if (SDL_Init(SDL_INIT_VIDEO) < 0) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL video subsystem: %s\n", SDL_GetError()); + return (1); + } + { + int status = 0; + SDL_Event event; + intptr_t eventNumber = SDL_RegisterEvents(1); + SDL_Thread* thread = SDL_CreateThread(&button_messagebox, "MessageBox", (void*)eventNumber); + + while (SDL_WaitEvent(&event)) + { + if (event.type == eventNumber) { + break; + } + } + + SDL_WaitThread(thread, &status); + + SDL_Log("Message box thread return %i\n", status); + } + + /* Test showing a message box with a parent window */ + { + SDL_Event event; + SDL_Window *window = SDL_CreateWindow("Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0); + + success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, + "Simple MessageBox", + "This is a simple error MessageBox with a parent window", + window); + if (success == -1) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError()); + quit(1); + } + + while (SDL_WaitEvent(&event)) + { + if (event.type == SDL_QUIT || event.type == SDL_KEYUP) { + break; + } + } + } + + SDL_Quit(); + return (0); +} diff --git a/pool/shard003/C/0067971_rs.c b/pool/shard003/C/0067971_rs.c new file mode 100644 index 0000000000000000000000000000000000000000..c54f9de1e317817c7aba633dea765002c2ca38c8 --- /dev/null +++ b/pool/shard003/C/0067971_rs.c @@ -0,0 +1,80 @@ + +#define _SYSTEM 1 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "glo.h" +#include "proto.h" +#include "util.h" +#include "region.h" + +/*===========================================================================* + * do_rs_set_priv * + *===========================================================================*/ +PUBLIC int do_rs_set_priv(message *m) +{ + int r, n, nr; + struct vmproc *vmp; + + nr = m->VM_RS_NR; + + if ((r = vm_isokendpt(nr, &n)) != OK) { + printf("do_rs_set_priv: message from strange source %d\n", nr); + return EINVAL; + } + + vmp = &vmproc[n]; + + if (m->VM_RS_BUF) { + r = sys_datacopy(m->m_source, (vir_bytes) m->VM_RS_BUF, + SELF, (vir_bytes) vmp->vm_call_mask, + sizeof(vmp->vm_call_mask)); + if (r != OK) + return r; + } + + return OK; +} + +/*===========================================================================* + * do_rs_update * + *===========================================================================*/ +PUBLIC int do_rs_update(message *m_ptr) +{ + endpoint_t src_e, dst_e; + int r; + + src_e = m_ptr->VM_RS_SRC_ENDPT; + dst_e = m_ptr->VM_RS_DST_ENDPT; + + /* Let the kernel do the update first. */ + r = sys_update(src_e, dst_e); + if(r != OK) { + return r; + } + + /* Do the update in VM now. */ + r = swap_proc(src_e, dst_e); + + return r; +} + diff --git a/pool/shard003/C/0067986_bptree.c b/pool/shard003/C/0067986_bptree.c new file mode 100644 index 0000000000000000000000000000000000000000..a0c90cc4d939e19f28f06883ac81faea2056dfe9 --- /dev/null +++ b/pool/shard003/C/0067986_bptree.c @@ -0,0 +1,225 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + +/* + * Copyright (c) 2012 by Delphix. All rights reserved. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * A bptree is a queue of root block pointers from destroyed datasets. When a + * dataset is destroyed its root block pointer is put on the end of the pool's + * bptree queue so the dataset's blocks can be freed asynchronously by + * dsl_scan_sync. This allows the delete operation to finish without traversing + * all the dataset's blocks. + * + * Note that while bt_begin and bt_end are only ever incremented in this code, + * they are effectively reset to 0 every time the entire bptree is freed because + * the bptree's object is destroyed and re-created. + */ + +struct bptree_args { + bptree_phys_t *ba_phys; /* data in bonus buffer, dirtied if freeing */ + boolean_t ba_free; /* true if freeing during traversal */ + + bptree_itor_t *ba_func; /* function to call for each blockpointer */ + void *ba_arg; /* caller supplied argument to ba_func */ + dmu_tx_t *ba_tx; /* caller supplied tx, NULL if not freeing */ +} bptree_args_t; + +uint64_t +bptree_alloc(objset_t *os, dmu_tx_t *tx) +{ + uint64_t obj; + dmu_buf_t *db; + bptree_phys_t *bt; + + obj = dmu_object_alloc(os, DMU_OTN_UINT64_METADATA, + SPA_MAXBLOCKSIZE, DMU_OTN_UINT64_METADATA, + sizeof (bptree_phys_t), tx); + + /* + * Bonus buffer contents are already initialized to 0, but for + * readability we make it explicit. + */ + VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db)); + dmu_buf_will_dirty(db, tx); + bt = db->db_data; + bt->bt_begin = 0; + bt->bt_end = 0; + bt->bt_bytes = 0; + bt->bt_comp = 0; + bt->bt_uncomp = 0; + dmu_buf_rele(db, FTAG); + + return (obj); +} + +int +bptree_free(objset_t *os, uint64_t obj, dmu_tx_t *tx) +{ + dmu_buf_t *db; + bptree_phys_t *bt; + + VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db)); + bt = db->db_data; + ASSERT3U(bt->bt_begin, ==, bt->bt_end); + ASSERT0(bt->bt_bytes); + ASSERT0(bt->bt_comp); + ASSERT0(bt->bt_uncomp); + dmu_buf_rele(db, FTAG); + + return (dmu_object_free(os, obj, tx)); +} + +void +bptree_add(objset_t *os, uint64_t obj, blkptr_t *bp, uint64_t birth_txg, + uint64_t bytes, uint64_t comp, uint64_t uncomp, dmu_tx_t *tx) +{ + dmu_buf_t *db; + bptree_phys_t *bt; + bptree_entry_phys_t bte; + + /* + * bptree objects are in the pool mos, therefore they can only be + * modified in syncing context. Furthermore, this is only modified + * by the sync thread, so no locking is necessary. + */ + ASSERT(dmu_tx_is_syncing(tx)); + + VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db)); + bt = db->db_data; + + bte.be_birth_txg = birth_txg; + bte.be_bp = *bp; + bzero(&bte.be_zb, sizeof (bte.be_zb)); + dmu_write(os, obj, bt->bt_end * sizeof (bte), sizeof (bte), &bte, tx); + + dmu_buf_will_dirty(db, tx); + bt->bt_end++; + bt->bt_bytes += bytes; + bt->bt_comp += comp; + bt->bt_uncomp += uncomp; + dmu_buf_rele(db, FTAG); +} + +/* ARGSUSED */ +static int +bptree_visit_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp, + const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg) +{ + int err; + struct bptree_args *ba = arg; + + if (bp == NULL) + return (0); + + err = ba->ba_func(ba->ba_arg, bp, ba->ba_tx); + if (err == 0 && ba->ba_free) { + ba->ba_phys->bt_bytes -= bp_get_dsize_sync(spa, bp); + ba->ba_phys->bt_comp -= BP_GET_PSIZE(bp); + ba->ba_phys->bt_uncomp -= BP_GET_UCSIZE(bp); + } + return (err); +} + +int +bptree_iterate(objset_t *os, uint64_t obj, boolean_t free, bptree_itor_t func, + void *arg, dmu_tx_t *tx) +{ + int err; + uint64_t i; + dmu_buf_t *db; + struct bptree_args ba; + + ASSERT(!free || dmu_tx_is_syncing(tx)); + + err = dmu_bonus_hold(os, obj, FTAG, &db); + if (err != 0) + return (err); + + if (free) + dmu_buf_will_dirty(db, tx); + + ba.ba_phys = db->db_data; + ba.ba_free = free; + ba.ba_func = func; + ba.ba_arg = arg; + ba.ba_tx = tx; + + err = 0; + for (i = ba.ba_phys->bt_begin; i < ba.ba_phys->bt_end; i++) { + bptree_entry_phys_t bte; + + ASSERT(!free || i == ba.ba_phys->bt_begin); + + err = dmu_read(os, obj, i * sizeof (bte), sizeof (bte), + &bte, DMU_READ_NO_PREFETCH); + if (err != 0) + break; + + err = traverse_dataset_destroyed(os->os_spa, &bte.be_bp, + bte.be_birth_txg, &bte.be_zb, + TRAVERSE_PREFETCH_METADATA | TRAVERSE_POST, + bptree_visit_cb, &ba); + if (free) { + ASSERT(err == 0 || err == ERESTART); + if (err != 0) { + /* save bookmark for future resume */ + ASSERT3U(bte.be_zb.zb_objset, ==, + ZB_DESTROYED_OBJSET); + ASSERT0(bte.be_zb.zb_level); + dmu_write(os, obj, i * sizeof (bte), + sizeof (bte), &bte, tx); + break; + } else { + ba.ba_phys->bt_begin++; + (void) dmu_free_range(os, obj, + i * sizeof (bte), sizeof (bte), tx); + } + } + } + + ASSERT(!free || err != 0 || ba.ba_phys->bt_begin == ba.ba_phys->bt_end); + + /* if all blocks are free there should be no used space */ + if (ba.ba_phys->bt_begin == ba.ba_phys->bt_end) { + ASSERT0(ba.ba_phys->bt_bytes); + ASSERT0(ba.ba_phys->bt_comp); + ASSERT0(ba.ba_phys->bt_uncomp); + } + + dmu_buf_rele(db, FTAG); + + return (err); +} diff --git a/pool/shard003/C/0067988_adjtime.c b/pool/shard003/C/0067988_adjtime.c new file mode 100644 index 0000000000000000000000000000000000000000..4c6a8eb93e6e8b3536ce6d7f280bb51dccffa825 --- /dev/null +++ b/pool/shard003/C/0067988_adjtime.c @@ -0,0 +1,44 @@ +/* Copyright (C) 1991-2013 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C 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. + + The GNU C 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 the GNU C Library; if not, see + . */ + +#include +#include +#include + +/* Adjust the current time of day by the amount in DELTA. + If OLDDELTA is not NULL, it is filled in with the amount + of time adjustment remaining to be done from the last `__adjtime' call. + This call is restricted to the super-user. */ +int +__adjtime (delta, olddelta) + const struct timeval *delta; + struct timeval *olddelta; +{ + error_t err; + mach_port_t hostpriv; + + hostpriv = __pid2task (-1); + if (hostpriv == MACH_PORT_NULL) + return -1; + err = __host_adjust_time (hostpriv, delta, olddelta); + __mach_port_deallocate (__mach_task_self (), hostpriv); + if (err) + return __hurd_fail (err); + return 0; +} + +weak_alias (__adjtime, adjtime) diff --git a/pool/shard003/C/0067996_util.c b/pool/shard003/C/0067996_util.c new file mode 100644 index 0000000000000000000000000000000000000000..6ed98af514f0c3ad58fbbbdc6ca41824a136f712 --- /dev/null +++ b/pool/shard003/C/0067996_util.c @@ -0,0 +1,256 @@ +/** + * Triplets Game - VIOPE 2014 + * @file: util.c + * @creation date 2014-05-15 + * + **/ + +/*===================================== + * System includes + *===================================*/ +#include +#include + +#ifdef _WIN32 + +#include + +void setWinTextColor(int, int); + +#else + +#include +#include +#include + +void setLinuxTextColor(int, int); + +#endif + +/*===================================== + * Local includes + *===================================*/ +#include "util.h" + +/*===================================== + * Prototypes of **private** functions + *===================================*/ + +/*===================================== + * Public functions + *===================================*/ + +void getDate(char dateExtended[]); +void set_game_counter(int gameCounter); +int get_game_counter(); +int increment_game_counter(); +int get_file_lines(char fileName[]); +void create_folder(char folderName[]); +void string_to_lower(char string[]); + + +/** + * This function receives a string and puts there the current date + * + * @v Empty String + * @return void + * @date 2014-05-15 + * @author João Ramos (PT) + **/ + +void getDate(char dateExtended[]) +{ + +#ifdef _WIN32 + SYSTEMTIME str_t; + GetSystemTime(&str_t); + +// printf("Date: %d/%d/%d f%d:%d",str_t.wYear,str_t.wMonth,str_t.wDay,str_t.wHour,str_t.wMinute); + + sprintf(dateExtended, "%d/%d/%d-%d:%d", str_t.wYear, str_t.wMonth, str_t.wDay, str_t.wHour, str_t.wMinute); + +#endif + +#ifdef linux + + time_t currTime; + struct tm *localTime; + currTime = time(NULL); + + localTime = localtime (&currTime); + +// printf("Date: %s", asctime(localTime)); + + strcpy(dateExtended, asctime(localTime)); + +#endif +} + +/** + * This function saves the new game counter + * + * @v gameCounter + * @return void + * @date 2014-05-16 + * @author João Ramos (PT) + **/ + +void set_game_counter(int gameCounter) +{ + FILE *counter; + + counter=fopen("data/logs/gamecounter.txt", "wt"); + if (counter==NULL) + { + printf("Error writing on game counter file."); + } + else + { + fprintf(counter, "game counter = %d", gameCounter); + + fclose(counter); + } + +} + +/** + * This function return the game counter + * + * @v + * @return gameCounter + * @date 2014-05-16 + * @author João Ramos (PT) + **/ + +int get_game_counter() +{ + FILE *counter; + int gameCounter=0; + + counter=fopen("data/logs/gamecounter.txt", "rt"); + if (counter!=NULL) + { + fscanf(counter, "game counter = %d", &gameCounter); + + fclose(counter); + } + + + return gameCounter; +} + +/** + * Increments game counter and saves + * + * @v + * @return gameCounter + * @date 2014-05-16 + * @author João Ramos (PT) + **/ + +int increment_game_counter() +{ + int gameCounter; + gameCounter=get_game_counter(); + gameCounter++; + set_game_counter(gameCounter); + + return gameCounter; +} + +/** + * This function returns the number of lines of a file + * + * @v + * @return gameCounter + * @date 2014-05-16 + * @author PT Team + **/ + +int get_file_lines(char fileName[]) +{ + FILE *fp; + int lineCounter=0; + int ch; + + fp=fopen(fileName, "rt"); + if (fp!=NULL){ + do + { + ch = fgetc(fp); + if( ch== '\n') + { + lineCounter++; + } + } + while( ch != EOF ); + + fclose(fp); + +} + +return lineCounter; +} + +/** + * This function creates a folder + * + * @v folderName + * @return void + * @date 2014-05-15 + * @author João Ramos (PT) + **/ + +void create_folder(char folderName[]) +{ + #ifdef _WIN32 + CreateDirectory(folderName,NULL); + #else + mkdir(folderName, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); + #endif +} + +/** + * This function puts a string in lower case + * + * @v + * @return void + * @date 2014-05-15 + * @author João Ramos (PT) + **/ +void string_to_lower(char string[]) +{ + int i; + + for (i=0;string[i]!='\0';i++) + { + string[i]=tolower(string[i]); + } +} + +/*===================================== + * Private functions + *===================================*/ + +void setTextColor(int foreground, int background) { + #ifdef _WIN32 + setWinTextColor(foreground, background); + #else + setLinuxTextColor(foreground, background); + #endif +} + +#ifdef _WIN32 +void setWinTextColor(int foreground, int background) { + HANDLE hConsole; + hConsole = GetStdHandle(STD_OUTPUT_HANDLE); + int k = foreground + background * 16; + SetConsoleTextAttribute(hConsole, k); +} +#else +void setLinuxTextColor(int foreground, int background) { + printf("\033[%d;%dm", 30 + foreground, 40 + background); + fflush(stdout); +} +#endif + diff --git a/pool/shard003/C/0068006_drv_led.c b/pool/shard003/C/0068006_drv_led.c new file mode 100644 index 0000000000000000000000000000000000000000..73128c243c5660d7cc4e6f3e0f59c1a5d5a175a0 --- /dev/null +++ b/pool/shard003/C/0068006_drv_led.c @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2006-2018, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + */ +#include +#include "board.h" +#include "drv_led.h" + + +/** +* +* LED1 <==> GPIO4[12] +* LED2 <==> GPIO4[13] +* +**/ + +#define LED_NUM 8 + +#define LED1_PIN 12 +#define LED1_PORT 4 + +#define LED2_PIN 13 +#define LED2_PORT 4 + +struct led_ctrl +{ + uint8_t num; + uint8_t port; +}; + +struct lpc_led +{ + /* inherit from rt_device */ + struct rt_device parent; + + struct led_ctrl ctrl[LED_NUM]; +}; + +static struct lpc_led led; + +static rt_err_t rt_led_init(rt_device_t dev) +{ + /* Enable clock and init GPIO outputs */ + LPC_CCU1->CLK_M4_GPIO_CFG = CCU_CLK_CFG_AUTO | CCU_CLK_CFG_RUN; + while (!(LPC_CCU1->CLK_M4_GPIO_STAT & CCU_CLK_STAT_RUN)); + + /* set GPIO4[12] GPIO4[13] as GPIO. */ + LPC_SCU->SFSP9_0 = 0; /* GPIO4[12] */ + LPC_SCU->SFSP9_1 = 0; /* GPIO4[13] */ + /* set GPIO4[12] GPIO4[13] output. */ + LPC_GPIO_PORT->DIR[LED1_PORT] |= 0x01 << LED1_PIN; + LPC_GPIO_PORT->DIR[LED2_PORT] |= 0x01 << LED2_PIN; + /* turn off all the led */ + LPC_GPIO_PORT->CLR[LED1_PORT] |= 0x01 << LED1_PIN; + LPC_GPIO_PORT->CLR[LED2_PORT] |= 0x01 << LED2_PIN; + + led.ctrl[0].num = LED1_PIN; + led.ctrl[0].port = LED1_PORT; + led.ctrl[1].num = LED2_PIN; + led.ctrl[1].port = LED2_PORT; + + return RT_EOK; +} + +static rt_err_t rt_led_open(rt_device_t dev, rt_uint16_t oflag) +{ + return RT_EOK; +} + +static rt_err_t rt_led_close(rt_device_t dev) +{ + return RT_EOK; +} + +static rt_size_t rt_led_read(rt_device_t dev, rt_off_t pos, void *buffer, + rt_size_t size) +{ + rt_ubase_t index = 0; + rt_ubase_t nr = size; + rt_uint8_t *value = buffer; + + RT_ASSERT(dev == &led.parent); + RT_ASSERT((pos + size) <= LED_NUM); + + for (index = 0; index < nr; index++) + { + if ((LPC_GPIO_PORT->PIN[led.ctrl[pos + index].port] & (1 << led.ctrl[pos + index].num)) != 0) + { + *value = 0; + } + else + { + *value = 1; + } + value++; + } + return index; +} + +static rt_size_t rt_led_write(rt_device_t dev, rt_off_t pos, + const void *buffer, rt_size_t size) +{ + rt_ubase_t index = 0; + rt_ubase_t nw = size; + const rt_uint8_t *value = buffer; + + RT_ASSERT(dev == &led.parent); + RT_ASSERT((pos + size) <= LED_NUM); + + for (index = 0; index < nw; index++) + { + if (*value++) + { + LPC_GPIO_PORT->CLR[led.ctrl[pos + index].port] = (1 << led.ctrl[pos + index].num); + } + else + { + LPC_GPIO_PORT->SET[led.ctrl[pos + index].port] = (1 << led.ctrl[pos + index].num); + } + } + return index; +} + +static rt_err_t rt_led_control(rt_device_t dev, int cmd, void *args) +{ + RT_ASSERT(dev == &led.parent); + + if (cmd == LED_DEVICE_CTRL) + { + rt_uint32_t *led_num = args; + *led_num = LED_NUM; + } + return RT_EOK; +} + +int rt_led_hw_init(void) +{ + led.parent.type = RT_Device_Class_Char; + led.parent.rx_indicate = RT_NULL; + led.parent.tx_complete = RT_NULL; + led.parent.init = rt_led_init; + led.parent.open = rt_led_open; + led.parent.close = rt_led_close; + led.parent.read = rt_led_read; + led.parent.write = rt_led_write; + led.parent.control = rt_led_control; + led.parent.user_data = RT_NULL; + + /* register a character device */ + rt_device_register(&led.parent, "led", RT_DEVICE_FLAG_RDWR); + /* init led device */ + rt_led_init(&led.parent); + return 0; +} +INIT_DEVICE_EXPORT(rt_led_hw_init); + +#ifdef RT_USING_FINSH +#include +void led_test(rt_uint32_t led_num, rt_uint32_t value) +{ + rt_uint8_t led_value = value; + rt_led_write(&led.parent, led_num, &led_value, 1); +} +FINSH_FUNCTION_EXPORT(led_test, e.g: led_test(0, 100).) +#endif diff --git a/pool/shard003/C/0068017_main.c b/pool/shard003/C/0068017_main.c new file mode 100644 index 0000000000000000000000000000000000000000..8ea29c3b89e19e4a9fbfcbb604739c5776b739f2 --- /dev/null +++ b/pool/shard003/C/0068017_main.c @@ -0,0 +1,74 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014, Erick Lavoie, Faiz Khan, Sujay Kathrotia, Vincent + * Foley-Bourgon, Laurie Hendren + * + * 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 "nqueen_cpu.h" +#include "../common/common.h" +#include + + +static struct option long_options[] = { + {"size", 1, NULL, 's'}, +}; + +int main(int argc, char *argv[]){ + int size = 18; + long long us = 0; + stopwatch sw; + int opt, option_index=0; + int status = 1; + + if(argc < 2){ + fprintf(stderr, "Usage: %s [-s board size\n", argv[0]); + exit(EXIT_FAILURE); + } + + + while ((opt = getopt_long(argc, argv, "s:", + long_options, &option_index)) != -1 ) { + if(opt == 's')size = atoi(optarg); + else{ + fprintf(stderr, "Usage: %s [-s board size\n", argv[0]); + exit(EXIT_FAILURE); + } + } + stopwatch_start(&sw); + long long solutions = nqueen_cpu(size, &us); + stopwatch_stop(&sw); + + /* Verification for n = 16 */ + if (size == 16) { + if (solutions != 14772512 || us != 1846955) { + status = 0; + } + } + + fprintf(stderr, "The number of solution is %lld, the number of unique solutions is " + "%lld and the total time it took is %lf seconds\n", solutions, us, + get_interval_by_sec(&sw)); + printf("{ \"status\": %d, \"options\": \"-s %d\", \"time\": %f }\n", status, size, get_interval_by_sec(&sw)); + return 0; +} diff --git a/pool/shard003/C/0068023_ehci-pci.c b/pool/shard003/C/0068023_ehci-pci.c new file mode 100644 index 0000000000000000000000000000000000000000..89804d12c139142c7a3582b56789cf25870bfe80 --- /dev/null +++ b/pool/shard003/C/0068023_ehci-pci.c @@ -0,0 +1,348 @@ +/* + * EHCI HCD (host Contoller Driver) PCI Bus Glue. + * + * Copyright (c) 2000-2004 by David Brownell + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#ifndef CONFIG_PCI +#error "This file is PCI bus glue. CONFIG_PCI must be defined." +#endif + +/*-------------------------------------------------------------------------*/ + +/* EHCI 0.96 (and later) section 5.1 says how to kick BIOS/SMM/... + * off the controller (maybe it can boot from highspeed USB disks). + */ +static int bios_handoff (struct ehci_hcd *ehci, int where, u32 cap) +{ + if (cap & (1 << 16)) { + int msec = 5000; + struct pci_dev *pdev = to_pci_dev(ehci->hcd.self.controller); + + /* request handoff to OS */ + cap |= 1 << 24; + pci_write_config_dword(pdev, where, cap); + + /* and wait a while for it to happen */ + do { + msleep(10); + msec -= 10; + pci_read_config_dword(pdev, where, &cap); + } while ((cap & (1 << 16)) && msec); + if (cap & (1 << 16)) { + ehci_err (ehci, "BIOS handoff failed (%d, %04x)\n", + where, cap); + // some BIOS versions seem buggy... + // return 1; + ehci_warn (ehci, "continuing after BIOS bug...\n"); + return 0; + } + ehci_dbg (ehci, "BIOS handoff succeeded\n"); + } + return 0; +} + +/* called by khubd or root hub init threads */ +static int ehci_pci_reset (struct usb_hcd *hcd) +{ + struct ehci_hcd *ehci = hcd_to_ehci (hcd); + u32 temp; + unsigned count = 256/4; + + spin_lock_init (&ehci->lock); + + ehci->caps = hcd->regs; + ehci->regs = hcd->regs + HC_LENGTH (readl (&ehci->caps->hc_capbase)); + dbg_hcs_params (ehci, "reset"); + dbg_hcc_params (ehci, "reset"); + + /* EHCI 0.96 and later may have "extended capabilities" */ + if (hcd->self.controller->bus == &pci_bus_type) { + struct pci_dev *pdev = to_pci_dev(ehci->hcd.self.controller); + + /* AMD8111 EHCI doesn't work, according to AMD errata */ + if ((pdev->vendor == PCI_VENDOR_ID_AMD) + && (pdev->device == 0x7463)) { + ehci_info (ehci, "ignoring AMD8111 (errata)\n"); + return -EIO; + } + + temp = HCC_EXT_CAPS (readl (&ehci->caps->hcc_params)); + } else + temp = 0; + while (temp && count--) { + u32 cap; + + pci_read_config_dword (to_pci_dev(ehci->hcd.self.controller), + temp, &cap); + ehci_dbg (ehci, "capability %04x at %02x\n", cap, temp); + switch (cap & 0xff) { + case 1: /* BIOS/SMM/... handoff */ + if (bios_handoff (ehci, temp, cap) != 0) + return -EOPNOTSUPP; + break; + case 0: /* illegal reserved capability */ + ehci_warn (ehci, "illegal capability!\n"); + cap = 0; + /* FALLTHROUGH */ + default: /* unknown */ + break; + } + temp = (cap >> 8) & 0xff; + } + if (!count) { + ehci_err (ehci, "bogus capabilities ... PCI problems!\n"); + return -EIO; + } + + /* cache this readonly data; minimize PCI reads */ + ehci->hcs_params = readl (&ehci->caps->hcs_params); + + /* at least the Genesys GL880S needs fixup here */ + temp = HCS_N_CC(ehci->hcs_params) * HCS_N_PCC(ehci->hcs_params); + temp &= 0x0f; + if (temp && HCS_N_PORTS(ehci->hcs_params) > temp) { + temp |= (ehci->hcs_params & ~0xf); + ehci->hcs_params = temp; + } + + /* force HC to halt state */ + return ehci_halt (ehci); +} + +static int ehci_pci_start (struct usb_hcd *hcd) +{ + struct ehci_hcd *ehci = hcd_to_ehci (hcd); + int result = 0; + + if (hcd->self.controller->bus == &pci_bus_type) { + struct pci_dev *pdev; + u16 port_wake; + + pdev = to_pci_dev(hcd->self.controller); + + /* Serial Bus Release Number is at PCI 0x60 offset */ + pci_read_config_byte(pdev, 0x60, &ehci->sbrn); + + /* port wake capability, reported by boot firmware */ + pci_read_config_word(pdev, 0x62, &port_wake); + hcd->can_wakeup = (port_wake & 1) != 0; + + /* help hc dma work well with cachelines */ + result = pci_set_mwi(pdev); + if (result) + ehci_dbg(ehci, "unable to enable MWI - not fatal.\n"); + } + + return ehci_run (hcd); + +} + +/* always called by thread; normally rmmod */ + +static void ehci_pci_stop (struct usb_hcd *hcd) +{ + ehci_stop (hcd); +} +/*-------------------------------------------------------------------------*/ + +#ifdef CONFIG_PM + +/* suspend/resume, section 4.3 */ + +/* These routines rely on the bus (pci, platform, etc) + * to handle powerdown and wakeup, and currently also on + * transceivers that don't need any software attention to set up + * the right sort of wakeup. + */ + +static int ehci_pci_suspend (struct usb_hcd *hcd, u32 state) +{ + struct ehci_hcd *ehci = hcd_to_ehci (hcd); + + if (time_before (jiffies, ehci->next_statechange)) + msleep (100); + +#ifdef CONFIG_USB_SUSPEND + (void) usb_suspend_device (hcd->self.root_hub, state); +#else + usb_lock_device (hcd->self.root_hub); + (void) ehci_hub_suspend (hcd); + usb_unlock_device (hcd->self.root_hub); +#endif + + // save (PCI) FLADJ in case of Vaux power loss + // ... we'd only use it to handle clock skew + + return 0; +} + +static int ehci_pci_resume (struct usb_hcd *hcd) +{ + struct ehci_hcd *ehci = hcd_to_ehci (hcd); + unsigned port; + struct usb_device *root = hcd->self.root_hub; + int retval = -EINVAL; + + // maybe restore (PCI) FLADJ + + if (time_before (jiffies, ehci->next_statechange)) + msleep (100); + + /* If any port is suspended, we know we can/must resume the HC. */ + for (port = HCS_N_PORTS (ehci->hcs_params); port > 0; ) { + u32 status; + port--; + status = readl (&ehci->regs->port_status [port]); + if (!(status & PORT_POWER)) + continue; + if (status & PORT_SUSPEND) { + down (&hcd->self.root_hub->serialize); + retval = ehci_hub_resume (hcd); + up (&hcd->self.root_hub->serialize); + break; + } + if (!root->children [port]) + continue; + dbg_port (ehci, __FUNCTION__, port + 1, status); + usb_set_device_state (root->children[port], + USB_STATE_NOTATTACHED); + } + + /* Else reset, to cope with power loss or flush-to-storage + * style "resume" having activated BIOS during reboot. + */ + if (port == 0) { + (void) ehci_halt (ehci); + (void) ehci_reset (ehci); + (void) ehci_pci_reset (hcd); + + /* emptying the schedule aborts any urbs */ + spin_lock_irq (&ehci->lock); + if (ehci->reclaim) + ehci->reclaim_ready = 1; + ehci_work (ehci, NULL); + spin_unlock_irq (&ehci->lock); + + /* restart; khubd will disconnect devices */ + retval = ehci_run (hcd); + + /* here we "know" root ports should always stay powered; + * but some controllers may lost all power. + */ + ehci_port_power (ehci, 1); + } + + return retval; +} + +#endif + + +static const struct hc_driver ehci_pci_hc_driver = { + .description = hcd_name, + + /* + * generic hardware linkage + */ + .irq = ehci_irq, + .flags = HCD_MEMORY | HCD_USB2, + + /* + * basic lifecycle operations + */ + .reset = ehci_pci_reset, + .start = ehci_pci_start, +#ifdef CONFIG_PM + .suspend = ehci_pci_suspend, + .resume = ehci_pci_resume, +#endif + .stop = ehci_pci_stop, + +#if 1 + /* + * memory lifecycle (except per-request) + */ + .hcd_alloc = ehci_hcd_alloc, +#endif + + /* + * managing i/o requests and associated device resources + */ + .urb_enqueue = ehci_urb_enqueue, + .urb_dequeue = ehci_urb_dequeue, + .endpoint_disable = ehci_endpoint_disable, + + /* + * scheduling support + */ + .get_frame_number = ehci_get_frame, + + /* + * root hub support + */ + .hub_status_data = ehci_hub_status_data, + .hub_control = ehci_hub_control, + .hub_suspend = ehci_hub_suspend, + .hub_resume = ehci_hub_resume, +}; + +/*-------------------------------------------------------------------------*/ + +/* PCI driver selection metadata; PCI hotplugging uses this */ +static const struct pci_device_id pci_ids [] = { { + /* handle any USB 2.0 EHCI controller */ + PCI_DEVICE_CLASS(((PCI_CLASS_SERIAL_USB << 8) | 0x20), ~0), + .driver_data = (unsigned long) &ehci_pci_hc_driver, + }, + { /* end: all zeroes */ } +}; +MODULE_DEVICE_TABLE (pci, pci_ids); + +/* pci driver glue; this is a "new style" PCI driver module */ +static struct pci_driver ehci_pci_driver = { + .name = (char *) hcd_name, + .id_table = pci_ids, + + .probe = usb_hcd_pci_probe, + .remove = usb_hcd_pci_remove, + +#ifdef CONFIG_PM + .suspend = usb_hcd_pci_suspend, + .resume = usb_hcd_pci_resume, +#endif +}; +static int __init ehci_hcd_pci_init (void) +{ + if (usb_disabled()) + return -ENODEV; + + pr_debug ("%s: block sizes: qh %Zd qtd %Zd itd %Zd sitd %Zd\n", + hcd_name, + sizeof (struct ehci_qh), sizeof (struct ehci_qtd), + sizeof (struct ehci_itd), sizeof (struct ehci_sitd)); + + return pci_register_driver (&ehci_pci_driver); +} +module_init (ehci_hcd_pci_init); + +static void __exit ehci_hcd_pci_cleanup (void) +{ + pci_unregister_driver (&ehci_pci_driver); +} +module_exit (ehci_hcd_pci_cleanup); + diff --git a/pool/shard003/C/0068024_mod_vhostdb_api.c b/pool/shard003/C/0068024_mod_vhostdb_api.c new file mode 100644 index 0000000000000000000000000000000000000000..8c3543b3dca43ad7445c2518049f0021942f732a --- /dev/null +++ b/pool/shard003/C/0068024_mod_vhostdb_api.c @@ -0,0 +1,41 @@ +/* + * http_vhostdb_api - virtual hosts mapping backend registration + * + * Copyright(c) 2017 Glenn Strauss gstrauss()gluelogic.com All rights reserved + * License: BSD 3-clause (same as lighttpd) + */ +#include "first.h" + +#include "mod_vhostdb_api.h" + +#include + + +static http_vhostdb_backend_t http_vhostdb_backends[8]; + +void http_vhostdb_dumbdata_reset (void) +{ + memset(http_vhostdb_backends, 0, sizeof(http_vhostdb_backends)); +} + +const http_vhostdb_backend_t * http_vhostdb_backend_get (const buffer *name) +{ + int i = 0; + while (NULL != http_vhostdb_backends[i].name + && 0 != strcmp(http_vhostdb_backends[i].name, name->ptr)) { + ++i; + } + return (NULL != http_vhostdb_backends[i].name) + ? http_vhostdb_backends+i + : NULL; +} + +void http_vhostdb_backend_set (const http_vhostdb_backend_t *backend) +{ + unsigned int i = 0; + while (NULL != http_vhostdb_backends[i].name) ++i; + /*(must resize http_vhostdb_backends[] if too many different backends)*/ + force_assert( + i < (sizeof(http_vhostdb_backends)/sizeof(http_vhostdb_backend_t))-1); + memcpy(http_vhostdb_backends+i, backend, sizeof(http_vhostdb_backend_t)); +} diff --git a/pool/shard003/C/0068049_cs4231.c b/pool/shard003/C/0068049_cs4231.c new file mode 100644 index 0000000000000000000000000000000000000000..409fa0ad7843b17f518b7b75678fed01f794f242 --- /dev/null +++ b/pool/shard003/C/0068049_cs4231.c @@ -0,0 +1,204 @@ +/* + * Generic driver for CS4231 chips + * Copyright (c) by Jaroslav Kysela + * Originally the CS4232/CS4232A driver, modified for use on CS4231 by + * Tugrul Galatali + * + * 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 +#include +#include + +#define CRD_NAME "Generic CS4231" +#define DEV_NAME "cs4231" + +MODULE_DESCRIPTION(CRD_NAME); +MODULE_AUTHOR("Jaroslav Kysela "); +MODULE_LICENSE("GPL"); +MODULE_SUPPORTED_DEVICE("{{Crystal Semiconductors,CS4231}}"); + +static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ +static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ +static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE; /* Enable this card */ +static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */ +static long mpu_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* PnP setup */ +static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,11,12,15 */ +static int mpu_irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 9,11,12,15 */ +static int dma1[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3,5,6,7 */ +static int dma2[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3,5,6,7 */ + +module_param_array(index, int, NULL, 0444); +MODULE_PARM_DESC(index, "Index value for " CRD_NAME " soundcard."); +module_param_array(id, charp, NULL, 0444); +MODULE_PARM_DESC(id, "ID string for " CRD_NAME " soundcard."); +module_param_array(enable, bool, NULL, 0444); +MODULE_PARM_DESC(enable, "Enable " CRD_NAME " soundcard."); +module_param_array(port, long, NULL, 0444); +MODULE_PARM_DESC(port, "Port # for " CRD_NAME " driver."); +module_param_array(mpu_port, long, NULL, 0444); +MODULE_PARM_DESC(mpu_port, "MPU-401 port # for " CRD_NAME " driver."); +module_param_array(irq, int, NULL, 0444); +MODULE_PARM_DESC(irq, "IRQ # for " CRD_NAME " driver."); +module_param_array(mpu_irq, int, NULL, 0444); +MODULE_PARM_DESC(mpu_irq, "MPU-401 IRQ # for " CRD_NAME " driver."); +module_param_array(dma1, int, NULL, 0444); +MODULE_PARM_DESC(dma1, "DMA1 # for " CRD_NAME " driver."); +module_param_array(dma2, int, NULL, 0444); +MODULE_PARM_DESC(dma2, "DMA2 # for " CRD_NAME " driver."); + +static int __devinit snd_cs4231_match(struct device *dev, unsigned int n) +{ + if (!enable[n]) + return 0; + + if (port[n] == SNDRV_AUTO_PORT) { + dev_err(dev, "please specify port\n"); + return 0; + } + if (irq[n] == SNDRV_AUTO_IRQ) { + dev_err(dev, "please specify irq\n"); + return 0; + } + if (dma1[n] == SNDRV_AUTO_DMA) { + dev_err(dev, "please specify dma1\n"); + return 0; + } + return 1; +} + +static int __devinit snd_cs4231_probe(struct device *dev, unsigned int n) +{ + struct snd_card *card; + struct snd_wss *chip; + struct snd_pcm *pcm; + int error; + + error = snd_card_create(index[n], id[n], THIS_MODULE, 0, &card); + if (error < 0) + return error; + + error = snd_wss_create(card, port[n], -1, irq[n], dma1[n], dma2[n], + WSS_HW_DETECT, 0, &chip); + if (error < 0) + goto out; + + card->private_data = chip; + + error = snd_wss_pcm(chip, 0, &pcm); + if (error < 0) + goto out; + + strcpy(card->driver, "CS4231"); + strcpy(card->shortname, pcm->name); + + sprintf(card->longname, "%s at 0x%lx, irq %d, dma %d", + pcm->name, chip->port, irq[n], dma1[n]); + if (dma2[n] >= 0) + sprintf(card->longname + strlen(card->longname), "&%d", dma2[n]); + + error = snd_wss_mixer(chip); + if (error < 0) + goto out; + + error = snd_wss_timer(chip, 0, NULL); + if (error < 0) + goto out; + + if (mpu_port[n] > 0 && mpu_port[n] != SNDRV_AUTO_PORT) { + if (mpu_irq[n] == SNDRV_AUTO_IRQ) + mpu_irq[n] = -1; + if (snd_mpu401_uart_new(card, 0, MPU401_HW_CS4232, + mpu_port[n], 0, mpu_irq[n], + NULL) < 0) + dev_warn(dev, "MPU401 not detected\n"); + } + + snd_card_set_dev(card, dev); + + error = snd_card_register(card); + if (error < 0) + goto out; + + dev_set_drvdata(dev, card); + return 0; + +out: snd_card_free(card); + return error; +} + +static int __devexit snd_cs4231_remove(struct device *dev, unsigned int n) +{ + snd_card_free(dev_get_drvdata(dev)); + dev_set_drvdata(dev, NULL); + return 0; +} + +#ifdef CONFIG_PM +static int snd_cs4231_suspend(struct device *dev, unsigned int n, pm_message_t state) +{ + struct snd_card *card = dev_get_drvdata(dev); + struct snd_wss *chip = card->private_data; + + snd_power_change_state(card, SNDRV_CTL_POWER_D3hot); + chip->suspend(chip); + return 0; +} + +static int snd_cs4231_resume(struct device *dev, unsigned int n) +{ + struct snd_card *card = dev_get_drvdata(dev); + struct snd_wss *chip = card->private_data; + + chip->resume(chip); + snd_power_change_state(card, SNDRV_CTL_POWER_D0); + return 0; +} +#endif + +static struct isa_driver snd_cs4231_driver = { + .match = snd_cs4231_match, + .probe = snd_cs4231_probe, + .remove = __devexit_p(snd_cs4231_remove), +#ifdef CONFIG_PM + .suspend = snd_cs4231_suspend, + .resume = snd_cs4231_resume, +#endif + .driver = { + .name = DEV_NAME + } +}; + +static int __init alsa_card_cs4231_init(void) +{ + return isa_register_driver(&snd_cs4231_driver, SNDRV_CARDS); +} + +static void __exit alsa_card_cs4231_exit(void) +{ + isa_unregister_driver(&snd_cs4231_driver); +} + +module_init(alsa_card_cs4231_init); +module_exit(alsa_card_cs4231_exit); diff --git a/pool/shard003/C/0068114_dtree_bycompat_test.c b/pool/shard003/C/0068114_dtree_bycompat_test.c new file mode 100644 index 0000000000000000000000000000000000000000..e8ca1b4bb466ad5276876ea844745adf462c1ab8 --- /dev/null +++ b/pool/shard003/C/0068114_dtree_bycompat_test.c @@ -0,0 +1,104 @@ +#include "dtree.h" +#include "test.h" + +void test_find_existent(void) +{ + test_start(); + + struct dtree_dev_t *dev = NULL; + int count = 0; + + while((dev = dtree_bycompat("simple-bus")) != NULL) { + count += 1; + + const char *name = dtree_dev_name(dev); + dtree_addr_t base = dtree_dev_base(dev); + + printf("DEV '%s' at 0x%08X\n", name, base); + dtree_dev_free(dev); + } + + fail_on_true(count == 0, "Could not find any device compatible with 'simple-bus'"); + + test_end(); +} + +void test_find_non_existent(void) +{ + test_start(); + + struct dtree_dev_t *dev = NULL; + dev = dtree_bycompat("@not-implemented-device"); + fail_on_true(dev != NULL, "Device '@not-implemented-device' was found!"); + + test_end(); +} + +void test_find_null(void) +{ + test_start(); + + struct dtree_dev_t *dev = NULL; + dev = dtree_bycompat(NULL); + fail_on_false(dev == NULL, "Device NULL was found!"); + + test_end(); +} + +void test_find_empty(void) +{ + test_start(); + + struct dtree_dev_t *dev = NULL; + dev = dtree_bycompat(""); + fail_on_false(dev == NULL, "Device '' was found!"); + + test_end(); +} + +void test_find_serial_1_00_a(void) +{ + test_start(); + + struct dtree_dev_t *dev = NULL; + int count = 0; + + while((dev = dtree_bycompat("xlnx,xps-uartlite-1.00.a")) != NULL) { + count += 1; + + const char *name = dtree_dev_name(dev); + dtree_addr_t base = dtree_dev_base(dev); + dtree_addr_t high = dtree_dev_high(dev); + + printf("DEV '%s' at 0x%08X .. 0x%08X\n", name, base, high); + dtree_dev_free(dev); + } + + fail_on_true(count != 2, "Expected two xlnx,xps-uartlite-1.00.a compatible components"); + + test_end(); +} + +int main(void) +{ + int err = dtree_open("device-tree"); + halt_on_error(err, "Can not open testing device-tree"); + + test_find_existent(); + dtree_reset(); + + test_find_non_existent(); + dtree_reset(); + + test_find_null(); + dtree_reset(); + + test_find_empty(); + dtree_reset(); + + test_find_serial_1_00_a(); + dtree_reset(); + + dtree_close(); +} + diff --git a/pool/shard003/C/0068115_cmd_ocrtc.c b/pool/shard003/C/0068115_cmd_ocrtc.c new file mode 100644 index 0000000000000000000000000000000000000000..db2c5484210a6c4df6e3a2d7da0ffb2a4a6f4bd6 --- /dev/null +++ b/pool/shard003/C/0068115_cmd_ocrtc.c @@ -0,0 +1,84 @@ +/* + * (C) Copyright 2003 + * Stefan Roese, esd gmbh germany, stefan.roese@esd-electronics.com + * + * 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 +#include +#include +#include + + +#if defined(CONFIG_CMD_BSP) + +/* + * Set device number on pci board + */ +int do_setdevice(cmd_tbl_t *cmdtp, int flag, int argc, char *argv[]) +{ + int idx = 1; /* start at 1 (skip device 0) */ + pci_dev_t bdf = 0; + u32 addr; + + while (bdf >= 0) { + if ((bdf = pci_find_device(PCI_VENDOR_ID_IBM, PCI_DEVICE_ID_IBM_405GP, idx++)) < 0) { + break; + } + printf("Found device nr %d at %x!\n", idx-1, bdf); + pci_read_config_dword(bdf, PCI_BASE_ADDRESS_1, &addr); + addr &= ~0xf; + *(u32 *)addr = (bdf & 0x0000f800) >> 11; + printf("Wrote %x at %x!\n", (bdf & 0x0000f800) >> 11, addr); + } + + return 0; +} +U_BOOT_CMD( + setdevice, 1, 1, do_setdevice, + "Set device number on pci adapter boards", + NULL +); + + +/* + * Get device number on pci board + */ +int do_getdevice(cmd_tbl_t *cmdtp, int flag, int argc, char *argv[]) +{ + u32 device; + char str[32]; + + device = *(u32 *)0x0; + device = 0x16 - device; /* calculate vxworks bp slot id */ + sprintf(str, "%d", device); + setenv("slot", str); + printf("Variabel slot set to %x\n", device); + + return 0; +} +U_BOOT_CMD( + getdevice, 1, 1, do_getdevice, + "Get device number and set slot env variable", + NULL +); + +#endif diff --git a/pool/shard003/C/0068119_47-no-threadescape.c b/pool/shard003/C/0068119_47-no-threadescape.c new file mode 100644 index 0000000000000000000000000000000000000000..0aef2403c2ea67235981db8509d8b3dca21d87eb --- /dev/null +++ b/pool/shard003/C/0068119_47-no-threadescape.c @@ -0,0 +1,20 @@ +// PARAM: --set ana.activated[-] escape +#include +int g = 10; + +void* t(void *v) { + int* p = (int*) v; + *p = 4711; +} + + +int main(void){ + int l = 42; + + pthread_t tid; + pthread_create(&tid, NULL, t, (void *)&l); + pthread_join(tid, NULL); + + assert(l==42); //UNKNOWN! + return 0; +} diff --git a/pool/shard003/C/0068149_test_random_isaac.c b/pool/shard003/C/0068149_test_random_isaac.c new file mode 100644 index 0000000000000000000000000000000000000000..bed8673e7104bca9d0189d5f801ff4a3336ef47b --- /dev/null +++ b/pool/shard003/C/0068149_test_random_isaac.c @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2015 Cisco and/or 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. + */ +/* + Copyright (c) 2005 Eliot Dresselhaus + + 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 + +static int verbose; +#define if_verbose(format,args...) \ + if (verbose) { clib_warning(format, ## args); } + +int +test_isaac_main (unformat_input_t * input) +{ + uword n_iterations, seed; + uword i, repeat_count; + uword *hash = 0; + uword print; + isaac_t ctx; + uword results[ISAAC_SIZE] = { 0 }; + uword n_results; + + n_iterations = 1000; + seed = 0; + print = 1 << 24; + + while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) + { + if (0 == unformat (input, "iter %d", &n_iterations) + && 0 == unformat (input, "print %d", &print) + && 0 == unformat (input, "seed %d", &seed)) + clib_error ("unknown input `%U'", format_unformat_error, input); + } + + if (!seed) + seed = random_default_seed (); + + results[0] = seed; + + if (n_iterations == 0) + n_iterations = ~0; + + if_verbose ("%d iterations, seed %d\n", n_iterations, seed); + + repeat_count = 0; + isaac_init (&ctx, results); + isaac (&ctx, results); + n_results = 0; + for (i = 0; i < n_iterations; i++) + { + uword r = results[n_results++]; + + if (!hash) + hash = hash_create (0, /* value bytes */ 0); + + if (hash_get (hash, r)) + goto repeat; + + hash_set1 (hash, r); + + if (n_results >= ARRAY_LEN (results)) + { + isaac (&ctx, results); + n_results = 0; + } + + if (verbose && 0 == (i & (print - 1))) + fformat (stderr, "0x%08x iterations %d repeats\n", i, repeat_count); + + if (hash_elts (hash) > 0x100000) + hash_free (hash); + + continue; + + repeat: + fformat (stderr, "repeat found at iteration %d/%d\n", i, n_iterations); + repeat_count++; + continue; + } + + return repeat_count > 0 ? 1 : 0; +} + +#ifdef CLIB_UNIX +int +main (int argc, char *argv[]) +{ + unformat_input_t i; + int ret; + + clib_mem_init (0, 64ULL << 20); + + verbose = (argc > 1); + unformat_init_command_line (&i, argv); + ret = test_isaac_main (&i); + unformat_free (&i); + + return ret; +} +#endif /* CLIB_UNIX */ + + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/pool/shard003/C/0068161_detect_contour.c b/pool/shard003/C/0068161_detect_contour.c new file mode 100644 index 0000000000000000000000000000000000000000..4d3db0dc1713b6c519a166f6d82aa917d224f86e --- /dev/null +++ b/pool/shard003/C/0068161_detect_contour.c @@ -0,0 +1,53 @@ +/* + * Copyright (C) Roland Meertens and Peng Lu + * + * 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, see + * . + */ +/** + * @file "modules/computer_vision/detect_contour.c" + * @author Roland Meertens and Peng Lu + * + */ + +#include "modules/computer_vision/cv.h" +#include "modules/computer_vision/detect_contour.h" +#include "modules/computer_vision/opencv_contour.h" + +// Function +struct image_t *contour_func(struct image_t *img); +struct image_t *contour_func(struct image_t *img) +{ + + if (img->type == IMAGE_YUV422) { + // Call OpenCV (C++ from paparazzi C function) + find_contour((char *) img->buf, img->w, img->h); + } + return img; +} + +void detect_contour_init(void) +{ + cv_add_to_device(&DETECT_CONTOUR_CAMERA, contour_func); + // in the mavlab, bright + cont_thres.lower_y = 16; cont_thres.lower_u = 135; cont_thres.lower_v = 80; + cont_thres.upper_y = 100; cont_thres.upper_u = 175; cont_thres.upper_v = 165; + // + // for cyberzoo: Y:12-95, U:129-161, V:80-165, turn white. + //int y1=16; int u1=129; int v1=80; % cyberzoo, dark + //int y2=100; int u2=161; int v2=165; +} + diff --git a/pool/shard003/C/0068168_builtin_io.c b/pool/shard003/C/0068168_builtin_io.c new file mode 100644 index 0000000000000000000000000000000000000000..617c55b6c11ff0226c47cdc30c344e527ce63efa --- /dev/null +++ b/pool/shard003/C/0068168_builtin_io.c @@ -0,0 +1,185 @@ +/* + * builtin_io.c + * + * rshell - CS 100 shell project + * Copyright (c) 2017 Ammon Smith and Brad Cai + * + * rshell 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. + * + * rshell 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 rshell. If not, see . + */ + +#include +#include + +#include +#include + +#include "builtin_io.h" +#include "builtins.h" +#include "core.h" +#include "state.h" + +static int cat(const char *argv0, int fd) +{ + char buf[4096]; + ssize_t ret; + + do { + ret = read(fd, buf, sizeof(buf)); + if (ret < 0) { + shell_perror(argv0, "unable to read"); + TRACE("read"); + return BAD_RETURN; + } + if (ret && fwrite(buf, ret, 1, stdout) != 1) { + shell_error(argv0, "unable to write"); + TRACE("fwrite"); + return BAD_RETURN; + } + } while (ret); + return 0; +} + +int builtin_cat(int argc, char **argv) +{ + int i; + + if (argc == 1) { + if (cat(argv[0], STDIN_FILENO)) { + TRACE(0); + return 1; + } + } else for (i = 1; i < argc; i++) { + int fd; + + fd = open(argv[i], O_RDONLY); + if (fd < 0) { + shell_perror(argv[0], "unable to open '%s'", argv[i]); + TRACE("open"); + return 1; + } + if (cat(argv[0], fd)) { + TRACE(0); + return 1; + } + if (close(fd)) { + shell_perror(argv[0], "unable to close '%s'", argv[i]); + TRACE("close"); + return 1; + } + } + return 0; +} + +int builtin_read(int argc, char **argv) +{ + static char *line; + static size_t len; + int i; + + if (getline(&line, &len, stdin) < 0) { + TRACE("getline"); + return BAD_RETURN; + } + + for (i = 1; i < argc; i++) { + if (state_set_variable(argv[i], line, 0)) { + TRACE(0); + return BAD_RETURN; + } + } + return 0; +} + +int builtin_tee(int argc, char **argv) +{ + struct { + FILE **files; + int len; + char mode[2]; + } opt; + int i, ch; + + /* Parse options */ + opt.mode[0] = 'w'; + opt.mode[1] = '\0'; + optind = 0; + while ((ch = getopt(argc, argv, ":a")) != -1) { + switch (ch) { + case 'a': + opt.mode[0] = 'a'; + break; + case '?': + return 1; + default: + die("Default case from tee::getopt(): '%c'", ch); + } + } + if (argc == optind) { + shell_error(argv[0], "missing operand"); + return 1; + } + + /* Allocate array */ + opt.len = argc - optind + 1; + opt.files = malloc(opt.len * sizeof(FILE *)); + if (!opt.files) { + shell_perror(argv[0], "unable to allocate"); + TRACE("malloc"); + return BAD_RETURN; + } + + /* Open files */ + opt.files[0] = stdout; + for (i = 1; i < opt.len; i++) { + FILE *fh; + const char *fn; + + fn = argv[optind + i - 1]; + fh = fopen(fn, opt.mode); + if (!fh) { + shell_perror(argv[0], "unable to open '%s'", fn); + TRACE("fopen"); + /* not fatal */ + } + opt.files[i] = fh; + } + + /* Read and tee */ + for (;;) { + char buf[4096]; + size_t ret; + + clearerr(stdin); + ret = fread(buf, 1, sizeof(buf), stdin); + if (ret < sizeof(buf)) { + if (feof(stdin) || ferror(stdin)) + goto end; + } + for (i = 0; i < opt.len; i++) { + if (fwrite(buf, 1, ret, opt.files[i]) != ret) { + shell_error(argv[0], "unable to write"); + TRACE("fwrite"); + goto end; + } + } + } + +end: + /* Close files */ + for (i = 1; i < opt.len; i++) { + if (fclose(opt.files[i])) + die("Failed to close '%s'", argv[optind + i - 1]); + } + return ferror(stdin); +} diff --git a/pool/shard003/C/0068177_kloadmap.c b/pool/shard003/C/0068177_kloadmap.c new file mode 100644 index 0000000000000000000000000000000000000000..5e302f905d68d2d5e1d45ed7408fa16d81fc7f88 --- /dev/null +++ b/pool/shard003/C/0068177_kloadmap.c @@ -0,0 +1,200 @@ +/* + * Id: kloadmap.c,v 1.1 1999/11/02 03:54:46 keithp Exp $ + * + * Copyright © 1999 Keith Packard + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of Keith Packard not be used in + * advertising or publicity pertaining to distribution of the software without + * specific, written prior permission. Keith Packard makes no + * representations about the suitability of this software for any purpose. It + * is provided "as is" without express or implied warranty. + * + * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, 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. + */ +/* $XFree86: xc/programs/Xserver/hw/kdrive/kloadmap.c,v 1.2 2000/02/23 20:29:54 dawes Exp $ */ + +#include "kdrive.h" +#include "kkeymap.h" + +#ifdef WINDOWS +#define KM_BUF 1024 +#define KM_EOF -1 + +typedef struct _km_file { + HANDLE handle; + char buf[KM_BUF]; + char *bufptr; + DWORD remain; +} km_file; + +int +km_fill (km_file *kf) +{ + BOOL r; + + NCD_DEBUG ((DEBUG_INIT, "km_fill")); + r = ReadFile (kf->handle, kf->buf, KM_BUF, + &kf->remain, NULL); + NCD_DEBUG ((DEBUG_INIT, "Got %d", kf->remain)); + if (!r || !kf->remain) + return KM_EOF; + kf->bufptr = kf->buf; + --kf->remain; + return *kf->bufptr++; +} + +#define km_getchar(kf) ((kf)->remain-- ? *kf->bufptr++ : km_fill (kf)) +#else +#define km_getchar(kf) getc(kf) +#endif + +BOOL +km_word (km_file *kf, char *buf, int len) +{ + int c; + + for (;;) + { + switch (c = km_getchar (kf)) { + case KM_EOF: + return FALSE; + case ' ': + case '\t': + case '\n': + case '\r': + continue; + } + break; + } + len--; + while (len--) + { + *buf++ = c; + switch (c = km_getchar (kf)) { + case KM_EOF: + case ' ': + case '\t': + case '\n': + case '\r': + *buf++ = '\0'; + return TRUE; + } + } + return FALSE; +} + +BOOL +km_int (km_file *kf, int *r) +{ + char word[64]; + + if (km_word (kf, word, sizeof (word))) + { + *r = strtol (word, NULL, 0); + return TRUE; + } + return FALSE; +} + +WCHAR *winKbdExtensions[] = { + L".xku", + L".xkb" +}; + +#define NUM_KBD_EXTENSIONS (sizeof (winKbdExtensions) / sizeof (winKbdExtensions[0])) + +BOOL +winLoadKeymap (void) +{ + WCHAR file[32 + KL_NAMELENGTH]; + WCHAR name[KL_NAMELENGTH]; + HKL layout; + km_file kf; + int width; + BOOL ret; + KeySym *m; + int scancode; + int w; + int e; + + layout = GetKeyboardLayout (0); + /* + * Pre-build 46 versions of ThinSTAR software return 0 + * for all layouts + */ + if (!layout) + return FALSE; + NCD_DEBUG ((DEBUG_INIT, "Keyboard layout 0x%x", layout)); + for (e = 0; e < NUM_KBD_EXTENSIONS; e++) + { + wstrcpy (file, L"\\Storage Card\\"); + wsprintf (name, TEXT("%08x"), layout); + wstrcat (file, name); + wstrcat (file, winKbdExtensions[e]); + NCD_DEBUG ((DEBUG_INIT, "Loading keymap from %S", file)); + kf.handle = CreateFile (file, + GENERIC_READ, + FILE_SHARE_READ|FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL); + if (kf.handle != INVALID_HANDLE_VALUE) + break; + } + if (kf.handle == INVALID_HANDLE_VALUE) + { + NCD_DEBUG ((DEBUG_INIT, "No such file")); + return FALSE; + } + ret = FALSE; + kf.remain = 0; + /* + * Keymap format: + * + * flags (optional) + * width + * keycode -> keysym array (num_keycodes * width) + */ + if (!km_int (&kf, &width)) + goto bail1; + if (width & KEYMAP_FLAGS) + { + CEKeymapFlags = (unsigned long) width; + if (!km_int (&kf, &width)) + goto bail1; + } + else + CEKeymapFlags = 0; + if (width > MAX_WIDTH) + goto bail1; + NCD_DEBUG ((DEBUG_INIT, "Keymap width %d flags 0x%x", + width, CEKeymapFlags)); + m = CEKeymap; + for (scancode = MIN_SCANCODE; scancode <= MAX_SCANCODE; scancode++) + { + for (w = 0; w < width; w++) + { + if (!km_int (&kf, m)) + break; + m++; + } + if (w != width) + break; + } + CEKeySyms.mapWidth = width; + ret = TRUE; +bail1: + CloseHandle (kf.handle); + return ret; +} diff --git a/pool/shard003/C/0068188_fseek.c b/pool/shard003/C/0068188_fseek.c new file mode 100644 index 0000000000000000000000000000000000000000..b2834e92df4bdfd04176b5d732cdcc1dd24f50c4 --- /dev/null +++ b/pool/shard003/C/0068188_fseek.c @@ -0,0 +1,58 @@ +/*- + * Copyright (c) 2005-2014 Rich Felker, et al. + * + * 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 + +int +fseek(FILE *f, long off, int whence) +{ + /* Adjust relative offset for unread data in buffer, if any */ + if ((whence == SEEK_CUR) && (f->rend != NULL)) { + off -= f->rend - f->rpos; + } + + /* Flush write buffer, and report error on failure */ + if (f->wpos != f->wbase) { + f->write(f, 0, 0); + + if (f->wpos == NULL) { + return -1; + } + } + + /* Leave writing mode */ + f->wpos = f->wbase = f->wend = 0; + + /* Perform the underlying seek. */ + if (f->seek(f, off, whence) < 0) { + return -1; + } + + /* If seek succeeded, file is seekable and we discard read buffer */ + f->rpos = f->rend = 0; + f->flags &= ~F_EOF; + + return 0; +} diff --git a/pool/shard003/C/0068215_sdhc.c b/pool/shard003/C/0068215_sdhc.c new file mode 100644 index 0000000000000000000000000000000000000000..88eb2f4b8e745ff3925fb09f16a99f4dc1f8b4c7 --- /dev/null +++ b/pool/shard003/C/0068215_sdhc.c @@ -0,0 +1,99 @@ + +#include "syscalls.h" +#include "types.h" +#include "sdhc.h" + +#include +#include + +/* IOCTL commands */ +#define IOCTL_SDHC_INIT 0x01 +#define IOCTL_SDHC_READ 0x02 +#define IOCTL_SDHC_WRITE 0x03 +#define IOCTL_SDHC_ISINSERTED 0x04 + +/* Constants */ +#define SDHC_SECTOR_SIZE 0x200 + +/* Variables */ +static char fs[] ATTRIBUTE_ALIGN(32) = "/dev/sdio/sdhc"; +static ioctlv io_vector[3] ATTRIBUTE_ALIGN(32); +static u32 io_buffer[3] ATTRIBUTE_ALIGN(32); +static s32 fd = -1; +static u32 sectorSz = SDHC_SECTOR_SIZE; + + +int sdhc_Init(void) +{ + //s32 ret; + + /* Already open */ + if (fd >= 0) + return 0; + + /* Open USB device */ + fd = os_open(fs, 1); + if (fd < 0) + return -11; + + /* Initialize USB storage */ + os_ioctlv(fd, IOCTL_SDHC_INIT, 0, 0, NULL); + + sectorSz = SDHC_SECTOR_SIZE; + + return 0; +} + + +bool sdhc_Read(u32 sector, u32 numSectors, void *buffer) +{ + u32 cnt; + s32 ret; + + /* Device not opened */ + if (fd < 0) + return false; + + /* Sector info */ + io_buffer[0] = sector; + io_buffer[1] = numSectors; + + /* Setup io_vector */ + io_vector[0].data = &io_buffer[0]; + io_vector[0].len = sizeof(u32); + io_vector[1].data = &io_buffer[1]; + io_vector[1].len = sizeof(u32); + io_vector[2].data = buffer; + io_vector[2].len = (sectorSz * numSectors); + + /* Flush cache */ + for (cnt = 0; cnt < 3; cnt++) + os_sync_after_write(io_vector[cnt].data, io_vector[cnt].len); + + os_sync_after_write(io_vector, sizeof(ioctlv) * 3); + + /* Read data */ + ret = os_ioctlv(fd, IOCTL_SDHC_READ, 2, 1, io_vector); + if (ret < 0) + return false; + + /* Invalidate cache */ + for (cnt = 0; cnt < 3; cnt++) + os_sync_before_read(io_vector[cnt].data, io_vector[cnt].len); + + return true; +} + + +bool sdhc_Shutdown(void) +{ + if (fd >= 0) { + /* Close USB device */ + os_close(fd); + /* Remove descriptor */ + fd = -1; + } + return true; +} + + diff --git a/pool/shard003/C/0068234_cache_digests.c b/pool/shard003/C/0068234_cache_digests.c new file mode 100644 index 0000000000000000000000000000000000000000..e6c763e6c36c8a44de9613cd1457776fa69ce5b5 --- /dev/null +++ b/pool/shard003/C/0068234_cache_digests.c @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2016 DeNA Co., Ltd., Kazuho Oku + * + * 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 "golombset.h" +#include "h2o/string_.h" +#include "h2o/cache_digests.h" + +struct st_h2o_cache_digests_frame_t { + H2O_VECTOR(uint64_t) keys; + unsigned capacity_bits; +}; + +static void dispose_frame_vector(h2o_cache_digests_frame_vector_t *v) +{ + size_t i; + for (i = 0; i != v->size; ++i) + free(v->entries[i].keys.entries); + free(v->entries); +} + +static void dispose_digests(h2o_cache_digests_t *digests) +{ + dispose_frame_vector(&digests->fresh.url_only); + dispose_frame_vector(&digests->fresh.url_and_etag); +} + +void h2o_cache_digests_destroy(h2o_cache_digests_t *digests) +{ + dispose_digests(digests); + free(digests); +} + +static void load_digest(h2o_cache_digests_t **digests, const char *gcs_base64, size_t gcs_base64_len, int with_validators, + int complete) +{ + h2o_cache_digests_frame_t frame = {{NULL}}; + h2o_iovec_t gcs_bin; + struct st_golombset_decode_t ctx = {NULL}; + uint64_t nbits, pbits; + + /* decode base64 */ + if ((gcs_bin = h2o_decode_base64url(NULL, gcs_base64, gcs_base64_len)).base == NULL) + goto Exit; + + /* prepare GCS context */ + ctx.src = (void *)(gcs_bin.base - 1); + ctx.src_max = (void *)(gcs_bin.base + gcs_bin.len); + ctx.src_shift = 0; + + /* decode nbits and pbits */ + if (golombset_decode_bits(&ctx, 5, &nbits) != 0 || golombset_decode_bits(&ctx, 5, &pbits) != 0) + goto Exit; + frame.capacity_bits = (unsigned)(nbits + pbits); + + /* decode the values */ + uint64_t value = UINT64_MAX, decoded; + while (golombset_decode_value(&ctx, (unsigned)pbits, &decoded) == 0) { + value += decoded + 1; + if (value >= (uint64_t)1 << frame.capacity_bits) + goto Exit; + h2o_vector_reserve(NULL, &frame.keys, frame.keys.size + 1); + frame.keys.entries[frame.keys.size++] = value; + } + + /* store the result */ + if (*digests == NULL) { + *digests = h2o_mem_alloc(sizeof(**digests)); + **digests = (h2o_cache_digests_t){{{NULL}}}; + } + h2o_cache_digests_frame_vector_t *target = with_validators ? &(*digests)->fresh.url_and_etag : &(*digests)->fresh.url_only; + h2o_vector_reserve(NULL, target, target->size + 1); + target->entries[target->size++] = frame; + frame = (h2o_cache_digests_frame_t){{NULL}}; + (*digests)->fresh.complete = complete; + +Exit: + free(frame.keys.entries); + free(gcs_bin.base); +} + +void h2o_cache_digests_load_header(h2o_cache_digests_t **digests, const char *value, size_t len) +{ + h2o_iovec_t iter = h2o_iovec_init(value, len); + const char *token; + size_t token_len; + + do { + const char *gcs_base64; + size_t gcs_base64_len; + int reset = 0, validators = 0, complete = 0, skip = 0; + h2o_iovec_t token_value; + + if ((gcs_base64 = h2o_next_token(&iter, ';', ',', &gcs_base64_len, NULL)) == NULL) + return; + while ((token = h2o_next_token(&iter, ';', ',', &token_len, &token_value)) != NULL && + !h2o_memis(token, token_len, H2O_STRLIT(","))) { + if (h2o_lcstris(token, token_len, H2O_STRLIT("reset"))) { + reset = 1; + } else if (h2o_lcstris(token, token_len, H2O_STRLIT("validators"))) { + validators = 1; + } else if (h2o_lcstris(token, token_len, H2O_STRLIT("complete"))) { + complete = 1; + } else { + skip = 1; + } + } + + if (reset && *digests != NULL) { + h2o_cache_digests_destroy(*digests); + *digests = NULL; + } + + if (skip) { + /* not supported for the time being */ + } else { + load_digest(digests, gcs_base64, gcs_base64_len, validators, complete); + } + } while (token != NULL); +} + +static uint64_t calc_hash(const char *url, size_t url_len, const char *etag, size_t etag_len) +{ + SHA256_CTX ctx; + union { + unsigned char bytes[SHA256_DIGEST_LENGTH]; + uint64_t u64; + } md; + + SHA256_Init(&ctx); + SHA256_Update(&ctx, url, url_len); + SHA256_Update(&ctx, etag, etag_len); + SHA256_Final(md.bytes, &ctx); + + if (*(uint16_t *)"\xde\xad" == 0xdead) + return md.u64; + else + return __builtin_bswap64(md.u64); +} + +static int cmp_key(const void *_x, const void *_y) +{ + uint64_t x = *(uint64_t *)_x, y = *(uint64_t *)_y; + + if (x < y) { + return -1; + } else if (x > y) { + return 1; + } else { + return 0; + } +} + +static int lookup(h2o_cache_digests_frame_vector_t *vector, const char *url, size_t url_len, const char *etag, size_t etag_len, + int is_fresh, int is_complete) +{ + if (vector->size != 0) { + uint64_t hash = calc_hash(url, url_len, etag, etag_len); + size_t i = 0; + do { + h2o_cache_digests_frame_t *frame = vector->entries + i; + uint64_t key = hash >> (64 - frame->capacity_bits); + if (frame->keys.entries != NULL && + bsearch(&key, frame->keys.entries, frame->keys.size, sizeof(frame->keys.entries[0]), cmp_key) != NULL) + return is_fresh ? H2O_CACHE_DIGESTS_STATE_FRESH : H2O_CACHE_DIGESTS_STATE_STALE; + } while (++i != vector->size); + } + + return is_complete ? H2O_CACHE_DIGESTS_STATE_NOT_CACHED : H2O_CACHE_DIGESTS_STATE_UNKNOWN; +} + +h2o_cache_digests_state_t h2o_cache_digests_lookup_by_url(h2o_cache_digests_t *digests, const char *url, size_t url_len) +{ + return lookup(&digests->fresh.url_only, url, url_len, "", 0, 1, digests->fresh.complete); +} + +h2o_cache_digests_state_t h2o_cache_digests_lookup_by_url_and_etag(h2o_cache_digests_t *digests, const char *url, size_t url_len, + const char *etag, size_t etag_len) +{ + return lookup(&digests->fresh.url_and_etag, url, url_len, etag, etag_len, 1, digests->fresh.complete); +} diff --git a/pool/shard003/C/0068235_cpt_err.c b/pool/shard003/C/0068235_cpt_err.c new file mode 100644 index 0000000000000000000000000000000000000000..139b9284e4f725915e05b82787d525023ec94a3a --- /dev/null +++ b/pool/shard003/C/0068235_cpt_err.c @@ -0,0 +1,103 @@ +/* crypto/cpt_err.c */ +/* ==================================================================== + * Copyright (c) 1999-2006 The OpenSSL Project. 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 acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED 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 OpenSSL PROJECT OR + * ITS 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. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* NOTE: this file was auto generated by the mkerr.pl script: any changes + * made to it will be overwritten when the script next updates this file, + * only reason strings will be preserved. + */ + +#include +#include +#include + +/* BEGIN ERROR CODES */ +#ifndef OPENSSL_NO_ERR + +#define ERR_FUNC(func) ERR_PACK(ERR_LIB_CRYPTO,func,0) +#define ERR_REASON(reason) ERR_PACK(ERR_LIB_CRYPTO,0,reason) + +static ERR_STRING_DATA CRYPTO_str_functs[]= + { +{ERR_FUNC(CRYPTO_F_CRYPTO_GET_EX_NEW_INDEX), "CRYPTO_get_ex_new_index"}, +{ERR_FUNC(CRYPTO_F_CRYPTO_GET_NEW_DYNLOCKID), "CRYPTO_get_new_dynlockid"}, +{ERR_FUNC(CRYPTO_F_CRYPTO_GET_NEW_LOCKID), "CRYPTO_get_new_lockid"}, +{ERR_FUNC(CRYPTO_F_CRYPTO_SET_EX_DATA), "CRYPTO_set_ex_data"}, +{ERR_FUNC(CRYPTO_F_DEF_ADD_INDEX), "DEF_ADD_INDEX"}, +{ERR_FUNC(CRYPTO_F_DEF_GET_CLASS), "DEF_GET_CLASS"}, +{ERR_FUNC(CRYPTO_F_INT_DUP_EX_DATA), "INT_DUP_EX_DATA"}, +{ERR_FUNC(CRYPTO_F_INT_FREE_EX_DATA), "INT_FREE_EX_DATA"}, +{ERR_FUNC(CRYPTO_F_INT_NEW_EX_DATA), "INT_NEW_EX_DATA"}, +{0,NULL} + }; + +static ERR_STRING_DATA CRYPTO_str_reasons[]= + { +{ERR_REASON(CRYPTO_R_NO_DYNLOCK_CREATE_CALLBACK),"no dynlock create callback"}, +{0,NULL} + }; + +#endif + +void ERR_load_CRYPTO_strings(void) + { +#ifndef OPENSSL_NO_ERR + + if (ERR_func_error_string(CRYPTO_str_functs[0].error) == NULL) + { + ERR_load_strings(0,CRYPTO_str_functs); + ERR_load_strings(0,CRYPTO_str_reasons); + } +#endif + } diff --git a/pool/shard003/C/0068257_pipe07.c b/pool/shard003/C/0068257_pipe07.c new file mode 100644 index 0000000000000000000000000000000000000000..55bb9f4195eeafd00fc3f2cc9a062b1ab53217a5 --- /dev/null +++ b/pool/shard003/C/0068257_pipe07.c @@ -0,0 +1,176 @@ +/* + * Copyright (c) International Business Machines Corp., 2002 + * Ported by Paul Larson + * Copyright (c) 2013 Cyril Hrubis + * + * 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 + */ + +/* + * Test the ability of pipe to open the maximum even number of file + * descriptors permitted (or (maxfds - 3)/2 pipes) + * + * ALGORITHM + * 1. record file descriptors open prior to test run + * 2. open pipes until EMFILE is returned + * 3. check to see that the number of pipes opened is (maxfds - 3) / 2 + * 4. close all fds in range 0, maximal fd that were not open prior to + * the test execution + */ +#include +#include +#include +#include +#include +#include +#include + +#include "test.h" +#include "safe_macros.h" + +char *TCID = "pipe07"; +int TST_TOTAL = 1; + +/* used to record file descriptors open at the test start */ +static int rec_fds[128]; +static int rec_fds_max; +static void record_open_fds(void); +static void close_test_fds(int max_fd); + +static void setup(void); +static void cleanup(void); + +int main(int ac, char **av) +{ + int lc; + int min, ret; + int npipes; + int pipes[2], max_fd = 0; + + tst_parse_opts(ac, av, NULL, NULL); + + setup(); + + min = getdtablesize() - rec_fds_max; + + for (lc = 0; TEST_LOOPING(lc); lc++) { + tst_count = 0; + + for (npipes = 0;; npipes++) { + ret = pipe(pipes); + if (ret < 0) { + if (errno != EMFILE) { + tst_brkm(TFAIL, cleanup, + "got unexpected error - %d", + errno); + } + break; + } + + max_fd = MAX(pipes[0], max_fd); + max_fd = MAX(pipes[1], max_fd); + } + + if (npipes == (min / 2)) + tst_resm(TPASS, "Opened %d pipes", npipes); + else + tst_resm(TFAIL, "Unable to open maxfds/2 pipes"); + + close_test_fds(max_fd); + max_fd = 0; + } + + cleanup(); + tst_exit(); +} + +static void setup(void) +{ + tst_sig(FORK, DEF_HANDLER, cleanup); + TEST_PAUSE; + + record_open_fds(); +} + +static void record_open_fds(void) +{ + DIR *dir = opendir("/proc/self/fd"); + int dir_fd, fd; + struct dirent *file; + + if (dir == NULL) + tst_brkm(TBROK | TERRNO, cleanup, "opendir()"); + + dir_fd = dirfd(dir); + + if (dir_fd == -1) + tst_brkm(TBROK | TERRNO, cleanup, "dirfd()"); + + errno = 0; + + while ((file = readdir(dir))) { + if (!strcmp(file->d_name, ".") || !strcmp(file->d_name, "..")) + continue; + + fd = atoi(file->d_name); + + if (fd == dir_fd) + continue; + + if (rec_fds_max >= (int)ARRAY_SIZE(rec_fds)) { + tst_brkm(TBROK, cleanup, + "Too much file descriptors open"); + } + + rec_fds[rec_fds_max++] = fd; + } + + if (errno) + tst_brkm(TBROK | TERRNO, cleanup, "readdir()"); + + closedir(dir); + + tst_resm(TINFO, "Found %u files open", rec_fds_max); +} + +static int not_recorded(int fd) +{ + int i; + + for (i = 0; i < rec_fds_max; i++) + if (fd == rec_fds[i]) + return 0; + + return 1; +} + +static void close_test_fds(int max_fd) +{ + int i; + + for (i = 0; i <= max_fd; i++) { + if (not_recorded(i)) { + if (close(i)) { + if (errno == EBADF) + continue; + tst_resm(TWARN | TERRNO, "close(%i)", i); + } + } + } +} + +static void cleanup(void) +{ +} diff --git a/pool/shard003/C/0068258_rain.c b/pool/shard003/C/0068258_rain.c new file mode 100644 index 0000000000000000000000000000000000000000..a7771b09d3e346831bb9b46a542b667d6164d695 --- /dev/null +++ b/pool/shard003/C/0068258_rain.c @@ -0,0 +1,133 @@ +/* + * $Id: rain.c,v 1.15 2000/09/02 18:41:22 tom Exp $ + */ +#include + +#include /* for tparm() */ + +#include + +/* rain 11/3/1980 EPS/CITHEP */ + +static float ranf(void); +static void onsig(int sig); + +static int next_j(int j) +{ + if (j==0) j=4; else --j; + if (has_colors()) { + int z = (int)(3*ranf()); + chtype color = COLOR_PAIR(z); + if (z) + color |= A_BOLD; + attrset(color); + } + return j; +} + +int +main( + int argc GCC_UNUSED, + char *argv[] GCC_UNUSED) +{ +int x, y, j; +static int xpos[5], ypos[5]; +float r; +float c; + + for (j=SIGHUP;j<=SIGTERM;j++) + if (signal(j,SIG_IGN)!=SIG_IGN) signal(j,onsig); + + initscr(); + if (has_colors()) { + int bg = COLOR_BLACK; + start_color(); +#if HAVE_USE_DEFAULT_COLORS + if (use_default_colors() == OK) + bg = -1; +#endif + init_pair(1, COLOR_BLUE, bg); + init_pair(2, COLOR_CYAN, bg); + } + nl(); + noecho(); + curs_set(0); + timeout(0); + + r = (float)(LINES - 4); + c = (float)(COLS - 4); + for (j=5;--j>=0;) { + xpos[j]=(int)(c* ranf())+2; + ypos[j]=(int)(r* ranf())+2; + } + + for (j=0;;) { + x=(int)(c*ranf())+2; + y=(int)(r*ranf())+2; + + mvaddch(y,x, '.'); + + mvaddch(ypos[j], xpos[j], 'o'); + + j = next_j(j); + mvaddch(ypos[j], xpos[j], 'O'); + + j = next_j(j); + mvaddch( ypos[j]-1, xpos[j], '-'); + mvaddstr(ypos[j], xpos[j]-1, "|.|"); + mvaddch( ypos[j]+1, xpos[j], '-'); + + j = next_j(j); + mvaddch( ypos[j]-2, xpos[j], '-'); + mvaddstr(ypos[j]-1, xpos[j]-1, "/ \\"); + mvaddstr(ypos[j], xpos[j]-2, "| O |"); + mvaddstr(ypos[j]+1, xpos[j]-1, "\\ /"); + mvaddch( ypos[j]+2, xpos[j], '-'); + + j = next_j(j); + mvaddch( ypos[j]-2, xpos[j], ' '); + mvaddstr(ypos[j]-1, xpos[j]-1, " "); + mvaddstr(ypos[j], xpos[j]-2, " "); + mvaddstr(ypos[j]+1, xpos[j]-1, " "); + mvaddch( ypos[j]+2, xpos[j], ' '); + + xpos[j] = x; ypos[j] = y; + + switch(getch()) + { + case('q'): + case('Q'): + curs_set(1); + endwin(); + return(EXIT_SUCCESS); + case 's': + nodelay(stdscr, FALSE); + break; + case ' ': + nodelay(stdscr, TRUE); + break; +#ifdef KEY_RESIZE + case(KEY_RESIZE): + r = (float)(LINES - 4); + c = (float)(COLS - 4); + break; +#endif + } + napms(50); + } +} + +static void +onsig(int n GCC_UNUSED) +{ + curs_set(1); + endwin(); + exit(EXIT_FAILURE); +} + +static float +ranf(void) +{ + long r = (rand() & 077777); + return ((float) r / 32768.); +} diff --git a/pool/shard003/C/0068262_aliyun_iot_common_timer.c b/pool/shard003/C/0068262_aliyun_iot_common_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..6243092551b4430db4af8cb5e5d160bd68ad194e --- /dev/null +++ b/pool/shard003/C/0068262_aliyun_iot_common_timer.c @@ -0,0 +1,98 @@ + +#include "aliyun_iot_platform_datatype.h" +#include "aliyun_iot_platform_timer.h" + +#include "aliyun_iot_common_timer.h" + +void aliyun_iot_timer_assignment(int32_t millisecond, aliot_time_t *timer) +{ + timer->time = millisecond; +} + +void aliyun_iot_timer_start_clock(aliot_time_t *timer) +{ + timer->time = aliot_platform_time_get_ms(); +} + +uint32_t aliyun_iot_timer_spend(aliot_time_t *start) +{ + uint32_t now, res; + + now = aliot_platform_time_get_ms(); + res = now - start->time; + return res; +} + +uint32_t aliyun_iot_timer_remain(aliot_time_t *end) +{ + uint32_t now, res; + + now = aliot_platform_time_get_ms(); + res = end->time - now; + return res; +} + +uint32_t aliyun_iot_timer_expired(aliot_time_t *timer) +{ + uint32_t cur_time = 0; + cur_time = aliot_platform_time_get_ms(); + + //hanle overflow + if ((timer->time <= cur_time) && ((cur_time - timer->time) < 0x80000000)) + { + return 1; + } + else + { + return 0; + } +} + +void aliyun_iot_timer_init(aliot_time_t *timer) +{ + timer->time = 0; +} + +void aliyun_iot_timer_cutdown(aliot_time_t *timer, uint32_t millisecond) +{ + //NOTE it may overflow + timer->time = aliot_platform_time_get_ms() + millisecond; +} + +uint32_t aliyun_iot_timer_now() +{ + return (uint32_t)(aliot_platform_time_get_ms()); +} + +uint32_t aliyun_iot_timer_interval(aliot_time_t *start, aliot_time_t *end) +{ + return (end->time - start->time); +} + + +uint64_t aliot_time_get_ms_64b(void) +{ + static uint32_t overflow_cnt = 0; + static uint32_t last; + + uint32_t new = aliot_platform_time_get_ms(); + + //#BUG: it may lose if this interface is not called over 49.7 days + if (new < last) { + ++overflow_cnt; + } + + return ((uint64_t)overflow_cnt << 32) | (new); +} + + +uint32_t aliot_time_get_ms(void) +{ + return (uint32_t)aliot_time_get_ms_64b(); +} + + +uint32_t aliot_time_get_s(void) +{ + return (uint32_t)(aliot_time_get_ms_64b()/1000); +} diff --git a/pool/shard003/C/0068285_clk-div6.c b/pool/shard003/C/0068285_clk-div6.c new file mode 100644 index 0000000000000000000000000000000000000000..ee66f49812df7c03b97362af3865925a1040cbff --- /dev/null +++ b/pool/shard003/C/0068285_clk-div6.c @@ -0,0 +1,284 @@ +/* + * r8a7790 Common Clock Framework support + * + * Copyright (C) 2013 Renesas Solutions Corp. + * + * Contact: Laurent Pinchart + * + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define CPG_DIV6_CKSTP BIT(8) +#define CPG_DIV6_DIV(d) ((d) & 0x3f) +#define CPG_DIV6_DIV_MASK 0x3f + +/** + * struct div6_clock - CPG 6 bit divider clock + * @hw: handle between common and hardware-specific interfaces + * @reg: IO-remapped register + * @div: divisor value (1-64) + */ +struct div6_clock { + struct clk_hw hw; + void __iomem *reg; + unsigned int div; + u32 src_shift; + u32 src_width; + u8 *parents; +}; + +#define to_div6_clock(_hw) container_of(_hw, struct div6_clock, hw) + +static int cpg_div6_clock_enable(struct clk_hw *hw) +{ + struct div6_clock *clock = to_div6_clock(hw); + u32 val; + + val = (clk_readl(clock->reg) & ~(CPG_DIV6_DIV_MASK | CPG_DIV6_CKSTP)) + | CPG_DIV6_DIV(clock->div - 1); + clk_writel(val, clock->reg); + + return 0; +} + +static void cpg_div6_clock_disable(struct clk_hw *hw) +{ + struct div6_clock *clock = to_div6_clock(hw); + u32 val; + + val = clk_readl(clock->reg); + val |= CPG_DIV6_CKSTP; + /* + * DIV6 clocks require the divisor field to be non-zero when stopping + * the clock. However, some clocks (e.g. ZB on sh73a0) fail to be + * re-enabled later if the divisor field is changed when stopping the + * clock + */ + if (!(val & CPG_DIV6_DIV_MASK)) + val |= CPG_DIV6_DIV_MASK; + clk_writel(val, clock->reg); +} + +static int cpg_div6_clock_is_enabled(struct clk_hw *hw) +{ + struct div6_clock *clock = to_div6_clock(hw); + + return !(clk_readl(clock->reg) & CPG_DIV6_CKSTP); +} + +static unsigned long cpg_div6_clock_recalc_rate(struct clk_hw *hw, + unsigned long parent_rate) +{ + struct div6_clock *clock = to_div6_clock(hw); + unsigned int div = (clk_readl(clock->reg) & CPG_DIV6_DIV_MASK) + 1; + + return parent_rate / div; +} + +static unsigned int cpg_div6_clock_calc_div(unsigned long rate, + unsigned long parent_rate) +{ + unsigned int div; + + if (!rate) + rate = 1; + + div = DIV_ROUND_CLOSEST(parent_rate, rate); + return clamp_t(unsigned int, div, 1, 64); +} + +static long cpg_div6_clock_round_rate(struct clk_hw *hw, unsigned long rate, + unsigned long *parent_rate) +{ + unsigned int div = cpg_div6_clock_calc_div(rate, *parent_rate); + + return *parent_rate / div; +} + +static int cpg_div6_clock_set_rate(struct clk_hw *hw, unsigned long rate, + unsigned long parent_rate) +{ + struct div6_clock *clock = to_div6_clock(hw); + unsigned int div = cpg_div6_clock_calc_div(rate, parent_rate); + u32 val; + + clock->div = div; + + val = clk_readl(clock->reg) & ~CPG_DIV6_DIV_MASK; + /* Only program the new divisor if the clock isn't stopped. */ + if (!(val & CPG_DIV6_CKSTP)) + clk_writel(val | CPG_DIV6_DIV(clock->div - 1), clock->reg); + + return 0; +} + +static u8 cpg_div6_clock_get_parent(struct clk_hw *hw) +{ + struct div6_clock *clock = to_div6_clock(hw); + unsigned int i; + u8 hw_index; + + if (clock->src_width == 0) + return 0; + + hw_index = (clk_readl(clock->reg) >> clock->src_shift) & + (BIT(clock->src_width) - 1); + for (i = 0; i < clk_hw_get_num_parents(hw); i++) { + if (clock->parents[i] == hw_index) + return i; + } + + pr_err("%s: %s DIV6 clock set to invalid parent %u\n", + __func__, __clk_get_name(hw->clk), hw_index); + return 0; +} + +static int cpg_div6_clock_set_parent(struct clk_hw *hw, u8 index) +{ + struct div6_clock *clock = to_div6_clock(hw); + u8 hw_index; + u32 mask; + + if (index >= clk_hw_get_num_parents(hw)) + return -EINVAL; + + mask = ~((BIT(clock->src_width) - 1) << clock->src_shift); + hw_index = clock->parents[index]; + + clk_writel((clk_readl(clock->reg) & mask) | + (hw_index << clock->src_shift), clock->reg); + + return 0; +} + +static const struct clk_ops cpg_div6_clock_ops = { + .enable = cpg_div6_clock_enable, + .disable = cpg_div6_clock_disable, + .is_enabled = cpg_div6_clock_is_enabled, + .get_parent = cpg_div6_clock_get_parent, + .set_parent = cpg_div6_clock_set_parent, + .recalc_rate = cpg_div6_clock_recalc_rate, + .round_rate = cpg_div6_clock_round_rate, + .set_rate = cpg_div6_clock_set_rate, +}; + +static void __init cpg_div6_clock_init(struct device_node *np) +{ + unsigned int num_parents, valid_parents; + const char **parent_names; + struct clk_init_data init; + struct div6_clock *clock; + const char *name; + struct clk *clk; + unsigned int i; + int ret; + + clock = kzalloc(sizeof(*clock), GFP_KERNEL); + if (!clock) + return; + + num_parents = of_clk_get_parent_count(np); + if (num_parents < 1) { + pr_err("%s: no parent found for %s DIV6 clock\n", + __func__, np->name); + return; + } + + clock->parents = kmalloc_array(num_parents, sizeof(*clock->parents), + GFP_KERNEL); + parent_names = kmalloc_array(num_parents, sizeof(*parent_names), + GFP_KERNEL); + if (!parent_names) + return; + + /* Remap the clock register and read the divisor. Disabling the + * clock overwrites the divisor, so we need to cache its value for the + * enable operation. + */ + clock->reg = of_iomap(np, 0); + if (clock->reg == NULL) { + pr_err("%s: failed to map %s DIV6 clock register\n", + __func__, np->name); + goto error; + } + + clock->div = (clk_readl(clock->reg) & CPG_DIV6_DIV_MASK) + 1; + + /* Parse the DT properties. */ + ret = of_property_read_string(np, "clock-output-names", &name); + if (ret < 0) { + pr_err("%s: failed to get %s DIV6 clock output name\n", + __func__, np->name); + goto error; + } + + + for (i = 0, valid_parents = 0; i < num_parents; i++) { + const char *name = of_clk_get_parent_name(np, i); + + if (name) { + parent_names[valid_parents] = name; + clock->parents[valid_parents] = i; + valid_parents++; + } + } + + switch (num_parents) { + case 1: + /* fixed parent clock */ + clock->src_shift = clock->src_width = 0; + break; + case 4: + /* clock with EXSRC bits 6-7 */ + clock->src_shift = 6; + clock->src_width = 2; + break; + case 8: + /* VCLK with EXSRC bits 12-14 */ + clock->src_shift = 12; + clock->src_width = 3; + break; + default: + pr_err("%s: invalid number of parents for DIV6 clock %s\n", + __func__, np->name); + goto error; + } + + /* Register the clock. */ + init.name = name; + init.ops = &cpg_div6_clock_ops; + init.flags = CLK_IS_BASIC; + init.parent_names = parent_names; + init.num_parents = valid_parents; + + clock->hw.init = &init; + + clk = clk_register(NULL, &clock->hw); + if (IS_ERR(clk)) { + pr_err("%s: failed to register %s DIV6 clock (%ld)\n", + __func__, np->name, PTR_ERR(clk)); + goto error; + } + + of_clk_add_provider(np, of_clk_src_simple_get, clk); + + kfree(parent_names); + return; + +error: + if (clock->reg) + iounmap(clock->reg); + kfree(parent_names); + kfree(clock); +} +CLK_OF_DECLARE(cpg_div6_clk, "renesas,cpg-div6-clock", cpg_div6_clock_init); diff --git a/pool/shard003/C/0068290_base64.c b/pool/shard003/C/0068290_base64.c new file mode 100644 index 0000000000000000000000000000000000000000..45b0ebae00539692b88bf01024e69cc23586d58e --- /dev/null +++ b/pool/shard003/C/0068290_base64.c @@ -0,0 +1,193 @@ +/* + * base64 encoding and decoding function + */ +#include +#include +#include +#include "hw1.h" +static const char B64TB[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/* + * 1. encode mode: + * treat all '\n' as binary until reaches the EOF, + * where fgetc==-1 and returns. Therefore EOF is not encoded. + * + * 2. decode mode: + * ignore '\n', if reading characters outside of base64 table, + * return -1. Else return characters read. + */ +int b64read ( unsigned char* inbuf, char mode, size_t max_count, FILE * fp ) +{ + int count = 0; + int temp = 0; + while ( count < max_count ) { + temp = fgetc ( fp ); + inbuf[count] = temp; + switch ( mode ) { + case 'e': + if ( temp >= 0 ) { + count++; + } else { + inbuf[count] = 0; //reset the EOF value(-1) to 0 + return count; + } + break; + case 'd': + if ( temp == 0xA ) { //if meets [newline], this will be replaced by next char + inbuf[count] = 0; + break; + } else if ( ( temp == 61 ) || ( temp == 43 ) || ( temp >= 47 && temp <= 57 ) || ( temp >= 65 && temp <= 90 ) || ( temp >= 97 && temp <= 122 ) ) { + count++; + } else if ( temp == -1 ) { + inbuf[count] = 0; + return count; + } else { + return -1; + } + break; + default: + fprintf ( stderr, "ERR: b64read invalid mode\n" ); + fclose ( fp ); + exit ( -1 ); + } + } + return count; +} +int b64dec ( FILE *fp ) +{ + int i, n = 0; + int padFlag = 0; //set when padding is detected + int space; + unsigned char *inbuf = malloc ( MAX_B64_DEC_BUF ); //sizeof 4 to read + unsigned char *outbuf = malloc ( MAX_B64_ENC_BUF ); //sizeof 3 to store encoded + + while ( !feof ( fp ) ) { + memset ( inbuf, 0, MAX_B64_DEC_BUF ); + memset ( outbuf, 0, MAX_B64_ENC_BUF ); + n = b64read ( inbuf, 'd', MAX_B64_DEC_BUF, fp ); + if ( n == -1 ) { + fprintf ( stderr, "ERR: b64dec illegal char detected\n" ); + free ( inbuf ); + free ( outbuf ); + fclose ( fp ); + exit ( -1 ); + } else if ( n == 0 ) { + break; + } else if ( n < 4 ) { + fprintf ( stderr, "ERR: b64dec illegal file format\n" ); + free ( inbuf ); + free ( outbuf ); + fclose ( fp ); + exit ( -1 ); + } + if ( ( inbuf[0] == 61 ) || ( inbuf[1] == 61 ) || ( padFlag == 1 ) ) { + fprintf ( stderr, "ERR: b64dec illegal padding position\n" ); + free ( inbuf ); + free ( outbuf ); + fclose ( fp ); + exit ( -1 ); + } + + space = 0; + if ( ( inbuf[2] == 61 ) && ( inbuf[3] == 61 ) ) { + inbuf[2] = 0; + inbuf[3] = 0; + space = 2; + padFlag = 1; + } else if ( inbuf[3] == 61 ) { + inbuf[3] = 0; + space = 1; + } + + for ( i = 0; i < ( MAX_B64_DEC_BUF - space ); i++ ) { + if ( inbuf[i] >= 65 && inbuf[i] <= 90 ) { + inbuf[i] = inbuf[i] - 65; + } else if ( inbuf[i] >= 97 && inbuf[i] <= 122 ) { + inbuf[i] = inbuf[i] - 71; + } else if ( inbuf[i] >= 48 && inbuf[i] <= 57 ) { + inbuf[i] = inbuf[i] + 4; + } else if ( inbuf[i] == 43 ) { + inbuf[i] = 62; + } else if ( inbuf[i] == 47 ) { + inbuf[i] = 63; + } + } + + outbuf[0] = ( ( inbuf[0] << 2 ) | ( inbuf[1] >> 4 ) ); + outbuf[1] = ( ( inbuf[1] & 15 ) << 4 ) | ( inbuf[2] >> 2 ); + outbuf[2] = ( ( inbuf[2] & 3 ) << 6 ) | inbuf[3]; + + for ( i = 0; i < ( MAX_B64_ENC_BUF - space ); i++ ) { + fprintf ( stdout, "%c", outbuf[i] ); + } + } + free ( inbuf ); + free ( outbuf ); + fclose ( fp ); + return 1; +} +int b64enc ( FILE *fp ) +{ + int i, n = 0, total = 0; + unsigned char *inbuf = malloc ( MAX_B64_ENC_BUF ); //sizeof 3 to read + unsigned char *outbuf = malloc ( MAX_B64_DEC_BUF ); //sizeof 4 to store encoded + + while ( !feof ( fp ) ) { + memset ( inbuf, 0, MAX_B64_ENC_BUF ); + memset ( outbuf, 0, MAX_B64_DEC_BUF ); + n = b64read ( inbuf, 'e', MAX_B64_ENC_BUF, fp ); + + outbuf[0] = B64TB[inbuf[0] >> 2]; + outbuf[1] = B64TB[ ( ( inbuf[0] & 3 ) << 4 ) | ( inbuf[1] >> 4 )]; + outbuf[2] = B64TB[ ( ( inbuf[1] & 15 ) << 2 ) | ( inbuf[2] >> 6 )]; + outbuf[3] = B64TB[inbuf[2] & 63]; + + if ( n == 1 ) { + outbuf[2] = '='; + outbuf[3] = '='; + n = 4; + } else if ( n == 2 ) { + outbuf[3] = '='; + n = 4; + } else if ( n == 3 ) { + n = 4; + } + for ( i = 0; i < n; i++ ) { + fprintf ( stdout, "%c", outbuf[i] ); + } + total = total + n; + if ( total == MAX_B64_LEN ) { + fprintf ( stdout, "\n" ); + total = 0; + } + } + if ( total != 0 ) { //append \n to the last line + fprintf ( stdout, "\n" ); + } + free ( inbuf ); + free ( outbuf ); + fclose ( fp ); + return 1; +} + +int b64main ( char* filepath, char* mode ) +{ + if ( strcmp ( mode, "enc" ) == 0 ) { + if ( b64enc ( fileopen ( filepath ) ) == 1 ) { + return 1; + } else { + fprintf ( stderr, "ERR: b64main encode error\n" ); + exit ( -1 ); + } + } else if ( strcmp ( mode, "dec" ) == 0 ) { + if ( b64dec ( fileopen ( filepath ) ) == 1 ) { + return 1; + } else { + fprintf ( stderr, "ERR: b64main decode error\n" ); + exit ( -1 ); + } + } else { + fprintf ( stderr, "ERR: b64main invalid mode\n" ); + exit ( -1 ); + } +} diff --git a/pool/shard003/C/0068291_p4-clockmod.c b/pool/shard003/C/0068291_p4-clockmod.c new file mode 100644 index 0000000000000000000000000000000000000000..74f593e70e191ffdd8c297377cf347a833a9dbce --- /dev/null +++ b/pool/shard003/C/0068291_p4-clockmod.c @@ -0,0 +1,286 @@ +/* + * Pentium 4/Xeon CPU on demand clock modulation/speed scaling + * (C) 2002 - 2003 Dominik Brodowski + * (C) 2002 Zwane Mwaikambo + * (C) 2002 Arjan van de Ven + * (C) 2002 Tora T. Engstad + * All Rights Reserved + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + * + * The author(s) of this software shall not be held liable for damages + * of any nature resulting due to the use of this software. This + * software is provided AS-IS with no warranties. + * + * Date Errata Description + * 20020525 N44, O17 12.5% or 25% DC causes lockup + * + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "speedstep-lib.h" + +#define PFX "p4-clockmod: " + +/* + * Duty Cycle (3bits), note DC_DISABLE is not specified in + * intel docs i just use it to mean disable + */ +enum { + DC_RESV, DC_DFLT, DC_25PT, DC_38PT, DC_50PT, + DC_64PT, DC_75PT, DC_88PT, DC_DISABLE +}; + +#define DC_ENTRIES 8 + + +static int has_N44_O17_errata[NR_CPUS]; +static unsigned int stock_freq; +static struct cpufreq_driver p4clockmod_driver; +static unsigned int cpufreq_p4_get(unsigned int cpu); + +static int cpufreq_p4_setdc(unsigned int cpu, unsigned int newstate) +{ + u32 l, h; + + if ((newstate > DC_DISABLE) || (newstate == DC_RESV)) + return -EINVAL; + + rdmsr_on_cpu(cpu, MSR_IA32_THERM_STATUS, &l, &h); + + if (l & 0x01) + pr_debug("CPU#%d currently thermal throttled\n", cpu); + + if (has_N44_O17_errata[cpu] && + (newstate == DC_25PT || newstate == DC_DFLT)) + newstate = DC_38PT; + + rdmsr_on_cpu(cpu, MSR_IA32_THERM_CONTROL, &l, &h); + if (newstate == DC_DISABLE) { + pr_debug("CPU#%d disabling modulation\n", cpu); + wrmsr_on_cpu(cpu, MSR_IA32_THERM_CONTROL, l & ~(1<<4), h); + } else { + pr_debug("CPU#%d setting duty cycle to %d%%\n", + cpu, ((125 * newstate) / 10)); + /* bits 63 - 5 : reserved + * bit 4 : enable/disable + * bits 3-1 : duty cycle + * bit 0 : reserved + */ + l = (l & ~14); + l = l | (1<<4) | ((newstate & 0x7)<<1); + wrmsr_on_cpu(cpu, MSR_IA32_THERM_CONTROL, l, h); + } + + return 0; +} + + +static struct cpufreq_frequency_table p4clockmod_table[] = { + {DC_RESV, CPUFREQ_ENTRY_INVALID}, + {DC_DFLT, 0}, + {DC_25PT, 0}, + {DC_38PT, 0}, + {DC_50PT, 0}, + {DC_64PT, 0}, + {DC_75PT, 0}, + {DC_88PT, 0}, + {DC_DISABLE, 0}, + {DC_RESV, CPUFREQ_TABLE_END}, +}; + + +static int cpufreq_p4_target(struct cpufreq_policy *policy, unsigned int index) +{ + int i; + + /* run on each logical CPU, + * see section 13.15.3 of IA32 Intel Architecture Software + * Developer's Manual, Volume 3 + */ + for_each_cpu(i, policy->cpus) + cpufreq_p4_setdc(i, p4clockmod_table[index].driver_data); + + return 0; +} + + +static unsigned int cpufreq_p4_get_frequency(struct cpuinfo_x86 *c) +{ + if (c->x86 == 0x06) { + if (cpu_has(c, X86_FEATURE_EST)) + printk_once(KERN_WARNING PFX "Warning: EST-capable " + "CPU detected. The acpi-cpufreq module offers " + "voltage scaling in addition to frequency " + "scaling. You should use that instead of " + "p4-clockmod, if possible.\n"); + switch (c->x86_model) { + case 0x0E: /* Core */ + case 0x0F: /* Core Duo */ + case 0x16: /* Celeron Core */ + case 0x1C: /* Atom */ + p4clockmod_driver.flags |= CPUFREQ_CONST_LOOPS; + return speedstep_get_frequency(SPEEDSTEP_CPU_PCORE); + case 0x0D: /* Pentium M (Dothan) */ + p4clockmod_driver.flags |= CPUFREQ_CONST_LOOPS; + /* fall through */ + case 0x09: /* Pentium M (Banias) */ + return speedstep_get_frequency(SPEEDSTEP_CPU_PM); + } + } + + if (c->x86 != 0xF) + return 0; + + /* on P-4s, the TSC runs with constant frequency independent whether + * throttling is active or not. */ + p4clockmod_driver.flags |= CPUFREQ_CONST_LOOPS; + + if (speedstep_detect_processor() == SPEEDSTEP_CPU_P4M) { + printk(KERN_WARNING PFX "Warning: Pentium 4-M detected. " + "The speedstep-ich or acpi cpufreq modules offer " + "voltage scaling in addition of frequency scaling. " + "You should use either one instead of p4-clockmod, " + "if possible.\n"); + return speedstep_get_frequency(SPEEDSTEP_CPU_P4M); + } + + return speedstep_get_frequency(SPEEDSTEP_CPU_P4D); +} + + + +static int cpufreq_p4_cpu_init(struct cpufreq_policy *policy) +{ + struct cpuinfo_x86 *c = &cpu_data(policy->cpu); + int cpuid = 0; + unsigned int i; + +#ifdef CONFIG_SMP + cpumask_copy(policy->cpus, cpu_sibling_mask(policy->cpu)); +#endif + + /* Errata workaround */ + cpuid = (c->x86 << 8) | (c->x86_model << 4) | c->x86_mask; + switch (cpuid) { + case 0x0f07: + case 0x0f0a: + case 0x0f11: + case 0x0f12: + has_N44_O17_errata[policy->cpu] = 1; + pr_debug("has errata -- disabling low frequencies\n"); + } + + if (speedstep_detect_processor() == SPEEDSTEP_CPU_P4D && + c->x86_model < 2) { + /* switch to maximum frequency and measure result */ + cpufreq_p4_setdc(policy->cpu, DC_DISABLE); + recalibrate_cpu_khz(); + } + /* get max frequency */ + stock_freq = cpufreq_p4_get_frequency(c); + if (!stock_freq) + return -EINVAL; + + /* table init */ + for (i = 1; (p4clockmod_table[i].frequency != CPUFREQ_TABLE_END); i++) { + if ((i < 2) && (has_N44_O17_errata[policy->cpu])) + p4clockmod_table[i].frequency = CPUFREQ_ENTRY_INVALID; + else + p4clockmod_table[i].frequency = (stock_freq * i)/8; + } + + /* cpuinfo and default policy values */ + + /* the transition latency is set to be 1 higher than the maximum + * transition latency of the ondemand governor */ + policy->cpuinfo.transition_latency = 10000001; + + return cpufreq_table_validate_and_show(policy, &p4clockmod_table[0]); +} + + +static unsigned int cpufreq_p4_get(unsigned int cpu) +{ + u32 l, h; + + rdmsr_on_cpu(cpu, MSR_IA32_THERM_CONTROL, &l, &h); + + if (l & 0x10) { + l = l >> 1; + l &= 0x7; + } else + l = DC_DISABLE; + + if (l != DC_DISABLE) + return stock_freq * l / 8; + + return stock_freq; +} + +static struct cpufreq_driver p4clockmod_driver = { + .verify = cpufreq_generic_frequency_table_verify, + .target_index = cpufreq_p4_target, + .init = cpufreq_p4_cpu_init, + .get = cpufreq_p4_get, + .name = "p4-clockmod", + .attr = cpufreq_generic_attr, +}; + +static const struct x86_cpu_id cpufreq_p4_id[] = { + { X86_VENDOR_INTEL, X86_FAMILY_ANY, X86_MODEL_ANY, X86_FEATURE_ACC }, + {} +}; + +/* + * Intentionally no MODULE_DEVICE_TABLE here: this driver should not + * be auto loaded. Please don't add one. + */ + +static int __init cpufreq_p4_init(void) +{ + int ret; + + /* + * THERM_CONTROL is architectural for IA32 now, so + * we can rely on the capability checks + */ + if (!x86_match_cpu(cpufreq_p4_id) || !boot_cpu_has(X86_FEATURE_ACPI)) + return -ENODEV; + + ret = cpufreq_register_driver(&p4clockmod_driver); + if (!ret) + printk(KERN_INFO PFX "P4/Xeon(TM) CPU On-Demand Clock " + "Modulation available\n"); + + return ret; +} + + +static void __exit cpufreq_p4_exit(void) +{ + cpufreq_unregister_driver(&p4clockmod_driver); +} + + +MODULE_AUTHOR("Zwane Mwaikambo "); +MODULE_DESCRIPTION("cpufreq driver for Pentium(TM) 4/Xeon(TM)"); +MODULE_LICENSE("GPL"); + +late_initcall(cpufreq_p4_init); +module_exit(cpufreq_p4_exit); diff --git a/pool/shard003/C/0068296_heatmap.c b/pool/shard003/C/0068296_heatmap.c new file mode 100644 index 0000000000000000000000000000000000000000..3de149d54e825c6f5334d6c82b7a73005e8b4b7c --- /dev/null +++ b/pool/shard003/C/0068296_heatmap.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include + +#include "classify.h" + + +int +main(int argc, char *argv[]) +{ + int opt, optindex = 0; + char *dir; + enum comparison_type cmp_type = NOW; /* default to now */ + + struct option options[] = { + {"now", no_argument, 0, 'n'}, + {"most-recent", no_argument, 0, 'm'}, + {0, 0, 0, 0} + }; + + while ((opt = getopt_long(argc, argv, "n;;m;;l;;", + options, &optindex)) != -1) { + switch (opt) { + case 'n': + cmp_type = NOW; + break; + case 'm': + case 'l': + cmp_type = MOST_RECENT; + break; + default: + fprintf(stderr, "Usage: hm [-nm] [DIR]\n"); + exit(EXIT_FAILURE); + } + } + + if (argc > 3) { + work_on_args(argc, argv, cmp_type); + } else { + dir = argv[optind] ? argv[optind] : "."; + classify_and_print(dir, cmp_type); + } + + return 0; +} diff --git a/pool/shard003/C/0068303_33.c b/pool/shard003/C/0068303_33.c new file mode 100644 index 0000000000000000000000000000000000000000..6d518b1c23d36200f09396b194039943ad9b5060 --- /dev/null +++ b/pool/shard003/C/0068303_33.c @@ -0,0 +1,20 @@ +#include + +#define NUM 1024 + + +int main(void) +{ + int array[NUM] = {1,2,3,4}; + int i = 0, sum = 0; + + for( i = 0; i < 4; i++ ) + { + if( array[i]%2 ==0) + { + sum += array[i]; + } + } + printf("%d",sum); + return 0; +} diff --git a/pool/shard003/C/0068317_bedReader.c b/pool/shard003/C/0068317_bedReader.c new file mode 100644 index 0000000000000000000000000000000000000000..d4019ac09ffbad283fff237c1addf3ae78e02d7e --- /dev/null +++ b/pool/shard003/C/0068317_bedReader.c @@ -0,0 +1,122 @@ +// Copyright 2013-2014 EMBL-EBI +// +// 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 "wiggleIterator.h" + +typedef struct bedReaderData_st { + char *filename; + FILE * file; + char * chrom; + int stop; +} BedReaderData; + +void BedReaderPop(WiggleIterator * wi) { + BedReaderData * data = (BedReaderData *) wi->data; + char line[5000]; + char chrom[1000]; + char sign = '.'; + int start, finish; + + if (wi->done) + return; + + while (fgets(line, 5000, data->file)) { + if (line[0] == '#' || line[0] == EOF) + continue; + + sscanf(line, "%s\t%i\t%i", chrom, &start, &finish); + // Conversion from 0 to 1-based... + start++; + finish++; + + if (strcmp(chrom, wi->chrom) < 0 || (strcmp(chrom, wi->chrom) == 0 && start < wi->start)) { + fprintf(stderr, "Bed file %s is not sorted!\nPosition %s:%i is before %s:%i\n", data->filename, chrom, start, wi->chrom, wi->start); + exit(1); + } + + wi->start = start; + wi->finish = finish; + + if (sign == '+') + wi->strand = 1; + else if (sign == '-') + wi->strand = -1; + else + wi->strand = 0; + + + // The reason for creating a new string instead of simply + // overwriting is that other functions may still be pointin + // at the old label + if (wi->chrom[0] == '\0' || strcmp(wi->chrom, chrom)) { + wi->chrom = (char *) calloc(strlen(chrom) + 1, sizeof(char)); + strcpy(wi->chrom, chrom); + } + + if (data->stop > 0) { + if ((wi->start >= data->stop && strcmp(wi->chrom, data->chrom) == 0) || strcmp(wi->chrom, data->chrom) > 0) { + wi->done = true; + return; + } else if (wi->finish > data->stop) { + wi->finish = data->stop; + } + } + + return; + } + + fclose(data->file); + data->file = NULL; + wi->done = true; +} + +void BedReaderSeek(WiggleIterator * wi, const char * chrom, int start, int finish) { + BedReaderData * data = (BedReaderData*) wi->data; + + data->stop = finish; + data->chrom = chrom; + + if (!data->file || strcmp(chrom, wi->chrom) < 0 || (strcmp(chrom, wi->chrom) == 0 && start < wi->start)) { + if (data->file) + fclose(data->file); + if (!(data->file = fopen(data->filename, "r"))) { + fprintf(stderr, "Could not open input file %s\n", data->filename); + exit(1); + } + wi->done = false; + pop(wi); + } + + while (!wi->done && (strcmp(wi->chrom, chrom) < 0 || (strcmp(chrom, wi->chrom) == 0 && wi->finish < start))) + pop(wi); + + if (!wi->done && strcmp(chrom, wi->chrom) == 0 && wi->start < start) + wi->start = start; +} + +WiggleIterator * BedReader(char * filename) { + BedReaderData * data = (BedReaderData *) calloc(1, sizeof(BedReaderData)); + data->filename = filename; + data->stop = -1; + if (!(data->file = fopen(filename, "r"))) { + fprintf(stderr, "Could not open bed file %s\n", filename); + exit(1); + } + WiggleIterator * res = newWiggleIterator(data, &BedReaderPop, &BedReaderSeek, 0); + res->overlaps = true; + return res; +} diff --git a/pool/shard003/C/0068319_ip_forward.c b/pool/shard003/C/0068319_ip_forward.c new file mode 100644 index 0000000000000000000000000000000000000000..df3fe50bbf0dc0a76cebf690c4ec8697c7889d1d --- /dev/null +++ b/pool/shard003/C/0068319_ip_forward.c @@ -0,0 +1,131 @@ +/* + * INET An implementation of the TCP/IP protocol suite for the LINUX + * operating system. INET is implemented using the BSD Socket + * interface as the means of communication with the user level. + * + * The IP forwarding functionality. + * + * Authors: see ip.c + * + * Fixes: + * Many : Split from ip.c , see ip_input.c for + * history. + * Dave Gregorich : NULL ip_rt_put fix for multicast + * routing. + * Jos Vos : Add call_out_firewall before sending, + * use output device for accounting. + * Jos Vos : Call forward firewall after routing + * (always use output device). + * Mike McLagan : Routing by source + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int ip_forward_finish(struct sk_buff *skb) +{ + struct ip_options * opt = &(IPCB(skb)->opt); + + IP_INC_STATS_BH(dev_net(skb->dst->dev), IPSTATS_MIB_OUTFORWDATAGRAMS); + + if (unlikely(opt->optlen)) + ip_forward_options(skb); + + return dst_output(skb); +} + +int ip_forward(struct sk_buff *skb) +{ + struct iphdr *iph; /* Our header */ + struct rtable *rt; /* Route we use */ + struct ip_options * opt = &(IPCB(skb)->opt); + + if (skb_warn_if_lro(skb)) + goto drop; + + if (!xfrm4_policy_check(NULL, XFRM_POLICY_FWD, skb)) + goto drop; + + if (IPCB(skb)->opt.router_alert && ip_call_ra_chain(skb)) + return NET_RX_SUCCESS; + + if (skb->pkt_type != PACKET_HOST) + goto drop; + + skb_forward_csum(skb); + + /* + * According to the RFC, we must first decrease the TTL field. If + * that reaches zero, we must reply an ICMP control message telling + * that the packet's lifetime expired. + */ + if (ip_hdr(skb)->ttl <= 1) + goto too_many_hops; + + if (!xfrm4_route_forward(skb)) + goto drop; + + rt = skb->rtable; + + if (opt->is_strictroute && rt->rt_dst != rt->rt_gateway) + goto sr_failed; + + if (unlikely(skb->len > dst_mtu(&rt->u.dst) && !skb_is_gso(skb) && + (ip_hdr(skb)->frag_off & htons(IP_DF))) && !skb->local_df) { + IP_INC_STATS(dev_net(rt->u.dst.dev), IPSTATS_MIB_FRAGFAILS); + icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED, + htonl(dst_mtu(&rt->u.dst))); + goto drop; + } + + /* We are about to mangle packet. Copy it! */ + if (skb_cow(skb, LL_RESERVED_SPACE(rt->u.dst.dev)+rt->u.dst.header_len)) + goto drop; + iph = ip_hdr(skb); + + /* Decrease ttl after skb cow done */ + ip_decrease_ttl(iph); + + /* + * We now generate an ICMP HOST REDIRECT giving the route + * we calculated. + */ + if (rt->rt_flags&RTCF_DOREDIRECT && !opt->srr && !skb_sec_path(skb)) + ip_rt_send_redirect(skb); + + skb->priority = rt_tos2priority(iph->tos); + + return NF_HOOK(PF_INET, NF_INET_FORWARD, skb, skb->dev, rt->u.dst.dev, + ip_forward_finish); + +sr_failed: + /* + * Strict routing permits no gatewaying + */ + icmp_send(skb, ICMP_DEST_UNREACH, ICMP_SR_FAILED, 0); + goto drop; + +too_many_hops: + /* Tell the sender its packet died... */ + IP_INC_STATS_BH(dev_net(skb->dst->dev), IPSTATS_MIB_INHDRERRORS); + icmp_send(skb, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL, 0); +drop: + kfree_skb(skb); + return NET_RX_DROP; +} diff --git a/pool/shard003/C/0068359_system_a2fxxxm3.c b/pool/shard003/C/0068359_system_a2fxxxm3.c new file mode 100644 index 0000000000000000000000000000000000000000..496974a4453175b58012db9cfe7ff81a14903ee2 --- /dev/null +++ b/pool/shard003/C/0068359_system_a2fxxxm3.c @@ -0,0 +1,199 @@ +/******************************************************************************* + * (c) Copyright 2009 Actel Corporation. All rights reserved. + * + * SmartFusion A2FxxxM3 CMSIS system initialization. + * + * SVN $Revision: 2069 $ + * SVN $Date: 2010-01-28 00:23:48 +0000 (Thu, 28 Jan 2010) $ + */ +#include "a2fxxxm3.h" +#include "mss_assert.h" + +/* System frequency (FCLK) coming out of reset is 25MHz. */ +#define RESET_SYSCLCK_FREQ 25000000uL + +/* + * SmartFusion Microcontroller Subsystem FLCK frequency. + * The value of SMARTFUSION_FCLK_FREQ is used to report the system's clock + * frequency in system's which either do not use the Actel System Boot or + * a version of the Actel System Boot older than 1.3.1. In eitehr of these cases + * SMARTFUSION_FCLK_FREQ should be defined in the projects settings to reflect + * the FCLK frequency selected in the Libero MSS configurator. + * Systems using the Actel System Boot version 1.3.1 or later do not require this + * define since the system's frequency is retrieved from eNVM spare pages where + * the MSS Configurator stored the frequency selected during hardware design/configuration. + */ +#ifdef SMARTFUSION_FCLK_FREQ +#define SMARTFUSION_FCLK_FREQ_DEFINED 1 +#else +#define SMARTFUSION_FCLK_FREQ_DEFINED 0 +#define SMARTFUSION_FCLK_FREQ RESET_SYSCLCK_FREQ +#endif + +/* Divider values for APB0, APB1 and ACE clocks. */ +#define RESET_PCLK0_DIV 4uL +#define RESET_PCLK1_DIV 4uL +#define RESET_ACE_DIV 4uL +#define RESET_FPGA_CLK_DIV 4uL + +/* System register clock control mask and shift for PCLK dividers. */ +#define PCLK_DIV_MASK 0x00000003uL +#define PCLK0_DIV_SHIFT 2uL +#define PCLK1_DIV_SHIFT 4uL +#define ACE_DIV_SHIFT 6uL + +/* System register MSS_CCC_DIV_CR mask and shift for GLB (FPGA fabric clock). */ +#define OBDIV_SHIFT 8uL +#define OBDIV_MASK 0x0000001FuL +#define OBDIVHALF_SHIFT 13uL +#define OBDIVHALF_MASK 0x00000001uL + +/* + * Actel system boot version defines used to extract the system clock from eNVM + * spare pages. + * These defines allow detecting the presence of Actel system boot in eNVM spare + * pages and the version of that system boot executable and associated + * configuration data. + */ +#define SYSBOOT_KEY_ADDR (uint32_t *)0x6008081C +#define SYSBOOT_KEY_VALUE 0x4C544341uL +#define SYSBOOT_VERSION_ADDR (uint32_t *)0x60080840 +#define SYSBOOT_1_3_FCLK_ADDR (uint32_t *)0x6008162C +#define SYSBOOT_2_x_FCLK_ADDR (uint32_t *)0x60081EAC + +/* + * The system boot version is stored in the least significant 24 bits of a word. + * The FCLK is stored in eNVM from version 1.3.1 of the system boot. We expect + * that the major version number of the system boot version will change if the + * system boot configuration data layout needs to change. + */ +#define SYSBOOT_VERSION_MASK 0x00FFFFFFuL +#define MIN_SYSBOOT_VERSION 0x00010301uL +#define SYSBOOT_VERSION_2_X 0x00020000uL +#define MAX_SYSBOOT_VERSION 0x00030000uL + +/* Standard CMSIS global variables. */ +uint32_t SystemFrequency = SMARTFUSION_FCLK_FREQ; /*!< System Clock Frequency (Core Clock) */ +uint32_t SystemCoreClock = SMARTFUSION_FCLK_FREQ; /*!< System Clock Frequency (Core Clock) */ + +/* SmartFusion specific clocks. */ +uint32_t g_FrequencyPCLK0 = (SMARTFUSION_FCLK_FREQ / RESET_PCLK0_DIV); /*!< Clock frequency of APB bus 0. */ +uint32_t g_FrequencyPCLK1 = (SMARTFUSION_FCLK_FREQ / RESET_PCLK1_DIV); /*!< Clock frequency of APB bus 1. */ +uint32_t g_FrequencyACE = (SMARTFUSION_FCLK_FREQ / RESET_ACE_DIV); /*!< Clock frequency of Analog Compute Engine. */ +uint32_t g_FrequencyFPGA = (SMARTFUSION_FCLK_FREQ / RESET_FPGA_CLK_DIV); /*!< Clock frequecny of FPGA fabric */ + +/* Local functions */ +static uint32_t GetSystemClock( void ); + +/***************************************************************************//** + * See system_a2fm3fxxx.h for details. + */ +void SystemInit(void) +{ +} + +/***************************************************************************//** + * + */ +void SystemCoreClockUpdate (void) +{ + uint32_t PclkDiv0; + uint32_t PclkDiv1; + uint32_t AceDiv; + uint32_t FabDiv; + + const uint32_t pclk_div_lut[4] = { 1uL, 2uL, 4uL, 1uL }; + + /* Read PCLK dividers from system registers. Multiply the value read from + * system register by two to get actual divider value. */ + PclkDiv0 = pclk_div_lut[((SYSREG->MSS_CLK_CR >> PCLK0_DIV_SHIFT) & PCLK_DIV_MASK)]; + PclkDiv1 = pclk_div_lut[((SYSREG->MSS_CLK_CR >> PCLK1_DIV_SHIFT) & PCLK_DIV_MASK)]; + AceDiv = pclk_div_lut[((SYSREG->MSS_CLK_CR >> ACE_DIV_SHIFT) & PCLK_DIV_MASK)]; + { + /* Compute the FPGA fabric frequency divider. */ + uint32_t obdiv; + uint32_t obdivhalf; + + obdiv = (SYSREG->MSS_CCC_DIV_CR >> OBDIV_SHIFT) & OBDIV_MASK; + obdivhalf = (SYSREG->MSS_CCC_DIV_CR >> OBDIVHALF_SHIFT) & OBDIVHALF_MASK; + FabDiv = obdiv + 1uL; + if ( obdivhalf != 0uL ) + { + FabDiv = FabDiv * 2uL; + } + } + + /* Retrieve FCLK from eNVM spare pages if Actel system boot programmed as part of the system. */ + + /* Read system clock from eNVM spare pages. */ + SystemCoreClock = GetSystemClock(); + g_FrequencyPCLK0 = SystemCoreClock / PclkDiv0; + g_FrequencyPCLK1 = SystemCoreClock / PclkDiv1; + g_FrequencyACE = SystemCoreClock / AceDiv; + g_FrequencyFPGA = SystemCoreClock / FabDiv; + + /* Keep SystemFrequency as well as SystemCoreClock for legacy reasons. */ + SystemFrequency = SystemCoreClock; +} + +/***************************************************************************//** + * Retrieve the system clock frequency from eNVM spare page if available. + * Returns the frequency defined through SMARTFUSION_FCLK_FREQ if FCLK cannot be + * retrieved from eNVM spare pages. + * The FCLK frequency value selected in the MSS Configurator software tool is + * stored in eNVM spare pages as part of the Actel system boot configuration data. + */ +uint32_t GetSystemClock( void ) +{ + uint32_t fclk = 0uL; + + uint32_t * p_sysboot_key = SYSBOOT_KEY_ADDR; + + if ( SYSBOOT_KEY_VALUE == *p_sysboot_key ) + { + /* Actel system boot programmed, check if it has the FCLK value stored. */ + uint32_t *p_sysboot_version = SYSBOOT_VERSION_ADDR; + uint32_t sysboot_version = *p_sysboot_version; + + sysboot_version &= SYSBOOT_VERSION_MASK; + + if ( sysboot_version >= MIN_SYSBOOT_VERSION ) + { + /* Handle change of eNVM location of FCLK between 1.3.x and 2.x.x versions of the system boot. */ + if ( sysboot_version < SYSBOOT_VERSION_2_X ) + { + /* Read FCLK value from MSS configurator generated configuration + * data stored in eNVM spare pages as part of system boot version 1.3.x + * configuration tables. */ + uint32_t *p_fclk = SYSBOOT_1_3_FCLK_ADDR; + fclk = *p_fclk; + } + else if ( sysboot_version < MAX_SYSBOOT_VERSION ) + { + /* Read FCLK value from MSS configurator generated configuration + * data stored in eNVM spare pages as part of system boot version 2.x.x + * configuration tables. */ + uint32_t *p_fclk = SYSBOOT_2_x_FCLK_ADDR; + fclk = *p_fclk; + } + else + { + fclk = 0uL; + } + } + } + + if ( 0uL == fclk ) + { + /* + * Could not retrieve FCLK from system boot configuration data. Fall back + * to using SMARTFUSION_FCLK_FREQ which must then be defined as part of + * project settings. + */ + ASSERT( SMARTFUSION_FCLK_FREQ_DEFINED ); + fclk = SMARTFUSION_FCLK_FREQ; + } + + return fclk; +} + diff --git a/pool/shard003/C/0068362_altera_jtag_uart.c b/pool/shard003/C/0068362_altera_jtag_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..cb11b3132659757ce67e94339165800079390de6 --- /dev/null +++ b/pool/shard003/C/0068362_altera_jtag_uart.c @@ -0,0 +1,154 @@ +/* + * (C) Copyright 2004, Psyent Corporation + * Scott McNutt + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +/* data register */ +#define ALTERA_JTAG_RVALID BIT(15) /* Read valid */ + +/* control register */ +#define ALTERA_JTAG_AC BIT(10) /* activity indicator */ +#define ALTERA_JTAG_RRDY BIT(12) /* read available */ +#define ALTERA_JTAG_WSPACE(d) ((d) >> 16) /* Write space avail */ +/* Write fifo size. FIXME: this should be extracted with sopc2dts */ +#define ALTERA_JTAG_WRITE_DEPTH 64 + +struct altera_jtaguart_regs { + u32 data; /* Data register */ + u32 control; /* Control register */ +}; + +struct altera_jtaguart_platdata { + struct altera_jtaguart_regs *regs; +}; + +static int altera_jtaguart_setbrg(struct udevice *dev, int baudrate) +{ + return 0; +} + +static int altera_jtaguart_putc(struct udevice *dev, const char ch) +{ + struct altera_jtaguart_platdata *plat = dev->platdata; + struct altera_jtaguart_regs *const regs = plat->regs; + u32 st = readl(®s->control); + +#ifdef CONFIG_ALTERA_JTAG_UART_BYPASS + if (!(st & ALTERA_JTAG_AC)) /* no connection yet */ + return -ENETUNREACH; +#endif + + if (ALTERA_JTAG_WSPACE(st) == 0) + return -EAGAIN; + + writel(ch, ®s->data); + + return 0; +} + +static int altera_jtaguart_pending(struct udevice *dev, bool input) +{ + struct altera_jtaguart_platdata *plat = dev->platdata; + struct altera_jtaguart_regs *const regs = plat->regs; + u32 st = readl(®s->control); + + if (input) + return st & ALTERA_JTAG_RRDY ? 1 : 0; + else + return !(ALTERA_JTAG_WSPACE(st) == ALTERA_JTAG_WRITE_DEPTH); +} + +static int altera_jtaguart_getc(struct udevice *dev) +{ + struct altera_jtaguart_platdata *plat = dev->platdata; + struct altera_jtaguart_regs *const regs = plat->regs; + u32 val; + + val = readl(®s->data); + + if (!(val & ALTERA_JTAG_RVALID)) + return -EAGAIN; + + return val & 0xff; +} + +static int altera_jtaguart_probe(struct udevice *dev) +{ +#ifdef CONFIG_ALTERA_JTAG_UART_BYPASS + struct altera_jtaguart_platdata *plat = dev->platdata; + struct altera_jtaguart_regs *const regs = plat->regs; + + writel(ALTERA_JTAG_AC, ®s->control); /* clear AC flag */ +#endif + return 0; +} + +static int altera_jtaguart_ofdata_to_platdata(struct udevice *dev) +{ + struct altera_jtaguart_platdata *plat = dev_get_platdata(dev); + + plat->regs = map_physmem(dev_get_addr(dev), + sizeof(struct altera_jtaguart_regs), + MAP_NOCACHE); + + return 0; +} + +static const struct dm_serial_ops altera_jtaguart_ops = { + .putc = altera_jtaguart_putc, + .pending = altera_jtaguart_pending, + .getc = altera_jtaguart_getc, + .setbrg = altera_jtaguart_setbrg, +}; + +static const struct udevice_id altera_jtaguart_ids[] = { + { .compatible = "altr,juart-1.0" }, + {} +}; + +U_BOOT_DRIVER(altera_jtaguart) = { + .name = "altera_jtaguart", + .id = UCLASS_SERIAL, + .of_match = altera_jtaguart_ids, + .ofdata_to_platdata = altera_jtaguart_ofdata_to_platdata, + .platdata_auto_alloc_size = sizeof(struct altera_jtaguart_platdata), + .probe = altera_jtaguart_probe, + .ops = &altera_jtaguart_ops, + .flags = DM_FLAG_PRE_RELOC, +}; + +#ifdef CONFIG_DEBUG_UART_ALTERA_JTAGUART + +#include + +static inline void _debug_uart_init(void) +{ +} + +static inline void _debug_uart_putc(int ch) +{ + struct altera_jtaguart_regs *regs = (void *)CONFIG_DEBUG_UART_BASE; + + while (1) { + u32 st = readl(®s->control); + + if (ALTERA_JTAG_WSPACE(st)) + break; + } + + writel(ch, ®s->data); +} + +DEBUG_UART_FUNCS + +#endif diff --git a/pool/shard003/C/0068371_enc_read.c b/pool/shard003/C/0068371_enc_read.c new file mode 100644 index 0000000000000000000000000000000000000000..4dfdac3146bc2a97a2182be7639fc75ce76eff42 --- /dev/null +++ b/pool/shard003/C/0068371_enc_read.c @@ -0,0 +1,139 @@ +/* des_read.c */ +/* Copyright (C) 1992 Eric Young - see COPYING for more details */ +#include +#include "des_local.h" + +/* This has some uglies in it but it works - even over sockets. */ +extern int errno; +int des_rw_mode=DES_PCBC_MODE; + +int des_enc_read(fd,buf,len,sched,iv) +int fd; +char *buf; +int len; +des_key_schedule sched; +des_cblock *iv; + { + /* data to be unencrypted */ + int net_num=0; + unsigned char net[BSIZE]; + /* extra unencrypted data + * for when a block of 100 comes in but is des_read one byte at + * a time. */ + static char unnet[BSIZE]; + static int unnet_start=0; + static int unnet_left=0; + int i; + long num=0,rnum; + unsigned char *p; + + /* left over data from last decrypt */ + if (unnet_left != 0) + { + if (unnet_left < len) + { + /* we still still need more data but will return + * with the number of bytes we have - should always + * check the return value */ + bcopy(&(unnet[unnet_start]),buf,unnet_left); + /* eay 26/08/92 I had the next 2 lines + * reversed :-( */ + i=unnet_left; + unnet_start=unnet_left=0; + } + else + { + bcopy(&(unnet[unnet_start]),buf,len); + unnet_start+=len; + unnet_left-=len; + i=len; + } + return(i); + } + + /* We need to get more data. */ + if (len > MAXWRITE) len=MAXWRITE; + + /* first - get the length */ + net_num=0; + while (net_num < HDRSIZE) + { + i=read(fd,&(net[net_num]),HDRSIZE-net_num); + if ((i == -1) && (errno == EINTR)) continue; + if (i <= 0) return(0); + net_num+=i; + } + + /* we now have at net_num bytes in net */ + p=net; + num=0; + n2l(p,num); + /* num should be rounded up to the next group of eight + * we make sure that we have read a multiple of 8 bytes from the net. + */ + rnum=(num < 8)?8:((num+7)/8*8); + net_num=0; + while (net_num < rnum) + { + i=read(fd,&(net[net_num]),rnum-net_num); + if ((i == -1) && (errno == EINTR)) continue; + if (i <= 0) return(0); + net_num+=i; + } + + /* Check if there will be data left over. */ + if (len < num) + { + if (des_rw_mode == DES_PCBC_MODE) + pcbc_encrypt((des_cblock *)net,(des_cblock *)unnet, + num,sched,iv,DES_DECRYPT); + else + cbc_encrypt((des_cblock *)net,(des_cblock *)unnet, + num,sched,iv,DES_DECRYPT); + bcopy(unnet,buf,len); + unnet_start=len; + unnet_left=num-len; + + /* The following line is done because we return num + * as the number of bytes read. */ + num=len; + } + else + { + /* >output is a multiple of 8 byes, if len < rnum + * >we must be careful. The user must be aware that this + * >routine will write more bytes than he asked for. + * >The length of the buffer must be correct. + * FIXED - Should be ok now 18-9-90 - eay */ + if (len < rnum) + { + char tmpbuf[BSIZE]; + + if (des_rw_mode == DES_PCBC_MODE) + pcbc_encrypt((des_cblock *)net, + (des_cblock *)tmpbuf, + num,sched,iv,DES_DECRYPT); + else + cbc_encrypt((des_cblock *)net, + (des_cblock *)tmpbuf, + num,sched,iv,DES_DECRYPT); + + /* eay 26/08/92 fix a bug that returned more + * bytes than you asked for (returned len bytes :-( */ + bcopy(tmpbuf,buf,num); + } + else + { + if (des_rw_mode == DES_PCBC_MODE) + pcbc_encrypt((des_cblock *)net, + (des_cblock *)buf,num,sched,iv, + DES_DECRYPT); + else + cbc_encrypt((des_cblock *)net, + (des_cblock *)buf,num,sched,iv, + DES_DECRYPT); + } + } + return(num); + } + diff --git a/pool/shard003/C/0068392_prog30.c b/pool/shard003/C/0068392_prog30.c new file mode 100644 index 0000000000000000000000000000000000000000..340ed7c51c527fb88405098ad9872ed106e35cd6 --- /dev/null +++ b/pool/shard003/C/0068392_prog30.c @@ -0,0 +1,57 @@ +#include +#include +#include +#include +#include + +#define handle_error(msg) \ + do { perror(msg); exit(EXIT_FAILURE); } while(0) + +int count; +char val; + +void sighupHandler(int sig) { + FILE *fp; + if( (fp=fopen("reconfigure.conf", "r")) == NULL) { + handle_error("fopen"); + } + if(fscanf(fp, "%c %d\n", &val, &count)) { + if(ferror(fp)) { + handle_error("fscanf"); + } + } + fclose(fp); + return; +} + + +int main(int argc, char *argv[]) { + sigset_t sigmask; + struct sigaction action; + int i; + + printf("Process id=%d\n", getpid()); + + /* Handle SIGINT */ + action.sa_handler = sighupHandler; + sigemptyset(&action.sa_mask); + action.sa_flags = SA_RESTART; + sigaction(SIGHUP, &action, NULL); + + /* Setup sigmask to handle critical region */ + sigemptyset(&sigmask); + sigaddset(&sigmask, SIGHUP); + + /* Kick start the process */ + sighupHandler(1); + while(1) { + sleep(1); + sigprocmask(SIG_BLOCK, &sigmask, NULL); + for(i=0; i in 2017 - 2019 + * + * https://github.com/zoff99/ToxBlinkenwall + * + */ +/* + * Copyright © 2016-2017 The TokTok team. + * Copyright © 2013 Tox project. + * Copyright © 2013 plutooo + * + * This file is part of Tox, the free peer to peer instant messenger. + * This file is donated to the Tox Project. + * + * Tox 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. + * + * Tox 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 Tox. If not, see . + */ +#include "rb.h" + +#include + +struct BWRingBuffer +{ + uint16_t size; /* Max size */ + uint16_t start; + uint16_t end; + void **data; + uint32_t *w; + uint32_t *h; +}; + +bool bw_rb_full(const BWRingBuffer *b) +{ + return (b->end + 1) % b->size == b->start; +} + +bool bw_rb_empty(const BWRingBuffer *b) +{ + return b->end == b->start; +} + +/* + * returns: NULL on success + start address of element to delete on ringbuffer full, new element ist still written into buffer + */ +void *bw_rb_write(BWRingBuffer *b, void *p, uint32_t w, uint32_t h) +{ + void *rc = NULL; + + if ((b->end + 1) % b->size == b->start) /* full */ + { + rc = b->data[b->start]; + } + + b->data[b->end] = p; + b->w[b->end] = w; + b->h[b->end] = h; + b->end = (b->end + 1) % b->size; + + if (b->end == b->start) + { + b->start = (b->start + 1) % b->size; + } + + return rc; +} + +bool bw_rb_read(BWRingBuffer *b, void **p, uint32_t *w, uint32_t *h) +{ + if (b->end == b->start) /* Empty */ + { + *p = NULL; + return false; + } + + *p = b->data[b->start]; + *w = b->w[b->start]; + *h = b->h[b->start]; + b->start = (b->start + 1) % b->size; + return true; +} + +BWRingBuffer *bw_rb_new(int size) +{ + BWRingBuffer *buf = (BWRingBuffer *)calloc(sizeof(BWRingBuffer), 1); + + if (!buf) + { + return NULL; + } + + buf->size = size + 1; /* include empty elem */ + + if (!(buf->data = (void **)calloc(buf->size, sizeof(void *)))) + { + free(buf); + return NULL; + } + + if (!(buf->w = (uint32_t *)calloc(buf->size, sizeof(uint32_t)))) + { + // TODO: ??? + } + + if (!(buf->h = (uint32_t *)calloc(buf->size, sizeof(uint32_t)))) + { + // TODO: ??? + } + + return buf; +} + +void bw_rb_kill(BWRingBuffer *b) +{ + if (b) + { + free(b->data); + free(b->w); + free(b->h); + free(b); + } +} + +uint16_t bw_rb_size(const BWRingBuffer *b) +{ + if (bw_rb_empty(b)) + { + return 0; + } + + return + b->end > b->start ? + b->end - b->start : + (b->size - b->start) + b->end; +} + +uint16_t bw_rb_data(const BWRingBuffer *b, void **dest) +{ + uint16_t i = 0; + + for (; i < bw_rb_size(b); i++) + { + dest[i] = b->data[(b->start + i) % b->size]; + } + + return i; +} + + + diff --git a/pool/shard003/C/0068446_ted-fetch.c b/pool/shard003/C/0068446_ted-fetch.c new file mode 100644 index 0000000000000000000000000000000000000000..5f956f652fc3f519793f6683968b29ac14ae198a --- /dev/null +++ b/pool/shard003/C/0068446_ted-fetch.c @@ -0,0 +1,235 @@ +/* + * ted-fetch.c - Phi2 data fetch for the TED emulation. + * + * Written by + * Andreas Boose + * Ettore Perazzoli + * Tibor Biczo + * + * This file is part of VICE, the Versatile Commodore Emulator. + * See README for copyright notice. + * + * 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 "vice.h" + +#include + +#include "alarm.h" +#include "dma.h" +#include "maincpu.h" +#include "ted-fetch.h" +#include "tedtypes.h" +#include "types.h" + + +/* Emulate a matrix line fetch, `num' bytes starting from `offs'. This takes + care of the 10-bit counter wraparound. */ +void ted_fetch_matrix(int offs, int num) +{ + uint8_t *p; + int start_char; + int c; + int dma_offset = (ted.ted_raster_counter & 7) + == (unsigned int)((ted.raster.ysmooth + 1) & 7) ? 0x0400 : 0; + + /* Matrix fetches are done during Phi2, the fabulous "bad lines" */ + p = ted.screen_ptr; + + start_char = (ted.memptr_col + offs + dma_offset) & 0x3ff; + c = 0x3ff - start_char + 1; + + if (c >= num) { + memcpy(ted.vbuf + offs, p + start_char, num); + } else { + memcpy(ted.vbuf + offs, p + start_char, c); + memcpy(ted.vbuf + offs + c, p, num - c); + } + /*memcpy(ted.cbuf, ted.cbuf_tmp, TED_SCREEN_TEXTCOLS);*/ + +/* log_debug("Fetch line : %03x, %03x", ted.ted_raster_counter, start_char);*/ +} + +inline void ted_fetch_color(int offs, int num) +{ + int start_char; + int c; + + start_char = (ted.memptr_col + offs) & 0x3ff; + c = 0x3ff - start_char + 1; + + if (c >= num) { + memcpy(ted.cbuf_tmp + offs, ted.color_ptr + start_char, num); + } else { + memcpy(ted.cbuf_tmp + offs, ted.color_ptr + start_char, c); + memcpy(ted.cbuf_tmp + offs + c, ted.color_ptr, num - c); + } +/* log_debug("Color fetch : %03x, %03x", ted.ted_raster_counter, start_char);*/ +} + +/* If we are on a bad line, do the DMA. Return nonzero if cycles have been + stolen. */ +inline static int do_matrix_fetch(CLOCK sub) +{ + int reval = 0; + + if (!ted.memory_fetch_done) { + raster_t *raster; + + raster = &ted.raster; + + ted.memory_fetch_done = 1; + ted.mem_counter = ted.memptr_col; + ted.chr_pos_count = ted.memptr; /* FIXME this is not here */ + + if ((ted.ted_raster_counter & 7) + == (unsigned int)((raster->ysmooth + 1) & 7) + && ted.allow_bad_lines + && ted.ted_raster_counter > ted.first_dma_line + /* && ted.bad_line */ + && ted.ted_raster_counter <= ted.last_dma_line) { + ted_fetch_matrix(0, TED_SCREEN_TEXTCOLS); + + raster->draw_idle_state = 0; + /* raster->ycounter = 0; */ + + ted.idle_state = 0; + ted.idle_data_location = IDLE_NONE; + ted.ycounter_reset_checked = 1; + ted.memory_fetch_done = 2; + + dma_maincpu_steal_cycles(ted.fetch_clk, + (TED_SCREEN_TEXTCOLS + 3) * 2 - sub, 0); + ted_delay_oldclk((TED_SCREEN_TEXTCOLS + 3) * 2 - sub); + ted.bad_line = 1; + reval = 1; + } + + if ((ted.ted_raster_counter & 7) == (unsigned int)raster->ysmooth + && ted.allow_bad_lines + && ted.ted_raster_counter >= ted.first_dma_line + && ted.ted_raster_counter < ted.last_dma_line) { + ted_fetch_color(0, TED_SCREEN_TEXTCOLS); +/* + raster->draw_idle_state = 0; + raster->ycounter = 0; + + ted.idle_state = 0; + ted.idle_data_location = IDLE_NONE; + ted.ycounter_reset_checked = 1; + ted.memory_fetch_done = 2; +*/ + dma_maincpu_steal_cycles(ted.fetch_clk, + (TED_SCREEN_TEXTCOLS + 3) * 2 - sub, 0); + ted_delay_oldclk((TED_SCREEN_TEXTCOLS + 3) * 2 - sub); + + ted.bad_line = 1; + reval = 1; + } + } + + return reval; +} + +inline static void handle_fetch_matrix(long offset, CLOCK sub, + CLOCK *write_offset) +{ + *write_offset = 0; + + do_matrix_fetch(sub); + + if ((ted.ted_raster_counter >= ted.first_dma_line) && + (ted.ted_raster_counter < ted.last_dma_line)) { + ted.fetch_clk += ted.cycles_per_line; + } else { + ted.fetch_clk += (ted.screen_height - ted.ted_raster_counter) * ted.cycles_per_line; + } + + alarm_set(ted.raster_fetch_alarm, ted.fetch_clk); + + return; +} + +/* Handle matrix fetch events. FIXME: could be made slightly faster. */ +void ted_fetch_alarm_handler(CLOCK offset, void *data) +{ + CLOCK last_opcode_first_write_clk; + CLOCK last_opcode_last_write_clk; + CLOCK sub; + CLOCK write_offset; + + /* This kludgy thing is used to emulate the behavior of the 6510 when BA + goes low. When BA goes low, every read access stops the processor + until BA is high again; write accesses happen as usual instead. */ + + if (offset > 0) { + switch (OPINFO_NUMBER(last_opcode_info)) { + case 0: + /* In BRK, IRQ and NMI the 3rd, 4th and 5th cycles are write + accesses, while the 1st, 2nd, 6th and 7th are read accesses. */ + last_opcode_first_write_clk = maincpu_clk - 10; + last_opcode_last_write_clk = maincpu_clk - 6; + break; + + case 0x20: + /* In JSR, the 4th and 5th cycles are write accesses, while the + 1st, 2nd, 3rd and 6th are read accesses. */ + last_opcode_first_write_clk = maincpu_clk - 6; + last_opcode_last_write_clk = maincpu_clk - 4; + break; + + default: + /* In all the other opcodes, all the write accesses are the last + ones. */ + if (maincpu_num_write_cycles() != 0) { + last_opcode_last_write_clk = maincpu_clk - 2; + last_opcode_first_write_clk = maincpu_clk + - maincpu_num_write_cycles() * 2; + } else { + last_opcode_first_write_clk = (CLOCK)0; + last_opcode_last_write_clk = last_opcode_first_write_clk; + } + break; + } + } else { /* offset <= 0, i.e. offset == 0 */ + /* If we are called with no offset, we don't have to care about write + accesses. */ + last_opcode_first_write_clk = last_opcode_last_write_clk = 0; + } + + if (ted.fetch_clk < (last_opcode_first_write_clk - 1) + || ted.fetch_clk > last_opcode_last_write_clk) { + sub = 0; + } else { + sub = last_opcode_last_write_clk - ted.fetch_clk + 1; + } + + handle_fetch_matrix(offset, sub, &write_offset); + last_opcode_last_write_clk += write_offset; + + if ((offset > 11) && (ted.fastmode)) { + dma_maincpu_steal_cycles(ted.fetch_clk, -(((signed)offset - 11) / 2), 0); + ted_delay_oldclk(-(((signed)offset - 11) / 2)); + } +} + +void ted_fetch_init(void) +{ + ted.raster_fetch_alarm = alarm_new(maincpu_alarm_context, "TEDRasterFetch", + ted_fetch_alarm_handler, NULL); +} diff --git a/pool/shard003/C/0068459_is_exec.c b/pool/shard003/C/0068459_is_exec.c new file mode 100644 index 0000000000000000000000000000000000000000..4e74c0a38075fa483fbc1b7429877dc6363f346a --- /dev/null +++ b/pool/shard003/C/0068459_is_exec.c @@ -0,0 +1,239 @@ +/* IS_EXEC.C + * + * Copyright (C) 1995 DJ Delorie + * Copyright (C) 1994 Eli Zaretskii + * + * (See the README file in this directory for the copyright and license + * history of this file.) + * + * This file 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 file 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 file. If not, see . + * + * Commentary: + * + * Given a filename or a file handle, and the extension of the file, + * determine if the file is executable. + * First, the file extension is checked in case it uniquely identifies + * the file as either an executable or not. Failing this, the first + * two bytes of the file are tested for known signatures of executable + * files. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern unsigned short _djstat_flags; +unsigned short _get_magic(const char *, int); +int _is_executable(const char *, int, const char *); + +/* + * Read a MAGIC NUMBER from a given file. These are the first + * two bytes of the file, if we look at them as an unsigned short. */ + +#define _STAT_EXEC_EXT 2 /* get execute bits from file extension? */ +#define _STAT_EXEC_MAGIC 4 /* get execute bits from magic signature? */ + +unsigned short +_get_magic(const char *s, int fh) +{ + __dpmi_regs regs; + unsigned short retval; + unsigned short fpos_high = 0, fpos_low = 0; + int read_fail = 0; + + /* If given a pathname, open the file. */ + if (s) + { + int handle; + if((handle = _open(s,0)) == -1) + return 0; + regs.x.bx = handle; + } + /* Else file already open. Remember its current file position + and move to beginning of file. */ + else + { + regs.x.ax = 0x4201; /* set pointer from current position */ + regs.x.bx = fh; + regs.x.cx = regs.x.dx = 0; /* move 0 bytes (i.e., stay put) */ + __dpmi_int(0x21, ®s); + if (regs.x.flags & 1) + { + errno = __doserr_to_errno(regs.x.ax); + return 0; + } + fpos_high = regs.x.dx; /* got current position */ + fpos_low = regs.x.ax; + + regs.x.ax = 0x4200; /* set pointer from the beginning of file */ + regs.x.cx = regs.x.dx = 0; /* move to beginning of file */ + __dpmi_int(0x21, ®s); + if (regs.x.flags & 1) + { + errno = __doserr_to_errno(regs.x.ax); + return 0; + } + } + regs.x.ds = __tb_segment; + regs.x.dx = __tb_offset; + + /* Read 2 bytes from the file. */ + regs.x.ax = 0x3f00; + regs.x.cx = 2; + __dpmi_int(0x21, ®s); + + /* We can either (1) succeed, (2) read less than 2 bytes, + or (3) fail to read at all. */ + if (regs.x.ax != 2) + read_fail = (regs.x.flags & 1) ? regs.x.ax : -1; + + /* If called with filename, close the file. */ + if (s) + { + regs.x.ax = 0x3e00; + __dpmi_int(0x21, ®s); + if (regs.x.flags & 1) + errno = __doserr_to_errno(regs.x.ax); + } + /* Else leave file pointer where we found it. */ + else + { + regs.x.ax = 0x4200; /* set pointer from the beginning of file */ + regs.x.bx = fh; + regs.x.cx = fpos_high; + regs.x.dx = fpos_low; + __dpmi_int(0x21, ®s); + if (regs.x.flags & 1) + { + errno = __doserr_to_errno(regs.x.ax); + return 0; + } + } + + if (read_fail == 0) + retval = _farpeekw(_dos_ds, __tb); + else + { + /* The file couldn't be read: assume non-executable. If the file + *is* executable, but was passed as a file-handle, and the user + opened it in write-only mode, they lose... */ + retval = 0; + if (read_fail != -1) + errno = __doserr_to_errno(read_fail); + } + + return retval; +} + +/* A list of extensions which designate executable files. These + are NOT tested for the magic number. */ +static char executables[] = "|EXE|COM|BAT|BTM|DLL|VXD|"; + +/* A list of extensions which belong to files known to NEVER be + executables. These exist to minimize read()'ing files while + detecting executables by magic number. You are welcome to + add to this list, but remember: only extensions which could + NEVER be present in executables should go here. */ +static char non_executables[] = "\ +|A|A01|A02|A03|A04|A05|ADL|ARC|ARJ|ASC|ASM|AUX|AWK\ +|BAS|BIB|BGI|BMP\ +|C|CC|CFG|CGZ|CH3|CHR|CI|CLP|CMF|CPI|CPP|CXX\ +|DAT|DBF|DIZ|DOC|DVI\ +|E|EL|ELC\ +|F77|FN3\ +|GIF|GZ\ +|H|HLP|HPP|HXX\ +|ICO|IN|INC|INF|INI\ +|JPG\ +|L|LEX|LF|LIB|LOG|LST|LZH\ +|M|MAK|MAP|MF|MID|MPG\ +|O|OBJ\ +|PAK|PAS|PBM|PCD|PCX|PDS|PIC|PIF|PN3|PRJ|PS\ +|RAS|RGB|RLE\ +|S|SND|SY3\ +|TAR|TAZ|TEX|TGA|TGZ|TIF|TXH|TXI|TXT\ +|VOC\ +|WAV|WK1|WK3|WKB|WQ1|WQ3|WQ4|WQ5|WQ6|WQ!\ +|XBM\ +|Y\ +|ZIP|ZOO|"; + +int +_is_executable(const char *filename, int fhandle, const char *extension) +{ + if (!extension && filename) + { + const char *cp, *ep=0; + for (cp=filename; *cp; cp++) + { + if (*cp == '.') + ep = cp; + if (*cp == '/' || *cp == '\\' || *cp == ':') + ep = 0; + } + extension = ep; + } + if ((_djstat_flags & _STAT_EXEC_EXT) == 0 + && extension + && *extension + && strlen(extension) <= ((extension[0]=='.') ? 4 : 3)) + { + /* Search the list of extensions in executables[]. */ + char tmp_buf[6], *tp = tmp_buf; + + *tp++ = '|'; + if (*extension == '.') + extension++; + while (*extension) + *tp++ = toupper (*extension++); + *tp++ = '|'; + *tp = '\0'; + if (strstr(non_executables, tmp_buf)) + return 0; + else if (strstr(executables, tmp_buf)) + return 1; + } + + /* No extension, or extension doesn't define execute + bits unambiguously. We are in for some dirty work. + Read the first two bytes of the file and see if they + are any of the known magic numbers which designate + executable files. + Unix-like shells, which have executable shell scripts + without extensions and DON'T have "#!" as their FIRST + TWO CHARACTERS, lose here. Sorry, folks. */ + if ( (_djstat_flags & _STAT_EXEC_MAGIC) == 0 ) + { + switch (_get_magic(filename, fhandle)) + { + case 0x5a4d: /* "MZ" */ + case 0x010b: + case 0x014c: + case 0x2123: /* "#!" */ + return 1; + } + } + + return 0; +} + +/* EOF */ diff --git a/pool/shard003/C/0068462_fs_mgmt.c b/pool/shard003/C/0068462_fs_mgmt.c new file mode 100644 index 0000000000000000000000000000000000000000..794bda547f9aef31ba110628468125aa07c8a0cc --- /dev/null +++ b/pool/shard003/C/0068462_fs_mgmt.c @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2018-2021 mcumgr authors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include "cborattr/cborattr.h" +#include "mgmt/mgmt.h" +#include "fs_mgmt/fs_mgmt.h" +#include "fs_mgmt/fs_mgmt_impl.h" +#include "fs_mgmt/fs_mgmt_config.h" + +static struct { + /** Whether an upload is currently in progress. */ + bool uploading; + + /** Expected offset of next upload request. */ + size_t off; + + /** Total length of file currently being uploaded. */ + size_t len; +} fs_mgmt_ctxt; + +static const struct mgmt_handler fs_mgmt_handlers[]; + + +/** + * Command handler: fs file (read) + */ +static int +fs_mgmt_file_download(struct mgmt_ctxt *ctxt) +{ + uint8_t file_data[FS_MGMT_DL_CHUNK_SIZE]; + char path[CONFIG_FS_MGMT_PATH_SIZE + 1]; + unsigned long long off; + CborError err; + size_t bytes_read; + size_t file_len; + int rc; + + const struct cbor_attr_t dload_attr[] = { + { + .attribute = "off", + .type = CborAttrUnsignedIntegerType, + .addr.uinteger = &off, + }, + { + .attribute = "name", + .type = CborAttrTextStringType, + .addr.string = path, + .len = sizeof(path), + }, + { 0 }, + }; + + off = ULLONG_MAX; + rc = cbor_read_object(&ctxt->it, dload_attr); + if (rc != 0 || off == ULLONG_MAX) { + return MGMT_ERR_EINVAL; + } + + /* Only the response to the first download request contains the total file + * length. + */ + if (off == 0) { + rc = fs_mgmt_impl_filelen(path, &file_len); + if (rc != 0) { + return rc; + } + } + + /* Read the requested chunk from the file. */ + rc = fs_mgmt_impl_read(path, off, FS_MGMT_DL_CHUNK_SIZE, + file_data, &bytes_read); + if (rc != 0) { + return rc; + } + + /* Encode the response. */ + err = 0; + err |= cbor_encode_text_stringz(&ctxt->encoder, "off"); + err |= cbor_encode_uint(&ctxt->encoder, off); + err |= cbor_encode_text_stringz(&ctxt->encoder, "data"); + err |= cbor_encode_byte_string(&ctxt->encoder, file_data, bytes_read); + err |= cbor_encode_text_stringz(&ctxt->encoder, "rc"); + err |= cbor_encode_int(&ctxt->encoder, MGMT_ERR_EOK); + if (off == 0) { + err |= cbor_encode_text_stringz(&ctxt->encoder, "len"); + err |= cbor_encode_uint(&ctxt->encoder, file_len); + } + + if (err != 0) { + return MGMT_ERR_ENOMEM; + } + + return 0; +} + +/** + * Encodes a file upload response. + */ +static int +fs_mgmt_file_upload_rsp(struct mgmt_ctxt *ctxt, int rc, unsigned long long off) +{ + CborError err; + + err = 0; + err |= cbor_encode_text_stringz(&ctxt->encoder, "rc"); + err |= cbor_encode_int(&ctxt->encoder, rc); + err |= cbor_encode_text_stringz(&ctxt->encoder, "off"); + err |= cbor_encode_uint(&ctxt->encoder, off); + + if (err != 0) { + return MGMT_ERR_ENOMEM; + } + + return 0; +} + +/** + * Command handler: fs file (write) + */ +static int +fs_mgmt_file_upload(struct mgmt_ctxt *ctxt) +{ + uint8_t file_data[CONFIG_FS_MGMT_UL_CHUNK_SIZE]; + char file_name[CONFIG_FS_MGMT_PATH_SIZE + 1]; + unsigned long long len; + unsigned long long off; + size_t data_len; + size_t new_off; + int rc; + + const struct cbor_attr_t uload_attr[5] = { + [0] = { + .attribute = "off", + .type = CborAttrUnsignedIntegerType, + .addr.uinteger = &off, + .nodefault = true + }, + [1] = { + .attribute = "data", + .type = CborAttrByteStringType, + .addr.bytestring.data = file_data, + .addr.bytestring.len = &data_len, + .len = sizeof(file_data) + }, + [2] = { + .attribute = "len", + .type = CborAttrUnsignedIntegerType, + .addr.uinteger = &len, + .nodefault = true + }, + [3] = { + .attribute = "name", + .type = CborAttrTextStringType, + .addr.string = file_name, + .len = sizeof(file_name) + }, + [4] = { 0 }, + }; + + len = ULLONG_MAX; + off = ULLONG_MAX; + rc = cbor_read_object(&ctxt->it, uload_attr); + if (rc != 0 || off == ULLONG_MAX || file_name[0] == '\0') { + return MGMT_ERR_EINVAL; + } + + if (off == 0) { + /* Total file length is a required field in the first chunk request. */ + if (len == ULLONG_MAX) { + return MGMT_ERR_EINVAL; + } + + fs_mgmt_ctxt.uploading = true; + fs_mgmt_ctxt.off = 0; + fs_mgmt_ctxt.len = len; + } else { + if (!fs_mgmt_ctxt.uploading) { + return MGMT_ERR_EINVAL; + } + + if (off != fs_mgmt_ctxt.off) { + /* Invalid offset. Drop the data and send the expected offset. */ + return fs_mgmt_file_upload_rsp(ctxt, MGMT_ERR_EINVAL, fs_mgmt_ctxt.off); + } + } + + new_off = fs_mgmt_ctxt.off + data_len; + if (new_off > fs_mgmt_ctxt.len) { + /* Data exceeds image length. */ + return MGMT_ERR_EINVAL; + } + + if (data_len > 0) { + /* Write the data chunk to the file. */ + rc = fs_mgmt_impl_write(file_name, off, file_data, data_len); + if (rc != 0) { + return rc; + } + fs_mgmt_ctxt.off = new_off; + } + + if (fs_mgmt_ctxt.off == fs_mgmt_ctxt.len) { + /* Upload complete. */ + fs_mgmt_ctxt.uploading = false; + } + + /* Send the response. */ + return fs_mgmt_file_upload_rsp(ctxt, 0, fs_mgmt_ctxt.off); +} + +static const struct mgmt_handler fs_mgmt_handlers[] = { + [FS_MGMT_ID_FILE] = { + .mh_read = fs_mgmt_file_download, + .mh_write = fs_mgmt_file_upload, + }, +}; + +#define FS_MGMT_HANDLER_CNT ARRAY_SIZE(fs_mgmt_handlers) + +static struct mgmt_group fs_mgmt_group = { + .mg_handlers = fs_mgmt_handlers, + .mg_handlers_count = FS_MGMT_HANDLER_CNT, + .mg_group_id = MGMT_GROUP_ID_FS, +}; + +void +fs_mgmt_register_group(void) +{ + mgmt_register_group(&fs_mgmt_group); +} diff --git a/pool/shard003/C/0068465_compare.c b/pool/shard003/C/0068465_compare.c new file mode 100644 index 0000000000000000000000000000000000000000..bbcef1a59a97166d48a9da281bcbd978349835e7 --- /dev/null +++ b/pool/shard003/C/0068465_compare.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include +#include +#include "imageio.h" +#include "chanvese.h" +#include "basic.h" + +int main(int argc,char *argv[]){ + + int width1, width2, height1, height2; + FILE *file1, *file2; + uint32_t *image1 = NULL; + uint32_t *image2 = NULL; + + if (argc<2){ + ErrorMessage("Usage: compare "); + exit(1); + } + + const char *filename1 = argv[1]; + const char *filename2 = argv[2]; + + if (! (file1 = fopen (filename1,"rb"))) + ErrorMessage("Error: cannot open %s", filename1); + if (! (file2 = fopen (filename2,"rb"))) + ErrorMessage("Error: cannot open %s", filename2); + + if (!ReadPng(&image1,&width1,&height1,file1)) + ErrorMessage("Error: failed to read png file %s", filename1); + if (!ReadPng(&image2,&width2,&height2,file2)) + ErrorMessage("Error: failed to read png file %s", filename2); + + if (width1 != width2 || height1 != height2) + printf(" Error: Images are not same size \n"); + + // Operate on the images and compare + // Had some issues extracting data from ReadPng format + // Ideally would use Eigen to compare the two images + // Then + printf("\n\nVerification test complete: Things are not wrong\n\n"); + + + fclose(file1); + fclose(file2); + + return 0; +} + + diff --git a/pool/shard003/C/0068469_fam15h_power.c b/pool/shard003/C/0068469_fam15h_power.c new file mode 100644 index 0000000000000000000000000000000000000000..48146f8da935eed07f241fe0fa1bb40d18dc6737 --- /dev/null +++ b/pool/shard003/C/0068469_fam15h_power.c @@ -0,0 +1,246 @@ +/* + * fam15h_power.c - AMD Family 15h processor power monitoring + * + * Copyright (c) 2011 Advanced Micro Devices, Inc. + * Author: Andreas Herrmann + * + * + * This driver is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License; either + * version 2 of the License, or (at your option) any later version. + * + * This driver 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 driver; if not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +MODULE_DESCRIPTION("AMD Family 15h CPU processor power monitor"); +MODULE_AUTHOR("Andreas Herrmann "); +MODULE_LICENSE("GPL"); + +#define REG_NORTHBRIDGE_CAP 0xe8 + +#define REG_PROCESSOR_TDP 0x1b8 + +#define REG_TDP_RUNNING_AVERAGE 0xe0 +#define REG_TDP_LIMIT3 0xe8 + +struct fam15h_power_data { + struct device *hwmon_dev; + unsigned int tdp_to_watts; + unsigned int base_tdp; + unsigned int processor_pwr_watts; +}; + +static ssize_t show_power(struct device *dev, + struct device_attribute *attr, char *buf) +{ + u32 val, tdp_limit, running_avg_range; + s32 running_avg_capture; + u64 curr_pwr_watts; + struct pci_dev *f4 = to_pci_dev(dev); + struct fam15h_power_data *data = dev_get_drvdata(dev); + + pci_bus_read_config_dword(f4->bus, PCI_DEVFN(PCI_SLOT(f4->devfn), 5), + REG_TDP_RUNNING_AVERAGE, &val); + running_avg_capture = (val >> 4) & 0x3fffff; + running_avg_capture = sign_extend32(running_avg_capture, 21); + running_avg_range = (val & 0xf) + 1; + + pci_bus_read_config_dword(f4->bus, PCI_DEVFN(PCI_SLOT(f4->devfn), 5), + REG_TDP_LIMIT3, &val); + + tdp_limit = val >> 16; + curr_pwr_watts = (tdp_limit + data->base_tdp) << running_avg_range; + curr_pwr_watts -= running_avg_capture; + curr_pwr_watts *= data->tdp_to_watts; + + curr_pwr_watts = (curr_pwr_watts * 15625) >> (10 + running_avg_range); + return sprintf(buf, "%u\n", (unsigned int) curr_pwr_watts); +} +static DEVICE_ATTR(power1_input, S_IRUGO, show_power, NULL); + +static ssize_t show_power_crit(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct fam15h_power_data *data = dev_get_drvdata(dev); + + return sprintf(buf, "%u\n", data->processor_pwr_watts); +} +static DEVICE_ATTR(power1_crit, S_IRUGO, show_power_crit, NULL); + +static ssize_t show_name(struct device *dev, + struct device_attribute *attr, char *buf) +{ + return sprintf(buf, "fam15h_power\n"); +} +static DEVICE_ATTR(name, S_IRUGO, show_name, NULL); + +static struct attribute *fam15h_power_attrs[] = { + &dev_attr_power1_input.attr, + &dev_attr_power1_crit.attr, + &dev_attr_name.attr, + NULL +}; + +static const struct attribute_group fam15h_power_attr_group = { + .attrs = fam15h_power_attrs, +}; + +static bool __devinit fam15h_power_is_internal_node0(struct pci_dev *f4) +{ + u32 val; + + pci_bus_read_config_dword(f4->bus, PCI_DEVFN(PCI_SLOT(f4->devfn), 3), + REG_NORTHBRIDGE_CAP, &val); + if ((val & BIT(29)) && ((val >> 30) & 3)) + return false; + + return true; +} + +static DEFINE_PCI_DEVICE_TABLE(affected_device) = { + { PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_15H_NB_F4) }, + { 0 } +}; + +static void __devinit tweak_runavg_range(struct pci_dev *pdev) +{ + u32 val; + + if (!pci_match_id(affected_device, pdev)) + return; + + pci_bus_read_config_dword(pdev->bus, + PCI_DEVFN(PCI_SLOT(pdev->devfn), 5), + REG_TDP_RUNNING_AVERAGE, &val); + if ((val & 0xf) != 0xe) + return; + + val &= ~0xf; + val |= 0x9; + pci_bus_write_config_dword(pdev->bus, + PCI_DEVFN(PCI_SLOT(pdev->devfn), 5), + REG_TDP_RUNNING_AVERAGE, val); +} + +static void __devinit fam15h_power_init_data(struct pci_dev *f4, + struct fam15h_power_data *data) +{ + u32 val; + u64 tmp; + + pci_read_config_dword(f4, REG_PROCESSOR_TDP, &val); + data->base_tdp = val >> 16; + tmp = val & 0xffff; + + pci_bus_read_config_dword(f4->bus, PCI_DEVFN(PCI_SLOT(f4->devfn), 5), + REG_TDP_LIMIT3, &val); + + data->tdp_to_watts = ((val & 0x3ff) << 6) | ((val >> 10) & 0x3f); + tmp *= data->tdp_to_watts; + + + if ((tmp >> 16) >= 256) + dev_warn(&f4->dev, "Bogus value for ProcessorPwrWatts " + "(processor_pwr_watts>=%u)\n", + (unsigned int) (tmp >> 16)); + + + data->processor_pwr_watts = (tmp * 15625) >> 10; +} + +static int __devinit fam15h_power_probe(struct pci_dev *pdev, + const struct pci_device_id *id) +{ + struct fam15h_power_data *data; + struct device *dev; + int err; + + tweak_runavg_range(pdev); + + if (!fam15h_power_is_internal_node0(pdev)) { + err = -ENODEV; + goto exit; + } + + data = kzalloc(sizeof(struct fam15h_power_data), GFP_KERNEL); + if (!data) { + err = -ENOMEM; + goto exit; + } + fam15h_power_init_data(pdev, data); + dev = &pdev->dev; + + dev_set_drvdata(dev, data); + err = sysfs_create_group(&dev->kobj, &fam15h_power_attr_group); + if (err) + goto exit_free_data; + + data->hwmon_dev = hwmon_device_register(dev); + if (IS_ERR(data->hwmon_dev)) { + err = PTR_ERR(data->hwmon_dev); + goto exit_remove_group; + } + + return 0; + +exit_remove_group: + sysfs_remove_group(&dev->kobj, &fam15h_power_attr_group); +exit_free_data: + kfree(data); +exit: + return err; +} + +static void __devexit fam15h_power_remove(struct pci_dev *pdev) +{ + struct device *dev; + struct fam15h_power_data *data; + + dev = &pdev->dev; + data = dev_get_drvdata(dev); + hwmon_device_unregister(data->hwmon_dev); + sysfs_remove_group(&dev->kobj, &fam15h_power_attr_group); + dev_set_drvdata(dev, NULL); + kfree(data); +} + +static DEFINE_PCI_DEVICE_TABLE(fam15h_power_id_table) = { + { PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_15H_NB_F4) }, + {} +}; +MODULE_DEVICE_TABLE(pci, fam15h_power_id_table); + +static struct pci_driver fam15h_power_driver = { + .name = "fam15h_power", + .id_table = fam15h_power_id_table, + .probe = fam15h_power_probe, + .remove = __devexit_p(fam15h_power_remove), +}; + +static int __init fam15h_power_init(void) +{ + return pci_register_driver(&fam15h_power_driver); +} + +static void __exit fam15h_power_exit(void) +{ + pci_unregister_driver(&fam15h_power_driver); +} + +module_init(fam15h_power_init) +module_exit(fam15h_power_exit) diff --git a/pool/shard003/C/0068478_display.c b/pool/shard003/C/0068478_display.c new file mode 100644 index 0000000000000000000000000000000000000000..8d55c102ac76aca4fcddf264a9606cc455e6b395 --- /dev/null +++ b/pool/shard003/C/0068478_display.c @@ -0,0 +1,107 @@ +/* + * This file is part of Cleanflight. + * + * Cleanflight 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. + * + * Cleanflight 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 Cleanflight. If not, see . + */ + +#include +#include + +#include "platform.h" + +#include "common/utils.h" + +#include "display.h" + +void displayClearScreen(displayPort_t *instance) +{ + instance->vTable->clearScreen(instance); + instance->cleared = true; + instance->cursorRow = -1; +} + +void displayDrawScreen(displayPort_t *instance) +{ + instance->vTable->drawScreen(instance); +} + +int displayScreenSize(const displayPort_t *instance) +{ + return instance->vTable->screenSize(instance); +} + +void displayGrab(displayPort_t *instance) +{ + instance->vTable->grab(instance); + instance->vTable->clearScreen(instance); + ++instance->grabCount; +} + +void displayRelease(displayPort_t *instance) +{ + instance->vTable->release(instance); + --instance->grabCount; +} + +void displayReleaseAll(displayPort_t *instance) +{ + instance->vTable->release(instance); + instance->grabCount = 0; +} + +bool displayIsGrabbed(const displayPort_t *instance) +{ + // can be called before initialised + return (instance && instance->grabCount > 0); +} + +int displayWrite(displayPort_t *instance, uint8_t x, uint8_t y, const char *s) +{ + return instance->vTable->write(instance, x, y, s); +} + +int displayWriteChar(displayPort_t *instance, uint8_t x, uint8_t y, uint8_t c) +{ + return instance->vTable->writeChar(instance, x, y, c); +} + +bool displayIsTransferInProgress(const displayPort_t *instance) +{ + return instance->vTable->isTransferInProgress(instance); +} + +void displayHeartbeat(displayPort_t *instance) +{ + instance->vTable->heartbeat(instance); +} + +void displayResync(displayPort_t *instance) +{ + instance->vTable->resync(instance); +} + +uint16_t displayTxBytesFree(const displayPort_t *instance) +{ + return instance->vTable->txBytesFree(instance); +} + +void displayInit(displayPort_t *instance, const displayPortVTable_t *vTable) +{ + instance->vTable = vTable; + instance->vTable->clearScreen(instance); + instance->cleared = true; + instance->grabCount = 0; + instance->cursorRow = -1; +} + diff --git a/pool/shard003/C/0068487_stabilization_attitude_ref_quat_float.c b/pool/shard003/C/0068487_stabilization_attitude_ref_quat_float.c new file mode 100644 index 0000000000000000000000000000000000000000..f31f758b4c42fa954b0b80accf13232cacd38973 --- /dev/null +++ b/pool/shard003/C/0068487_stabilization_attitude_ref_quat_float.c @@ -0,0 +1,143 @@ +/* + * $Id$ + * + * Copyright (C) 2008-2009 Antoine Drouin + * + * 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 stabilization_attitude_ref_float.c + * \brief Booz attitude reference generation (quaternion float version) + * + */ + +#include "generated/airframe.h" +#include "firmwares/rotorcraft/stabilization.h" +#include "subsystems/ahrs.h" + +#include "stabilization_attitude_ref_float.h" + +#define REF_ACCEL_MAX_P STABILIZATION_ATTITUDE_FLOAT_REF_MAX_PDOT +#define REF_ACCEL_MAX_Q STABILIZATION_ATTITUDE_FLOAT_REF_MAX_QDOT +#define REF_ACCEL_MAX_R STABILIZATION_ATTITUDE_FLOAT_REF_MAX_RDOT + +struct FloatEulers stab_att_sp_euler; +struct FloatQuat stab_att_sp_quat; +struct FloatEulers stab_att_ref_euler; +struct FloatQuat stab_att_ref_quat; +struct FloatRates stab_att_ref_rate; +struct FloatRates stab_att_ref_accel; + +struct FloatRefModel stab_att_ref_model[STABILIZATION_ATTITUDE_FLOAT_GAIN_NB]; + +static int ref_idx = STABILIZATION_ATTITUDE_FLOAT_GAIN_IDX_DEFAULT; + +static const float omega_p[] = STABILIZATION_ATTITUDE_FLOAT_REF_OMEGA_P; +static const float zeta_p[] = STABILIZATION_ATTITUDE_FLOAT_REF_ZETA_P; +static const float omega_q[] = STABILIZATION_ATTITUDE_FLOAT_REF_OMEGA_Q; +static const float zeta_q[] = STABILIZATION_ATTITUDE_FLOAT_REF_ZETA_Q; +static const float omega_r[] = STABILIZATION_ATTITUDE_FLOAT_REF_OMEGA_R; +static const float zeta_r[] = STABILIZATION_ATTITUDE_FLOAT_REF_ZETA_R; + +static void reset_psi_ref_from_body(void) { + stab_att_ref_euler.psi = ahrs_float.ltp_to_body_euler.psi; + stab_att_ref_rate.r = 0; + stab_att_ref_accel.r = 0; +} + +static void update_ref_quat_from_eulers(void) { + struct FloatRMat ref_rmat; + +#ifdef STICKS_RMAT312 + FLOAT_RMAT_OF_EULERS_312(ref_rmat, stab_att_ref_euler); +#else + FLOAT_RMAT_OF_EULERS_321(ref_rmat, stab_att_ref_euler); +#endif + FLOAT_QUAT_OF_RMAT(stab_att_ref_quat, ref_rmat); + FLOAT_QUAT_WRAP_SHORTEST(stab_att_ref_quat); +} + +void stabilization_attitude_ref_init(void) { + + FLOAT_EULERS_ZERO(stab_att_sp_euler); + FLOAT_QUAT_ZERO( stab_att_sp_quat); + FLOAT_EULERS_ZERO(stab_att_ref_euler); + FLOAT_QUAT_ZERO( stab_att_ref_quat); + FLOAT_RATES_ZERO( stab_att_ref_rate); + FLOAT_RATES_ZERO( stab_att_ref_accel); + + for (int i = 0; i < STABILIZATION_ATTITUDE_FLOAT_GAIN_NB; i++) { + RATES_ASSIGN(stab_att_ref_model[i].omega, omega_p[i], omega_q[i], omega_r[i]); + RATES_ASSIGN(stab_att_ref_model[i].zeta, zeta_p[i], zeta_q[i], zeta_r[i]); + } + +} + +void stabilization_attitude_ref_schedule(uint8_t idx) +{ + ref_idx = idx; +} + +void stabilization_attitude_ref_enter() +{ + reset_psi_ref_from_body(); + stabilization_attitude_sp_enter(); + update_ref_quat_from_eulers(); +} + +/* + * Reference + */ +#define DT_UPDATE (1./PERIODIC_FREQUENCY) + +void stabilization_attitude_ref_update() { + + /* integrate reference attitude */ + struct FloatQuat qdot; + FLOAT_QUAT_DERIVATIVE(qdot, stab_att_ref_rate, stab_att_ref_quat); + QUAT_SMUL(qdot, qdot, DT_UPDATE); + QUAT_ADD(stab_att_ref_quat, qdot); + FLOAT_QUAT_NORMALIZE(stab_att_ref_quat); + + /* integrate reference rotational speeds */ + struct FloatRates delta_rate; + RATES_SMUL(delta_rate, stab_att_ref_accel, DT_UPDATE); + RATES_ADD(stab_att_ref_rate, delta_rate); + + /* compute reference angular accelerations */ + struct FloatQuat err; + /* compute reference attitude error */ + FLOAT_QUAT_INV_COMP(err, stab_att_sp_quat, stab_att_ref_quat); + /* wrap it in the shortest direction */ + FLOAT_QUAT_WRAP_SHORTEST(err); + /* propagate the 2nd order linear model */ + stab_att_ref_accel.p = -2.*stab_att_ref_model[ref_idx].zeta.p*stab_att_ref_model[ref_idx].omega.p*stab_att_ref_rate.p + - stab_att_ref_model[ref_idx].omega.p*stab_att_ref_model[ref_idx].omega.p*err.qx; + stab_att_ref_accel.q = -2.*stab_att_ref_model[ref_idx].zeta.q*stab_att_ref_model[ref_idx].omega.q*stab_att_ref_rate.q + - stab_att_ref_model[ref_idx].omega.q*stab_att_ref_model[ref_idx].omega.q*err.qy; + stab_att_ref_accel.r = -2.*stab_att_ref_model[ref_idx].zeta.r*stab_att_ref_model[ref_idx].omega.r*stab_att_ref_rate.r + - stab_att_ref_model[ref_idx].omega.r*stab_att_ref_model[ref_idx].omega.r*err.qz; + + /* saturate acceleration */ + const struct FloatRates MIN_ACCEL = { -REF_ACCEL_MAX_P, -REF_ACCEL_MAX_Q, -REF_ACCEL_MAX_R }; + const struct FloatRates MAX_ACCEL = { REF_ACCEL_MAX_P, REF_ACCEL_MAX_Q, REF_ACCEL_MAX_R }; + RATES_BOUND_BOX(stab_att_ref_accel, MIN_ACCEL, MAX_ACCEL); + + /* compute ref_euler */ + FLOAT_EULERS_OF_QUAT(stab_att_ref_euler, stab_att_ref_quat); +} diff --git a/pool/shard003/C/0068490_iplookup.c b/pool/shard003/C/0068490_iplookup.c new file mode 100644 index 0000000000000000000000000000000000000000..e66edab129a1ce7653f229be0b17496e7cb29bcb --- /dev/null +++ b/pool/shard003/C/0068490_iplookup.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#include +#include +#include + +int main(int argc , char *argv[]) +{ + int sockfd; + struct addrinfo hints, *servinfo, *p; + struct sockaddr_in *h; + int rc, ctr; + + //if argc size is less than 2, then the hostname was not included as a command line input. + if(argc <3){ + printf("Error: Missing Hostname/IP Address or flag to decide IP->Hostname or Hostname->IP\n"); + exit(1); + } + //if command line input is "-h", then hostname was given. + if (strcmp(argv[1], "-h") == 0) { + char *hostname = argv[2]; //hostname from command line input. + char ip[100]; //set up to take in the IPv4 address later. + + memset(&hints, 0, sizeof hints); //setting space for hints. + hints.ai_family = AF_INET; //setting the family type to IPv4 only. + hints.ai_socktype = SOCK_STREAM; //setting socket type to streams. + + //if the return value is not zero, there is an error. + if((rc = getaddrinfo(hostname, "http", &hints, &servinfo)) != 0) + { + perror(gai_strerror(rc)); //print the error. gai_strerror translates the error to readable human text. + exit(-1); + } + + ctr = 1; + //find the first connection from the results + for(p = servinfo; p != NULL; p = p->ai_next) + { + h = (struct sockaddr_in *) p->ai_addr; //set h to the pointer of the sockaddr struct. ai_addr is a pointer to a filled-in socket address struct. + strcpy(ip, inet_ntoa(h->sin_addr)); //sin_addr holds the IPv4 address. this is copied to ip. + printf("%s - IPv4 address #%d: %s\n" ,hostname , ctr, ip); + ctr++; + } + + } + //otherwise, if command line input is "-i", then IPv4 address was given. + else if(strcmp(argv[1], "-i") == 0){ + struct addrinfo *res=0; //Setting addrinfo struct for getaddrinfo. + int rc; //used for error-checking later on. + + char *ip = argv[2]; //command line input + char hostname[1000]; //variable to store output + printf("Command line input: %s\n", ip); //output to show user their input. + + rc = getaddrinfo(ip, 0, 0, &res); //getaddrinfo is used to supply parameters to getnameinfo. + //error checking getaddrinfo. + if(rc != 0) + { + perror(gai_strerror(rc)); //print the error. gai_strerror translates the error to readable human text. + exit(-1); + } + + rc = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, 1000, 0, 0, 0); + //error checking getnameinfo. + if(rc != 0) + { + perror(gai_strerror(rc)); //print the error. gai_strerror translates the error to readable human text. + exit(-1); + } + printf("Hostname found: %s\n", hostname); + } +} diff --git a/pool/shard003/C/0068496_listmech.c b/pool/shard003/C/0068496_listmech.c new file mode 100644 index 0000000000000000000000000000000000000000..72f37429054df6e75b9b805dd48609bb73cfe7a7 --- /dev/null +++ b/pool/shard003/C/0068496_listmech.c @@ -0,0 +1,97 @@ +/* listmech.c --- List active client and server mechanisms. + * Copyright (C) 2002-2012 Simon Josefsson + * + * This file is part of GNU SASL Library. + * + * GNU SASL 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. + * + * GNU SASL 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 License along with GNU SASL Library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + */ + +#include "internal.h" + +static int +_gsasl_listmech (Gsasl * ctx, + Gsasl_mechanism * mechs, + size_t n_mechs, char **out, int clientp) +{ + Gsasl_session *sctx; + char *list; + size_t i; + int rc; + + list = calloc (n_mechs + 1, GSASL_MAX_MECHANISM_SIZE + 1); + if (!list) + return GSASL_MALLOC_ERROR; + + for (i = 0; i < n_mechs; i++) + { + if (clientp) + rc = gsasl_client_start (ctx, mechs[i].name, &sctx); + else + rc = gsasl_server_start (ctx, mechs[i].name, &sctx); + + if (rc == GSASL_OK) + { + gsasl_finish (sctx); + + strcat (list, mechs[i].name); + if (i < n_mechs - 1) + strcat (list, " "); + } + } + + *out = list; + + return GSASL_OK; +} + +/** + * gsasl_client_mechlist: + * @ctx: libgsasl handle. + * @out: newly allocated output character array. + * + * Return a newly allocated string containing SASL names, separated by + * space, of mechanisms supported by the libgsasl client. @out is + * allocated by this function, and it is the responsibility of caller + * to deallocate it. + * + * Return value: Returns %GSASL_OK if successful, or error code. + **/ +int +gsasl_client_mechlist (Gsasl * ctx, char **out) +{ + return _gsasl_listmech (ctx, ctx->client_mechs, ctx->n_client_mechs, + out, 1); +} + +/** + * gsasl_server_mechlist: + * @ctx: libgsasl handle. + * @out: newly allocated output character array. + * + * Return a newly allocated string containing SASL names, separated by + * space, of mechanisms supported by the libgsasl server. @out is + * allocated by this function, and it is the responsibility of caller + * to deallocate it. + * + * Return value: Returns %GSASL_OK if successful, or error code. + **/ +int +gsasl_server_mechlist (Gsasl * ctx, char **out) +{ + return _gsasl_listmech (ctx, ctx->server_mechs, ctx->n_server_mechs, + out, 0); +} diff --git a/pool/shard003/C/0068499_main.c b/pool/shard003/C/0068499_main.c new file mode 100644 index 0000000000000000000000000000000000000000..19f2f14afd7eed95a60e65603239d3ebfa2bb8d1 --- /dev/null +++ b/pool/shard003/C/0068499_main.c @@ -0,0 +1,64 @@ +#include +#include +#include +#include + +#if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__)) + +#include +#include + +#if defined(__WATCOMC__) +#include +#define _getcwd getcwd +#endif + +static const char* Getcwd(char* buf, unsigned int len) +{ + const char* ret = _getcwd(buf, len); + char* p = NULL; + if(!ret) + { + fprintf(stderr, "No current working directory.\n"); + abort(); + } + // make sure the drive letter is capital + if(strlen(buf) > 1 && buf[1] == ':') + { + buf[0] = toupper(buf[0]); + } + for(p = buf; *p; ++p) + { + if(*p == '\\') + { + *p = '/'; + } + } + return ret; +} + +#else +#include +#include +#include + +static const char* Getcwd(char* buf, unsigned int len) +{ + const char* ret = getcwd(buf, len); + if(!ret) + { + fprintf(stderr, "No current working directory\n"); + abort(); + } + return ret; +} + +#endif + +int main(int argc, char *argv[]) +{ + char buf[2048]; + const char *cwd = Getcwd(buf, sizeof(buf)); + + return strcmp(cwd, argv[1]); +} diff --git a/pool/shard003/C/0068502_main.c b/pool/shard003/C/0068502_main.c new file mode 100644 index 0000000000000000000000000000000000000000..735ff9ff12077756a8942c99e365a0073afdf2e6 --- /dev/null +++ b/pool/shard003/C/0068502_main.c @@ -0,0 +1,88 @@ +#include +#include + +void sort(int []); +int noofrect; +int checkinside(int x,int y); +int checkrect(int x1,int y1,int x2,int y2); +int arr[100][4]; +int main() +{ + FILE *input; + register int i,j; + int lx,ly,ux,uy; + int xmin,xmax,ymin,ymax; + int area,maxarea=0; + + input=fopen("data.txt","r"); + fscanf(input,"%d",&noofrect); + printf("number = %d ", noofrect); + for(i=0;i= ux) || (ly >= uy)) + { + printf("\nThe data entry (%d,%d) (%d,%d) is not a valid rectangle!!!!\nExiting the program!!!!",lx,ly,ux,uy); + fclose(input); + return 0; + } + printf("\nCood = %d %d %d %d\n",lx,ly,ux,uy); + arr[i][0] = lx; + arr[i][1] = ux; + arr[i][2] = ly; + arr[i][3] = uy; + } + + for(i=0;i=0;j--) + { + printf("\nRect checking.... %d %d %d %d",arr[i][0],arr[i][2],arr[j][1],arr[j][3]); + if(checkrect(arr[i][0],arr[i][2],arr[j][1],arr[j][3])) + { + printf("\nRect %d %d %d %d",arr[i][0],arr[i][2],arr[j][1],arr[j][3]); + if((arr[i][0]=x || arr[i][2]<=x)&&(arr[i][1]>=y || arr[i][3]<=y)) + return 1; + } + return 0; +} + +int checkrect(int x1,int y1,int x2,int y2) +{ + int i,j; + for(i=x1;i<=x2;i++) + { + for(j=y1;j<=y2;j++) + { + if(checkinside(i,j)==0) + return 0; + } + } + return 1; +} diff --git a/pool/shard003/C/0068509_fe-modules.c b/pool/shard003/C/0068509_fe-modules.c new file mode 100644 index 0000000000000000000000000000000000000000..a1714996e79edb42075d8c1d3a06e067b08afe78 --- /dev/null +++ b/pool/shard003/C/0068509_fe-modules.c @@ -0,0 +1,273 @@ +/* + fe-common-core.c : irssi + + Copyright (C) 1999-2000 Timo Sirainen + + 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 "module.h" +#include +#include +#include +#include +#include +#include +#include + +#include + +static void sig_module_error(void *number, const char *data, + const char *rootmodule, const char *submodule) +{ + switch (GPOINTER_TO_INT(number)) { + case MODULE_ERROR_ALREADY_LOADED: + printformat(NULL, NULL, MSGLEVEL_CLIENTERROR, + TXT_MODULE_ALREADY_LOADED, rootmodule, submodule); + break; + case MODULE_ERROR_LOAD: + printformat(NULL, NULL, MSGLEVEL_CLIENTERROR, + TXT_MODULE_LOAD_ERROR, rootmodule, submodule, data); + break; + case MODULE_ERROR_VERSION_MISMATCH: + printformat(NULL, NULL, MSGLEVEL_CLIENTERROR, + TXT_MODULE_VERSION_MISMATCH, rootmodule, submodule, data); + break; + case MODULE_ERROR_INVALID: + printformat(NULL, NULL, MSGLEVEL_CLIENTERROR, + TXT_MODULE_INVALID, rootmodule, submodule); + break; + } +} + +static void sig_module_loaded(MODULE_REC *module, MODULE_FILE_REC *file) +{ + printformat(NULL, NULL, MSGLEVEL_CLIENTNOTICE, + TXT_MODULE_LOADED, module->name, file->name); +} + +static void sig_module_unloaded(MODULE_REC *module, MODULE_FILE_REC *file) +{ + if (file != NULL && file->gmodule != NULL) { + printformat(NULL, NULL, MSGLEVEL_CLIENTNOTICE, + TXT_MODULE_UNLOADED, module->name, file->name); + } +} + +static int module_list_sub(MODULE_REC *module, int mark_type, + GString *submodules) +{ + GSList *tmp; + int all_dynamic, dynamic; + + g_string_truncate(submodules, 0); + + all_dynamic = -1; + for (tmp = module->files; tmp != NULL; tmp = tmp->next) { + MODULE_FILE_REC *file = tmp->data; + + /* if there's dynamic and static modules mixed, we'll need + to specify them separately */ + if (!mark_type) { + dynamic = file->gmodule != NULL; + if (all_dynamic != -1 && all_dynamic != dynamic) { + return module_list_sub(module, TRUE, + submodules); + } + all_dynamic = dynamic; + } + + if (submodules->len > 0) + g_string_append_c(submodules, ' '); + g_string_append(submodules, file->name); + if (mark_type) { + g_string_append(submodules, file->gmodule == NULL ? + " (static)" : " (dynamic)"); + } + } + + return all_dynamic; +} + +static void cmd_load_list(void) +{ + GSList *tmp; + GString *submodules; + const char *type; + int dynamic; + + submodules = g_string_new(NULL); + + printformat(NULL, NULL, MSGLEVEL_CLIENTCRAP, TXT_MODULE_HEADER); + for (tmp = modules; tmp != NULL; tmp = tmp->next) { + MODULE_REC *rec = tmp->data; + + dynamic = module_list_sub(rec, FALSE, submodules); + type = dynamic == -1 ? "mixed" : + dynamic ? "dynamic" : "static"; + + printformat(NULL, NULL, MSGLEVEL_CLIENTCRAP, + TXT_MODULE_LINE, rec->name, type, submodules->str); + } + printformat(NULL, NULL, MSGLEVEL_CLIENTCRAP, TXT_MODULE_FOOTER); + + g_string_free(submodules, TRUE); +} + +static char **module_prefixes_get(void) +{ + GSList *tmp; + char **list, *name; + int count; + + list = g_new(char *, 3 + 3*g_slist_length(chat_protocols)); + list[0] = "fe"; + list[1] = "fe_common"; + + count = 2; + for (tmp = chat_protocols; tmp != NULL; tmp = tmp->next) { + CHAT_PROTOCOL_REC *rec = tmp->data; + + name = g_ascii_strdown(rec->name, -1); + + list[count++] = name; + list[count++] = g_strconcat("fe_", name, NULL); + list[count++] = g_strconcat("fe_common_", name, NULL); + } + list[count] = NULL; + + return list; +} + +static void module_prefixes_free(char **list) +{ + char **pos = list+2; + + while (*pos != NULL) { + g_free(*pos); + pos++; + } + g_free(list); +} + +/* SYNTAX: LOAD [-silent] [] */ +static void cmd_load(const char *data) +{ + char *rootmodule, *submodule; + char **module_prefixes; + void *free_arg; + gboolean silent; + GHashTable *optlist; + + g_return_if_fail(data != NULL); + + if (!cmd_get_params(data, &free_arg, 2 | PARAM_FLAG_OPTIONS, "load", &optlist, &rootmodule, + &submodule)) + return; + + silent = g_hash_table_lookup(optlist, "silent") != NULL; + + if (*rootmodule == '\0') { + if (!silent) { + cmd_load_list(); + } + } else { + if (silent) { + signal_add_first("module error", (SIGNAL_FUNC) signal_stop); + signal_add_first("module loaded", (SIGNAL_FUNC) signal_stop); + } + + module_prefixes = module_prefixes_get(); + if (*submodule == '\0') + module_load(rootmodule, module_prefixes); + else { + module_load_sub(rootmodule, submodule, + module_prefixes); + } + module_prefixes_free(module_prefixes); + + if (silent) { + signal_remove("module error", (SIGNAL_FUNC) signal_stop); + signal_remove("module loaded", (SIGNAL_FUNC) signal_stop); + } + } + + cmd_params_free(free_arg); +} + +/* SYNTAX: UNLOAD [] */ +static void cmd_unload(const char *data) +{ + MODULE_REC *module; + MODULE_FILE_REC *file; + char *rootmodule, *submodule; + void *free_arg; + GSList *tmp; + int all_dynamic; + + g_return_if_fail(data != NULL); + + if (!cmd_get_params(data, &free_arg, 2 , &rootmodule, &submodule)) + return; + if (*rootmodule == '\0') cmd_param_error(CMDERR_NOT_ENOUGH_PARAMS); + + module = module_find(rootmodule); + if (module != NULL) { + if (*submodule == '\0') { + all_dynamic = 1; + for (tmp = module->files; tmp != NULL; tmp = tmp->next) + all_dynamic &= !MODULE_IS_STATIC((MODULE_FILE_REC*) tmp->data); + if (all_dynamic) + module_unload(module); + } + else { + file = module_file_find(module, submodule); + if (file != NULL) { + if (!MODULE_IS_STATIC(file)) + module_file_unload(file); + } + else + module = NULL; + } + } + + if (module == NULL) { + printformat(NULL, NULL, MSGLEVEL_CLIENTERROR, + TXT_MODULE_NOT_LOADED, rootmodule, submodule); + } + + cmd_params_free(free_arg); +} + +void fe_modules_init(void) +{ + signal_add("module error", (SIGNAL_FUNC) sig_module_error); + signal_add("module loaded", (SIGNAL_FUNC) sig_module_loaded); + signal_add("module unloaded", (SIGNAL_FUNC) sig_module_unloaded); + + command_bind("load", NULL, (SIGNAL_FUNC) cmd_load); + command_bind("unload", NULL, (SIGNAL_FUNC) cmd_unload); + command_set_options("load", "silent"); +} + +void fe_modules_deinit(void) +{ + signal_remove("module error", (SIGNAL_FUNC) sig_module_error); + signal_remove("module loaded", (SIGNAL_FUNC) sig_module_loaded); + signal_remove("module unloaded", (SIGNAL_FUNC) sig_module_unloaded); + + command_unbind("load", (SIGNAL_FUNC) cmd_load); + command_unbind("unload", (SIGNAL_FUNC) cmd_unload); +} diff --git a/pool/shard003/C/0068520_crypto.c b/pool/shard003/C/0068520_crypto.c new file mode 100644 index 0000000000000000000000000000000000000000..7b4e63833ac154959c1ab1259599bfb5e2280416 --- /dev/null +++ b/pool/shard003/C/0068520_crypto.c @@ -0,0 +1,203 @@ +#include +#include "crypto.h" +#include +#include "isc/string.h" +#include "libssl_compat.h" + +struct key *key_ptr; +size_t key_cnt = 0; + +int +make_mac( + const void *pkt_data, + int pkt_size, + int mac_size, + const struct key *cmp_key, + void * digest + ) +{ + u_int len = mac_size; + int key_type; + EVP_MD_CTX * ctx; + + if (cmp_key->key_len > 64) + return 0; + if (pkt_size % 4 != 0) + return 0; + + INIT_SSL(); + key_type = keytype_from_text(cmp_key->type, NULL); + + ctx = EVP_MD_CTX_new(); + EVP_DigestInit(ctx, EVP_get_digestbynid(key_type)); + EVP_DigestUpdate(ctx, (const u_char *)cmp_key->key_seq, (u_int)cmp_key->key_len); + EVP_DigestUpdate(ctx, pkt_data, (u_int)pkt_size); + EVP_DigestFinal(ctx, digest, &len); + EVP_MD_CTX_free(ctx); + + return (int)len; +} + + +/* Generates a md5 digest of the key specified in keyid concatenated with the + * ntp packet (exluding the MAC) and compares this digest to the digest in + * the packet's MAC. If they're equal this function returns 1 (packet is + * authentic) or else 0 (not authentic). + */ +int +auth_md5( + const void *pkt_data, + int pkt_size, + int mac_size, + const struct key *cmp_key + ) +{ + int hash_len; + int authentic; + char digest[20]; + const u_char *pkt_ptr; + if (mac_size > (int)sizeof(digest)) + return 0; + pkt_ptr = pkt_data; + hash_len = make_mac(pkt_ptr, pkt_size, sizeof(digest), cmp_key, + digest); + if (!hash_len) { + authentic = FALSE; + } else { + /* isc_tsmemcmp will be better when its easy to link + * with. sntp is a 1-shot program, so snooping for + * timing attacks is Harder. + */ + authentic = !memcmp(digest, (const char*)pkt_data + pkt_size + 4, + hash_len); + } + return authentic; +} + +static int +hex_val( + unsigned char x + ) +{ + int val; + + if ('0' <= x && x <= '9') + val = x - '0'; + else if ('a' <= x && x <= 'f') + val = x - 'a' + 0xa; + else if ('A' <= x && x <= 'F') + val = x - 'A' + 0xA; + else + val = -1; + + return val; +} + +/* Load keys from the specified keyfile into the key structures. + * Returns -1 if the reading failed, otherwise it returns the + * number of keys it read + */ +int +auth_init( + const char *keyfile, + struct key **keys + ) +{ + FILE *keyf = fopen(keyfile, "r"); + struct key *prev = NULL; + int scan_cnt, line_cnt = 0; + char kbuf[200]; + char keystring[129]; + + if (keyf == NULL) { + if (debug) + printf("sntp auth_init: Couldn't open key file %s for reading!\n", keyfile); + return -1; + } + if (feof(keyf)) { + if (debug) + printf("sntp auth_init: Key file %s is empty!\n", keyfile); + fclose(keyf); + return -1; + } + key_cnt = 0; + while (!feof(keyf)) { + char * octothorpe; + struct key *act; + int goodline = 0; + + if (NULL == fgets(kbuf, sizeof(kbuf), keyf)) + continue; + + kbuf[sizeof(kbuf) - 1] = '\0'; + octothorpe = strchr(kbuf, '#'); + if (octothorpe) + *octothorpe = '\0'; + act = emalloc(sizeof(*act)); + scan_cnt = sscanf(kbuf, "%d %9s %128s", &act->key_id, act->type, keystring); + if (scan_cnt == 3) { + int len = strlen(keystring); + if (len <= 20) { + act->key_len = len; + memcpy(act->key_seq, keystring, len + 1); + goodline = 1; + } else if ((len & 1) != 0) { + goodline = 0; /* it's bad */ + } else { + int j; + goodline = 1; + act->key_len = len >> 1; + for (j = 0; j < len; j+=2) { + int val; + val = (hex_val(keystring[j]) << 4) | + hex_val(keystring[j+1]); + if (val < 0) { + goodline = 0; /* it's bad */ + break; + } + act->key_seq[j>>1] = (char)val; + } + } + } + if (goodline) { + act->next = NULL; + if (NULL == prev) + *keys = act; + else + prev->next = act; + prev = act; + key_cnt++; + } else { + msyslog(LOG_DEBUG, "auth_init: scanf %d items, skipping line %d.", + scan_cnt, line_cnt); + free(act); + } + line_cnt++; + } + fclose(keyf); + + key_ptr = *keys; + return key_cnt; +} + +/* Looks for the key with keyid key_id and sets the d_key pointer to the + * address of the key. If no matching key is found the pointer is not touched. + */ +void +get_key( + int key_id, + struct key **d_key + ) +{ + struct key *itr_key; + + if (key_cnt == 0) + return; + for (itr_key = key_ptr; itr_key; itr_key = itr_key->next) { + if (itr_key->key_id == key_id) { + *d_key = itr_key; + break; + } + } + return; +} diff --git a/pool/shard003/C/0068526_channel.c b/pool/shard003/C/0068526_channel.c new file mode 100644 index 0000000000000000000000000000000000000000..7f55c78e5a44311ca519942a8d993d830f837987 --- /dev/null +++ b/pool/shard003/C/0068526_channel.c @@ -0,0 +1,203 @@ +#include +#include +#include + +#include "channel.h" +#include "mp3.h" +#include "event.h" +#include "song.h" +#include "time_tool.h" +#include "display.h" +#include "hash.h" +#include "song_queue.h" + +#define MAX_CHANNEL_QUEUE_SIZE 128 + +struct channel { + struct channel *next; + char *name; + user_t *user; + struct timeval start; + song_t *song; + mp3_stream_t *stream; + + song_queue_t *queue; +}; + +static channel_t *channel_first = NULL; +static hash_t *channel_list = NULL; + +static void channel_update(event_t *t, const struct timeval *now, void *data) +{ + channel_t *c; + int64_t pos; + mp3_buffer_t cur_buf; + int ret; + + (void) t; + (void) data; + + c = channel_first; + + while(c) { + int nb; + int *fd; + + nb = user_get_nb_socket(c->user); + fd = user_get_socket(c->user); + + if(nb) { + if(c->stream == NULL) { + int mid; + + mid = song_queue_next(c->queue); + c->song = song_get(mid); + c->stream = mp3_stream_open(c->song->dst); + if(mid == -1) { + song_queue_add(c->queue, c->song->mid); + song_queue_next(c->queue); + } + } + + pos = timeval_diff(now, &c->start); + ret = mp3_stream_read(c->stream, pos, &cur_buf); + if(ret == -1) { + print_error("Error on reading song channel %s: %m", c->name); + mp3_stream_close(c->stream); + c->stream = NULL; + continue; + } + } + + for(fd = fd + nb -1; nb--; fd--) { + retry: + ret = send(*fd, cur_buf.buf, cur_buf.size, MSG_DONTWAIT | MSG_NOSIGNAL); + if(ret == -1) { + if(errno == EINTR) + goto retry; + + if(errno == EAGAIN || + errno == EWOULDBLOCK || + errno == ENOBUFS) { + print_debug("Skip %i bytes channel=%s fd=%i", cur_buf.size, c->name, *fd); + continue; + } + + print_debug("Close connection channel=%s fd=%i: %m", c->name, *fd); + close(user_remove_socket(c->user, *fd)); + continue; + } + } + if(c->stream->offset == c->stream->data_size) { + print_debug("End of Song channel=%s", c->name); + timeval_add_usec(&c->start, c->stream->pos); + mp3_stream_close(c->stream); + c->stream = NULL; + continue; + } + c = c->next; + } +} + +static channel_t * channel_new(char *user) +{ + channel_t *c; + struct timeval now; + + gettimeofday(&now, NULL); + + c = (channel_t *) malloc(sizeof(channel_t)); + + c->stream = NULL; + c->name = strdup(user); + c->start = now; + c->next = channel_first; + c->user = NULL; + c->queue = song_queue_new(MAX_CHANNEL_QUEUE_SIZE); + + channel_first = c; + + hash_add(channel_list, c->name, c); + + return c; +} + +channel_t * channel_add_user(char *channel, user_t *u) +{ + channel_t *c; + struct timeval now; + + c = hash_get(channel_list, channel); + if(c) { + if(c->user != NULL && c->user != u) + return NULL; // must manage multi user + + if(user_get_nb_socket(u) == 1) { // Resynchronisation + gettimeofday(&now, NULL); + c->start = now; + timeval_add_usec(&c->start, -c->stream->pos); + } + + + c->user = u; + + return c; + } + c = channel_new(channel); + c->user = u; + + return c; +} + +void channel_init(void) +{ + channel_list = hash_new(hash_str_cmp, hash_str_hash, 8); + event_timer_add(200, EVENT_TIMER_KIND_PERIODIC, channel_update, NULL); +} + +song_t * channel_current_song(channel_t *c) +{ + return c->song; +} + +int channel_current_song_elapsed(channel_t *c) +{ + if(c == NULL || c->stream == NULL) + return 0; + return c->stream->pos; +} + +song_queue_t * channel_get_queue(channel_t *c) +{ + return c->queue; +} + +int channel_next(channel_t *c) +{ + if(c->stream) { + timeval_add_usec(&c->start, c->stream->pos); + mp3_stream_close(c->stream); + c->stream = NULL; + } + + return 0; +} + +int channel_previous(channel_t *c) +{ + int mid; + + mid = song_queue_previous(c->queue); + if(mid == -1) + return -1; + + if(c->stream) { + timeval_add_usec(&c->start, c->stream->pos); + mp3_stream_close(c->stream); + c->song = song_get(mid); + c->stream = mp3_stream_open(c->song->dst); + song_queue_add(c->queue, c->song->mid); + } + + return 0; +} diff --git a/pool/shard003/C/0068534_hashtable.c b/pool/shard003/C/0068534_hashtable.c new file mode 100644 index 0000000000000000000000000000000000000000..4462dc0ff8ad1bde3adfe5e44f3bce43e2a8c8b0 --- /dev/null +++ b/pool/shard003/C/0068534_hashtable.c @@ -0,0 +1,86 @@ +#include +#include + +#include "libterm.h" +#include "linkedlist.h" + +/* stupid hash function */ +static uchar hash_function(char *key) { + uchar hash = 0; + size_t i; + + for(i = 0; i < strlen(key); i++) + switch(i%3) { + case 0: + hash ^= key[i] << 1; + break; + case 1: + hash ^= key[i]; + break; + case 2: + /* ensure logical bit shift... */ + hash ^= (uchar)key[i] >> 1; + break; + } + + return hash; +} + +int hashtable_set_pair(struct list_node *hashtable[], char *key, void *data, uint len) { + uchar bucket = hash_function(key); + struct list_node **head, *node; + char *databuf; + int ret = 0; + + head = &hashtable[bucket]; + node = linkedlist_find_str_node(*head, key); + + if(node) { + free(node->data); + + databuf = malloc(len); + if(!databuf) SYS_ERR("malloc", NULL, error); + + memcpy(databuf, data, len); + + node->data = databuf; + node->len = len; + } else + if(linkedlist_add_str_node(head, key, data, len) == -1) return -1; + +error: + return ret; +} + +int hashtable_del_pair(struct list_node *hashtable[], char *key) { + struct list_node **head, *node; + uchar bucket = hash_function(key); + + head = &hashtable[bucket]; + node = linkedlist_find_str_node(*head, key); + + if(!node) return -1; + + linkedlist_del_node(head, node); + + return 0; +} + +void *hashtable_get_value(struct list_node *hashtable[], char *key) { + struct list_node *node; + uchar bucket = hash_function(key); + + node = linkedlist_find_str_node(hashtable[bucket], key); + + if(node) + return node->data; + else + return NULL; +} + +void hashtable_free(struct list_node *hashtable[]) { + short i; + + for(i = 0; i < 256; i++) + if(hashtable[i]) linkedlist_free(&hashtable[i]); +} diff --git a/pool/shard003/C/0068558_l52util.c b/pool/shard003/C/0068558_l52util.c new file mode 100644 index 0000000000000000000000000000000000000000..1a7355ddfe2433b9993e42f26f9bc9eff3fc391d --- /dev/null +++ b/pool/shard003/C/0068558_l52util.c @@ -0,0 +1,121 @@ +#include "l52util.h" + +#include +#include + +#if LUA_VERSION_NUM >= 502 + +int luaL_typerror (lua_State *L, int narg, const char *tname) { + const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, + luaL_typename(L, narg)); + return luaL_argerror(L, narg, msg); +} + +#ifndef luaL_register + +void luaL_register (lua_State *L, const char *libname, const luaL_Reg *l){ + if(libname) lua_newtable(L); + luaL_setfuncs(L, l, 0); +} + +#endif + +#else + +void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup){ + luaL_checkstack(L, nup, "too many upvalues"); + for (; l->name != NULL; l++) { /* fill the table with given functions */ + int i; + for (i = 0; i < nup; i++) /* copy upvalues to the top */ + lua_pushvalue(L, -nup); + lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ + lua_setfield(L, -(nup + 2), l->name); + } + lua_pop(L, nup); /* remove upvalues */ +} + +void lua_rawgetp(lua_State *L, int index, const void *p){ + index = lua_absindex(L, index); + lua_pushlightuserdata(L, (void *)p); + lua_rawget(L, index); +} + +void lua_rawsetp (lua_State *L, int index, const void *p){ + index = lua_absindex(L, index); + lua_pushlightuserdata(L, (void *)p); + lua_insert(L, -2); + lua_rawset(L, index); +} + +#endif + +int lutil_newmetatablep (lua_State *L, const void *p) { + lua_rawgetp(L, LUA_REGISTRYINDEX, p); + if (!lua_isnil(L, -1)) /* name already in use? */ + return 0; /* leave previous value on top, but return 0 */ + lua_pop(L, 1); + + lua_newtable(L); /* create metatable */ + lua_pushvalue(L, -1); /* duplicate metatable to set*/ + lua_rawsetp(L, LUA_REGISTRYINDEX, p); + + return 1; +} + +void lutil_getmetatablep (lua_State *L, const void *p) { + lua_rawgetp(L, LUA_REGISTRYINDEX, p); +} + +void lutil_setmetatablep (lua_State *L, const void *p) { + lutil_getmetatablep(L, p); + assert(lua_istable(L,-1)); + lua_setmetatable (L, -2); +} + +int lutil_isudatap (lua_State *L, int ud, const void *p) { + if (lua_isuserdata(L, ud)){ + if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ + int res; + lutil_getmetatablep(L,p); /* get correct metatable */ + res = lua_rawequal(L, -1, -2); /* does it have the correct mt? */ + lua_pop(L, 2); /* remove both metatables */ + return res; + } + } + return 0; +} + +void *lutil_checkudatap (lua_State *L, int ud, const void *p) { + void *up = lua_touserdata(L, ud); + if (up != NULL) { /* value is a userdata? */ + if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ + lutil_getmetatablep(L,p); /* get correct metatable */ + if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */ + lua_pop(L, 2); /* remove both metatables */ + return up; + } + } + } + luaL_typerror(L, ud, p); /* else error */ + return NULL; /* to avoid warnings */ +} + +int lutil_createmetap (lua_State *L, const void *p, const luaL_Reg *methods, int nup) { + if (!lutil_newmetatablep(L, p)) + return 0; + + lua_insert(L, -1 - nup); /* move mt prior upvalues */ + luaL_setfuncs (L, methods, nup); /* define methods */ + lua_pushliteral (L, "__index"); /* define metamethods */ + lua_pushvalue (L, -2); + lua_settable (L, -3); + + return 1; +} + +void *lutil_newudatap_impl(lua_State *L, size_t size, const void *p){ + void *obj = lua_newuserdata (L, size); + memset(obj, 0, size); + lutil_setmetatablep(L, p); + return obj; +} diff --git a/pool/shard003/C/0068561_t-compose_series_divconquer.c b/pool/shard003/C/0068561_t-compose_series_divconquer.c new file mode 100644 index 0000000000000000000000000000000000000000..8877802a2662fe7c874548c7d6da7bef0342661b --- /dev/null +++ b/pool/shard003/C/0068561_t-compose_series_divconquer.c @@ -0,0 +1,134 @@ +/* + Copyright (C) 2010 William Hart + Copyright (C) 2011 Sebastian Pancratz + + This file is part of FLINT. + + FLINT 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.1 of the License, or + (at your option) any later version. See . +*/ + +#include +#include +#include +#include "flint.h" +#include "nmod_poly.h" +#include "ulong_extras.h" + +int +main(void) +{ + int i, result = 1; + FLINT_TEST_INIT(state); + + + flint_printf("compose_series_divconquer...."); + fflush(stdout); + + /* Aliasing */ + for (i = 0; i < 500 * flint_test_multiplier(); i++) + { + nmod_poly_t a, b, c; + mp_limb_t n = n_randtest_not_zero(state); + slong N = n_randint(state, 50); + + nmod_poly_init(a, n); + nmod_poly_init(b, n); + nmod_poly_init(c, n); + nmod_poly_randtest(a, state, n_randint(state, 30)); + nmod_poly_randtest(b, state, n_randint(state, 15)); + + nmod_poly_compose_series_divconquer(c, a, b, N); + nmod_poly_compose_series_divconquer(a, a, b, N); + + result = nmod_poly_equal(c, a); + if (!result) + { + flint_printf("FAIL:\n"); + flint_printf("a->length = %wd, n = %wu\n", a->length, a->mod.n); + nmod_poly_print(c), flint_printf("\n\n"); + nmod_poly_print(a), flint_printf("\n\n"); + fflush(stdout); + flint_abort(); + } + + nmod_poly_clear(a); + nmod_poly_clear(b); + nmod_poly_clear(c); + } + + /* Aliasing */ + for (i = 0; i < 500 * flint_test_multiplier(); i++) + { + nmod_poly_t a, b, c; + mp_limb_t n = n_randtest_not_zero(state); + slong N = n_randint(state, 50); + + nmod_poly_init(a, n); + nmod_poly_init(b, n); + nmod_poly_init(c, n); + nmod_poly_randtest(a, state, n_randint(state, 30)); + nmod_poly_randtest(b, state, n_randint(state, 15)); + + nmod_poly_compose_series_divconquer(c, a, b, N); + nmod_poly_compose_series_divconquer(b, a, b, N); + + result = nmod_poly_equal(c, b); + if (!result) + { + flint_printf("FAIL:\n"); + flint_printf("a->length = %wd, n = %wu\n", a->length, a->mod.n); + nmod_poly_print(c), flint_printf("\n\n"); + nmod_poly_print(b), flint_printf("\n\n"); + fflush(stdout); + flint_abort(); + } + + nmod_poly_clear(a); + nmod_poly_clear(b); + nmod_poly_clear(c); + } + + /* Compare with compose */ + for (i = 0; i < 500 * flint_test_multiplier(); i++) + { + nmod_poly_t a, b, r1, r2; + mp_limb_t n = n_randtest_not_zero(state); + slong N = n_randint(state, 50); + + nmod_poly_init(a, n); + nmod_poly_init(b, n); + nmod_poly_init(r1, n); + nmod_poly_init(r2, n); + nmod_poly_randtest(a, state, n_randint(state, 30)); + nmod_poly_randtest(b, state, n_randint(state, 15)); + + nmod_poly_compose_series_divconquer(r1, a, b, N); + nmod_poly_compose(r2, a, b); + nmod_poly_truncate(r2, N); + + result = nmod_poly_equal(r1, r2); + if (!result) + { + flint_printf("FAIL:\n"); + flint_printf("a->length = %wd, n = %wu\n", a->length, a->mod.n); + nmod_poly_print(r1), flint_printf("\n\n"); + nmod_poly_print(r2), flint_printf("\n\n"); + fflush(stdout); + flint_abort(); + } + + nmod_poly_clear(a); + nmod_poly_clear(b); + nmod_poly_clear(r1); + nmod_poly_clear(r2); + } + + FLINT_TEST_CLEANUP(state); + + flint_printf("PASS\n"); + return EXIT_SUCCESS; +} + diff --git a/pool/shard003/C/0068575_logout.c b/pool/shard003/C/0068575_logout.c new file mode 100644 index 0000000000000000000000000000000000000000..53be6bf846f2335d8576545101f8f3920545f390 --- /dev/null +++ b/pool/shard003/C/0068575_logout.c @@ -0,0 +1,61 @@ +/* GNU Mailutils -- a suite of utilities for electronic mail + Copyright (C) 2010-2012 Free Software Foundation, Inc. + + 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 3 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 + . */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include +#include + +int +mu_imap_logout (mu_imap_t imap) +{ + int status; + + if (imap == NULL) + return EINVAL; + if (!imap->io) + return MU_ERR_NO_TRANSPORT; + if (imap->session_state == MU_IMAP_SESSION_INIT) + return MU_ERR_SEQ; + + switch (imap->client_state) + { + case MU_IMAP_CLIENT_READY: + status = _mu_imap_tag_next (imap); + MU_IMAP_CHECK_EAGAIN (imap, status); + status = mu_imapio_printf (imap->io, "%s LOGOUT\r\n", + imap->tag_str); + MU_IMAP_CHECK_EAGAIN (imap, status); + MU_IMAP_FCLR (imap, MU_IMAP_RESP); + imap->client_state = MU_IMAP_CLIENT_LOGOUT_RX; + + case MU_IMAP_CLIENT_LOGOUT_RX: + status = _mu_imap_response (imap, NULL, NULL); + MU_IMAP_CHECK_EAGAIN (imap, status); + imap->client_state = MU_IMAP_CLIENT_READY; + imap->session_state = MU_IMAP_SESSION_INIT; + break; + + default: + status = EINPROGRESS; + } + return status; +} + diff --git a/pool/shard003/C/0068578_t-shift_left_right.c b/pool/shard003/C/0068578_t-shift_left_right.c new file mode 100644 index 0000000000000000000000000000000000000000..83b56b0ee8e5e67d7f70f872c088ec0b240a77f5 --- /dev/null +++ b/pool/shard003/C/0068578_t-shift_left_right.c @@ -0,0 +1,112 @@ +/* + Copyright (C) 2009 William Hart + Copyright (C) 2013 Fredrik Johansson + + This file is part of Arb. + + Arb 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.1 of the License, or + (at your option) any later version. See . +*/ + +#include "arb_poly.h" + +int +main(void) +{ + int i, result; + flint_rand_t state; + + flint_printf("shift_left/right...."); + fflush(stdout); + + flint_randinit(state); + + /* Check aliasing of a and b for left shift */ + for (i = 0; i < 1000; i++) + { + arb_poly_t a, b; + slong shift = n_randint(state, 100); + + arb_poly_init(a); + arb_poly_init(b); + arb_poly_randtest(a, state, n_randint(state, 100), 2 + n_randint(state, 200), 10); + + arb_poly_shift_left(b, a, shift); + arb_poly_shift_left(a, a, shift); + + result = (arb_poly_equal(a, b)); + if (!result) + { + flint_printf("FAIL:\n"); + arb_poly_printd(a, 10), flint_printf("\n\n"); + arb_poly_printd(b, 10), flint_printf("\n\n"); + abort(); + } + + arb_poly_clear(a); + arb_poly_clear(b); + } + + /* Check aliasing of a and b for right shift */ + for (i = 0; i < 1000; i++) + { + arb_poly_t a, b; + slong shift = n_randint(state, 100); + + arb_poly_init(a); + arb_poly_init(b); + arb_poly_randtest(a, state, n_randint(state, 100), 2 + n_randint(state, 200), 10); + + arb_poly_shift_right(b, a, shift); + arb_poly_shift_right(a, a, shift); + + result = (arb_poly_equal(a, b)); + if (!result) + { + flint_printf("FAIL:\n"); + arb_poly_printd(a, 10), flint_printf("\n\n"); + arb_poly_printd(b, 10), flint_printf("\n\n"); + abort(); + } + + arb_poly_clear(a); + arb_poly_clear(b); + } + + /* Check shift left then right does nothing */ + for (i = 0; i < 1000; i++) + { + arb_poly_t a, b, c; + slong shift = n_randint(state, 100); + + arb_poly_init(a); + arb_poly_init(b); + arb_poly_init(c); + arb_poly_randtest(a, state, n_randint(state, 100), 2 + n_randint(state, 200), 10); + + arb_poly_shift_left(b, a, shift); + arb_poly_shift_right(c, b, shift); + + result = (arb_poly_equal(c, a)); + if (!result) + { + flint_printf("FAIL:\n"); + arb_poly_printd(a, 10), flint_printf("\n\n"); + arb_poly_printd(b, 10), flint_printf("\n\n"); + arb_poly_printd(c, 10), flint_printf("\n\n"); + abort(); + } + + arb_poly_clear(a); + arb_poly_clear(b); + arb_poly_clear(c); + } + + flint_randclear(state); + flint_cleanup(); + flint_printf("PASS\n"); + return 0; +} + diff --git a/pool/shard003/C/0068580_ui32_to_f128M.c b/pool/shard003/C/0068580_ui32_to_f128M.c new file mode 100644 index 0000000000000000000000000000000000000000..8d4ff43720d2930ed39288219d41fbcadc88310b --- /dev/null +++ b/pool/shard003/C/0068580_ui32_to_f128M.c @@ -0,0 +1,76 @@ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3e, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016 The 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: + + 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 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. + +=============================================================================*/ + +#include +#include "platform.h" +#include "internals.h" +#include "softfloat.h" + +#ifdef SOFTFLOAT_FAST_INT64 + +void ui32_to_f128M( uint32_t a, float128_t *zPtr ) +{ + + *zPtr = ui32_to_f128( a ); + +} + +#else + +void ui32_to_f128M( uint32_t a, float128_t *zPtr ) +{ + uint32_t *zWPtr, uiZ96, uiZ64; + int_fast8_t shiftDist; + uint64_t normA; + + zWPtr = (uint32_t *) zPtr; + uiZ96 = 0; + uiZ64 = 0; + if ( a ) { + shiftDist = softfloat_countLeadingZeros32( a ) + 17; + normA = (uint64_t) a<>32 ); + uiZ64 = normA; + } + zWPtr[indexWord( 4, 3 )] = uiZ96; + zWPtr[indexWord( 4, 2 )] = uiZ64; + zWPtr[indexWord( 4, 1 )] = 0; + zWPtr[indexWord( 4, 0 )] = 0; + +} + +#endif + diff --git a/pool/shard003/C/0068587_PcieMaxPayload.c b/pool/shard003/C/0068587_PcieMaxPayload.c new file mode 100644 index 0000000000000000000000000000000000000000..edf877264b73fe2a732b0958281d3b7eb47fc936 --- /dev/null +++ b/pool/shard003/C/0068587_PcieMaxPayload.c @@ -0,0 +1,376 @@ +/* $NoKeywords:$ */ +/** + * @file + * + * Configure Max Payload + * + * + * + * @xrefitem bom "File Content Label" "Release Content" + * @e project: AGESA + * @e sub-project: GNB + * @e \$Revision: + * + */ +/* +***************************************************************************** +* + * Copyright (c) 2008 - 2013, Advanced Micro Devices, 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 Advanced Micro Devices, 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 ADVANCED MICRO DEVICES, INC. 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. +* *************************************************************************** +* +*/ + +/*---------------------------------------------------------------------------------------- + * M O D U L E S U S E D + *---------------------------------------------------------------------------------------- + */ +#include "AGESA.h" +#include "Ids.h" +#include "amdlib.h" +#include "Gnb.h" +#include "GnbPcie.h" +#include "GnbCommonLib.h" +#include "GnbPcieConfig.h" +#include "PcieMaxPayload.h" +#include "OptionGnb.h" +#include "GnbFamServices.h" +#include "Filecode.h" +#define FILECODE PROC_GNB_MODULES_GNBPCIEMAXPAYLOAD_PCIEMAXPAYLOAD_FILECODE + +/*---------------------------------------------------------------------------------------- + * D E F I N I T I O N S A N D M A C R O S + *---------------------------------------------------------------------------------------- + */ +extern GNB_BUILD_OPTIONS GnbBuildOptions; + + +/*---------------------------------------------------------------------------------------- + * T Y P E D E F S A N D S T R U C T U R E S + *---------------------------------------------------------------------------------------- + */ +typedef struct { + GNB_PCI_SCAN_DATA ScanData; + UINT8 MaxPayload; +} PCIE_MAX_PAYLOAD_DATA; + + +/*---------------------------------------------------------------------------------------- + * P R O T O T Y P E S O F L O C A L F U N C T I O N S + *---------------------------------------------------------------------------------------- + */ + + +SCAN_STATUS +PcieGetMaxPayloadCallback ( + IN PCI_ADDR Device, + IN OUT GNB_PCI_SCAN_DATA *ScanData + ); + +SCAN_STATUS +PcieSetMaxPayloadCallback ( + IN PCI_ADDR Device, + IN OUT GNB_PCI_SCAN_DATA *ScanData + ); + +AGESA_STATUS +PciePayloadBlackListFeature ( + IN PCI_ADDR Device, + IN UINT8 *MaxPayload, + IN AMD_CONFIG_PARAMS *StdHeader + ); + +AGESA_STATUS +PcieMaxPayloadInterface ( + IN AMD_CONFIG_PARAMS *StdHeader + ); + +/*----------------------------------------------------------------------------------------*/ +/** + * Determine maximum payload size for PCIe segment + * + * Scan through all link in segment to determine maximum payload by EPs. + * + * @param[in] DownstreamPort PCI address of PCIe port + * @param[in] EngineMaxPayload MaxPayload supported by the engine + * @param[in] StdHeader Standard configuration header + * + */ + +VOID +PcieSetMaxPayload ( + IN PCI_ADDR DownstreamPort, + IN UINT8 EngineMaxPayload, + IN AMD_CONFIG_PARAMS *StdHeader + ) +{ + PCIE_MAX_PAYLOAD_DATA PcieMaxPayloadData; + + IDS_HDT_CONSOLE (GNB_TRACE, " PcieSetMaxPayload for Device = %d:%d:%d\n", + DownstreamPort.Address.Bus, + DownstreamPort.Address.Device, + DownstreamPort.Address.Function + ); + PcieMaxPayloadData.MaxPayload = EngineMaxPayload; + PcieMaxPayloadData.ScanData.StdHeader = StdHeader; + PcieMaxPayloadData.ScanData.GnbScanCallback = PcieGetMaxPayloadCallback; + GnbLibPciScan (DownstreamPort, DownstreamPort, &PcieMaxPayloadData.ScanData); + PcieMaxPayloadData.ScanData.GnbScanCallback = PcieSetMaxPayloadCallback; + GnbLibPciScan (DownstreamPort, DownstreamPort, &PcieMaxPayloadData.ScanData); + IDS_HDT_CONSOLE (GNB_TRACE, " PcieSetMaxPayloadExit\n"); +} + +/*----------------------------------------------------------------------------------------*/ +/** + * Evaluate device Max Payload - save SMALLEST Max Payload for PCIe Segment + * + * + * + * @param[in] Device PCI Address + * @param[in,out] ScanData Scan configuration data + * @retval Scan Status of 0 + */ + +SCAN_STATUS +PcieGetMaxPayloadCallback ( + IN PCI_ADDR Device, + IN OUT GNB_PCI_SCAN_DATA *ScanData + ) +{ + SCAN_STATUS ScanStatus; + PCIE_MAX_PAYLOAD_DATA *PcieMaxPayloadData; + PCIE_DEVICE_TYPE DeviceType; + UINT32 Value; + UINT8 PcieCapPtr; + UINT8 DeviceMaxPayload; + + PcieMaxPayloadData = (PCIE_MAX_PAYLOAD_DATA*) ScanData; + ScanStatus = SCAN_SUCCESS; + IDS_HDT_CONSOLE (GNB_TRACE, " PcieGetMaxPayloadCallback for Device = %d:%d:%d\n", + Device.Address.Bus, + Device.Address.Device, + Device.Address.Function + ); + PcieCapPtr = GnbLibFindPciCapability (Device.AddressValue, PCIE_CAP_ID, ScanData->StdHeader); + if (PcieCapPtr != 0) { + GnbLibPciRead ( + Device.AddressValue | (PcieCapPtr + PCIE_DEVICE_CAP_REGISTER), + AccessWidth32, + &Value, + ScanData->StdHeader + ); + DeviceMaxPayload = (UINT8) (Value & 0x7); + PciePayloadBlackListFeature (Device, &DeviceMaxPayload, ScanData->StdHeader); + IDS_HDT_CONSOLE (GNB_TRACE, " Found DeviceMaxPayload as %d (Value = %x\n", DeviceMaxPayload, Value); + if (DeviceMaxPayload < PcieMaxPayloadData->MaxPayload) { + PcieMaxPayloadData->MaxPayload = DeviceMaxPayload; + } + } + DeviceType = GnbLibGetPcieDeviceType (Device, ScanData->StdHeader); + switch (DeviceType) { + case PcieDeviceRootComplex: + case PcieDeviceDownstreamPort: + case PcieDeviceUpstreamPort: + GnbLibPciScanSecondaryBus (Device, &PcieMaxPayloadData->ScanData); + break; + case PcieDeviceEndPoint: + case PcieDeviceLegacyEndPoint: + break; + default: + break; + } + return SCAN_SUCCESS; +} + +/*----------------------------------------------------------------------------------------*/ +/** + * Configure the Max Payload setting to all devices in the PCIe Segment + * + * + * + * @param[in] Device PCI Address + * @param[in,out] ScanData Scan configuration data + * @retval Scan Status of 0 + */ + +SCAN_STATUS +PcieSetMaxPayloadCallback ( + IN PCI_ADDR Device, + IN OUT GNB_PCI_SCAN_DATA *ScanData + ) +{ + SCAN_STATUS ScanStatus; + PCIE_MAX_PAYLOAD_DATA *PcieMaxPayloadData; + PCIE_DEVICE_TYPE DeviceType; + UINT8 PcieCapPtr; + + PcieMaxPayloadData = (PCIE_MAX_PAYLOAD_DATA*) ScanData; + ScanStatus = SCAN_SUCCESS; + IDS_HDT_CONSOLE (GNB_TRACE, " PcieSetMaxPayloadCallback for Device = %d:%d:%d to %d\n", + Device.Address.Bus, + Device.Address.Device, + Device.Address.Function, + PcieMaxPayloadData->MaxPayload + ); + PcieCapPtr = GnbLibFindPciCapability (Device.AddressValue, PCIE_CAP_ID, ScanData->StdHeader); + if (PcieCapPtr != 0) { + GnbLibPciRMW ( + Device.AddressValue | (PcieCapPtr + PCIE_DEVICE_CTRL_REGISTER), + AccessWidth32, + ~(UINT32) (0x7 << 5), + ((UINT32)PcieMaxPayloadData->MaxPayload << 5), + ScanData->StdHeader + ); + } + DeviceType = GnbLibGetPcieDeviceType (Device, ScanData->StdHeader); + switch (DeviceType) { + case PcieDeviceRootComplex: + case PcieDeviceDownstreamPort: + case PcieDeviceUpstreamPort: + GnbLibPciScanSecondaryBus (Device, &PcieMaxPayloadData->ScanData); + break; + case PcieDeviceEndPoint: + case PcieDeviceLegacyEndPoint: + break; + default: + break; + } + return SCAN_SUCCESS; +} + +UINT16 PayloadBlacklistDeviceTable[] = { + 0x1969, 0x1083, (UINT16) MAX_PAYLOAD_128 +}; + +/*----------------------------------------------------------------------------------------*/ +/** + * Pcie Max_Payload_Size Black List + * + * + * + * @param[in] Device PCI_ADDR of PCIe Device to evaluate + * @param[in] MaxPayload Pointer to Max_Payload_Size value + * @param[in] StdHeader Standard configuration header + * @retval AGESA_STATUS + */ + +AGESA_STATUS +PciePayloadBlackListFeature ( + IN PCI_ADDR Device, + IN UINT8 *MaxPayload, + IN AMD_CONFIG_PARAMS *StdHeader + ) +{ + UINT32 TargetDeviceId; + UINTN i; + UINT32 DeviceId; + UINT32 VendorId; + + GnbLibPciRead (Device.AddressValue, AccessWidth32, &TargetDeviceId, StdHeader); + for (i = 0; i < (sizeof (PayloadBlacklistDeviceTable) / sizeof (UINT16)); i = i + 3) { + VendorId = PayloadBlacklistDeviceTable[i]; + DeviceId = PayloadBlacklistDeviceTable[i + 1]; + if (VendorId == (UINT16)TargetDeviceId) { + if (DeviceId == 0xFFFF || DeviceId == (TargetDeviceId >> 16)) { + *MaxPayload = (UINT8) PayloadBlacklistDeviceTable[i + 2]; + } + } + } + return AGESA_SUCCESS; +} + +/*----------------------------------------------------------------------------------------*/ +/** + * Callback to init various features on all active ports + * + * + * + * + * @param[in] Engine Pointer to engine config descriptor + * @param[in, out] Buffer Not used + * @param[in] Pcie Pointer to global PCIe configuration + * + */ + +VOID +STATIC +PcieMaxPayloadInitCallback ( + IN PCIe_ENGINE_CONFIG *Engine, + IN OUT VOID *Buffer, + IN PCIe_PLATFORM_CONFIG *Pcie + ) +{ + PCIE_MAXPAYLOAD_SERVICE *PcieMaxPayloadProtocol; + UINT8 EngineMaxPayload; + AGESA_STATUS Status; + PCIe_COMPLEX_CONFIG *Complex; + + + + if ((GnbBuildOptions.CfgMaxPayloadEnable != 0) && + (!PcieConfigIsSbPcieEngine (Engine)) && + (PcieConfigCheckPortStatus (Engine, INIT_STATUS_PCIE_TRAINING_SUCCESS))) { + EngineMaxPayload = MAX_PAYLOAD; + Complex = (PCIe_COMPLEX_CONFIG *) PcieConfigGetParent (DESCRIPTOR_COMPLEX, &Engine->Header); + Status = GnbLibLocateService (GnbPcieMaxPayloadService, Complex->SocketId, (VOID **)&PcieMaxPayloadProtocol, GnbLibGetHeader (Pcie)); + if (Status == AGESA_SUCCESS) { + EngineMaxPayload = PcieMaxPayloadProtocol->SetMaxPayload (Engine); + } + PcieSetMaxPayload (Engine->Type.Port.Address, EngineMaxPayload, GnbLibGetHeader (Pcie)); + } +} + +/**----------------------------------------------------------------------------------------*/ +/** + * Interface to configure MaxPayloadSize on PCIE interface + * + * + * + * @param[in] StdHeader Standard configuration header + * + * @retval AGESA_STATUS + */ + /*----------------------------------------------------------------------------------------*/ +AGESA_STATUS +PcieMaxPayloadInterface ( + IN AMD_CONFIG_PARAMS *StdHeader + ) +{ + AGESA_STATUS AgesaStatus; + PCIe_PLATFORM_CONFIG *Pcie; + IDS_HDT_CONSOLE (GNB_TRACE, "PcieMaxPayloadInterface Enter\n"); + AgesaStatus = PcieLocateConfigurationData (StdHeader, &Pcie); + if (AgesaStatus == AGESA_SUCCESS) { + PcieConfigRunProcForAllEngines ( + DESCRIPTOR_ALLOCATED | DESCRIPTOR_PCIE_ENGINE, + PcieMaxPayloadInitCallback, + NULL, + Pcie + ); + } + IDS_HDT_CONSOLE (GNB_TRACE, "PcieMaxPayloadInterface Exit [0x%x]\n", AgesaStatus); + return AgesaStatus; +} + diff --git a/pool/shard003/C/0068597_Exp1.c b/pool/shard003/C/0068597_Exp1.c new file mode 100644 index 0000000000000000000000000000000000000000..4edd6cac7285f7b2e180c2c156f56d1fc84aa8ef --- /dev/null +++ b/pool/shard003/C/0068597_Exp1.c @@ -0,0 +1,93 @@ +#include +#include "NUC1xx.h" +#include "Driver\DrvGPIO.h" +#include "Driver\DrvSYS.h" + +uint32_t i=0 ; +uint32_t count=12; + +void delay2 (uint32_t count) +{ + uint32_t j ; + + for(j=0;j +#include "ace_sha.h" +#include +#include + +#ifdef CONFIG_SHA_HW_ACCEL +#include +#include +#include + +/* SHA1 value for the message of zero length */ +static const unsigned char sha1_digest_emptymsg[SHA1_SUM_LEN] = { + 0xDA, 0x39, 0xA3, 0xEE, 0x5E, 0x6B, 0x4B, 0x0D, + 0x32, 0x55, 0xBF, 0xFF, 0x95, 0x60, 0x18, 0x90, + 0xAF, 0xD8, 0x07, 0x09}; + +/* SHA256 value for the message of zero length */ +static const unsigned char sha256_digest_emptymsg[SHA256_SUM_LEN] = { + 0xE3, 0xB0, 0xC4, 0x42, 0x98, 0xFC, 0x1C, 0x14, + 0x9A, 0xFB, 0xF4, 0xC8, 0x99, 0x6F, 0xB9, 0x24, + 0x27, 0xAE, 0x41, 0xE4, 0x64, 0x9B, 0x93, 0x4C, + 0xA4, 0x95, 0x99, 0x1B, 0x78, 0x52, 0xB8, 0x55}; + +int ace_sha_hash_digest(const unsigned char *pbuf, unsigned int buf_len, + unsigned char *pout, unsigned int hash_type) +{ + unsigned int i, reg, len; + unsigned int *pdigest; + struct exynos_ace_sfr *ace_sha_reg = + (struct exynos_ace_sfr *)samsung_get_base_ace_sfr(); + + if (buf_len == 0) { + /* ACE H/W cannot compute hash value for empty string */ + if (hash_type == ACE_SHA_TYPE_SHA1) + memcpy(pout, sha1_digest_emptymsg, SHA1_SUM_LEN); + else + memcpy(pout, sha256_digest_emptymsg, SHA256_SUM_LEN); + return 0; + } + + /* Flush HRDMA */ + writel(ACE_FC_HRDMACFLUSH_ON, &ace_sha_reg->fc_hrdmac); + writel(ACE_FC_HRDMACFLUSH_OFF, &ace_sha_reg->fc_hrdmac); + + /* Set byte swap of data in */ + writel(ACE_HASH_SWAPDI_ON | ACE_HASH_SWAPDO_ON | ACE_HASH_SWAPIV_ON, + &ace_sha_reg->hash_byteswap); + + /* Select Hash input mux as external source */ + reg = readl(&ace_sha_reg->fc_fifoctrl); + reg = (reg & ~ACE_FC_SELHASH_MASK) | ACE_FC_SELHASH_EXOUT; + writel(reg, &ace_sha_reg->fc_fifoctrl); + + /* Set Hash as SHA1 or SHA256 and start Hash engine */ + reg = (hash_type == ACE_SHA_TYPE_SHA1) ? + ACE_HASH_ENGSEL_SHA1HASH : ACE_HASH_ENGSEL_SHA256HASH; + reg |= ACE_HASH_STARTBIT_ON; + writel(reg, &ace_sha_reg->hash_control); + + /* Enable FIFO mode */ + writel(ACE_HASH_FIFO_ON, &ace_sha_reg->hash_fifo_mode); + + /* Set message length */ + writel(buf_len, &ace_sha_reg->hash_msgsize_low); + writel(0, &ace_sha_reg->hash_msgsize_high); + + /* Set HRDMA */ + writel((unsigned int)pbuf, &ace_sha_reg->fc_hrdmas); + writel(buf_len, &ace_sha_reg->fc_hrdmal); + + while ((readl(&ace_sha_reg->hash_status) & ACE_HASH_MSGDONE_MASK) == + ACE_HASH_MSGDONE_OFF) { + /* + * PRNG error bit goes HIGH if a PRNG request occurs without + * a complete seed setup. We are using this bit to check h/w + * fault because proper setup is not expected in that case. + */ + if ((readl(&ace_sha_reg->hash_status) + & ACE_HASH_PRNGERROR_MASK) == ACE_HASH_PRNGERROR_ON) + return -EBUSY; + } + + /* Clear MSG_DONE bit */ + writel(ACE_HASH_MSGDONE_ON, &ace_sha_reg->hash_status); + + /* Read hash result */ + pdigest = (unsigned int *)pout; + len = (hash_type == ACE_SHA_TYPE_SHA1) ? SHA1_SUM_LEN : SHA256_SUM_LEN; + + for (i = 0; i < len / 4; i++) + pdigest[i] = readl(&ace_sha_reg->hash_result[i]); + + /* Clear HRDMA pending bit */ + writel(ACE_FC_HRDMA, &ace_sha_reg->fc_intpend); + + return 0; +} + +void hw_sha256(const unsigned char *pbuf, unsigned int buf_len, + unsigned char *pout, unsigned int chunk_size) +{ + if (ace_sha_hash_digest(pbuf, buf_len, pout, ACE_SHA_TYPE_SHA256)) + debug("ACE was not setup properly or it is faulty\n"); +} + +void hw_sha1(const unsigned char *pbuf, unsigned int buf_len, + unsigned char *pout, unsigned int chunk_size) +{ + if (ace_sha_hash_digest(pbuf, buf_len, pout, ACE_SHA_TYPE_SHA1)) + debug("ACE was not setup properly or it is faulty\n"); +} +#endif /* CONFIG_SHA_HW_ACCEL */ + +#ifdef CONFIG_LIB_HW_RAND +static unsigned int seed_done; + +void srand(unsigned int seed) +{ + struct exynos_ace_sfr *reg = + (struct exynos_ace_sfr *)samsung_get_base_ace_sfr(); + int i, status; + + /* Seed data */ + for (i = 0; i < ACE_HASH_PRNG_REG_NUM; i++) + writel(seed << i, ®->hash_seed[i]); + + /* Wait for seed setup done */ + while (1) { + status = readl(®->hash_status); + if ((status & ACE_HASH_SEEDSETTING_MASK) || + (status & ACE_HASH_PRNGERROR_MASK)) + break; + } + + seed_done = 1; +} + +unsigned int rand(void) +{ + struct exynos_ace_sfr *reg = + (struct exynos_ace_sfr *)samsung_get_base_ace_sfr(); + int i, status; + unsigned int seed = (unsigned int)&status; + unsigned int ret = 0; + + if (!seed_done) + srand(seed); + + /* Start PRNG */ + writel(ACE_HASH_ENGSEL_PRNG | ACE_HASH_STARTBIT_ON, ®->hash_control); + + /* Wait for PRNG done */ + while (1) { + status = readl(®->hash_status); + if (status & ACE_HASH_PRNGDONE_MASK) + break; + if (status & ACE_HASH_PRNGERROR_MASK) { + seed_done = 0; + return 0; + } + } + + /* Clear Done IRQ */ + writel(ACE_HASH_PRNGDONE_MASK, ®->hash_status); + + /* Read a PRNG result */ + for (i = 0; i < ACE_HASH_PRNG_REG_NUM; i++) + ret += readl(®->hash_prng[i]); + + seed_done = 0; + return ret; +} + +unsigned int rand_r(unsigned int *seedp) +{ + srand(*seedp); + + return rand(); +} +#endif /* CONFIG_LIB_HW_RAND */ diff --git a/pool/shard003/C/0068635_alloc.c b/pool/shard003/C/0068635_alloc.c new file mode 100644 index 0000000000000000000000000000000000000000..254fcc613cd6f8330361219e07720cfb072cc2e0 --- /dev/null +++ b/pool/shard003/C/0068635_alloc.c @@ -0,0 +1,33 @@ +#include "sc_alloc.h" +#include "sc_error.h" + +void +sc_stackalloc_init(sc_stackalloc_t *alloc, void *mem, size_t size) +{ + alloc->mem = mem; + alloc->size = size; + alloc->used = 0; +} + +void * +sc_stackalloc_alloc(sc_stackalloc_t *alloc, size_t size) +{ + void *rv; + if (alloc->used + size > alloc->size) { + sc_set_error(SC_EOOM, NULL, 0, "out of memory on stack allocation"); + return NULL; + } + rv = (void *)((uintptr_t)alloc->mem + alloc->used); + alloc->used += size; + return rv; +} + +void * +sc_memassert(void *p) +{ + if (!p) { + sc_critical_error(SC_EOOM, NULL, 0, "out of memory on general allocation"); + exit(1); + } + return p; +} diff --git a/pool/shard003/C/0068647_mpc836x_mds.c b/pool/shard003/C/0068647_mpc836x_mds.c new file mode 100644 index 0000000000000000000000000000000000000000..fd44dd03e1f3a4f90bf0efc3f81565c527dec204 --- /dev/null +++ b/pool/shard003/C/0068647_mpc836x_mds.c @@ -0,0 +1,222 @@ +/* + * Copyright 2006 Freescale Semiconductor, Inc. All rights reserved. + * + * Author: Li Yang + * Yin Olivia + * + * Description: + * MPC8360E MDS board specific routines. + * + * Changelog: + * Jun 21, 2006 Initial version + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mpc83xx.h" + +#undef DEBUG +#ifdef DEBUG +#define DBG(fmt...) udbg_printf(fmt) +#else +#define DBG(fmt...) +#endif + +/* ************************************************************************ + * + * Setup the architecture + * + */ +static void __init mpc836x_mds_setup_arch(void) +{ + struct device_node *np; + u8 __iomem *bcsr_regs = NULL; + + mpc83xx_setup_arch(); + + /* Map BCSR area */ + np = of_find_node_by_name(NULL, "bcsr"); + if (np) { + struct resource res; + + of_address_to_resource(np, 0, &res); + bcsr_regs = ioremap(res.start, resource_size(&res)); + of_node_put(np); + } + +#ifdef CONFIG_QUICC_ENGINE + if ((np = of_find_node_by_name(NULL, "par_io")) != NULL) { + par_io_init(np); + of_node_put(np); + + for_each_node_by_name(np, "ucc") + par_io_of_config(np); +#ifdef CONFIG_QE_USB + /* Must fixup Par IO before QE GPIO chips are registered. */ + par_io_config_pin(1, 2, 1, 0, 3, 0); /* USBOE */ + par_io_config_pin(1, 3, 1, 0, 3, 0); /* USBTP */ + par_io_config_pin(1, 8, 1, 0, 1, 0); /* USBTN */ + par_io_config_pin(1, 10, 2, 0, 3, 0); /* USBRXD */ + par_io_config_pin(1, 9, 2, 1, 3, 0); /* USBRP */ + par_io_config_pin(1, 11, 2, 1, 3, 0); /* USBRN */ + par_io_config_pin(2, 20, 2, 0, 1, 0); /* CLK21 */ +#endif /* CONFIG_QE_USB */ + } + + if ((np = of_find_compatible_node(NULL, "network", "ucc_geth")) + != NULL){ + uint svid; + + /* Reset the Ethernet PHY */ +#define BCSR9_GETHRST 0x20 + clrbits8(&bcsr_regs[9], BCSR9_GETHRST); + udelay(1000); + setbits8(&bcsr_regs[9], BCSR9_GETHRST); + + /* handle mpc8360ea rev.2.1 erratum 2: RGMII Timing */ + svid = mfspr(SPRN_SVR); + if (svid == 0x80480021) { + void __iomem *immap; + + immap = ioremap(get_immrbase() + 0x14a8, 8); + + /* + * IMMR + 0x14A8[4:5] = 11 (clk delay for UCC 2) + * IMMR + 0x14A8[18:19] = 11 (clk delay for UCC 1) + */ + setbits32(immap, 0x0c003000); + + /* + * IMMR + 0x14AC[20:27] = 10101010 + * (data delay for both UCC's) + */ + clrsetbits_be32(immap + 4, 0xff0, 0xaa0); + + iounmap(immap); + } + + iounmap(bcsr_regs); + of_node_put(np); + } +#endif /* CONFIG_QUICC_ENGINE */ +} + +machine_device_initcall(mpc836x_mds, mpc83xx_declare_of_platform_devices); + +#ifdef CONFIG_QE_USB +static int __init mpc836x_usb_cfg(void) +{ + u8 __iomem *bcsr; + struct device_node *np; + const char *mode; + int ret = 0; + + np = of_find_compatible_node(NULL, NULL, "fsl,mpc8360mds-bcsr"); + if (!np) + return -ENODEV; + + bcsr = of_iomap(np, 0); + of_node_put(np); + if (!bcsr) + return -ENOMEM; + + np = of_find_compatible_node(NULL, NULL, "fsl,mpc8323-qe-usb"); + if (!np) { + ret = -ENODEV; + goto err; + } + +#define BCSR8_TSEC1M_MASK (0x3 << 6) +#define BCSR8_TSEC1M_RGMII (0x0 << 6) +#define BCSR8_TSEC2M_MASK (0x3 << 4) +#define BCSR8_TSEC2M_RGMII (0x0 << 4) + /* + * Default is GMII (2), but we should set it to RGMII (0) if we use + * USB (Eth PHY is in RGMII mode anyway). + */ + clrsetbits_8(&bcsr[8], BCSR8_TSEC1M_MASK | BCSR8_TSEC2M_MASK, + BCSR8_TSEC1M_RGMII | BCSR8_TSEC2M_RGMII); + +#define BCSR13_USBMASK 0x0f +#define BCSR13_nUSBEN 0x08 /* 1 - Disable, 0 - Enable */ +#define BCSR13_USBSPEED 0x04 /* 1 - Full, 0 - Low */ +#define BCSR13_USBMODE 0x02 /* 1 - Host, 0 - Function */ +#define BCSR13_nUSBVCC 0x01 /* 1 - gets VBUS, 0 - supplies VBUS */ + + clrsetbits_8(&bcsr[13], BCSR13_USBMASK, BCSR13_USBSPEED); + + mode = of_get_property(np, "mode", NULL); + if (mode && !strcmp(mode, "peripheral")) { + setbits8(&bcsr[13], BCSR13_nUSBVCC); + qe_usb_clock_set(QE_CLK21, 48000000); + } else { + setbits8(&bcsr[13], BCSR13_USBMODE); + /* + * The BCSR GPIOs are used to control power and + * speed of the USB transceiver. This is needed for + * the USB Host only. + */ + simple_gpiochip_init("fsl,mpc8360mds-bcsr-gpio"); + } + + of_node_put(np); +err: + iounmap(bcsr); + return ret; +} +machine_arch_initcall(mpc836x_mds, mpc836x_usb_cfg); +#endif /* CONFIG_QE_USB */ + +/* + * Called very early, MMU is off, device-tree isn't unflattened + */ +static int __init mpc836x_mds_probe(void) +{ + return of_machine_is_compatible("MPC836xMDS"); +} + +define_machine(mpc836x_mds) { + .name = "MPC836x MDS", + .probe = mpc836x_mds_probe, + .setup_arch = mpc836x_mds_setup_arch, + .init_IRQ = mpc83xx_ipic_and_qe_init_IRQ, + .get_irq = ipic_get_irq, + .restart = mpc83xx_restart, + .time_init = mpc83xx_time_init, + .calibrate_decr = generic_calibrate_decr, + .progress = udbg_progress, +}; diff --git a/pool/shard003/C/0068658_binary_test.c b/pool/shard003/C/0068658_binary_test.c new file mode 100644 index 0000000000000000000000000000000000000000..edb6fd3eaba46739d5b9da5e8a7798d2580db748 --- /dev/null +++ b/pool/shard003/C/0068658_binary_test.c @@ -0,0 +1,157 @@ +/** + * Summary: Freetds binary patch test. + * Author: Gerhard Esterhuizen + * Date: April 2003 + */ + +#include "common.h" +#include + +static char software_version[] = "$Id: binary_test.c,v 1.9 2010/07/05 09:20:32 freddy77 Exp $"; +static void *no_unused_var_warn[] = { software_version, no_unused_var_warn }; + +#define ERR_BUF_SIZE 256 +/* + Name of table used by the test. Should contain single column, + of IMAGE type and should contain NO rows at time of program invocation. +*/ +#define TEST_TABLE_NAME "#binary_test" + +/* + Size (in bytes) of the test pattern written to and read from + the database. +*/ +#define TEST_BUF_LEN (1024*128) + + +static unsigned char *buf; + +static void +show_error(const char *where, const char *what) +{ + printf("ERROR in %s: %s.\n", where, what); +} + +static void +clean_up(void) +{ + free(buf); + odbc_disconnect(); +} + +static int +test_insert(void *buf, SQLLEN buflen) +{ + SQLHSTMT odbc_stmt = SQL_NULL_HSTMT; + SQLLEN strlen_or_ind; + const char *qstr = "insert into " TEST_TABLE_NAME " values (?)"; + + assert(odbc_conn); + assert(odbc_env); + + /* allocate new statement handle */ + CHKAllocHandle(SQL_HANDLE_STMT, odbc_conn, &odbc_stmt, "SI"); + + /* execute query */ + CHKPrepare((SQLCHAR *) qstr, SQL_NTS, "SI"); + + strlen_or_ind = buflen; + CHKBindParameter(1, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, (SQLUINTEGER) (-1), 0, buf, buflen, + &strlen_or_ind, "SI"); + + CHKExecute("SI"); + + /* this command shouldn't fail */ + odbc_command("DECLARE @i INT"); + + SQLFreeHandle(SQL_HANDLE_STMT, odbc_stmt); + return 0; +} + + +static int +test_select(void *buf, SQLINTEGER buflen, SQLLEN * bytes_returned) +{ + SQLHSTMT odbc_stmt = SQL_NULL_HSTMT; + SQLLEN strlen_or_ind = 0; + const char *qstr = "select * from " TEST_TABLE_NAME; + + assert(odbc_conn); + assert(odbc_env); + + /* allocate new statement handle */ + CHKAllocHandle(SQL_HANDLE_STMT, odbc_conn, &odbc_stmt, "SI"); + + /* execute query */ + CHKExecDirect((SQLCHAR *) qstr, SQL_NTS, "SINo"); + + /* fetch first page of first result row of unbound column */ + CHKFetch("S"); + + strlen_or_ind = 0; + CHKGetData(1, SQL_C_BINARY, buf, buflen, &strlen_or_ind, "SINo"); + + *bytes_returned = ((strlen_or_ind > buflen || (strlen_or_ind == SQL_NO_TOTAL)) ? buflen : strlen_or_ind); + + /* ensure that this was the only row */ + CHKFetch("No"); + + SQLFreeHandle(SQL_HANDLE_STMT, odbc_stmt); + return 0; +} + +#define BYTE_AT(n) (((n) * 123) & 0xff) + +int +main(int argc, char **argv) +{ + int i; + SQLLEN bytes_returned; + + /* do not allocate so big memory in stack */ + buf = (unsigned char *) malloc(TEST_BUF_LEN); + + odbc_connect(); + + odbc_command("create table " TEST_TABLE_NAME " (im IMAGE)"); + odbc_command("SET TEXTSIZE 1000000"); + + /* populate test buffer with ramp */ + for (i = 0; i < TEST_BUF_LEN; i++) { + buf[i] = BYTE_AT(i); + } + + /* insert test pattern into database */ + if (test_insert(buf, TEST_BUF_LEN) == -1) { + clean_up(); + return -1; + } + + memset(buf, 0, TEST_BUF_LEN); + + /* read test pattern from database */ + if (test_select(buf, TEST_BUF_LEN, &bytes_returned) == -1) { + clean_up(); + return -1; + } + + /* compare inserted and read back test patterns */ + if (bytes_returned != TEST_BUF_LEN) { + show_error("main(): comparing buffers", "Mismatch in input and output pattern sizes."); + clean_up(); + return -1; + } + + for (i = 0; i < TEST_BUF_LEN; ++i) { + if (buf[i] != BYTE_AT(i)) { + printf("mismatch at pos %d %d != %d\n", i, buf[i], BYTE_AT(i)); + show_error("main(): comparing buffers", "Mismatch in input and output patterns."); + clean_up(); + return -1; + } + } + + printf("Input and output buffers of length %d match.\nTest passed.\n", TEST_BUF_LEN); + clean_up(); + return 0; +} diff --git a/pool/shard003/C/0068662_udpclitimeo3.c b/pool/shard003/C/0068662_udpclitimeo3.c new file mode 100644 index 0000000000000000000000000000000000000000..57e3be5965ef7c39b747c0363254bd522a425f94 --- /dev/null +++ b/pool/shard003/C/0068662_udpclitimeo3.c @@ -0,0 +1,77 @@ +/* + * ===================================================================================== + * + * Filename: udpcli01.c + * + * Description: udp client for connecting timeout. + * + * Version: 1.0 + * Created: 11/03/13 17:28:15 + * Revision: none + * Compiler: gcc + * + * Author: Li Xiang (gk), lixiang-best@163.com + * Company: Li Xiang in Xiamen China. + * + * ===================================================================================== + */ +#include "unp.h" + +static void sig_alrm(int); + +int main(int argc, char **argv){ + int sockfd; + struct sockaddr_in servaddr; + + if(argc != 2) + err_quit("usage: udpcli "); + + bzero(&servaddr, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_port = htons(SERV_PORT); + /*servaddr.sin_port = htons(7);*//*use the standard echo server port.*/ + Inet_pton(AF_INET, argv[1], &servaddr.sin_addr); + + sockfd = Socket(AF_INET, SOCK_DGRAM, 0); + + /*upd bind defined port for test.*/ + /* + bzero(&cliaddr, sizeof(cliaddr)); + cliaddr.sin_family = AF_INET; + cliaddr.sin_addr.s_addr = htonl(INADDR_ANY); + cliaddr.sin_port = htons(35887); + Bind(sockfd, (SA*)&cliaddr, sizeof(cliaddr)); + */ + + dg_cli(stdin, sockfd, (SA*)&servaddr, sizeof(servaddr)); + exit(0); +} + +void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen){ + int n; + char sendline[MAXLINE], recvline[MAXLINE + 1]; + + Signal(SIGALRM, sig_alrm); + + while(Fgets(sendline, MAXLINE, fp) != NULL){ + Sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen); + + alarm(5);/*set timeout for recvfrom*/ + if( (n = Recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL)) < 0){ + if(errno == EINTR) + fprintf(stderr, "socket timeout\n"); + else + err_sys("recvfrom error"); + }else{ + alarm(0); + recvline[n] = 0;/*null terminate*/ + Fputs(recvline, stdout); + } + } +} + +static void sig_alrm(int signo){ + printf("catch sig_alrm.\n"); + return; +} + diff --git a/pool/shard003/C/0068664_xsub.c b/pool/shard003/C/0068664_xsub.c new file mode 100644 index 0000000000000000000000000000000000000000..ad060087f5a7037d7ed6110b0d179ef9b6f9a6a1 --- /dev/null +++ b/pool/shard003/C/0068664_xsub.c @@ -0,0 +1,210 @@ +// +// Copyright 2021 Staysail Systems, Inc. +// Copyright 2018 Capitar IT Group BV +// +// This software is supplied under the terms of the MIT License, a +// copy of which should be located in the distribution where this +// file was obtained (LICENSE.txt). A copy of the license may also be +// found online at https://opensource.org/licenses/MIT. +// + +#include + +#include "core/nng_impl.h" +#include "nng/protocol/pubsub0/sub.h" + +// Subscriber protocol. The SUB protocol receives messages sent to +// it from publishers, and filters out those it is not interested in, +// only passing up ones that match known subscriptions. + +#ifndef NNI_PROTO_SUB_V0 +#define NNI_PROTO_SUB_V0 NNI_PROTO(2, 1) +#endif + +#ifndef NNI_PROTO_PUB_V0 +#define NNI_PROTO_PUB_V0 NNI_PROTO(2, 0) +#endif + +typedef struct xsub0_pipe xsub0_pipe; +typedef struct xsub0_sock xsub0_sock; + +static void xsub0_recv_cb(void *); +static void xsub0_pipe_fini(void *); + +// xsub0_sock is our per-socket protocol private structure. +struct xsub0_sock { + nni_msgq *urq; + nni_mtx lk; +}; + +// sub0_pipe is our per-pipe protocol private structure. +struct xsub0_pipe { + nni_pipe * pipe; + xsub0_sock *sub; + nni_aio aio_recv; +}; + +static void +xsub0_sock_init(void *arg, nni_sock *sock) +{ + xsub0_sock *s = arg; + + s->urq = nni_sock_recvq(sock); +} + +static void +xsub0_sock_fini(void *arg) +{ + xsub0_sock *s = arg; + nni_mtx_fini(&s->lk); +} + +static void +xsub0_sock_open(void *arg) +{ + NNI_ARG_UNUSED(arg); +} + +static void +xsub0_sock_close(void *arg) +{ + NNI_ARG_UNUSED(arg); +} + +static void +xsub0_pipe_stop(void *arg) +{ + xsub0_pipe *p = arg; + + nni_aio_stop(&p->aio_recv); +} + +static void +xsub0_pipe_fini(void *arg) +{ + xsub0_pipe *p = arg; + + nni_aio_fini(&p->aio_recv); +} + +static int +xsub0_pipe_init(void *arg, nni_pipe *pipe, void *s) +{ + xsub0_pipe *p = arg; + + nni_aio_init(&p->aio_recv, xsub0_recv_cb, p); + + p->pipe = pipe; + p->sub = s; + return (0); +} + +static int +xsub0_pipe_start(void *arg) +{ + xsub0_pipe *p = arg; + + if (nni_pipe_peer(p->pipe) != NNI_PROTO_PUB_V0) { + // Peer protocol mismatch. + return (NNG_EPROTO); + } + + nni_pipe_recv(p->pipe, &p->aio_recv); + return (0); +} + +static void +xsub0_pipe_close(void *arg) +{ + xsub0_pipe *p = arg; + + nni_aio_close(&p->aio_recv); +} + +static void +xsub0_recv_cb(void *arg) +{ + xsub0_pipe *p = arg; + xsub0_sock *s = p->sub; + nni_msgq * urq = s->urq; + nni_msg * msg; + + if (nni_aio_result(&p->aio_recv) != 0) { + nni_pipe_close(p->pipe); + return; + } + + msg = nni_aio_get_msg(&p->aio_recv); + nni_aio_set_msg(&p->aio_recv, NULL); + nni_msg_set_pipe(msg, nni_pipe_id(p->pipe)); + + if (nni_msgq_tryput(urq, msg) != 0) { + // This only happens for two reasons. For flow control, + // in which case we just want to discard the message and + // carry on, and for a close of the socket (which is very + // hard to achieve, since we close the pipes.) In either + // case the easiest thing to do is just free the message + // and try again. + nni_msg_free(msg); + } + nni_pipe_recv(p->pipe, &p->aio_recv); +} + +static void +xsub0_sock_send(void *arg, nni_aio *aio) +{ + NNI_ARG_UNUSED(arg); + nni_aio_finish_error(aio, NNG_ENOTSUP); +} + +static void +xsub0_sock_recv(void *arg, nni_aio *aio) +{ + xsub0_sock *s = arg; + + nni_msgq_aio_get(s->urq, aio); +} + +// This is the global protocol structure -- our linkage to the core. +// This should be the only global non-static symbol in this file. +static nni_proto_pipe_ops xsub0_pipe_ops = { + .pipe_size = sizeof(xsub0_pipe), + .pipe_init = xsub0_pipe_init, + .pipe_fini = xsub0_pipe_fini, + .pipe_start = xsub0_pipe_start, + .pipe_close = xsub0_pipe_close, + .pipe_stop = xsub0_pipe_stop, +}; + +static nni_option xsub0_sock_options[] = { + // terminate list + { + .o_name = NULL, + }, +}; + +static nni_proto_sock_ops xsub0_sock_ops = { + .sock_size = sizeof(xsub0_sock), + .sock_init = xsub0_sock_init, + .sock_fini = xsub0_sock_fini, + .sock_open = xsub0_sock_open, + .sock_close = xsub0_sock_close, + .sock_send = xsub0_sock_send, + .sock_recv = xsub0_sock_recv, + .sock_options = xsub0_sock_options, +}; + +static nni_proto xsub0_proto = { + .proto_version = NNI_PROTOCOL_VERSION, + .proto_self = { NNI_PROTO_SUB_V0, "sub" }, + .proto_peer = { NNI_PROTO_PUB_V0, "pub" }, + .proto_flags = NNI_PROTO_FLAG_RCV | NNI_PROTO_FLAG_RAW, + .proto_sock_ops = &xsub0_sock_ops, + .proto_pipe_ops = &xsub0_pipe_ops, +}; + +int +nng_sub0_open_raw(nng_socket *sidp) +{ + return (nni_proto_open(sidp, &xsub0_proto)); +} diff --git a/pool/shard003/C/0068666_cockpitsshoptions.c b/pool/shard003/C/0068666_cockpitsshoptions.c new file mode 100644 index 0000000000000000000000000000000000000000..44faf1ec8c8f864ebda714bf9ebe866394f2de69 --- /dev/null +++ b/pool/shard003/C/0068666_cockpitsshoptions.c @@ -0,0 +1,127 @@ +/* + * This file is part of Cockpit. + * + * Copyright (C) 2016 Red Hat, Inc. + * + * Cockpit 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. + * + * Cockpit 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 Cockpit; If not, see . + */ + +#include "config.h" + +#include "common/cockpitconf.h" + +#include "cockpitsshoptions.h" + +static const gchar *default_command = "cockpit-bridge"; + +static gboolean +has_environment_val (gchar **env, + const gchar *name) +{ + const gchar *v = g_environ_getenv (env, name); + return v != NULL && v[0] != '\0'; +} + +static const gchar * +get_environment_val (gchar **env, + const gchar *name, + const gchar *defawlt) +{ + if (has_environment_val (env, name)) + return g_environ_getenv (env, name); + else + return defawlt; +} + +static gchar ** +set_environment_val (gchar **env, + const gchar *name, + const gchar *val) +{ + return g_environ_setenv (env, name, val ? val : "", TRUE); +} + +static gboolean +get_environment_bool (gchar **env, + const gchar *name, + gboolean defawlt) +{ + const gchar *value = get_environment_val (env, name, NULL); + + if (!value) + return defawlt; + + return g_strcmp0 (value, "yes") == 0 || + g_strcmp0 (value, "true") == 0 || + g_strcmp0 (value, "1") == 0; +} + +static gchar ** +set_environment_bool (gchar **env, + const gchar *name, + gboolean val) +{ + return g_environ_setenv (env, name, val ? "1" : "", TRUE); +} + +static gboolean +get_connect_to_unknown_hosts (gchar **env) +{ + /* Fallback to deprecated allowUnknown option; use cockpit_conf_string() to + * test for existence as _bool() cannot tell apart "unset" from "set to false". */ + if (!cockpit_conf_string (COCKPIT_CONF_SSH_SECTION, "connectToUnknownHosts") && + cockpit_conf_bool (COCKPIT_CONF_SSH_SECTION, "allowUnknown", FALSE)) + return TRUE; + + if (cockpit_conf_bool (COCKPIT_CONF_SSH_SECTION, "connectToUnknownHosts", FALSE)) + return TRUE; + + if (!has_environment_val (env, "COCKPIT_SSH_CONNECT_TO_UNKNOWN_HOSTS")) + return get_environment_bool (env, "COCKPIT_SSH_ALLOW_UNKNOWN", FALSE); + return get_environment_bool (env, "COCKPIT_SSH_CONNECT_TO_UNKNOWN_HOSTS", FALSE); +} + +CockpitSshOptions * +cockpit_ssh_options_from_env (gchar **env) +{ + + CockpitSshOptions *options = g_new0 (CockpitSshOptions, 1); + options->knownhosts_file = get_environment_val (env, "COCKPIT_SSH_KNOWN_HOSTS_FILE", NULL); + options->command = get_environment_val (env, "COCKPIT_SSH_BRIDGE_COMMAND", default_command); + options->remote_peer = get_environment_val (env, "COCKPIT_REMOTE_PEER", "localhost"); + options->connect_to_unknown_hosts = get_connect_to_unknown_hosts (env); + + return options; +} + +gchar ** +cockpit_ssh_options_to_env (CockpitSshOptions *options, + gchar **env) +{ + env = set_environment_bool (env, "COCKPIT_SSH_CONNECT_TO_UNKNOWN_HOSTS", + options->connect_to_unknown_hosts); + env = set_environment_val (env, "COCKPIT_SSH_KNOWN_HOSTS_FILE", + options->knownhosts_file); + env = set_environment_val (env, "COCKPIT_REMOTE_PEER", + options->remote_peer); + + /* Don't reset these vars unless we have values for them */ + if (options->command) + { + env = set_environment_val (env, "COCKPIT_SSH_BRIDGE_COMMAND", + options->command); + } + + return env; +} diff --git a/pool/shard003/C/0068683_move.c b/pool/shard003/C/0068683_move.c new file mode 100644 index 0000000000000000000000000000000000000000..a4f306179e3dcf0759b42c55a78c64bcd681c372 --- /dev/null +++ b/pool/shard003/C/0068683_move.c @@ -0,0 +1,168 @@ +/* + * Copyright (c) 1999 Apple Computer, Inc. All rights reserved. + * + * @APPLE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this + * file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_LICENSE_HEADER_END@ + */ +/* $OpenBSD: move.c,v 1.2 1996/06/26 05:31:21 deraadt Exp $ */ +/* $NetBSD: move.c,v 1.5 1995/03/26 03:27:57 glass Exp $ */ + +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Hugh Smith at The University of Guelph. + * + * 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 the University of + * California, Berkeley and its contributors. + * 4. 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 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. + */ + +#ifndef lint +#if 0 +static char sccsid[] = "@(#)move.c 8.3 (Berkeley) 4/2/94"; +static char rcsid[] = "$OpenBSD: move.c,v 1.2 1996/06/26 05:31:21 deraadt Exp $"; +#endif +#endif /* not lint */ + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "archive.h" +#include "extern.h" +#include "pathnames.h" + +/* + * move -- + * Change location of named members in archive - if 'b' or 'i' option + * selected then named members are placed before 'posname'. If 'a' + * option selected members go after 'posname'. If no options, members + * are moved to end of archive. + */ +int +move(argv) + char **argv; +{ + CF cf; + off_t size, tsize; + int afd, curfd, mods, tfd1, tfd2, tfd3; + char *file; + + afd = open_archive(O_RDWR); + mods = options & (AR_A|AR_B); + + tfd1 = tmp(); /* Files before key file. */ + tfd2 = tmp(); /* Files selected by user. */ + tfd3 = tmp(); /* Files after key file. */ + + /* + * Break archive into three parts -- selected entries and entries + * before and after the key entry. If positioning before the key, + * place the key at the beginning of the after key entries and if + * positioning after the key, place the key at the end of the before + * key entries. Put it all back together at the end. + */ + + /* Read and write to an archive; pad on both. */ + SETCF(afd, archive, 0, tname, RPAD|WPAD); + for (curfd = tfd1; get_arobj(afd);) { + if (*argv && (file = files(argv))) { + if (options & AR_V) + (void)printf("m - %s\n", file); + cf.wfd = tfd2; + put_arobj(&cf, (struct stat *)NULL); + continue; + } + if (mods && compare(posname)) { + mods = 0; + if (options & AR_B) + curfd = tfd3; + cf.wfd = curfd; + put_arobj(&cf, (struct stat *)NULL); + if (options & AR_A) + curfd = tfd3; + } else { + cf.wfd = curfd; + put_arobj(&cf, (struct stat *)NULL); + } + } + + if (mods) { + warnx("%s: archive member not found", posarg); + close_archive(afd); + return (1); + } + (void)lseek(afd, (off_t)SARMAG, SEEK_SET); + + SETCF(tfd1, tname, afd, archive, NOPAD); + tsize = size = lseek(tfd1, (off_t)0, SEEK_CUR); + (void)lseek(tfd1, (off_t)0, SEEK_SET); + copy_ar(&cf, size); + + tsize += size = lseek(tfd2, (off_t)0, SEEK_CUR); + (void)lseek(tfd2, (off_t)0, SEEK_SET); + cf.rfd = tfd2; + copy_ar(&cf, size); + + tsize += size = lseek(tfd3, (off_t)0, SEEK_CUR); + (void)lseek(tfd3, (off_t)0, SEEK_SET); + cf.rfd = tfd3; + copy_ar(&cf, size); + + (void)ftruncate(afd, tsize + SARMAG); + close_archive(afd); + + if (*argv) { + orphans(argv); + return (1); + } + return (0); +} diff --git a/pool/shard003/C/0068729_main.c b/pool/shard003/C/0068729_main.c new file mode 100644 index 0000000000000000000000000000000000000000..85d5dc98f676d261d809c41e7face2acb27c2c8c --- /dev/null +++ b/pool/shard003/C/0068729_main.c @@ -0,0 +1,151 @@ +/* Full-stack IoT client example. */ + +/* + * Copyright (c) 2018 Linaro Ltd + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include + +LOG_MODULE_REGISTER(net_google_iot_mqtt, LOG_LEVEL_INF); + +#include + +#include "dhcp.h" +#include "protocol.h" + +#include +#include +#include + +/* This comes from newlib. */ +#include +#include + +s64_t time_base; + +void do_sntp(struct addrinfo *addr) +{ + struct sntp_ctx ctx; + int rc; + s64_t stamp; + u64_t epoch_time; + char time_str[sizeof("1970-01-01T00:00:00")]; + + LOG_INF("Sending NTP request for current time:"); + + /* Initialize sntp */ + rc = sntp_init(&ctx, addr->ai_addr, sizeof(struct sockaddr_in)); + if (rc < 0) { + LOG_ERR("Unable to init sntp context: %d", rc); + return; + } + + rc = sntp_request(&ctx, K_FOREVER, &epoch_time); + if (rc == 0) { + stamp = k_uptime_get(); + time_base = epoch_time * MSEC_PER_SEC - stamp; + + /* Convert time to make sure. */ + time_t now = epoch_time; + struct tm now_tm; + + gmtime_r(&now, &now_tm); + strftime(time_str, sizeof(time_str), "%FT%T", &now_tm); + LOG_INF(" Acquired time: %s", log_strdup(time_str)); + + } else { + LOG_ERR(" Failed to acquire SNTP, code %d\n", rc); + } + + sntp_close(&ctx); +} + +/* + * TODO: These need to be configurable. + */ +#define MBEDTLS_NETWORK_TIMEOUT 30000 + +static void show_addrinfo(struct addrinfo *addr) +{ + char hr_addr[NET_IPV6_ADDR_LEN]; + void *a; + +top: + LOG_DBG(" flags : %d", addr->ai_flags); + LOG_DBG(" family : %d", addr->ai_family); + LOG_DBG(" socktype: %d", addr->ai_socktype); + LOG_DBG(" protocol: %d", addr->ai_protocol); + LOG_DBG(" addrlen : %d", addr->ai_addrlen); + + /* Assume two words. */ + LOG_DBG(" addr[0]: 0x%lx", ((uint32_t *)addr->ai_addr)[0]); + LOG_DBG(" addr[1]: 0x%lx", ((uint32_t *)addr->ai_addr)[1]); + + if (addr->ai_next != 0) { + addr = addr->ai_next; + goto top; + } + + a = &net_sin(addr->ai_addr)->sin_addr; + + LOG_INF(" Got %s", + log_strdup(net_addr_ntop(addr->ai_family, a, + hr_addr, sizeof(hr_addr)))); + +} + +/* + * Things that make sense in a demo app that would need to be more + * robust in a real application: + * + * - DHCP happens once. If it fails, or we change networks, the + * network will just stop working. + * + */ +void main(void) +{ + char time_ip[NET_IPV6_ADDR_LEN]; + static struct addrinfo hints; + struct addrinfo *haddr; + int res; + int cnt = 0; + + LOG_INF("Main entered"); + + app_dhcpv4_startup(); + + LOG_INF("Should have DHCPv4 lease at this point."); + + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_DGRAM; + hints.ai_protocol = 0; + while ((res = getaddrinfo("time.google.com", "123", &hints, + &haddr)) && cnt < 3) { + LOG_ERR("Unable to get address for NTP server, retrying"); + cnt++; + } + + if (res != 0) { + LOG_ERR("Unable to get address of NTP server, exiting %d", res); + return; + } + + + LOG_INF("DNS resolved for time.google.com:123"); + time_base = 0; + inet_ntop(AF_INET, &net_sin(haddr->ai_addr)->sin_addr, time_ip, + haddr->ai_addrlen); + show_addrinfo(haddr); + do_sntp(haddr); + freeaddrinfo(haddr); + + /* early return if we failed to acquire time */ + if (time_base == 0) { + LOG_ERR("Failed to get NTP time"); + return; + } + + mqtt_startup("mqtt.googleapis.com", 8883); +} diff --git a/pool/shard003/C/0068744_evgpeinit.c b/pool/shard003/C/0068744_evgpeinit.c new file mode 100644 index 0000000000000000000000000000000000000000..ce9aa9f9a9724e818d5d6e6fe568e35a3bf9d39c --- /dev/null +++ b/pool/shard003/C/0068744_evgpeinit.c @@ -0,0 +1,442 @@ +/****************************************************************************** + * + * Module Name: evgpeinit - System GPE initialization and update + * + *****************************************************************************/ + +/* + * Copyright (C) 2000 - 2011, Intel Corp. + * 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, + * without modification. + * 2. Redistributions in binary form must reproduce at minimum a disclaimer + * substantially similar to the "NO WARRANTY" disclaimer below + * ("Disclaimer") and any redistribution must be conditioned upon + * including a substantially similar Disclaimer requirement for further + * binary redistribution. + * 3. Neither the names of the above-listed copyright holders nor the names + * of any contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * Alternatively, this software may be distributed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + * NO WARRANTY + * 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 MERCHANTIBILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. + */ + +#include +#include "accommon.h" +#include "acevents.h" +#include "acnamesp.h" + +#define _COMPONENT ACPI_EVENTS +ACPI_MODULE_NAME("evgpeinit") + +/* + * Note: History of _PRW support in ACPICA + * + * Originally (2000 - 2010), the GPE initialization code performed a walk of + * the entire namespace to execute the _PRW methods and detect all GPEs + * capable of waking the system. + * + * As of 10/2010, the _PRW method execution has been removed since it is + * actually unnecessary. The host OS must in fact execute all _PRW methods + * in order to identify the device/power-resource dependencies. We now put + * the onus on the host OS to identify the wake GPEs as part of this process + * and to inform ACPICA of these GPEs via the acpi_setup_gpe_for_wake interface. This + * not only reduces the complexity of the ACPICA initialization code, but in + * some cases (on systems with very large namespaces) it should reduce the + * kernel boot time as well. + */ + +/******************************************************************************* + * + * FUNCTION: acpi_ev_gpe_initialize + * + * PARAMETERS: None + * + * RETURN: Status + * + * DESCRIPTION: Initialize the GPE data structures and the FADT GPE 0/1 blocks + * + ******************************************************************************/ +acpi_status acpi_ev_gpe_initialize(void) +{ + u32 register_count0 = 0; + u32 register_count1 = 0; + u32 gpe_number_max = 0; + acpi_status status; + + ACPI_FUNCTION_TRACE(ev_gpe_initialize); + + status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE); + if (ACPI_FAILURE(status)) { + return_ACPI_STATUS(status); + } + + /* + * Initialize the GPE Block(s) defined in the FADT + * + * Why the GPE register block lengths are divided by 2: From the ACPI + * Spec, section "General-Purpose Event Registers", we have: + * + * "Each register block contains two registers of equal length + * GPEx_STS and GPEx_EN (where x is 0 or 1). The length of the + * GPE0_STS and GPE0_EN registers is equal to half the GPE0_LEN + * The length of the GPE1_STS and GPE1_EN registers is equal to + * half the GPE1_LEN. If a generic register block is not supported + * then its respective block pointer and block length values in the + * FADT table contain zeros. The GPE0_LEN and GPE1_LEN do not need + * to be the same size." + */ + + /* + * Determine the maximum GPE number for this machine. + * + * Note: both GPE0 and GPE1 are optional, and either can exist without + * the other. + * + * If EITHER the register length OR the block address are zero, then that + * particular block is not supported. + */ + if (acpi_gbl_FADT.gpe0_block_length && + acpi_gbl_FADT.xgpe0_block.address) { + + /* GPE block 0 exists (has both length and address > 0) */ + + register_count0 = (u16)(acpi_gbl_FADT.gpe0_block_length / 2); + + gpe_number_max = + (register_count0 * ACPI_GPE_REGISTER_WIDTH) - 1; + + /* Install GPE Block 0 */ + + status = acpi_ev_create_gpe_block(acpi_gbl_fadt_gpe_device, + &acpi_gbl_FADT.xgpe0_block, + register_count0, 0, + acpi_gbl_FADT.sci_interrupt, + &acpi_gbl_gpe_fadt_blocks[0]); + + if (ACPI_FAILURE(status)) { + ACPI_EXCEPTION((AE_INFO, status, + "Could not create GPE Block 0")); + } + } + + if (acpi_gbl_FADT.gpe1_block_length && + acpi_gbl_FADT.xgpe1_block.address) { + + /* GPE block 1 exists (has both length and address > 0) */ + + register_count1 = (u16)(acpi_gbl_FADT.gpe1_block_length / 2); + + /* Check for GPE0/GPE1 overlap (if both banks exist) */ + + if ((register_count0) && + (gpe_number_max >= acpi_gbl_FADT.gpe1_base)) { + ACPI_ERROR((AE_INFO, + "GPE0 block (GPE 0 to %u) overlaps the GPE1 block " + "(GPE %u to %u) - Ignoring GPE1", + gpe_number_max, acpi_gbl_FADT.gpe1_base, + acpi_gbl_FADT.gpe1_base + + ((register_count1 * + ACPI_GPE_REGISTER_WIDTH) - 1))); + + /* Ignore GPE1 block by setting the register count to zero */ + + register_count1 = 0; + } else { + /* Install GPE Block 1 */ + + status = + acpi_ev_create_gpe_block(acpi_gbl_fadt_gpe_device, + &acpi_gbl_FADT.xgpe1_block, + register_count1, + acpi_gbl_FADT.gpe1_base, + acpi_gbl_FADT. + sci_interrupt, + &acpi_gbl_gpe_fadt_blocks + [1]); + + if (ACPI_FAILURE(status)) { + ACPI_EXCEPTION((AE_INFO, status, + "Could not create GPE Block 1")); + } + + /* + * GPE0 and GPE1 do not have to be contiguous in the GPE number + * space. However, GPE0 always starts at GPE number zero. + */ + gpe_number_max = acpi_gbl_FADT.gpe1_base + + ((register_count1 * ACPI_GPE_REGISTER_WIDTH) - 1); + } + } + + /* Exit if there are no GPE registers */ + + if ((register_count0 + register_count1) == 0) { + + /* GPEs are not required by ACPI, this is OK */ + + ACPI_DEBUG_PRINT((ACPI_DB_INIT, + "There are no GPE blocks defined in the FADT\n")); + status = AE_OK; + goto cleanup; + } + + /* Check for Max GPE number out-of-range */ + + if (gpe_number_max > ACPI_GPE_MAX) { + ACPI_ERROR((AE_INFO, + "Maximum GPE number from FADT is too large: 0x%X", + gpe_number_max)); + status = AE_BAD_VALUE; + goto cleanup; + } + + cleanup: + (void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE); + return_ACPI_STATUS(AE_OK); +} + +/******************************************************************************* + * + * FUNCTION: acpi_ev_update_gpes + * + * PARAMETERS: table_owner_id - ID of the newly-loaded ACPI table + * + * RETURN: None + * + * DESCRIPTION: Check for new GPE methods (_Lxx/_Exx) made available as a + * result of a Load() or load_table() operation. If new GPE + * methods have been installed, register the new methods. + * + ******************************************************************************/ + +void acpi_ev_update_gpes(acpi_owner_id table_owner_id) +{ + struct acpi_gpe_xrupt_info *gpe_xrupt_info; + struct acpi_gpe_block_info *gpe_block; + struct acpi_gpe_walk_info walk_info; + acpi_status status = AE_OK; + + /* + * Find any _Lxx/_Exx GPE methods that have just been loaded. + * + * Any GPEs that correspond to new _Lxx/_Exx methods are immediately + * enabled. + * + * Examine the namespace underneath each gpe_device within the + * gpe_block lists. + */ + status = acpi_ut_acquire_mutex(ACPI_MTX_EVENTS); + if (ACPI_FAILURE(status)) { + return; + } + + walk_info.count = 0; + walk_info.owner_id = table_owner_id; + walk_info.execute_by_owner_id = TRUE; + + /* Walk the interrupt level descriptor list */ + + gpe_xrupt_info = acpi_gbl_gpe_xrupt_list_head; + while (gpe_xrupt_info) { + + /* Walk all Gpe Blocks attached to this interrupt level */ + + gpe_block = gpe_xrupt_info->gpe_block_list_head; + while (gpe_block) { + walk_info.gpe_block = gpe_block; + walk_info.gpe_device = gpe_block->node; + + status = acpi_ns_walk_namespace(ACPI_TYPE_METHOD, + walk_info.gpe_device, + ACPI_UINT32_MAX, + ACPI_NS_WALK_NO_UNLOCK, + acpi_ev_match_gpe_method, + NULL, &walk_info, NULL); + if (ACPI_FAILURE(status)) { + ACPI_EXCEPTION((AE_INFO, status, + "While decoding _Lxx/_Exx methods")); + } + + gpe_block = gpe_block->next; + } + + gpe_xrupt_info = gpe_xrupt_info->next; + } + + if (walk_info.count) { + ACPI_INFO((AE_INFO, "Enabled %u new GPEs", walk_info.count)); + } + + (void)acpi_ut_release_mutex(ACPI_MTX_EVENTS); + return; +} + +/******************************************************************************* + * + * FUNCTION: acpi_ev_match_gpe_method + * + * PARAMETERS: Callback from walk_namespace + * + * RETURN: Status + * + * DESCRIPTION: Called from acpi_walk_namespace. Expects each object to be a + * control method under the _GPE portion of the namespace. + * Extract the name and GPE type from the object, saving this + * information for quick lookup during GPE dispatch. Allows a + * per-owner_id evaluation if execute_by_owner_id is TRUE in the + * walk_info parameter block. + * + * The name of each GPE control method is of the form: + * "_Lxx" or "_Exx", where: + * L - means that the GPE is level triggered + * E - means that the GPE is edge triggered + * xx - is the GPE number [in HEX] + * + * If walk_info->execute_by_owner_id is TRUE, we only execute examine GPE methods + * with that owner. + * + ******************************************************************************/ + +acpi_status +acpi_ev_match_gpe_method(acpi_handle obj_handle, + u32 level, void *context, void **return_value) +{ + struct acpi_namespace_node *method_node = + ACPI_CAST_PTR(struct acpi_namespace_node, obj_handle); + struct acpi_gpe_walk_info *walk_info = + ACPI_CAST_PTR(struct acpi_gpe_walk_info, context); + struct acpi_gpe_event_info *gpe_event_info; + u32 gpe_number; + char name[ACPI_NAME_SIZE + 1]; + u8 type; + + ACPI_FUNCTION_TRACE(ev_match_gpe_method); + + /* Check if requested owner_id matches this owner_id */ + + if ((walk_info->execute_by_owner_id) && + (method_node->owner_id != walk_info->owner_id)) { + return_ACPI_STATUS(AE_OK); + } + + /* + * Match and decode the _Lxx and _Exx GPE method names + * + * 1) Extract the method name and null terminate it + */ + ACPI_MOVE_32_TO_32(name, &method_node->name.integer); + name[ACPI_NAME_SIZE] = 0; + + /* 2) Name must begin with an underscore */ + + if (name[0] != '_') { + return_ACPI_STATUS(AE_OK); /* Ignore this method */ + } + + /* + * 3) Edge/Level determination is based on the 2nd character + * of the method name + */ + switch (name[1]) { + case 'L': + type = ACPI_GPE_LEVEL_TRIGGERED; + break; + + case 'E': + type = ACPI_GPE_EDGE_TRIGGERED; + break; + + default: + /* Unknown method type, just ignore it */ + + ACPI_DEBUG_PRINT((ACPI_DB_LOAD, + "Ignoring unknown GPE method type: %s " + "(name not of form _Lxx or _Exx)", name)); + return_ACPI_STATUS(AE_OK); + } + + /* 4) The last two characters of the name are the hex GPE Number */ + + gpe_number = ACPI_STRTOUL(&name[2], NULL, 16); + if (gpe_number == ACPI_UINT32_MAX) { + + /* Conversion failed; invalid method, just ignore it */ + + ACPI_DEBUG_PRINT((ACPI_DB_LOAD, + "Could not extract GPE number from name: %s " + "(name is not of form _Lxx or _Exx)", name)); + return_ACPI_STATUS(AE_OK); + } + + /* Ensure that we have a valid GPE number for this GPE block */ + + gpe_event_info = + acpi_ev_low_get_gpe_info(gpe_number, walk_info->gpe_block); + if (!gpe_event_info) { + /* + * This gpe_number is not valid for this GPE block, just ignore it. + * However, it may be valid for a different GPE block, since GPE0 + * and GPE1 methods both appear under \_GPE. + */ + return_ACPI_STATUS(AE_OK); + } + + if ((gpe_event_info->flags & ACPI_GPE_DISPATCH_MASK) == + ACPI_GPE_DISPATCH_HANDLER) { + + /* If there is already a handler, ignore this GPE method */ + + return_ACPI_STATUS(AE_OK); + } + + if ((gpe_event_info->flags & ACPI_GPE_DISPATCH_MASK) == + ACPI_GPE_DISPATCH_METHOD) { + /* + * If there is already a method, ignore this method. But check + * for a type mismatch (if both the _Lxx AND _Exx exist) + */ + if (type != (gpe_event_info->flags & ACPI_GPE_XRUPT_TYPE_MASK)) { + ACPI_ERROR((AE_INFO, + "For GPE 0x%.2X, found both _L%2.2X and _E%2.2X methods", + gpe_number, gpe_number, gpe_number)); + } + return_ACPI_STATUS(AE_OK); + } + + /* Disable the GPE in case it's been enabled already. */ + (void)acpi_hw_low_set_gpe(gpe_event_info, ACPI_GPE_DISABLE); + + /* + * Add the GPE information from above to the gpe_event_info block for + * use during dispatch of this GPE. + */ + gpe_event_info->flags &= ~(ACPI_GPE_DISPATCH_MASK); + gpe_event_info->flags |= (u8)(type | ACPI_GPE_DISPATCH_METHOD); + gpe_event_info->dispatch.method_node = method_node; + + ACPI_DEBUG_PRINT((ACPI_DB_LOAD, + "Registered GPE method %s as GPE number 0x%.2X\n", + name, gpe_number)); + return_ACPI_STATUS(AE_OK); +} diff --git a/pool/shard003/C/0068757_test_phash.c b/pool/shard003/C/0068757_test_phash.c new file mode 100644 index 0000000000000000000000000000000000000000..47711c28dbc4ee21ba8cd85e4e686bbe4dd680c8 --- /dev/null +++ b/pool/shard003/C/0068757_test_phash.c @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2015 Cisco and/or 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. + */ +/* + Copyright (c) 2005 Eliot Dresselhaus + + 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 + +static int verbose; +#define if_verbose(format,args...) \ + if (verbose) { clib_warning(format, ## args); } + +int +test_phash_main (unformat_input_t * input) +{ + phash_main_t _pm = { 0 }, *pm = &_pm; + int n_keys, random_keys; + u32 seed; + clib_error_t *error; + + random_keys = 1; + n_keys = 1000; + while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) + { + if (0 == unformat (input, "keys %d", &n_keys) + && 0 == unformat (input, "verbose %=", &verbose, 1) + && 0 == unformat (input, "random-keys %=", &random_keys, 1) + && 0 == unformat (input, "sequential-keys %=", &random_keys, 0) + && 0 == unformat (input, "seed %d", &pm->random_seed) + && 0 == unformat (input, "64-bit %|", &pm->flags, PHASH_FLAG_MIX64) + && 0 == unformat (input, "32-bit %|", &pm->flags, PHASH_FLAG_MIX32) + && 0 == unformat (input, "fast %|", &pm->flags, + PHASH_FLAG_FAST_MODE) + && 0 == unformat (input, "slow %|", &pm->flags, + PHASH_FLAG_SLOW_MODE) + && 0 == unformat (input, "minimal %|", &pm->flags, + PHASH_FLAG_MINIMAL) + && 0 == unformat (input, "non-minimal %|", &pm->flags, + PHASH_FLAG_NON_MINIMAL)) + clib_error ("unknown input `%U'", format_unformat_error, input); + } + + if (!pm->random_seed) + pm->random_seed = random_default_seed (); + + if_verbose + ("%d %d-bit keys, random seed %d, %s mode, looking for %sminimal hash", + n_keys, (pm->flags & PHASH_FLAG_MIX64) ? 64 : 32, pm->random_seed, + (pm->flags & PHASH_FLAG_FAST_MODE) ? "fast" : "slow", + (pm->flags & PHASH_FLAG_MINIMAL) ? "" : "non-"); + + seed = pm->random_seed; + + /* Initialize random keys. */ + { + phash_key_t *k; + + vec_resize (pm->keys, n_keys); + vec_foreach (k, pm->keys) + { + k->key = k - pm->keys; + if (random_keys) + { + if (pm->flags & PHASH_FLAG_MIX64) + k->key = random_u64 (&seed); + else + k->key = random_u32 (&seed); + } + } + } + + error = phash_find_perfect_hash (pm); + if (error) + { + clib_error_report (error); + return 1; + } + else + { + if_verbose ("(%d,%d) (a,b) bits, %d seeds tried, %d tree walks", + pm->a_bits, pm->b_bits, + pm->n_seed_trials, pm->n_perfect_calls); + + error = phash_validate (pm); + if (error) + { + clib_error_report (error); + return 1; + } + } + + return 0; +} + +#ifdef CLIB_UNIX +int +main (int argc, char *argv[]) +{ + unformat_input_t i; + int res; + + clib_mem_init (0, 64ULL << 20); + + verbose = (argc > 1); + unformat_init_command_line (&i, argv); + res = test_phash_main (&i); + unformat_free (&i); + return res; +} +#endif + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/pool/shard003/C/0068793_CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnvp_06.c b/pool/shard003/C/0068793_CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnvp_06.c new file mode 100644 index 0000000000000000000000000000000000000000..236b4f57a8f3823fadd7d25fd100e9893aee96d8 --- /dev/null +++ b/pool/shard003/C/0068793_CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnvp_06.c @@ -0,0 +1,242 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnvp_06.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-06.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Fixed string + * Sink: w32_spawnvp + * BadSink : execute command with wspawnvp + * Flow Variant: 06 Control flow: if(STATIC_CONST_FIVE==5) and if(STATIC_CONST_FIVE!=5) + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"ls" +#define COMMAND_ARG2 L"-la" +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define LISTEN_BACKLOG 5 + +#include + +/* The variable below is declared "const", so a tool should be able + * to identify that reads of this will always give its initialized value. */ +static const int STATIC_CONST_FIVE = 5; + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnvp_06_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(STATIC_CONST_FIVE==5) + { + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + wchar_t *replace; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + size_t dataLen = wcslen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a listen socket */ + listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listenSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = INADDR_ANY; + service.sin_port = htons(TCP_PORT); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed */ + recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; + /* Eliminate CRLF */ + replace = wcschr(data, L'\r'); + if (replace) + { + *replace = L'\0'; + } + replace = wcschr(data, L'\n'); + if (replace) + { + *replace = L'\0'; + } + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wspawnvp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _wspawnvp(_P_WAIT, COMMAND_INT, args); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the STATIC_CONST_FIVE==5 to STATIC_CONST_FIVE!=5 */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(STATIC_CONST_FIVE!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wspawnvp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _wspawnvp(_P_WAIT, COMMAND_INT, args); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(STATIC_CONST_FIVE==5) + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wspawnvp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _wspawnvp(_P_WAIT, COMMAND_INT, args); + } +} + +void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnvp_06_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnvp_06_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnvp_06_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard003/C/0068796_string.c b/pool/shard003/C/0068796_string.c new file mode 100644 index 0000000000000000000000000000000000000000..17d1836d2ab595a431072bb54e1b44a6606750a9 --- /dev/null +++ b/pool/shard003/C/0068796_string.c @@ -0,0 +1,88 @@ +#include +#include +#include + +#include "string.struct.h" +#include "inttype.h" +#include "object_type.h" + +#define CHARS self->chars + +O_DEF_CLASS(String, Object) + +override +def(ctor, void : va_list * @args_ptr) { + CHARS = va_arg(* args_ptr, char *); +} + +override +def(dtor, void) { + free(self); +} + +override +def(equals, bool : o @_obj) { + struct String * obj = _obj; + return (((struct Object *) obj)->class == String && + strcmp(CHARS, obj->chars) == 0); +} + +override +def(hash_code, uint_t) { + uint_t len = strlen(CHARS); + uint_t hval = len; + for(uint_t i = 0; i < len; i++) { + hval <<= 4; + hval += CHARS[i]; + } + return hval; +} + +override +def(inspect, char *) { + return CHARS; +} + +def(set, void : char * @chars) { + CHARS = chars; +} + +def(index, uint_t : bool (* @func)(o _self_, char c) . o @_self_) { + uint_t len = strlen(CHARS); + for(uint_t i = 0; i < len; i++) { + if(func(_self_, CHARS[i])) { + return i; + } + } + return -1; +} + +def(rindex, uint_t : bool (* @func)(o _self_, char c) . o @_self_) { + uint_t i = strlen(CHARS); + while(i > 0) { + i -= 1; + if(func(_self_, CHARS[i])) { + return i; + } + } + return -1; +} + +def(strip, void) { + + bool not_whitespace_p(o unused, char c) { + return !(c == ' ' || c == '\t' || + c == 0x0A || c == 0x0D); + } + + char * chars = CHARS; + uint_t start = String_index(self, not_whitespace_p, NULL); + if(start == -1) start = 0; + uint_t end = String_rindex(self, not_whitespace_p, NULL); + if(end == -1) end = strlen(chars) - 1; + uint_t len = end - start + 1; + if(start > 0) { + memmove(chars, chars + start, len); + } + chars[len] = '\0'; +} diff --git a/pool/shard003/C/0068798_thread_pthread.c b/pool/shard003/C/0068798_thread_pthread.c new file mode 100644 index 0000000000000000000000000000000000000000..1ea91ea277eb79675674944dd5df5e2f4a075d4b --- /dev/null +++ b/pool/shard003/C/0068798_thread_pthread.c @@ -0,0 +1,165 @@ +#include +/* Copyright (c) 2015, Google Inc. + * + * 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 "internal.h" + +#if !defined(OPENSSL_WINDOWS) && !defined(OPENSSL_NO_THREADS) + +#include +#include +#include + +#include +#include + + +OPENSSL_COMPILE_ASSERT(sizeof(CRYPTO_MUTEX) >= sizeof(pthread_rwlock_t), + CRYPTO_MUTEX_too_small); + +void CRYPTO_MUTEX_init(CRYPTO_MUTEX *lock) { + if (pthread_rwlock_init((pthread_rwlock_t *) lock, NULL) != 0) { + abort(); + } +} + +void CRYPTO_MUTEX_lock_read(CRYPTO_MUTEX *lock) { + if (pthread_rwlock_rdlock((pthread_rwlock_t *) lock) != 0) { + abort(); + } +} + +void CRYPTO_MUTEX_lock_write(CRYPTO_MUTEX *lock) { + if (pthread_rwlock_wrlock((pthread_rwlock_t *) lock) != 0) { + abort(); + } +} + +void CRYPTO_MUTEX_unlock(CRYPTO_MUTEX *lock) { + if (pthread_rwlock_unlock((pthread_rwlock_t *) lock) != 0) { + abort(); + } +} + +void CRYPTO_MUTEX_cleanup(CRYPTO_MUTEX *lock) { + pthread_rwlock_destroy((pthread_rwlock_t *) lock); +} + +void CRYPTO_STATIC_MUTEX_lock_read(struct CRYPTO_STATIC_MUTEX *lock) { + if (pthread_rwlock_rdlock(&lock->lock) != 0) { + abort(); + } +} + +void CRYPTO_STATIC_MUTEX_lock_write(struct CRYPTO_STATIC_MUTEX *lock) { + if (pthread_rwlock_wrlock(&lock->lock) != 0) { + abort(); + } +} + +void CRYPTO_STATIC_MUTEX_unlock(struct CRYPTO_STATIC_MUTEX *lock) { + if (pthread_rwlock_unlock(&lock->lock) != 0) { + abort(); + } +} + +void CRYPTO_once(CRYPTO_once_t *once, void (*init)(void)) { + if (pthread_once(once, init) != 0) { + abort(); + } +} + +static pthread_mutex_t g_destructors_lock = PTHREAD_MUTEX_INITIALIZER; +static thread_local_destructor_t g_destructors[NUM_OPENSSL_THREAD_LOCALS]; + +static void thread_local_destructor(void *arg) { + if (arg == NULL) { + return; + } + + thread_local_destructor_t destructors[NUM_OPENSSL_THREAD_LOCALS]; + if (pthread_mutex_lock(&g_destructors_lock) != 0) { + return; + } + memcpy(destructors, g_destructors, sizeof(destructors)); + pthread_mutex_unlock(&g_destructors_lock); + + unsigned i; + void **pointers = arg; + for (i = 0; i < NUM_OPENSSL_THREAD_LOCALS; i++) { + if (destructors[i] != NULL) { + destructors[i](pointers[i]); + } + } + + OPENSSL_free(pointers); +} + +static pthread_once_t g_thread_local_init_once = PTHREAD_ONCE_INIT; +static pthread_key_t g_thread_local_key; +static int g_thread_local_failed = 0; + +static void thread_local_init(void) { + g_thread_local_failed = + pthread_key_create(&g_thread_local_key, thread_local_destructor) != 0; +} + +void *CRYPTO_get_thread_local(thread_local_data_t index) { + CRYPTO_once(&g_thread_local_init_once, thread_local_init); + if (g_thread_local_failed) { + return NULL; + } + + void **pointers = pthread_getspecific(g_thread_local_key); + if (pointers == NULL) { + return NULL; + } + return pointers[index]; +} + +int CRYPTO_set_thread_local(thread_local_data_t index, void *value, + thread_local_destructor_t destructor) { + CRYPTO_once(&g_thread_local_init_once, thread_local_init); + if (g_thread_local_failed) { + destructor(value); + return 0; + } + + void **pointers = pthread_getspecific(g_thread_local_key); + if (pointers == NULL) { + pointers = OPENSSL_malloc(sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS); + if (pointers == NULL) { + destructor(value); + return 0; + } + memset(pointers, 0, sizeof(void *) * NUM_OPENSSL_THREAD_LOCALS); + if (pthread_setspecific(g_thread_local_key, pointers) != 0) { + OPENSSL_free(pointers); + destructor(value); + return 0; + } + } + + if (pthread_mutex_lock(&g_destructors_lock) != 0) { + destructor(value); + return 0; + } + g_destructors[index] = destructor; + pthread_mutex_unlock(&g_destructors_lock); + + pointers[index] = value; + return 1; +} + +#endif /* !OPENSSL_WINDOWS && !OPENSSL_NO_THREADS */ diff --git a/pool/shard003/C/0068803_main-ex11.c b/pool/shard003/C/0068803_main-ex11.c new file mode 100644 index 0000000000000000000000000000000000000000..7f17ed8c8421a93702a315a102b4892390869fde --- /dev/null +++ b/pool/shard003/C/0068803_main-ex11.c @@ -0,0 +1,205 @@ +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" +#include +#include +#include + +/* Private variables ---------------------------------------------------------*/ +TIM_HandleTypeDef htim3, htim1; +UART_HandleTypeDef huart2; + +void MX_TIM3_Init(void); +void MX_TIM1_Init(void); + +char msg[40]; +uint8_t dir = 0; +uint16_t cnt1 = 0, cnt2 = 0; +uint32_t tick = 0; +uint16_t diff = 0; +uint16_t tim1_ch1_pulse, tim1_ch2_pulse; +uint16_t speed = 0; + +#define PULSES_PER_REVOLUTION 4 + +int main(void) { + HAL_Init(); + + Nucleo_BSP_Init(); + MX_TIM1_Init(); + MX_TIM3_Init(); + + HAL_TIM_Encoder_Start(&htim3, TIM_CHANNEL_ALL); + HAL_TIM_OC_Start(&htim1, TIM_CHANNEL_1); + HAL_TIM_OC_Start(&htim1, TIM_CHANNEL_2); + + cnt1 = __HAL_TIM_GET_COUNTER(&htim3); + tick = HAL_GetTick(); + + while (1) { + if (HAL_GetTick() - tick > 1000L) { + cnt2 = __HAL_TIM_GET_COUNTER(&htim3); + if (__HAL_TIM_IS_TIM_COUNTING_DOWN(&htim3)) { + if (cnt2 < cnt1) /* Check for counter underflow */ + diff = cnt1 - cnt2; + else + diff = (65535 - cnt2) + cnt1; + } else { + if (cnt2 > cnt1) /* Check for counter overflow */ + diff = cnt2 - cnt1; + else + diff = (65535 - cnt1) + cnt2; + } + + sprintf(msg, "Difference: %d\r\n", diff); + HAL_UART_Transmit(&huart2, (uint8_t*) msg, strlen(msg), HAL_MAX_DELAY); + + speed = ((diff / PULSES_PER_REVOLUTION) / 60); + + /* If the first three bits of SMCR register are set to 0x3 + * then the timer is set in X4 mode (TIM_ENCODERMODE_TI12) + * and we need to divide the pulses counter by two, because + * they include the pulses for both the channels */ + if ((TIM3->SMCR & 0x3) == 0x3) + speed /= 2; + + sprintf(msg, "Speed: %d RPM\r\n", speed); + HAL_UART_Transmit(&huart2, (uint8_t*) msg, strlen(msg), HAL_MAX_DELAY); + + dir = __HAL_TIM_IS_TIM_COUNTING_DOWN(&htim3); + sprintf(msg, "Direction: %d\r\n", dir); + HAL_UART_Transmit(&huart2, (uint8_t*) msg, strlen(msg), HAL_MAX_DELAY); + + tick = HAL_GetTick(); + cnt1 = __HAL_TIM_GET_COUNTER(&htim3); + } + + if (HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13) == GPIO_PIN_RESET) { + /* Invert rotation by swapping CH1 and CH2 CCR value */ + tim1_ch1_pulse = __HAL_TIM_GET_COMPARE(&htim1, TIM_CHANNEL_1); + tim1_ch2_pulse = __HAL_TIM_GET_COMPARE(&htim1, TIM_CHANNEL_2); + + __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, tim1_ch2_pulse); + __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_2, tim1_ch1_pulse); + } + } +} + +/* TIM1 init function */ +void MX_TIM1_Init(void) { + TIM_OC_InitTypeDef sConfigOC; + + htim1.Instance = TIM1; + htim1.Init.Prescaler = 9; + htim1.Init.CounterMode = TIM_COUNTERMODE_UP; + htim1.Init.Period = 999; + HAL_TIM_Base_Init(&htim1); + + sConfigOC.OCMode = TIM_OCMODE_TOGGLE; + sConfigOC.Pulse = 499; + sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; + sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET; + sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH; + sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET; + HAL_TIM_OC_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_1); + + sConfigOC.Pulse = 999; /* Phase B is shifted by 90° */ + HAL_TIM_OC_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_2); +} + +/* TIM3 init function */ +void MX_TIM3_Init(void) { + TIM_Encoder_InitTypeDef sEncoderConfig; + + htim3.Instance = TIM3; + htim3.Init.Prescaler = 0; + htim3.Init.CounterMode = TIM_COUNTERMODE_UP; + htim3.Init.Period = 65535; + + sEncoderConfig.EncoderMode = TIM_ENCODERMODE_TI12; + + sEncoderConfig.IC1Polarity = TIM_ICPOLARITY_RISING; + sEncoderConfig.IC1Selection = TIM_ICSELECTION_DIRECTTI; + sEncoderConfig.IC1Prescaler = TIM_ICPSC_DIV1; + sEncoderConfig.IC1Filter = 0; + + sEncoderConfig.IC2Polarity = TIM_ICPOLARITY_RISING; + sEncoderConfig.IC2Selection = TIM_ICSELECTION_DIRECTTI; + sEncoderConfig.IC2Prescaler = TIM_ICPSC_DIV1; + sEncoderConfig.IC2Filter = 0; + + HAL_TIM_Encoder_Init(&htim3, &sEncoderConfig); +} + +void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef* htim_base) { + GPIO_InitTypeDef GPIO_InitStruct; + if (htim_base->Instance == TIM3) { + __TIM3_CLK_ENABLE(); + + /**TIM3 GPIO Configuration + PA6 ------> TIM3_CH1 + PA7 ------> TIM3_CH2 + */ + GPIO_InitStruct.Pin = GPIO_PIN_6 | GPIO_PIN_7; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF1_TIM3; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + } +} + +void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base) { + GPIO_InitTypeDef GPIO_InitStruct; + if (htim_base->Instance == TIM1) { + /* USER CODE BEGIN TIM1_MspInit 0 */ + + /* USER CODE END TIM1_MspInit 0 */ + /* Peripheral clock enable */ + __TIM1_CLK_ENABLE(); + + /**TIM1 GPIO Configuration + PA8 ------> TIM1_CH1 + PA9 ------> TIM1_CH2 + */ + GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_LOW; + GPIO_InitStruct.Alternate = GPIO_AF2_TIM1; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + /* USER CODE BEGIN TIM1_MspInit 1 */ + + /* USER CODE END TIM1_MspInit 1 */ + } +} + +#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 CODE BEGIN 6 */ + /* 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) */ + /* USER CODE END 6 */ + +} + +#endif + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard003/C/0068804_run_tcp_connect.c b/pool/shard003/C/0068804_run_tcp_connect.c new file mode 100644 index 0000000000000000000000000000000000000000..bf8d9b82f1257daa523d2135d02176aa2e405fe5 --- /dev/null +++ b/pool/shard003/C/0068804_run_tcp_connect.c @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2003-2011 The Music Player Daemon Project + * http://www.musicpd.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. + */ + +#include "config.h" +#include "resolver.h" +#include "io_thread.h" +#include "tcp_connect.h" +#include "fd_util.h" + +#include +#include + +#ifdef WIN32 +#include +#include +#else +#include +#include +#endif + +static struct tcp_connect *handle; +static GMutex *mutex; +static GCond *cond; +static bool done, success; + +static void +my_tcp_connect_success(int fd, G_GNUC_UNUSED void *ctx) +{ + assert(!done); + assert(!success); + + close_socket(fd); + g_print("success\n"); + + g_mutex_lock(mutex); + done = success = true; + g_cond_signal(cond); + g_mutex_unlock(mutex); +} + +static void +my_tcp_connect_error(GError *error, G_GNUC_UNUSED void *ctx) +{ + assert(!done); + assert(!success); + + g_printerr("error: %s\n", error->message); + g_error_free(error); + + g_mutex_lock(mutex); + done = true; + g_cond_signal(cond); + g_mutex_unlock(mutex); +} + +static void +my_tcp_connect_timeout(G_GNUC_UNUSED void *ctx) +{ + assert(!done); + assert(!success); + + g_printerr("timeout\n"); + + g_mutex_lock(mutex); + done = true; + g_cond_signal(cond); + g_mutex_unlock(mutex); +} + +static void +my_tcp_connect_canceled(G_GNUC_UNUSED void *ctx) +{ + assert(!done); + assert(!success); + + g_printerr("canceled\n"); + + g_mutex_lock(mutex); + done = true; + g_cond_signal(cond); + g_mutex_unlock(mutex); +} + +static const struct tcp_connect_handler my_tcp_connect_handler = { + .success = my_tcp_connect_success, + .error = my_tcp_connect_error, + .timeout = my_tcp_connect_timeout, + .canceled = my_tcp_connect_canceled, +}; + +int main(int argc, char **argv) +{ + if (argc != 2) { + g_printerr("Usage: run_tcp_connect IP:PORT\n"); + return 1; + } + + GError *error = NULL; + struct addrinfo *ai = resolve_host_port(argv[1], 80, 0, SOCK_STREAM, + &error); + if (ai == NULL) { + g_printerr("%s\n", error->message); + g_error_free(error); + return EXIT_FAILURE; + } + + /* initialize GLib */ + + g_thread_init(NULL); + + /* initialize MPD */ + + io_thread_init(); + if (!io_thread_start(&error)) { + freeaddrinfo(ai); + g_printerr("%s", error->message); + g_error_free(error); + return EXIT_FAILURE; + } + + /* open the connection */ + + mutex = g_mutex_new(); + cond = g_cond_new(); + + tcp_connect_address(ai->ai_addr, ai->ai_addrlen, 5000, + &my_tcp_connect_handler, NULL, + &handle); + freeaddrinfo(ai); + + if (handle != NULL) { + g_mutex_lock(mutex); + while (!done) + g_cond_wait(cond, mutex); + g_mutex_unlock(mutex); + + tcp_connect_free(handle); + } + + g_cond_free(cond); + g_mutex_free(mutex); + + /* deinitialize everything */ + + io_thread_deinit(); + + return EXIT_SUCCESS; +} diff --git a/pool/shard003/C/0068818_ctan.c b/pool/shard003/C/0068818_ctan.c new file mode 100644 index 0000000000000000000000000000000000000000..9286e24a957a20618c47b823457ed26fff6b0e35 --- /dev/null +++ b/pool/shard003/C/0068818_ctan.c @@ -0,0 +1,59 @@ +/* $NetBSD: ctan.c,v 1.2 2011/07/03 06:45:24 mrg Exp $ */ + +/*- + * Copyright (c) 2007 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software written by Stephen L. Moshier. + * It is redistributed by the NetBSD Foundation by permission of the author. + * + * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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 "../src/namespace.h" +#include +#include +#include +#include "cephes_subr.h" + +#define MAXNUM DBL_MAX + +double complex +ctan(double complex z) +{ + double complex w; + double d; + + d = cos(2.0 * creal(z)) + cosh(2.0 * cimag(z)); + + if (fabs(d) < 0.25) + d = _ctans(z); + + if (d == 0.0) { + /* mtherr ("ctan", OVERFLOW); */ + w = MAXNUM + MAXNUM * I; + return w; + } + + w = sin(2.0 * creal(z)) / d + (sinh(2.0 * cimag(z)) / d) * I; + return w; +} diff --git a/pool/shard003/C/0068838_t5403.c b/pool/shard003/C/0068838_t5403.c new file mode 100644 index 0000000000000000000000000000000000000000..e11cd3938d673ac77be07c7467375a438ec6f003 --- /dev/null +++ b/pool/shard003/C/0068838_t5403.c @@ -0,0 +1,275 @@ +/* + * t5403.c - Support for EPCOS T5403 pressure/temperature sensor + * + * Copyright (c) 2014 Peter Meerwald + * + * This file is subject to the terms and conditions of version 2 of + * the GNU General Public License. See the file COPYING in the main + * directory of this archive for more details. + * + * (7-bit I2C slave address 0x77) + * + * TODO: end-of-conversion irq + */ + +#include +#include +#include +#include +#include + +#define T5403_DATA 0xf5 /* data, LSB first, 16 bit */ +#define T5403_CALIB_DATA 0x8e /* 10 calibration coeff., LSB first, 16 bit */ +#define T5403_SLAVE_ADDR 0x88 /* I2C slave address, 0x77 */ +#define T5403_COMMAND 0xf1 + +/* command bits */ +#define T5403_MODE_SHIFT 3 /* conversion time: 2, 8, 16, 66 ms */ +#define T5403_PT BIT(1) /* 0 .. pressure, 1 .. temperature measurement */ +#define T5403_SCO BIT(0) /* start conversion */ + +#define T5403_MODE_LOW 0 +#define T5403_MODE_STANDARD 1 +#define T5403_MODE_HIGH 2 +#define T5403_MODE_ULTRA_HIGH 3 + +#define T5403_I2C_MASK (~BIT(7)) +#define T5403_I2C_ADDR 0x77 + +static const int t5403_pressure_conv_ms[] = {2, 8, 16, 66}; + +struct t5403_data { + struct i2c_client *client; + struct mutex lock; + int mode; + __le16 c[10]; +}; + +#define T5403_C_U16(i) le16_to_cpu(data->c[(i) - 1]) +#define T5403_C(i) sign_extend32(T5403_C_U16(i), 15) + +static int t5403_read(struct t5403_data *data, bool pressure) +{ + int wait_time = 3; /* wakeup time in ms */ + + int ret = i2c_smbus_write_byte_data(data->client, T5403_COMMAND, + (pressure ? (data->mode << T5403_MODE_SHIFT) : T5403_PT) | + T5403_SCO); + if (ret < 0) + return ret; + + wait_time += pressure ? t5403_pressure_conv_ms[data->mode] : 2; + + msleep(wait_time); + + return i2c_smbus_read_word_data(data->client, T5403_DATA); +} + +static int t5403_comp_pressure(struct t5403_data *data, int *val, int *val2) +{ + int ret; + s16 t_r; + u16 p_r; + s32 S, O, X; + + mutex_lock(&data->lock); + + ret = t5403_read(data, false); + if (ret < 0) + goto done; + t_r = ret; + + ret = t5403_read(data, true); + if (ret < 0) + goto done; + p_r = ret; + + /* see EPCOS application note */ + S = T5403_C_U16(3) + (s32) T5403_C_U16(4) * t_r / 0x20000 + + T5403_C(5) * t_r / 0x8000 * t_r / 0x80000 + + T5403_C(9) * t_r / 0x8000 * t_r / 0x8000 * t_r / 0x10000; + + O = T5403_C(6) * 0x4000 + T5403_C(7) * t_r / 8 + + T5403_C(8) * t_r / 0x8000 * t_r / 16 + + T5403_C(9) * t_r / 0x8000 * t_r / 0x10000 * t_r; + + X = (S * p_r + O) / 0x4000; + + X += ((X - 75000) * (X - 75000) / 0x10000 - 9537) * + T5403_C(10) / 0x10000; + + *val = X / 1000; + *val2 = (X % 1000) * 1000; + +done: + mutex_unlock(&data->lock); + return ret; +} + +static int t5403_comp_temp(struct t5403_data *data, int *val) +{ + int ret; + s16 t_r; + + mutex_lock(&data->lock); + ret = t5403_read(data, false); + if (ret < 0) + goto done; + t_r = ret; + + /* see EPCOS application note */ + *val = ((s32) T5403_C_U16(1) * t_r / 0x100 + + (s32) T5403_C_U16(2) * 0x40) * 1000 / 0x10000; + +done: + mutex_unlock(&data->lock); + return ret; +} + +static int t5403_read_raw(struct iio_dev *indio_dev, + struct iio_chan_spec const *chan, + int *val, int *val2, long mask) +{ + struct t5403_data *data = iio_priv(indio_dev); + int ret; + + switch (mask) { + case IIO_CHAN_INFO_PROCESSED: + switch (chan->type) { + case IIO_PRESSURE: + ret = t5403_comp_pressure(data, val, val2); + if (ret < 0) + return ret; + return IIO_VAL_INT_PLUS_MICRO; + case IIO_TEMP: + ret = t5403_comp_temp(data, val); + if (ret < 0) + return ret; + return IIO_VAL_INT; + default: + return -EINVAL; + } + case IIO_CHAN_INFO_INT_TIME: + *val = 0; + *val2 = t5403_pressure_conv_ms[data->mode] * 1000; + return IIO_VAL_INT_PLUS_MICRO; + default: + return -EINVAL; + } +} + +static int t5403_write_raw(struct iio_dev *indio_dev, + struct iio_chan_spec const *chan, + int val, int val2, long mask) +{ + struct t5403_data *data = iio_priv(indio_dev); + int i; + + switch (mask) { + case IIO_CHAN_INFO_INT_TIME: + if (val != 0) + return -EINVAL; + for (i = 0; i < ARRAY_SIZE(t5403_pressure_conv_ms); i++) + if (val2 == t5403_pressure_conv_ms[i] * 1000) { + mutex_lock(&data->lock); + data->mode = i; + mutex_unlock(&data->lock); + return 0; + } + return -EINVAL; + default: + return -EINVAL; + } +} + +static const struct iio_chan_spec t5403_channels[] = { + { + .type = IIO_PRESSURE, + .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED) | + BIT(IIO_CHAN_INFO_INT_TIME), + }, + { + .type = IIO_TEMP, + .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), + }, +}; + +static IIO_CONST_ATTR_INT_TIME_AVAIL("0.002 0.008 0.016 0.066"); + +static struct attribute *t5403_attributes[] = { + &iio_const_attr_integration_time_available.dev_attr.attr, + NULL +}; + +static const struct attribute_group t5403_attribute_group = { + .attrs = t5403_attributes, +}; + +static const struct iio_info t5403_info = { + .read_raw = &t5403_read_raw, + .write_raw = &t5403_write_raw, + .attrs = &t5403_attribute_group, + .driver_module = THIS_MODULE, +}; + +static int t5403_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + struct t5403_data *data; + struct iio_dev *indio_dev; + int ret; + + if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_WORD_DATA | + I2C_FUNC_SMBUS_I2C_BLOCK)) + return -ENODEV; + + ret = i2c_smbus_read_byte_data(client, T5403_SLAVE_ADDR); + if (ret < 0) + return ret; + if ((ret & T5403_I2C_MASK) != T5403_I2C_ADDR) + return -ENODEV; + + indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data)); + if (!indio_dev) + return -ENOMEM; + + data = iio_priv(indio_dev); + data->client = client; + mutex_init(&data->lock); + + i2c_set_clientdata(client, indio_dev); + indio_dev->info = &t5403_info; + indio_dev->name = id->name; + indio_dev->dev.parent = &client->dev; + indio_dev->modes = INDIO_DIRECT_MODE; + indio_dev->channels = t5403_channels; + indio_dev->num_channels = ARRAY_SIZE(t5403_channels); + + data->mode = T5403_MODE_STANDARD; + + ret = i2c_smbus_read_i2c_block_data(data->client, T5403_CALIB_DATA, + sizeof(data->c), (u8 *) data->c); + if (ret < 0) + return ret; + + return devm_iio_device_register(&client->dev, indio_dev); +} + +static const struct i2c_device_id t5403_id[] = { + { "t5403", 0 }, + { } +}; +MODULE_DEVICE_TABLE(i2c, t5403_id); + +static struct i2c_driver t5403_driver = { + .driver = { + .name = "t5403", + }, + .probe = t5403_probe, + .id_table = t5403_id, +}; +module_i2c_driver(t5403_driver); + +MODULE_AUTHOR("Peter Meerwald "); +MODULE_DESCRIPTION("EPCOS T5403 pressure/temperature sensor driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard003/C/0068843_jit-sum.c b/pool/shard003/C/0068843_jit-sum.c new file mode 100644 index 0000000000000000000000000000000000000000..7d843e67a6a5f18945938e8a71ecb4445196a06b --- /dev/null +++ b/pool/shard003/C/0068843_jit-sum.c @@ -0,0 +1,127 @@ +#include + +#include +#include +#include + +void die(const char* c) +{ + fprintf(stderr, "ERROR: %s\n", c); + exit(EXIT_FAILURE); +} + +int main (int argc, char **argv) +{ + gcc_jit_context *ctx; + ctx = gcc_jit_context_acquire (); + if (ctx == NULL) + die("acquired context is NULL"); + + gcc_jit_type *int_type = gcc_jit_context_get_type(ctx, GCC_JIT_TYPE_INT); + + // 'int n' as a parameter + gcc_jit_param *param_n = gcc_jit_context_new_param(ctx, /* loc */ NULL, int_type, "n"); + gcc_jit_rvalue *rval_n = gcc_jit_param_as_rvalue(param_n); + + // int sum(int n) + gcc_jit_param* params[] = { param_n }; + gcc_jit_function *sum_function = gcc_jit_context_new_function(ctx, /* loc */ NULL, + GCC_JIT_FUNCTION_EXPORTED, int_type, "sum", + sizeof(params)/sizeof(*params), params, /* is_variadic */ 0); + + // Local variables + // int s; + gcc_jit_lvalue* sum_var = gcc_jit_function_new_local(sum_function, /* loc */ NULL, int_type, "s"); + gcc_jit_rvalue* rval_sum = gcc_jit_lvalue_as_rvalue(sum_var); + // int i; + gcc_jit_lvalue* ind_var = gcc_jit_function_new_local(sum_function, /* loc */ NULL, int_type, "i"); + gcc_jit_rvalue* rval_ind = gcc_jit_lvalue_as_rvalue(ind_var); + + // init + // | + // V + // .-- loop_header <--. + // | | | + // | V | + // | loop_body------' + // | + // `--> return + // + gcc_jit_block *init_block = gcc_jit_function_new_block(sum_function, "init"); + gcc_jit_block *loop_header_block = gcc_jit_function_new_block(sum_function, "loop_header"); + gcc_jit_block *loop_body_block = gcc_jit_function_new_block(sum_function, "loop_body"); + gcc_jit_block *return_block = gcc_jit_function_new_block(sum_function, "return"); + + // Block --- init + // sum = 0 + gcc_jit_block_add_assignment(init_block, /* loc */ NULL, + sum_var, + gcc_jit_context_new_rvalue_from_int(ctx, int_type, 0)); + // init = 0 + gcc_jit_block_add_assignment(init_block, /* loc */ NULL, + ind_var, + gcc_jit_context_new_rvalue_from_int(ctx, int_type, 0)); + // goto loop_header + gcc_jit_block_end_with_jump(init_block, /* loc */ NULL, loop_header_block); + + // Block --- loop_header + // if (i < n) + // goto loop_body; + // else + // goto return; + gcc_jit_block_end_with_conditional( + loop_header_block, /* loc */ NULL, + gcc_jit_context_new_comparison( + ctx, /* loc */ NULL, + GCC_JIT_COMPARISON_LT, + rval_ind, + rval_n), + loop_body_block, + return_block); + + // Block --- loop_body + // s += i; + gcc_jit_block_add_assignment_op ( + loop_body_block, /* loc */ NULL, + sum_var, + GCC_JIT_BINARY_OP_PLUS, + rval_ind); + // i += 1; + gcc_jit_block_add_assignment_op ( + loop_body_block, /* loc */ NULL, + ind_var, + GCC_JIT_BINARY_OP_PLUS, + gcc_jit_context_one(ctx, int_type)); + // goto loop_header + gcc_jit_block_end_with_jump( + loop_body_block, /* loc */ NULL, + loop_header_block); + + // Block --- return + // return sum; + gcc_jit_block_end_with_return(return_block, /* loc */ NULL, + rval_sum); + + // Dump to dot + gcc_jit_function_dump_to_dot(sum_function, "sum.dot"); + + // Compile the code + gcc_jit_result *result = gcc_jit_context_compile(ctx); + if (result == NULL) + die("compilation failed"); + + // Test it! + void *function_addr = gcc_jit_result_get_code(result, "sum"); + + typedef int (*ptr_sum_t)(int); + ptr_sum_t sum = (ptr_sum_t)function_addr; + + int x = sum(100); + fprintf(stderr, "SUM(0..99) = %d\n", x); + assert(x == 4950); + + gcc_jit_result_release(result); + gcc_jit_context_release (ctx); + + return 0; +} diff --git a/pool/shard003/C/0068847_10801.c b/pool/shard003/C/0068847_10801.c new file mode 100644 index 0000000000000000000000000000000000000000..aaf6b8577a5a34af3e4cb22120261098479ec8fb --- /dev/null +++ b/pool/shard003/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/pool/shard003/C/0068871_cortina.c b/pool/shard003/C/0068871_cortina.c new file mode 100644 index 0000000000000000000000000000000000000000..1a4d04afb7f047110441781d65973376f6f58a2c --- /dev/null +++ b/pool/shard003/C/0068871_cortina.c @@ -0,0 +1,111 @@ +/* + * Copyright 2017 NXP + * + * 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. + * + * CORTINA is a registered trademark of Cortina Systems, Inc. + * + */ +#include +#include + +#define PHY_ID_CS4340 0x13e51002 + +#define VILLA_GLOBAL_CHIP_ID_LSB 0x0 +#define VILLA_GLOBAL_CHIP_ID_MSB 0x1 + +#define VILLA_GLOBAL_GPIO_1_INTS 0x017 + +static int cortina_read_reg(struct phy_device *phydev, u16 regnum) +{ + return mdiobus_read(phydev->mdio.bus, phydev->mdio.addr, + MII_ADDR_C45 | regnum); +} + +static int cortina_read_status(struct phy_device *phydev) +{ + int gpio_int_status, ret = 0; + + gpio_int_status = cortina_read_reg(phydev, VILLA_GLOBAL_GPIO_1_INTS); + if (gpio_int_status < 0) { + ret = gpio_int_status; + goto err; + } + + if (gpio_int_status & 0x8) { + /* up when edc_convergedS set */ + phydev->speed = SPEED_10000; + phydev->duplex = DUPLEX_FULL; + phydev->link = 1; + } else { + phydev->link = 0; + } + +err: + return ret; +} + +static int cortina_probe(struct phy_device *phydev) +{ + u32 phy_id = 0; + int id_lsb = 0, id_msb = 0; + + /* Read device id from phy registers. */ + id_lsb = cortina_read_reg(phydev, VILLA_GLOBAL_CHIP_ID_LSB); + if (id_lsb < 0) + return -ENXIO; + + phy_id = id_lsb << 16; + + id_msb = cortina_read_reg(phydev, VILLA_GLOBAL_CHIP_ID_MSB); + if (id_msb < 0) + return -ENXIO; + + phy_id |= id_msb; + + /* Make sure the device tree binding matched the driver with the + * right device. + */ + if (phy_id != phydev->drv->phy_id) { + phydev_err(phydev, "Error matching phy with %s driver\n", + phydev->drv->name); + return -ENODEV; + } + + return 0; +} + +static struct phy_driver cortina_driver[] = { +{ + .phy_id = PHY_ID_CS4340, + .phy_id_mask = 0xffffffff, + .name = "Cortina CS4340", + .features = PHY_10GBIT_FEATURES, + .config_init = gen10g_config_init, + .config_aneg = gen10g_config_aneg, + .read_status = cortina_read_status, + .soft_reset = gen10g_no_soft_reset, + .probe = cortina_probe, +}, +}; + +module_phy_driver(cortina_driver); + +static struct mdio_device_id __maybe_unused cortina_tbl[] = { + { PHY_ID_CS4340, 0xffffffff}, + {}, +}; + +MODULE_DEVICE_TABLE(mdio, cortina_tbl); + +MODULE_DESCRIPTION("Cortina EDC CDR 10G Ethernet PHY driver"); +MODULE_AUTHOR("NXP"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard003/C/0068872_ot1200.c b/pool/shard003/C/0068872_ot1200.c new file mode 100644 index 0000000000000000000000000000000000000000..acf95cb372ac2a48c574bce6005c3bce4575f4c4 --- /dev/null +++ b/pool/shard003/C/0068872_ot1200.c @@ -0,0 +1,261 @@ +/* + * Copyright (C) 2010-2013 Freescale Semiconductor, Inc. + * Copyright (C) 2014, Bachmann electronic GmbH + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +#define OUTPUT_40OHM (PAD_CTL_SPEED_MED|PAD_CTL_DSE_40ohm) + +#define UART_PAD_CTRL (PAD_CTL_PUS_100K_UP | \ + OUTPUT_40OHM | PAD_CTL_SRE_FAST | PAD_CTL_HYS) + +#define USDHC_PAD_CTRL (PAD_CTL_PUS_47K_UP | \ + PAD_CTL_SPEED_LOW | PAD_CTL_DSE_80ohm | \ + PAD_CTL_SRE_FAST | PAD_CTL_HYS) + +#define ENET_PAD_CTRL (PAD_CTL_PUS_100K_UP | OUTPUT_40OHM | \ + PAD_CTL_HYS) + +#define SPI_PAD_CTRL (PAD_CTL_HYS | OUTPUT_40OHM | \ + PAD_CTL_SRE_FAST) + +#define I2C_PAD_CTRL (PAD_CTL_PUS_100K_UP | OUTPUT_40OHM | \ + PAD_CTL_HYS | PAD_CTL_ODE | PAD_CTL_SRE_FAST) + +int dram_init(void) +{ + gd->ram_size = get_ram_size((void *)PHYS_SDRAM, PHYS_SDRAM_SIZE); + + return 0; +} + +static iomux_v3_cfg_t const uart1_pads[] = { + MX6_PAD_CSI0_DAT10__UART1_TX_DATA | MUX_PAD_CTRL(UART_PAD_CTRL), + MX6_PAD_CSI0_DAT11__UART1_RX_DATA | MUX_PAD_CTRL(UART_PAD_CTRL), +}; + +static void setup_iomux_uart(void) +{ + imx_iomux_v3_setup_multiple_pads(uart1_pads, ARRAY_SIZE(uart1_pads)); +} + +static iomux_v3_cfg_t const enet_pads[] = { + MX6_PAD_KEY_ROW1__ENET_COL | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_KEY_COL3__ENET_CRS | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_ENET_MDIO__ENET_MDIO | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_ENET_MDC__ENET_MDC | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_GPIO_16__ENET_REF_CLK | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_GPIO_18__ENET_RX_CLK | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_ENET_RXD0__ENET_RX_DATA0 | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_ENET_RXD1__ENET_RX_DATA1 | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_KEY_COL2__ENET_RX_DATA2 | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_KEY_COL0__ENET_RX_DATA3 | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_ENET_CRS_DV__ENET_RX_EN | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_ENET_REF_CLK__ENET_TX_CLK | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_ENET_TXD0__ENET_TX_DATA0 | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_ENET_TXD1__ENET_TX_DATA1 | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_KEY_ROW2__ENET_TX_DATA2 | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_KEY_ROW0__ENET_TX_DATA3 | MUX_PAD_CTRL(ENET_PAD_CTRL), + MX6_PAD_ENET_TX_EN__ENET_TX_EN | MUX_PAD_CTRL(ENET_PAD_CTRL), +}; + +static void setup_iomux_enet(void) +{ + imx_iomux_v3_setup_multiple_pads(enet_pads, ARRAY_SIZE(enet_pads)); +} + +static iomux_v3_cfg_t const ecspi1_pads[] = { + MX6_PAD_DISP0_DAT3__ECSPI3_SS0 | MUX_PAD_CTRL(SPI_PAD_CTRL), + MX6_PAD_DISP0_DAT4__ECSPI3_SS1 | MUX_PAD_CTRL(SPI_PAD_CTRL), + MX6_PAD_DISP0_DAT2__ECSPI3_MISO | MUX_PAD_CTRL(SPI_PAD_CTRL), + MX6_PAD_DISP0_DAT1__ECSPI3_MOSI | MUX_PAD_CTRL(SPI_PAD_CTRL), + MX6_PAD_DISP0_DAT0__ECSPI3_SCLK | MUX_PAD_CTRL(SPI_PAD_CTRL), +}; + +static void setup_iomux_spi(void) +{ + imx_iomux_v3_setup_multiple_pads(ecspi1_pads, ARRAY_SIZE(ecspi1_pads)); +} + +int board_spi_cs_gpio(unsigned bus, unsigned cs) +{ + return (bus == 2 && cs == 0) ? (IMX_GPIO_NR(1, 3)) : -1; +} + +int board_early_init_f(void) +{ + setup_iomux_uart(); + setup_iomux_spi(); + + return 0; +} + +static iomux_v3_cfg_t const usdhc3_pads[] = { + MX6_PAD_SD3_CLK__SD3_CLK | MUX_PAD_CTRL(USDHC_PAD_CTRL), + MX6_PAD_SD3_CMD__SD3_CMD | MUX_PAD_CTRL(USDHC_PAD_CTRL), + MX6_PAD_SD3_DAT0__SD3_DATA0 | MUX_PAD_CTRL(USDHC_PAD_CTRL), + MX6_PAD_SD3_DAT1__SD3_DATA1 | MUX_PAD_CTRL(USDHC_PAD_CTRL), + MX6_PAD_SD3_DAT2__SD3_DATA2 | MUX_PAD_CTRL(USDHC_PAD_CTRL), + MX6_PAD_SD3_DAT3__SD3_DATA3 | MUX_PAD_CTRL(USDHC_PAD_CTRL), + MX6_PAD_SD3_DAT4__SD3_DATA4 | MUX_PAD_CTRL(USDHC_PAD_CTRL), + MX6_PAD_SD3_DAT5__SD3_DATA5 | MUX_PAD_CTRL(USDHC_PAD_CTRL), + MX6_PAD_SD3_DAT6__SD3_DATA6 | MUX_PAD_CTRL(USDHC_PAD_CTRL), + MX6_PAD_SD3_DAT7__SD3_DATA7 | MUX_PAD_CTRL(USDHC_PAD_CTRL), + MX6_PAD_SD3_RST__SD3_RESET | MUX_PAD_CTRL(USDHC_PAD_CTRL), +}; + +int board_mmc_getcd(struct mmc *mmc) +{ + return 1; +} + +struct fsl_esdhc_cfg usdhc_cfg[] = { + {USDHC3_BASE_ADDR}, +}; + +int board_mmc_init(bd_t *bis) +{ + usdhc_cfg[0].sdhc_clk = mxc_get_clock(MXC_ESDHC3_CLK); + usdhc_cfg[0].max_bus_width = 8; + + imx_iomux_v3_setup_multiple_pads(usdhc3_pads, ARRAY_SIZE(usdhc3_pads)); + + return fsl_esdhc_initialize(bis, &usdhc_cfg[0]); +} + +#define PC MUX_PAD_CTRL(I2C_PAD_CTRL) + +/* I2C3 - IO expander */ +static struct i2c_pads_info i2c_pad_info2 = { + .scl = { + .i2c_mode = MX6_PAD_EIM_D17__I2C3_SCL | PC, + .gpio_mode = MX6_PAD_EIM_D17__GPIO3_IO17 | PC, + .gp = IMX_GPIO_NR(3, 17) + }, + .sda = { + .i2c_mode = MX6_PAD_EIM_D18__I2C3_SDA | PC, + .gpio_mode = MX6_PAD_EIM_D18__GPIO3_IO18 | PC, + .gp = IMX_GPIO_NR(3, 18) + } +}; + +static iomux_v3_cfg_t const pwm_pad[] = { + MX6_PAD_SD1_CMD__PWM4_OUT | MUX_PAD_CTRL(OUTPUT_40OHM), +}; + +static void leds_on(void) +{ + /* turn on all possible leds connected via GPIO expander */ + i2c_set_bus_num(2); + pca953x_set_dir(CONFIG_SYS_I2C_PCA953X_ADDR, 0xffff, PCA953X_DIR_OUT); + pca953x_set_val(CONFIG_SYS_I2C_PCA953X_ADDR, 0xffff, 0x0); +} + +static void backlight_lcd_off(void) +{ + unsigned gpio = IMX_GPIO_NR(2, 0); + gpio_direction_output(gpio, 0); + + gpio = IMX_GPIO_NR(2, 3); + gpio_direction_output(gpio, 0); +} + +int board_eth_init(bd_t *bis) +{ + uint32_t base = IMX_FEC_BASE; + struct mii_dev *bus = NULL; + struct phy_device *phydev = NULL; + int ret; + + setup_iomux_enet(); + + bus = fec_get_miibus(base, -1); + if (!bus) + return 0; + + /* scan phy 0 and 5 */ + phydev = phy_find_by_mask(bus, 0x21, PHY_INTERFACE_MODE_RGMII); + if (!phydev) { + free(bus); + return 0; + } + + /* depending on the phy address we can detect our board version */ + if (phydev->addr == 0) + setenv("boardver", ""); + else + setenv("boardver", "mr"); + + printf("using phy at %d\n", phydev->addr); + ret = fec_probe(bis, -1, base, bus, phydev); + if (ret) { + printf("FEC MXC: %s:failed\n", __func__); + free(phydev); + free(bus); + } + return 0; +} + +int board_init(void) +{ + gd->bd->bi_boot_params = PHYS_SDRAM + 0x100; + + backlight_lcd_off(); + + setup_i2c(2, CONFIG_SYS_I2C_SPEED, 0x7f, &i2c_pad_info2); + + leds_on(); + + /* enable ecspi3 clocks */ + enable_cspi_clock(1, 2); + +#ifdef CONFIG_CMD_SATA + setup_sata(); +#endif + + return 0; +} + +int checkboard(void) +{ + puts("Board: "CONFIG_SYS_BOARD"\n"); + return 0; +} + +#ifdef CONFIG_CMD_BMODE +static const struct boot_mode board_boot_modes[] = { + /* 4 bit bus width */ + {"mmc0", MAKE_CFGVAL(0x40, 0x30, 0x00, 0x00)}, + {NULL, 0}, +}; +#endif + +int misc_init_r(void) +{ +#ifdef CONFIG_CMD_BMODE + add_board_boot_modes(board_boot_modes); +#endif + return 0; +} diff --git a/pool/shard003/C/0068898_eventlogadm.c b/pool/shard003/C/0068898_eventlogadm.c new file mode 100644 index 0000000000000000000000000000000000000000..036ce3ad4b97131865bf4c4e17415bb68a2c46c5 --- /dev/null +++ b/pool/shard003/C/0068898_eventlogadm.c @@ -0,0 +1,228 @@ + +/* + * Samba Unix/Linux SMB client utility + * Write Eventlog records to a tdb, perform other eventlog related functions + * + * + * Copyright (C) Brian Moran 2005. + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + + +#include "includes.h" + +#undef DBGC_CLASS +#define DBGC_CLASS DBGC_UTIL_EVENTLOG + + +extern int optind; +extern char *optarg; + +int opt_debug = 0; + +static void usage( char *s ) +{ + printf( "\nUsage: %s [OPTION]\n\n", s ); + printf( " -o write \t\t\t\t\tWrites records to eventlog from STDIN\n" ); + printf( " -o addsource \tAdds the specified source & DLL eventlog registry entry\n" ); + printf( "\nMiscellaneous options:\n" ); + printf( " -d\t\t\t\t\t\t\t\tturn debug on\n" ); + printf( " -h\t\t\t\t\t\t\t\tdisplay help\n\n" ); +} + +static void display_eventlog_names( void ) +{ + const char **elogs; + int i; + + elogs = lp_eventlog_list( ); + printf( "Active eventlog names (from smb.conf):\n" ); + printf( "--------------------------------------\n" ); + if ( elogs ) { + for ( i = 0; elogs[i]; i++ ) { + printf( "\t%s\n", elogs[i] ); + } + } + else + printf( "\t\n"); +} + +int DoAddSourceCommand( int argc, char **argv, BOOL debugflag, char *exename ) +{ + + if ( argc < 3 ) { + printf( "need more arguments:\n" ); + printf( "-o addsource EventlogName SourceName /path/to/EventMessageFile.dll\n" ); + return -1; + } + /* must open the registry before we access it */ + if ( !regdb_init( ) ) { + printf( "Can't open the registry.\n" ); + return -1; + } + + if ( !eventlog_add_source( argv[0], argv[1], argv[2] ) ) + return -2; + return 0; +} + +int DoWriteCommand( int argc, char **argv, BOOL debugflag, char *exename ) +{ + FILE *f1; + char *argfname; + ELOG_TDB *etdb; + + /* fixed constants are bad bad bad */ + pstring linein; + BOOL is_eor; + Eventlog_entry ee; + int rcnum; + + f1 = stdin; + if ( !f1 ) { + printf( "Can't open STDIN\n" ); + return -1; + } + + if ( debugflag ) { + printf( "Starting write for eventlog [%s]\n", argv[0] ); + display_eventlog_names( ); + } + + argfname = argv[0]; + + if ( !( etdb = elog_open_tdb( argfname, False ) ) ) { + printf( "can't open the eventlog TDB (%s)\n", argfname ); + return -1; + } + + ZERO_STRUCT( ee ); /* MUST initialize between records */ + + while ( !feof( f1 ) ) { + fgets( linein, sizeof( linein ) - 1, f1 ); + linein[strlen( linein ) - 1] = 0; /* whack the line delimiter */ + + if ( debugflag ) + printf( "Read line [%s]\n", linein ); + + is_eor = False; + + + parse_logentry( ( char * ) &linein, &ee, &is_eor ); + /* should we do something with the return code? */ + + if ( is_eor ) { + fixup_eventlog_entry( &ee ); + + if ( opt_debug ) + printf( "record number [%d], tg [%d] , tw [%d]\n", ee.record.record_number, ee.record.time_generated, ee.record.time_written ); + + if ( ee.record.time_generated != 0 ) { + + /* printf("Writing to the event log\n"); */ + + rcnum = write_eventlog_tdb( ELOG_TDB_CTX(etdb), &ee ); + if ( !rcnum ) { + printf( "Can't write to the event log\n" ); + } else { + if ( opt_debug ) + printf( "Wrote record %d\n", + rcnum ); + } + } else { + if ( opt_debug ) + printf( "\n" ); + } + ZERO_STRUCT( ee ); /* MUST initialize between records */ + } + } + + elog_close_tdb( etdb , False ); + + return 0; +} + +/* would be nice to use the popT stuff here, however doing so forces us to drag in a lot of other infrastructure */ + +int main( int argc, char *argv[] ) +{ + int opt, rc; + char *exename; + + + fstring opname; + + load_case_tables(); + + opt_debug = 0; /* todo set this from getopts */ + + lp_load( dyn_CONFIGFILE, True, False, False, True); + + exename = argv[0]; + + /* default */ + + fstrcpy( opname, "write" ); /* the default */ + +#if 0 /* TESTING CODE */ + eventlog_add_source( "System", "TestSourceX", "SomeTestPathX" ); +#endif + while ( ( opt = getopt( argc, argv, "dho:" ) ) != EOF ) { + switch ( opt ) { + + case 'o': + fstrcpy( opname, optarg ); + break; + + case 'h': + usage( exename ); + display_eventlog_names( ); + exit( 0 ); + break; + + case 'd': + opt_debug = 1; + break; + } + } + + argc -= optind; + argv += optind; + + if ( argc < 1 ) { + printf( "\nNot enough arguments!\n" ); + usage( exename ); + exit( 1 ); + } + + /* note that the separate command types should call usage if they need to... */ + while ( 1 ) { + if ( !StrCaseCmp( opname, "addsource" ) ) { + rc = DoAddSourceCommand( argc, argv, opt_debug, + exename ); + break; + } + if ( !StrCaseCmp( opname, "write" ) ) { + rc = DoWriteCommand( argc, argv, opt_debug, exename ); + break; + } + printf( "unknown command [%s]\n", opname ); + usage( exename ); + exit( 1 ); + break; + } + return rc; +} diff --git a/pool/shard003/C/0068905_rboot-api.c b/pool/shard003/C/0068905_rboot-api.c new file mode 100644 index 0000000000000000000000000000000000000000..93538d43fb4ad3850010d79bda0d060206bfc882 --- /dev/null +++ b/pool/shard003/C/0068905_rboot-api.c @@ -0,0 +1,209 @@ +////////////////////////////////////////////////// +// rBoot OTA and config API for ESP8266. +// Copyright 2015 Richard A Burton +// richardaburton@gmail.com +// See license.txt for license terms. +// OTA code based on SDK sample from Espressif. +////////////////////////////////////////////////// + +#include +#include +#include + +// detect rtos sdk (not ideal method!) +#ifdef IRAM_ATTR +#define os_free(s) vPortFree(s) +#define os_malloc(s) pvPortMalloc(s) +#else +#include +#endif + +#ifdef RBOOT_INTEGRATION +#include +#endif + +#include "rboot-api.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(BOOT_CONFIG_CHKSUM) || defined(BOOT_RTC_ENABLED) +// calculate checksum for block of data +// from start up to (but excluding) end +static uint8 calc_chksum(uint8 *start, uint8 *end) { + uint8 chksum = CHKSUM_INIT; + while(start < end) { + chksum ^= *start; + start++; + } + return chksum; +} +#endif + +// get the rboot config +rboot_config ICACHE_FLASH_ATTR rboot_get_config(void) { + rboot_config conf; + spi_flash_read(BOOT_CONFIG_SECTOR * SECTOR_SIZE, (uint32*)&conf, sizeof(rboot_config)); + return conf; +} + +// write the rboot config +// preserves the contents of the rest of the sector, +// so the rest of the sector can be used to store user data +// updates checksum automatically (if enabled) +bool ICACHE_FLASH_ATTR rboot_set_config(rboot_config *conf) { + uint8 *buffer; + buffer = (uint8*)os_malloc(SECTOR_SIZE); + if (!buffer) { + //os_printf("No ram!\r\n"); + return false; + } + +#ifdef BOOT_CONFIG_CHKSUM + conf->chksum = calc_chksum((uint8*)conf, (uint8*)&conf->chksum); +#endif + + spi_flash_read(BOOT_CONFIG_SECTOR * SECTOR_SIZE, (uint32*)((void*)buffer), SECTOR_SIZE); + memcpy(buffer, conf, sizeof(rboot_config)); + spi_flash_erase_sector(BOOT_CONFIG_SECTOR); + //spi_flash_write(BOOT_CONFIG_SECTOR * SECTOR_SIZE, (uint32*)((void*)buffer), SECTOR_SIZE); + spi_flash_write(BOOT_CONFIG_SECTOR * SECTOR_SIZE, (uint32*)((void*)buffer), SECTOR_SIZE); + + os_free(buffer); + return true; +} + +// get current boot rom +uint8 ICACHE_FLASH_ATTR rboot_get_current_rom(void) { + rboot_config conf; + conf = rboot_get_config(); + return conf.current_rom; +} + +// set current boot rom +bool ICACHE_FLASH_ATTR rboot_set_current_rom(uint8 rom) { + rboot_config conf; + conf = rboot_get_config(); + if (rom >= conf.count) return false; + conf.current_rom = rom; + return rboot_set_config(&conf); +} + +// create the write status struct, based on supplied start address +rboot_write_status ICACHE_FLASH_ATTR rboot_write_init(uint32 start_addr) { + rboot_write_status status = {0}; + status.start_addr = start_addr; + status.start_sector = start_addr / SECTOR_SIZE; + status.last_sector_erased = status.start_sector - 1; + //status.max_sector_count = 200; + //os_printf("init addr: 0x%08x\r\n", start_addr); + return status; +} + +// function to do the actual writing to flash +// call repeatedly with more data (max len per write is the flash sector size (4k)) +bool ICACHE_FLASH_ATTR rboot_write_flash(rboot_write_status *status, uint8 *data, uint16 len) { + + bool ret = false; + uint8 *buffer; + int32 lastsect; + + if (data == NULL || len == 0) { + return true; + } + + // get a buffer + buffer = (uint8 *)os_malloc(len + status->extra_count); + if (!buffer) { + ets_printf("rboot_write_flash: out of memory\n"); + //ets_printf("No ram!\r\n"); + return false; + } + + // copy in any remaining bytes from last chunk + memcpy(buffer, status->extra_bytes, status->extra_count); + // copy in new data + memcpy(buffer + status->extra_count, data, len); + + // calculate length, must be multiple of 4 + // save any remaining bytes for next go + len += status->extra_count; + status->extra_count = len % 4; + len -= status->extra_count; + memcpy(status->extra_bytes, buffer + len, status->extra_count); + + // check data will fit + //if (status->start_addr + len < (status->start_sector + status->max_sector_count) * SECTOR_SIZE) { + + // erase any additional sectors needed by this chunk + lastsect = ((status->start_addr + len) - 1) / SECTOR_SIZE; + while (lastsect > status->last_sector_erased) { + status->last_sector_erased++; + spi_flash_erase_sector(status->last_sector_erased); + } + + // write current chunk + //ets_printf("write addr: 0x%08x, len: 0x%04x\r\n", status->start_addr, len); + if (spi_flash_write(status->start_addr, (uint32 *)((void*)buffer), len) == SPI_FLASH_RESULT_OK) { + ret = true; + status->start_addr += len; + } + //} + + os_free(buffer); + return ret; +} + +#ifdef BOOT_RTC_ENABLED +bool ICACHE_FLASH_ATTR rboot_get_rtc_data(rboot_rtc_data *rtc) { + if (system_rtc_mem_read(RBOOT_RTC_ADDR, rtc, sizeof(rboot_rtc_data))) { + return (rtc->chksum == calc_chksum((uint8*)rtc, (uint8*)&rtc->chksum)); + } + return false; +} + +bool ICACHE_FLASH_ATTR rboot_set_rtc_data(rboot_rtc_data *rtc) { + // calculate checksum + rtc->chksum = calc_chksum((uint8*)rtc, (uint8*)&rtc->chksum); + return system_rtc_mem_write(RBOOT_RTC_ADDR, rtc, sizeof(rboot_rtc_data)); +} + +bool ICACHE_FLASH_ATTR rboot_set_temp_rom(uint8 rom) { + rboot_rtc_data rtc; + // invalid data in rtc? + if (!rboot_get_rtc_data(&rtc)) { + // set basics + rtc.magic = RBOOT_RTC_MAGIC; + rtc.last_mode = MODE_STANDARD; + rtc.last_rom = 0; + } + // set next boot to temp mode with specified rom + rtc.next_mode = MODE_TEMP_ROM; + rtc.temp_rom = rom; + + return rboot_set_rtc_data(&rtc); +} + +bool ICACHE_FLASH_ATTR rboot_get_last_boot_rom(uint8 *rom) { + rboot_rtc_data rtc; + if (rboot_get_rtc_data(&rtc)) { + *rom = rtc.last_rom; + return true; + } + return false; +} + +bool ICACHE_FLASH_ATTR rboot_get_last_boot_mode(uint8 *mode) { + rboot_rtc_data rtc; + if (rboot_get_rtc_data(&rtc)) { + *mode = rtc.last_mode; + return true; + } + return false; +} +#endif + +#ifdef __cplusplus +} +#endif diff --git a/pool/shard003/C/0068948_dummy_shell.c b/pool/shard003/C/0068948_dummy_shell.c new file mode 100644 index 0000000000000000000000000000000000000000..b5e76986f9f078fd24115298fe9fe390f352b941 --- /dev/null +++ b/pool/shard003/C/0068948_dummy_shell.c @@ -0,0 +1,125 @@ +/* + * SSH Dummy Shell + * + * Copyright (c) 2014, Carlos Alves + * 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. + * + * 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. + */ + +#include +#include +#include +#include +#include +#include + +#define MOTD "/etc/motd" + + +int +display_motd(char *filename) +{ + /* + * Display the message of the day. + */ + FILE *file; + char buf[256]; + + file = fopen(filename, "r"); + if ( file == NULL ) { + perror("Error while opening the motd file.\n"); + return (-1); + } + else { + while (fgets(buf, sizeof(buf), file)) + fputs(buf, stdout); + } + fclose(file); + return 0; +} + + +void +clear(void) +{ + /* Function to clear the screen + * based on VT100 ANSI escape sequences + * More specifically: + * + * * 033 is the octal of ESC + * * 2J is for clearing the entire console/terminal screen + * (and moves cursor to upper left on DOS ANSI.SYS) + * * 1;1H moves the cursor to row 1 and column 1 + */ + fputs("\033[2J\033[1;1H", stdout); +} + + +void +get_time(void) +{ + time_t now; + time(&now); + + printf("%s", ctime(&now)); /* Use ctime to format time to a string. */ +} + + +void +log_entry(char *user_name, char *tty, char *ip_addr) +{ + openlog("dummy", LOG_CONS, LOG_AUTH); + syslog(LOG_CRIT, "Session opened for user %s on %s from %s", + user_name, tty, ip_addr); + closelog(); +} + +int +main(void) +{ + char *ssh_connection; + char *ssh_tty; + char *ssh_logname; + char *delimiter = " "; + char *ip_address; + + ssh_connection = getenv("SSH_CONNECTION"); + ssh_tty = getenv("SSH_TTY"); + ssh_logname = getenv("LOGNAME"); + ip_address = strtok(ssh_connection, delimiter); + + if (ssh_connection) { + log_entry(ssh_logname, ssh_tty, ip_address); + while (1) { + clear(); + get_time(); + display_motd(MOTD); + sleep(60); + } + } + else { + puts("This shell is meant to use only for ssh forward users."); + } + + return 0; +} diff --git a/pool/shard003/C/0068949_SDL_emscriptenmouse.c b/pool/shard003/C/0068949_SDL_emscriptenmouse.c new file mode 100644 index 0000000000000000000000000000000000000000..8d9689612814e5146f398111a09da1bff5aceb32 --- /dev/null +++ b/pool/shard003/C/0068949_SDL_emscriptenmouse.c @@ -0,0 +1,283 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2020 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#if SDL_VIDEO_DRIVER_EMSCRIPTEN + +#include +#include + +#include "SDL_emscriptenmouse.h" +#include "SDL_emscriptenvideo.h" + +#include "../../events/SDL_mouse_c.h" + +static SDL_Cursor* +Emscripten_CreateCursorFromString(const char* cursor_str, SDL_bool is_custom) +{ + SDL_Cursor* cursor; + Emscripten_CursorData *curdata; + + cursor = SDL_calloc(1, sizeof(SDL_Cursor)); + if (cursor) { + curdata = (Emscripten_CursorData *) SDL_calloc(1, sizeof(*curdata)); + if (!curdata) { + SDL_OutOfMemory(); + SDL_free(cursor); + return NULL; + } + + curdata->system_cursor = cursor_str; + curdata->is_custom = is_custom; + cursor->driverdata = curdata; + } + else { + SDL_OutOfMemory(); + } + + return cursor; +} + +static SDL_Cursor* +Emscripten_CreateDefaultCursor() +{ + return Emscripten_CreateCursorFromString("default", SDL_FALSE); +} + +static SDL_Cursor* +Emscripten_CreateCursor(SDL_Surface* surface, int hot_x, int hot_y) +{ + const char *cursor_url = NULL; + SDL_Surface *conv_surf; + + conv_surf = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_ABGR8888, 0); + + if (!conv_surf) { + return NULL; + } + + cursor_url = (const char *)EM_ASM_INT({ + var w = $0; + var h = $1; + var hot_x = $2; + var hot_y = $3; + var pixels = $4; + + var canvas = document.createElement("canvas"); + canvas.width = w; + canvas.height = h; + + var ctx = canvas.getContext("2d"); + + var image = ctx.createImageData(w, h); + var data = image.data; + var src = pixels >> 2; + var dst = 0; + var num; + if (typeof CanvasPixelArray !== 'undefined' && data instanceof CanvasPixelArray) { + // IE10/IE11: ImageData objects are backed by the deprecated CanvasPixelArray, + // not UInt8ClampedArray. These don't have buffers, so we need to revert + // to copying a byte at a time. We do the undefined check because modern + // browsers do not define CanvasPixelArray anymore. + num = data.length; + while (dst < num) { + var val = HEAP32[src]; // This is optimized. Instead, we could do {{{ makeGetValue('buffer', 'dst', 'i32') }}}; + data[dst ] = val & 0xff; + data[dst+1] = (val >> 8) & 0xff; + data[dst+2] = (val >> 16) & 0xff; + data[dst+3] = (val >> 24) & 0xff; + src++; + dst += 4; + } + } else { + var data32 = new Int32Array(data.buffer); + num = data32.length; + data32.set(HEAP32.subarray(src, src + num)); + } + + ctx.putImageData(image, 0, 0); + var url = hot_x === 0 && hot_y === 0 + ? "url(" + canvas.toDataURL() + "), auto" + : "url(" + canvas.toDataURL() + ") " + hot_x + " " + hot_y + ", auto"; + + var urlBuf = _malloc(url.length + 1); + stringToUTF8(url, urlBuf, url.length + 1); + + return urlBuf; + }, surface->w, surface->h, hot_x, hot_y, conv_surf->pixels); + + SDL_FreeSurface(conv_surf); + + return Emscripten_CreateCursorFromString(cursor_url, SDL_TRUE); +} + +static SDL_Cursor* +Emscripten_CreateSystemCursor(SDL_SystemCursor id) +{ + const char *cursor_name = NULL; + + switch(id) { + case SDL_SYSTEM_CURSOR_ARROW: + cursor_name = "default"; + break; + case SDL_SYSTEM_CURSOR_IBEAM: + cursor_name = "text"; + break; + case SDL_SYSTEM_CURSOR_WAIT: + cursor_name = "wait"; + break; + case SDL_SYSTEM_CURSOR_CROSSHAIR: + cursor_name = "crosshair"; + break; + case SDL_SYSTEM_CURSOR_WAITARROW: + cursor_name = "progress"; + break; + case SDL_SYSTEM_CURSOR_SIZENWSE: + cursor_name = "nwse-resize"; + break; + case SDL_SYSTEM_CURSOR_SIZENESW: + cursor_name = "nesw-resize"; + break; + case SDL_SYSTEM_CURSOR_SIZEWE: + cursor_name = "ew-resize"; + break; + case SDL_SYSTEM_CURSOR_SIZENS: + cursor_name = "ns-resize"; + break; + case SDL_SYSTEM_CURSOR_SIZEALL: + cursor_name = "move"; + break; + case SDL_SYSTEM_CURSOR_NO: + cursor_name = "not-allowed"; + break; + case SDL_SYSTEM_CURSOR_HAND: + cursor_name = "pointer"; + break; + default: + SDL_assert(0); + return NULL; + } + + return Emscripten_CreateCursorFromString(cursor_name, SDL_FALSE); +} + +static void +Emscripten_FreeCursor(SDL_Cursor* cursor) +{ + Emscripten_CursorData *curdata; + if (cursor) { + curdata = (Emscripten_CursorData *) cursor->driverdata; + + if (curdata != NULL) { + if (curdata->is_custom) { + SDL_free((char *)curdata->system_cursor); + } + SDL_free(cursor->driverdata); + } + + SDL_free(cursor); + } +} + +static int +Emscripten_ShowCursor(SDL_Cursor* cursor) +{ + Emscripten_CursorData *curdata; + if (SDL_GetMouseFocus() != NULL) { + if(cursor && cursor->driverdata) { + curdata = (Emscripten_CursorData *) cursor->driverdata; + + if(curdata->system_cursor) { + EM_ASM_INT({ + if (Module['canvas']) { + Module['canvas'].style['cursor'] = UTF8ToString($0); + } + return 0; + }, curdata->system_cursor); + } + } + else { + EM_ASM( + if (Module['canvas']) { + Module['canvas'].style['cursor'] = 'none'; + } + ); + } + } + return 0; +} + +static void +Emscripten_WarpMouse(SDL_Window* window, int x, int y) +{ + SDL_Unsupported(); +} + +static int +Emscripten_SetRelativeMouseMode(SDL_bool enabled) +{ + SDL_Window *window; + SDL_WindowData *window_data; + + /* TODO: pointer lock isn't actually enabled yet */ + if(enabled) { + window = SDL_GetMouseFocus(); + if (window == NULL) { + return -1; + } + + window_data = (SDL_WindowData *) window->driverdata; + + if(emscripten_request_pointerlock(window_data->canvas_id, 1) >= EMSCRIPTEN_RESULT_SUCCESS) { + return 0; + } + } else { + if(emscripten_exit_pointerlock() >= EMSCRIPTEN_RESULT_SUCCESS) { + return 0; + } + } + return -1; +} + +void +Emscripten_InitMouse() +{ + SDL_Mouse* mouse = SDL_GetMouse(); + + mouse->CreateCursor = Emscripten_CreateCursor; + mouse->ShowCursor = Emscripten_ShowCursor; + mouse->FreeCursor = Emscripten_FreeCursor; + mouse->WarpMouse = Emscripten_WarpMouse; + mouse->CreateSystemCursor = Emscripten_CreateSystemCursor; + mouse->SetRelativeMouseMode = Emscripten_SetRelativeMouseMode; + + SDL_SetDefaultCursor(Emscripten_CreateDefaultCursor()); +} + +void +Emscripten_FiniMouse() +{ +} + +#endif /* SDL_VIDEO_DRIVER_EMSCRIPTEN */ + +/* vi: set ts=4 sw=4 expandtab: */ + diff --git a/pool/shard003/C/0068965_systick.c b/pool/shard003/C/0068965_systick.c new file mode 100644 index 0000000000000000000000000000000000000000..4eac583e2a05a8667eff51143de866423901aee2 --- /dev/null +++ b/pool/shard003/C/0068965_systick.c @@ -0,0 +1,140 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2013, 2014 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 "irq.h" +#include "systick.h" +#include "pybthread.h" + +extern __IO uint32_t uwTick; + +// We provide our own version of HAL_Delay that calls __WFI while waiting, +// and works when interrupts are disabled. This function is intended to be +// used only by the ST HAL functions. +void HAL_Delay(uint32_t Delay) { + if (query_irq() == IRQ_STATE_ENABLED) { + // IRQs enabled, so can use systick counter to do the delay + uint32_t start = uwTick; + // Wraparound of tick is taken care of by 2's complement arithmetic. + while (uwTick - start < Delay) { + // Enter sleep mode, waiting for (at least) the SysTick interrupt. + __WFI(); + } + } else { + // IRQs disabled, use mp_hal_delay_ms routine. + mp_hal_delay_ms(Delay); + } +} + +// Core delay function that does an efficient sleep and may switch thread context. +// If IRQs are enabled then we must have the GIL. +void mp_hal_delay_ms(mp_uint_t Delay) { + if (query_irq() == IRQ_STATE_ENABLED) { + // IRQs enabled, so can use systick counter to do the delay + uint32_t start = uwTick; + // Wraparound of tick is taken care of by 2's complement arithmetic. + while (uwTick - start < Delay) { + // This macro will execute the necessary idle behaviour. It may + // raise an exception, switch threads or enter sleep mode (waiting for + // (at least) the SysTick interrupt). + MICROPY_EVENT_POLL_HOOK + } + } else { + // IRQs disabled, so need to use a busy loop for the delay. + // To prevent possible overflow of the counter we use a double loop. + const uint32_t count_1ms = HAL_RCC_GetSysClockFreq() / 4000; + for (int i = 0; i < Delay; i++) { + for (uint32_t count = 0; ++count <= count_1ms;) { + } + } + } +} + +// delay for given number of microseconds +void mp_hal_delay_us(mp_uint_t usec) { + if (query_irq() == IRQ_STATE_ENABLED) { + // IRQs enabled, so can use systick counter to do the delay + uint32_t start = mp_hal_ticks_us(); + while (mp_hal_ticks_us() - start < usec) { + } + } else { + // IRQs disabled, so need to use a busy loop for the delay + // sys freq is always a multiple of 2MHz, so division here won't lose precision + const uint32_t ucount = HAL_RCC_GetSysClockFreq() / 2000000 * usec / 2; + for (uint32_t count = 0; ++count <= ucount;) { + } + } +} + +bool sys_tick_has_passed(uint32_t start_tick, uint32_t delay_ms) { + return HAL_GetTick() - start_tick >= delay_ms; +} + +// waits until at least delay_ms milliseconds have passed from the sampling of +// startTick. Handles overflow properly. Assumes stc was taken from +// HAL_GetTick() some time before calling this function. +void sys_tick_wait_at_least(uint32_t start_tick, uint32_t delay_ms) { + while (!sys_tick_has_passed(start_tick, delay_ms)) { + __WFI(); // enter sleep mode, waiting for interrupt + } +} + +mp_uint_t mp_hal_ticks_ms(void) { + return uwTick; +} + +// The SysTick timer counts down at 168 MHz, so we can use that knowledge +// to grab a microsecond counter. +// +// We assume that HAL_GetTickis returns milliseconds. +mp_uint_t mp_hal_ticks_us(void) { + mp_uint_t irq_state = disable_irq(); + uint32_t counter = SysTick->VAL; + uint32_t milliseconds = HAL_GetTick(); + uint32_t status = SysTick->CTRL; + enable_irq(irq_state); + + // It's still possible for the countflag bit to get set if the counter was + // reloaded between reading VAL and reading CTRL. With interrupts disabled + // it definitely takes less than 50 HCLK cycles between reading VAL and + // reading CTRL, so the test (counter > 50) is to cover the case where VAL + // is +ve and very close to zero, and the COUNTFLAG bit is also set. + if ((status & SysTick_CTRL_COUNTFLAG_Msk) && counter > 50) { + // This means that the HW reloaded VAL between the time we read VAL and the + // time we read CTRL, which implies that there is an interrupt pending + // to increment the tick counter. + milliseconds++; + } + uint32_t load = SysTick->LOAD; + counter = load - counter; // Convert from decrementing to incrementing + + // ((load + 1) / 1000) is the number of counts per microsecond. + // + // counter / ((load + 1) / 1000) scales from the systick clock to microseconds + // and is the same thing as (counter * 1000) / (load + 1) + return milliseconds * 1000 + (counter * 1000) / (load + 1); +} diff --git a/pool/shard003/C/0068971_progressbar.c b/pool/shard003/C/0068971_progressbar.c new file mode 100644 index 0000000000000000000000000000000000000000..e74773470f8cca2177cd771367220769ad5e0b00 --- /dev/null +++ b/pool/shard003/C/0068971_progressbar.c @@ -0,0 +1,95 @@ + +#include "progressbar.h" +#include "gui.h" +#include "gfx.h" + +#include +#include + + +typedef struct { + widget_t* widget; + color_t bar_color; + uint8_t progress; +} progressbar_t; + + +static void progressbar_paint(paint_event_t* event); +static void progressbar_destroy(widget_t* w); + + +static const widget_class_t progressbar_widget_class = { + .on_paint = progressbar_paint, + .on_destroy = progressbar_destroy, +}; + +widget_t* +progressbar_create(widget_t* parent, rect_t rect, color_t bg_color, color_t bar_color) +{ + progressbar_t* l = calloc(1, sizeof(progressbar_t)); + + l->progress = 0; + l->bar_color = bar_color; + + l->widget = widget_create(parent, &progressbar_widget_class, l, rect); + widget_set_background(l->widget, bg_color); + + return l->widget; +} + +uint8_t +progressbar_get_progress(widget_t* w) +{ + progressbar_t* l = widget_get_instance_data(w); + + return l->progress; +} + +void +progressbar_set_progress(widget_t* w, uint8_t progress) +{ + progressbar_t* l = widget_get_instance_data(w); + + if (progress > 100) + progress = 100; + + if (l->progress != progress) { + l->progress = progress; + widget_invalidate(w); + } +} + +static void +progressbar_destroy(widget_t* w) +{ + progressbar_t* l = widget_get_instance_data(w); + free(l); +} + +static void +progressbar_paint(paint_event_t* event) +{ +// char prog_str[8]; + progressbar_t* l = widget_get_instance_data(event->widget); + rect_t rect = widget_get_rect(event->widget); +// point_t center = rect_center(rect); + + rect.x += 5; + rect.y += 5; + rect.width -= 10; + rect.height -= 10; + + rect.width = rect.width * l->progress / 100; + + gfx_set_fg_color(l->bar_color); + gfx_fill_rect(rect); + +// sprintf(prog_str, "%d %%", l->progress); +// Extents_t ext = font_text_extents(font_opensans_16, prog_str); +// +// gfx_set_font(font_opensans_16); +// gfx_set_fg_color(WHITE); +// gfx_draw_str(prog_str, -1, +// center.x - (ext.width / 2), +// center.y - (ext.height / 2)); +} diff --git a/pool/shard003/C/0068979_rc-evga-indtube.c b/pool/shard003/C/0068979_rc-evga-indtube.c new file mode 100644 index 0000000000000000000000000000000000000000..3a2d72607d81a5ff1d553e1c525cc59f1942f19b --- /dev/null +++ b/pool/shard003/C/0068979_rc-evga-indtube.c @@ -0,0 +1,62 @@ +/* evga-indtube.h - Keytable for evga_indtube Remote Controller + * + * keymap imported from ir-keymaps.c + * + * Copyright (c) 2010 by Mauro Carvalho Chehab + * + * 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 +#include + +/* EVGA inDtube + Devin Heitmueller + */ + +static struct rc_map_table evga_indtube[] = { + { 0x12, KEY_POWER}, + { 0x02, KEY_MODE}, /* TV */ + { 0x14, KEY_MUTE}, + { 0x1a, KEY_CHANNELUP}, + { 0x16, KEY_TV2}, /* PIP */ + { 0x1d, KEY_VOLUMEUP}, + { 0x05, KEY_CHANNELDOWN}, + { 0x0f, KEY_PLAYPAUSE}, + { 0x19, KEY_VOLUMEDOWN}, + { 0x1c, KEY_REWIND}, + { 0x0d, KEY_RECORD}, + { 0x18, KEY_FORWARD}, + { 0x1e, KEY_PREVIOUS}, + { 0x1b, KEY_STOP}, + { 0x1f, KEY_NEXT}, + { 0x13, KEY_CAMERA}, +}; + +static struct rc_map_list evga_indtube_map = { + .map = { + .scan = evga_indtube, + .size = ARRAY_SIZE(evga_indtube), + .rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */ + .name = RC_MAP_EVGA_INDTUBE, + } +}; + +static int __init init_rc_map_evga_indtube(void) +{ + return rc_map_register(&evga_indtube_map); +} + +static void __exit exit_rc_map_evga_indtube(void) +{ + rc_map_unregister(&evga_indtube_map); +} + +module_init(init_rc_map_evga_indtube) +module_exit(exit_rc_map_evga_indtube) + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Mauro Carvalho Chehab "); diff --git a/pool/shard003/C/0068992_ex05_16.c b/pool/shard003/C/0068992_ex05_16.c new file mode 100644 index 0000000000000000000000000000000000000000..c4b59a69117f00cb417132325ffee28a47ffc417 --- /dev/null +++ b/pool/shard003/C/0068992_ex05_16.c @@ -0,0 +1,42 @@ +/* + * Filename: ex05_16.c + * Author: Andrew Laing + * Email: parisianconnections@gmail.com + * Date: 27/04/2017 + * Description: Calculate Integer exponent + */ + +#include + + +int integerPower(int base, int exponent); + + +int main() +{ + int base, exponent, result; + + printf("Enter the base: "); + scanf("%d", &base); + + printf("Enter the exponent: "); + scanf("%d", &exponent); + + result = integerPower(base, exponent); + printf("The result is %d\n", result); + + return 0; +} + + +int integerPower(int base, int exponent) +{ + int result = base; + int i; + + for(i=1; i + +int pn547_get_hw_revision(void) +{ +#if defined(CONFIG_LGE_NFC_HW_TI_OMAP4430) + int hw_revision = LGE_PCB_MAX; + hw_revision = system_rev; +#else + hw_rev_type hw_revision = HW_REV_MAX; + hw_revision = lge_get_board_revno(); +#endif + dprintk(PN547_DRV_NAME ":ioctl: pn547_read hw revision : %d\n", hw_revision); + return (int)hw_revision; +} + +unsigned int pn547_get_irq_pin(struct pn547_dev *dev) +{ +#if defined(CONFIG_LGE_NFC_HW_TI_OMAP4430) + return OMAP_GPIO_IRQ(dev->irq_gpio); +#elif defined(CONFIG_LGE_NFC_HW_NV_AP3X) + return dev->client->irq; +#else + return dev->client->irq; +#endif +} + +int pn547_gpio_to_irq(struct pn547_dev *dev) +{ +#if defined(CONFIG_LGE_NFC_HW_TI_OMAP4430)||defined(CONFIG_LGE_NFC_HW_QCT_MSM8255) + return gpio_to_irq(dev->irq_gpio); +#else + return dev->client->irq; +#endif +} + +void pn547_gpio_enable(struct pn547_dev *pn547_dev) +{ +#if defined(CONFIG_LGE_NFC_HW_NV_AP3X) + tegra_gpio_enable(pn547_dev->ven_gpio); + tegra_gpio_enable(pn547_dev->firm_gpio); + tegra_gpio_enable(pn547_dev->irq_gpio); +#endif + return; +} + +void pn547_shutdown_cb(struct pn547_dev *pn547_dev) +{ +#if defined(CONFIG_LGE_NFC_HW_QCT_MSM8660) + dprintk("================ pn547_shutdown() start ================\n"); + + // + gpio_set_value(pn547_dev->ven_gpio, 0); + gpio_set_value(pn547_dev->firm_gpio, 0); + msleep(10); + dprintk("Output GPIO Status : VEN = %d, FIRM = %d\n", + gpio_get_value(pn547_dev->ven_gpio), + gpio_get_value(pn547_dev->firm_gpio)); + + dprintk("================ pn547_shutdown() end ================\n"); + +#elif defined(CONFIG_LGE_NFC_HW_NV_AP3X) + gpio_set_value(pn547_dev->ven_gpio, 0); +#endif + return; +} + +#ifdef CONFIG_LGE_NFC_USE_PMIC +void pn547_get_clk_source(struct pn547_dev *pn547_dev) +{ +#if 0 // + pn547_dev->clk_cont = clk_get(&pn547_client->dev, "xo_cont"); + if (pn547_dev->clk_cont == NULL) { + pr_err("%s: PN547 could not get cont. clock!\n", __func__); + } + pn547_dev->clk_pin = clk_get(&pn547_client->dev, "xo_pin"); + if (pn547_dev->clk_pin == NULL) { + pr_err("%s: PN547 could not get pin clock!\n", __func__); + } + // +#else + pn547_dev->clk_cont = &cxo_d1.c; + pn547_dev->clk_pin = &cxo_d1_pin.c; + // +#endif +} +#endif + +void pn547_parse_dt(struct device *dev, struct pn547_dev *pn547_dev) +{ + struct device_node *np = dev->of_node; +#if defined(CONFIG_LGE_NFC_HW_ODIN) + int val = 0; + + if (!of_property_read_u32(np,"nxp,gpio_ven", &val)) + pn547_dev->ven_gpio = val; + val = 0; + + if (!of_property_read_u32(np,"nxp,gpio_mode", &val)) + pn547_dev->firm_gpio = val; + val = 0; + + if (!of_property_read_u32(np,"nxp,gpio_irq", &val)) + pn547_dev->irq_gpio = val; +#else + /* */ + pn547_dev->ven_gpio = of_get_named_gpio_flags(np, "nxp,gpio_ven", 0, NULL); + pn547_dev->firm_gpio = of_get_named_gpio_flags(np, "nxp,gpio_mode", 0, NULL); + pn547_dev->irq_gpio = of_get_named_gpio_flags(np, "nxp,gpio_irq", 0, NULL); +#endif +} diff --git a/pool/shard003/C/0069016_module.c b/pool/shard003/C/0069016_module.c new file mode 100644 index 0000000000000000000000000000000000000000..e2fc5d00be08a481395b102885a1121c499e40d4 --- /dev/null +++ b/pool/shard003/C/0069016_module.c @@ -0,0 +1,303 @@ +/* +Copyright (C) 2012 Brady Catherman + +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 +#include +#include +#include +#include + +#include +#include +#include +#include +#include + + + +struct module_file_list { + // The actual module_file structure we are storing. + module_file data; + struct module_file_list *next; +}; + + +/** + Walks through a module_file_list linked list and frees the elements. + + This will free all memory used in a module_file_list linked list, including + the file name allocations and such. + + Arguments: + p: The module_file_list linked list to free. + */ +static +void +free_module_file_list( + struct module_file_list *p) +{ + while (p != NULL) { + struct module_file_list *p_next = p->next; + if (p->data.filename != NULL) { + free(p->data.filename); + } + free(p); + p = p_next; + } +} + + +/** + Called to add a given file to the list. + + Arguments: + f: The read object from fts_read(). + head: A pointer to the address storing the pointer to the list. + length: The length of the list in head. + + Returns: + modifies head, return 0 on success, non zero on failure. + + Errors: + ENOMEM: If malloc() returns a NULL for any reason. + */ +int +modules_load_add( + FTSENT *f, + struct module_file_list **head, + int *length) +{ + struct module_file_list *m = + (struct module_file_list *) malloc(sizeof(struct module_file_list)); + if (m == NULL) { + errno = ENOMEM; + return ENOMEM; + } + + // Filename. + m->data.filename = (char *) malloc(f->fts_pathlen + 1); + if (m->data.filename == NULL) { + free(m); + errno = ENOMEM; + return ENOMEM; + } + memcpy(m->data.filename, f->fts_path, f->fts_pathlen); + m->data.filename[f->fts_pathlen] = '\0'; + + // Basic file stats. + m->data.inode = f->fts_statp->st_dev; + m->data.modified_time = f->fts_statp->st_mtime; + + m->next = *head; + *head = m; + (*length)++; + return 0; +} + + +/** + Called once the directory is opened to read each file item one by one. + + Note: This function should only ever be called from modules_load_getlist. + + Arguments: + path: The path being processed, used for error messages. + d: The FTS structure opened in modules_load_getlist. + list: A pointer to the pointer containing the head of the list. + length: A pointer to an integer containing the length of the list. + + Returns: + 0 on success, or anything else on failure. + */ +static +int +modules_load_walkfiles( + const char *path, + FTS *d, + struct module_file_list **list, + int *length) +{ + // Initialize a cache to store cached security information in. + strhash *cache = strhash_init(511); + if (cache == NULL) { + log_debug("strhash_init(511) error: %s", strerror(errno)); + return errno; + } + + // Walk the results. + while (true) { + errno = 0; + FTSENT *f = fts_read(d); + if (errno != 0) { + log_error( + "Error reading modules directory (%s): %s", + path, + strerror(errno)); + } + + if (f == NULL) { + // End of the file stream with no errors. Clear up the cache and + // return success. + strhash_destroy(cache, NULL); + return 0; + } + + // On recursion fts returns FTS_DC when it returns to a directory. We + // simply ignore this type. + if (f->fts_info == FTS_DP) { + continue; + } + + // Don't bother loading anything that isn't even a file or directory. + if ( (f->fts_info & (FTS_F | FTS_D)) == 0) { + log_debug("Not considering module in non-file: %s\n", f->fts_path); + continue; + } + + // We only load files with the ".irkmod" extension. This ensures that we + // do not accidentally load some unrelated library with a horrible + // _init() function. + if ((f->fts_info & FTS_F) != 0 && + (f->fts_namelen < 7 || + strncmp(f->fts_name + f->fts_namelen - 7, ".irkmod", 7))) { + log_info("Not loading file (%s): bad extension.", f->fts_path); + continue; + } + + // SECURITY CHECKS + if (security_check_path(f->fts_path, cache) != S_OK) { + log_debug("security_check_path(%s) failed.", f->fts_path); + log_error("Can not load module file %s, it is not secure.", f->fts_path); + break; + } + + // Beyond checking permissions we do nothing with directories. + if ( (f->fts_info & FTS_D) != 0) { + continue; + } + + // Attempt to add this file to the list of modules that we will load. + if (modules_load_add(f, list, length) != 0) { + log_error( + "Error reading fts_read() output (%s): %s", + path, + strerror(errno)); + break; + } + } + + // If we have gotten here then there has been an error somewhere. + // Make sure we free the list we allocated, then return NULL. + strhash_destroy(cache, NULL); + free_module_file_list(*list); + return -1; +} + + +/** + Opens the directory and starts walking through files with in it. + + Note: This function should only ever be called form modules_load. + + Arguments: + path: The path to open and read modules from. + list: A pointer to the pointer containing the head of the list. + length: A pointer to an integer containing the length of the list. + + Returns: + 0 on success, anything else on failure. + */ +static +int +modules_load_getlist( + const char *path, + struct module_file_list **head, + int *length) +{ + // Walk through the path structure, returning each file, one by one as + // somewhat complicated data structures. We use this in order to simplify + // path expansion, link following, and to get the stat of the file so we + // can find out if it has been modified and therefor needs updated. + // FTS_LOGICAL = Follow symlinks, return the stat on the destination. + // FTS_NOCHDIR = Do not use chdir during this process. + errno = 0; + // This is a super funky definition that is necessary given how fts_open + // accepts arguments. + char *path_argv[2] = {(char *) path, NULL}; + FTS *d = fts_open(path_argv, (int) (FTS_LOGICAL | FTS_NOCHDIR), NULL); + if (d == NULL) { + log_error( + "Unable to traverse modules directory (%s): %s", + path, + strerror(errno)); + return -1; + } + + if (modules_load_walkfiles(path, d, head, length) != 0) { + log_error( + "Unknown error from modules_load_walkfiles() is preventing loading."); + return -1; + } + + if (fts_close(d)) { + log_error( + "Error closing the modules directory (%s): %s", + path, + strerror(errno)); + } + + return 0; +} + + +int +modules_load( + const char *path, + const module_file **existing_modules, + int *modules_length) +{ + if (path == NULL) { + errno = EINVAL; + return EINVAL; + } + + struct module_file_list *new_list = NULL; + int new_length = 0; + if (modules_load_getlist(path, &new_list, &new_length) != 0) { + // This module actually logs its own errors so we need not attempt to + // log the error here. Instead we just return failure. + return -1; + } + + // FIXME! + struct module_file_list *p = new_list; + while (p != NULL) { + fprintf(stderr, "loaded: %s\n", p->data.filename); + p = p->next; + } + + // TODO + return 0; +} diff --git a/pool/shard003/C/0069018_cmd.c b/pool/shard003/C/0069018_cmd.c new file mode 100644 index 0000000000000000000000000000000000000000..8997bc357659535252d02c71a9994b31d905fa2d --- /dev/null +++ b/pool/shard003/C/0069018_cmd.c @@ -0,0 +1,172 @@ +/** + * \file + * + * + * \brief Implementation of the command protocol between the board and the host + * + * + * \author Giovanni Bajo + * \author Marco Benelli + * \author Bernie Innocenti + * \author Daniele Basile + */ + +#include "cmd.h" +#include "verstag.h" + +#include "hw/hw_input.h" + +#include "cfg/cfg_parser.h" + +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include + +// Define the format string for ADC +#define ADC_FORMAT_STR "dddd" +#define ADC_CHANNEL_NUM 4 + +static Sipo *local_sipo; +static uint8_t reg_status_dout; + + +MAKE_CMD(ver, "", "ddd", +({ + args[1].l = VERS_MAJOR; + args[2].l = VERS_MINOR; + args[3].l = VERS_REV; + 0; +}), 0); + +/* Sleep. Example of declaring function body directly in macro call. */ +MAKE_CMD(sleep, "d", "", +({ + timer_delay((mtime_t)args[1].l); + 0; +}), 0) + +/* Ping. */ +MAKE_CMD(ping, "", "", +({ + //Silence "args not used" warning. + (void)args; + 0; +}), 0) + +/* Dout */ +MAKE_CMD(dout, "d", "", +({ + kfile_putc((uint8_t)args[1].l, &local_sipo->fd); + + //Store status of dout ports. + reg_status_dout = (uint8_t)args[1].l; + 0; +}), 0) + +/* rdout read the status of out ports.*/ +MAKE_CMD(rdout, "", "d", +({ + args[1].l = reg_status_dout; + 0; +}), 0) + + +/* Reset */ +MAKE_CMD(reset, "", "", +({ + //Silence "args not used" warning. + (void)args; + wdt_enable(WDTO_2S); + + /*We want to have an infinite loop that lock access on watchdog timer. + This piece of code it's equivalent to a while(true), but we have done this because + gcc generate a warning message that suggest to use "noreturn" parameter in function reset.*/ + ASSERT(args); + while(args); + 0; + +}), 0) + +/* Din */ +MAKE_CMD(din, "", "d", +({ + args[1].l = INPUT_GET(); + 0; +}), 0) + + +/* Ain */ +MAKE_CMD(ain, "", ADC_FORMAT_STR, +({ + STATIC_ASSERT((sizeof(ADC_FORMAT_STR) - 1) == ADC_CHANNEL_NUM); + for(int i = 0; i < ADC_CHANNEL_NUM; i++) + args[i+1].l = adc_read(i); + + 0; +}), 0) + +/* Beep */ +MAKE_CMD(beep, "d", "", +({ + buz_beep(args[1].l); + 0; +}), 0) + +/* Register commands. */ +void cmd_register(void) +{ + REGISTER_CMD(ver); + REGISTER_CMD(sleep); + REGISTER_CMD(ping); + REGISTER_CMD(dout); + REGISTER_CMD(rdout); + REGISTER_CMD(reset); + REGISTER_CMD(din); + REGISTER_CMD(ain); + REGISTER_CMD(beep); +} + +void cmd_init(Sipo *sipo) +{ + ASSERT(sipo); + local_sipo = sipo; + reg_status_dout = 0; +} diff --git a/pool/shard003/C/0069022_oss-switch.c b/pool/shard003/C/0069022_oss-switch.c new file mode 100644 index 0000000000000000000000000000000000000000..54c3e028515989d322d278e0bde6f27111e2e2c5 --- /dev/null +++ b/pool/shard003/C/0069022_oss-switch.c @@ -0,0 +1,267 @@ +/* + * Copyright (C) 2014 Michal Ratajsky + * + * 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 licence, 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 . + */ + +#include +#include +#include +#include +#include + +#include "oss-common.h" +#include "oss-stream.h" +#include "oss-switch.h" +#include "oss-switch-option.h" + +struct _OssSwitchPrivate +{ + gint fd; + GList *options; +}; + +static void oss_switch_class_init (OssSwitchClass *klass); +static void oss_switch_init (OssSwitch *swtch); +static void oss_switch_dispose (GObject *object); +static void oss_switch_finalize (GObject *object); + +G_DEFINE_TYPE_WITH_PRIVATE (OssSwitch, oss_switch, MATE_MIXER_TYPE_STREAM_SWITCH) + +static gboolean oss_switch_set_active_option (MateMixerSwitch *mms, + MateMixerSwitchOption *mmso); + +static const GList * oss_switch_list_options (MateMixerSwitch *mms); + +static OssSwitchOption *choose_default_option (OssSwitch *swtch); + +static void +oss_switch_class_init (OssSwitchClass *klass) +{ + GObjectClass *object_class; + MateMixerSwitchClass *switch_class; + + object_class = G_OBJECT_CLASS (klass); + object_class->dispose = oss_switch_dispose; + object_class->finalize = oss_switch_finalize; + + switch_class = MATE_MIXER_SWITCH_CLASS (klass); + switch_class->set_active_option = oss_switch_set_active_option; + switch_class->list_options = oss_switch_list_options; +} + +static void +oss_switch_init (OssSwitch *swtch) +{ + swtch->priv = oss_switch_get_instance_private (swtch); +} + +static void +oss_switch_dispose (GObject *object) +{ + OssSwitch *swtch; + + swtch = OSS_SWITCH (object); + + if (swtch->priv->options != NULL) { + g_list_free_full (swtch->priv->options, g_object_unref); + swtch->priv->options = NULL; + } + + G_OBJECT_CLASS (oss_switch_parent_class)->dispose (object); +} + +static void +oss_switch_finalize (GObject *object) +{ + OssSwitch *swtch; + + swtch = OSS_SWITCH (object); + + if (swtch->priv->fd != -1) + close (swtch->priv->fd); + + G_OBJECT_CLASS (oss_switch_parent_class)->finalize (object); +} + +OssSwitch * +oss_switch_new (OssStream *stream, + const gchar *name, + const gchar *label, + gint fd, + GList *options) +{ + OssSwitch *swtch; + gint newfd; + + g_return_val_if_fail (OSS_IS_STREAM (stream), NULL); + g_return_val_if_fail (name != NULL, NULL); + g_return_val_if_fail (label != NULL, NULL); + g_return_val_if_fail (options != NULL, NULL); + + newfd = dup (fd); + if (newfd == -1) { + g_warning ("Failed to duplicate file descriptor: %s", + g_strerror (errno)); + return NULL; + } + + swtch = g_object_new (OSS_TYPE_SWITCH, + "name", name, + "label", label, + "role", MATE_MIXER_STREAM_SWITCH_ROLE_PORT, + "stream", stream, + NULL); + + /* Takes ownership of options */ + swtch->priv->fd = newfd; + swtch->priv->options = options; + + return swtch; +} + +void +oss_switch_load (OssSwitch *swtch) +{ + OssSwitchOption *option; + gint recsrc; + gint ret; + + g_return_if_fail (OSS_IS_SWITCH (swtch)); + + if (G_UNLIKELY (swtch->priv->fd == -1)) + return; + + /* Recsrc contains a bitmask of currently enabled recording sources */ + ret = ioctl (swtch->priv->fd, MIXER_READ (SOUND_MIXER_RECSRC), &recsrc); + if (ret == -1) + return; + + if (recsrc != 0) { + GList *list = swtch->priv->options; + + /* Find out which option is currently selected */ + while (list != NULL) { + gint devnum; + + option = OSS_SWITCH_OPTION (list->data); + devnum = oss_switch_option_get_devnum (option); + + if (recsrc & (1 << devnum)) { + /* It is possible that some hardware might allow and have more recording + * sources active at the same time, but we only support one active + * source at a time */ + _mate_mixer_switch_set_active_option (MATE_MIXER_SWITCH (swtch), + MATE_MIXER_SWITCH_OPTION (option)); + return; + } + list = list->next; + } + + g_debug ("Switch %s has an unknown device as the active option", + mate_mixer_switch_get_name (MATE_MIXER_SWITCH (swtch))); + + /* OSS shouldn't let a non-record device be selected, let's step in and select + * something reasonable instead... */ + } else { + g_debug ("Switch %s has no active device", + mate_mixer_switch_get_name (MATE_MIXER_SWITCH (swtch))); + + /* According to the OSS Programmer's Guide, if the recsrc value is 0, the + * microphone will be selected implicitly. + * Let's not assume that's true everywhere and select something explicitly... */ + } + + option = choose_default_option (swtch); + + g_debug ("Selecting default device %s as active for switch %s", + mate_mixer_switch_option_get_name (MATE_MIXER_SWITCH_OPTION (option)), + mate_mixer_switch_get_name (MATE_MIXER_SWITCH (swtch))); + + if (mate_mixer_switch_set_active_option (MATE_MIXER_SWITCH (swtch), + MATE_MIXER_SWITCH_OPTION (option)) == FALSE) { + g_debug ("Failed to set the default device, assuming it is selected anyway"); + + _mate_mixer_switch_set_active_option (MATE_MIXER_SWITCH (swtch), + MATE_MIXER_SWITCH_OPTION (option)); + } +} + +void +oss_switch_close (OssSwitch *swtch) +{ + g_return_if_fail (OSS_IS_SWITCH (swtch)); + + if (swtch->priv->fd == -1) + return; + + close (swtch->priv->fd); + swtch->priv->fd = -1; +} + +static gboolean +oss_switch_set_active_option (MateMixerSwitch *mms, MateMixerSwitchOption *mmso) +{ + OssSwitch *swtch; + gint ret; + gint recsrc; + + g_return_val_if_fail (OSS_IS_SWITCH (mms), FALSE); + g_return_val_if_fail (OSS_IS_SWITCH_OPTION (mmso), FALSE); + + swtch = OSS_SWITCH (mms); + + if (G_UNLIKELY (swtch->priv->fd == -1)) + return FALSE; + + recsrc = 1 << oss_switch_option_get_devnum (OSS_SWITCH_OPTION (mmso)); + + ret = ioctl (swtch->priv->fd, MIXER_WRITE (SOUND_MIXER_RECSRC), &recsrc); + if (ret == -1) + return FALSE; + + return TRUE; +} + +static const GList * +oss_switch_list_options (MateMixerSwitch *mms) +{ + g_return_val_if_fail (OSS_IS_SWITCH (mms), NULL); + + return OSS_SWITCH (mms)->priv->options; +} + +#define OSS_SWITCH_PREFERRED_DEFAULT_DEVNUM 7 /* Microphone */ + +static OssSwitchOption * +choose_default_option (OssSwitch *swtch) +{ + GList *list = swtch->priv->options; + + /* Search for the preferred device */ + while (list != NULL) { + OssSwitchOption *option; + gint devnum; + + option = OSS_SWITCH_OPTION (list->data); + devnum = oss_switch_option_get_devnum (option); + + if (devnum == OSS_SWITCH_PREFERRED_DEFAULT_DEVNUM) + return option; + + list = list->next; + } + /* If the preferred device is not present, use the first available one */ + return OSS_SWITCH_OPTION (swtch->priv->options->data); +} diff --git a/pool/shard003/C/0069024_glcore_driver.c b/pool/shard003/C/0069024_glcore_driver.c new file mode 100644 index 0000000000000000000000000000000000000000..25778160419548ee02b3ad097e786e4a551cd88e --- /dev/null +++ b/pool/shard003/C/0069024_glcore_driver.c @@ -0,0 +1,128 @@ +/* + * Copyright 2006 Red Hat, Inc. + * + * 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 + * on the rights to use, copy, modify, merge, publish, distribute, sub + * license, 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 (including the next + * paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS 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. + */ + +/* + * This implements a software-only "DRI" driver. It doesn't actually speak + * any DRI protocol or talk to the DRM, it just looks enough like a DRI driver + * that libglx in the server can load it for software rendering in the + * unaccelerated case. + */ + +static GLboolean +glcoreInitDriver(__DRIscreenPrivate *driScreenPriv) +{ +} + +static void +glcoreDestroyScreen(__DRIScreenPrivate *driScreenPriv) +{ +} + +static GLboolean +glcoreCreateContext(const __GLcontextModes *glVisual, + __DRIcontextPrivate *driContextPriv, + void *shared_context) +{ +} + +static void +glcoreDestroyContext(__DRIcontextPrivate *driContextPriv) +{ +} + +static GLboolean +glcoreCreateBuffer(__DRIscreenPrivate *driScreenPriv, + __DRIdrawablePrivate *driDrawablePriv, + const __GLcontextModes *mesaVisual, + GLboolean isPixmap) +{ +} + +static void +glcoreDestroyBuffer(__DRIdrawablePrivate *driDrawablePriv) +{ +} + +static void +glcoreSwapBuffers(__DRIdrawablePrivate *driDrawablePriv) +{ +} + +static GLboolean +glcoreMakeCurrent(__DRIcontextPrivate *driContextPriv, + __DRIdrawablePrivate *driDrawablePriv, + __DRIdrawablePrivate *driReadablePriv) +{ +} + +static GLboolean +glcoreUnbindContext(__DRIcontextPrivate *driContextPriv) +{ +} + +static struct __DriverAPIRec glcore_api = { + .InitDriver = glcoreInitDriver, + .DestroyScreen = glcoreDestroyScreen, + .CreateContext = glcoreCreateContext, + .DestroyContext = glcoreDestroyContext, + .CreateBuffer = glcoreCreateBuffer, + .DestroyBuffer = glcoreDestroyBuffer, + .SwapBuffers = glcoreSwapBuffers, + .MakeCurrent = glcoreMakeCurrent, + .UnbindContext = glcoreUnbindContext, +}; + +static __GLcontextModes * +glcoreFillInModes(unsigned pixel_bits) +{ +} + +PUBLIC void * +__driCreateNewScreen_20050727(__DRInativeDisplay *dpy, int scrn, + __DRIscreen *psc, const __GLcontextModes *modes, + const __DRIversion *ddx_version, + const __DRIversion *dri_version, + const __DRIversion *drm_version, + const __DRIframebuffer *fb, drmAddress pSarea, + int fd, int internal_api_version, + const ___DRIinterfaceMethods *interface, + __GLcontextModes **driver_modes) +{ + __DRIscreenPrivate *driScreenPriv; + glcoreDriverPrivate *glcoreDriverPriv; + + /* would normally check ddx/dri/drm versions here */ + + driScreenPriv = __driUtilCreateNewScreen(dpy, scrn, psc, NULL, ddx_version, + dri_version, drm_version, fb, + internal_api_version, &glcore_api); + if (!driScreenPriv) + return NULL; + + glcoreDriverPriv = driScreenPriv->pDrvPriv; + + *driver_modes = glcoreFillInModes(glcoreDriverPriv->bpp); + + driInitExtensions(NULL, NULL, GL_FALSE); + + return driScreenPriv; +} diff --git a/pool/shard003/C/0069029_proresdsp_init.c b/pool/shard003/C/0069029_proresdsp_init.c new file mode 100644 index 0000000000000000000000000000000000000000..91ff2575648bc52fb4b5551929db2e5915031a67 --- /dev/null +++ b/pool/shard003/C/0069029_proresdsp_init.c @@ -0,0 +1,57 @@ +/* + * Apple ProRes compatible decoder + * + * Copyright (c) 2010-2011 Maxim Poliakovski + * + * This file is part of FFmpeg. + * + * FFmpeg 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. + * + * FFmpeg 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 FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "libavutil/x86/cpu.h" +#include "libavcodec/dsputil.h" +#include "libavcodec/proresdsp.h" + +void ff_prores_idct_put_10_sse2(uint16_t *dst, int linesize, + int16_t *block, const int16_t *qmat); +void ff_prores_idct_put_10_sse4(uint16_t *dst, int linesize, + int16_t *block, const int16_t *qmat); +void ff_prores_idct_put_10_avx (uint16_t *dst, int linesize, + int16_t *block, const int16_t *qmat); + +void ff_proresdsp_x86_init(ProresDSPContext *dsp, AVCodecContext *avctx) +{ +#if ARCH_X86_64 + int flags = av_get_cpu_flags(); + + if(avctx->flags & CODEC_FLAG_BITEXACT) + return; + + if (EXTERNAL_SSE2(flags)) { + dsp->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM; + dsp->idct_put = ff_prores_idct_put_10_sse2; + } + + if (EXTERNAL_SSE4(flags)) { + dsp->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM; + dsp->idct_put = ff_prores_idct_put_10_sse4; + } + + if (EXTERNAL_AVX(flags)) { + dsp->idct_permutation_type = FF_TRANSPOSE_IDCT_PERM; + dsp->idct_put = ff_prores_idct_put_10_avx; + } +#endif /* ARCH_X86_64 */ +} diff --git a/pool/shard003/C/0069035_inode.c b/pool/shard003/C/0069035_inode.c new file mode 100644 index 0000000000000000000000000000000000000000..0a88917605aee65bf36b9314d24f5094a94c5eeb --- /dev/null +++ b/pool/shard003/C/0069035_inode.c @@ -0,0 +1,246 @@ +/* + * Resizable simple ram filesystem for Linux. + * + * Copyright (C) 2000 Linus Torvalds. + * 2000 Transmeta Corp. + * + * Usage limits added by David Gibson, Linuxcare Australia. + * This file is released under the GPL. + */ + +/* + * NOTE! This filesystem is probably most useful + * not as a real filesystem, but as an example of + * how virtual filesystems can be written. + * + * It doesn't get much simpler than this. Consider + * that this file implements the full semantics of + * a POSIX-compliant read-write filesystem. + * + * Note in particular how the filesystem does not + * need to implement any data structures of its own + * to keep track of the virtual data: using the VFS + * caches is sufficient. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +/* some random number */ +#define RAMFS_MAGIC 0x858458f6 + +static struct super_operations ramfs_ops; +static struct address_space_operations ramfs_aops; +static struct inode_operations ramfs_file_inode_operations; +static struct inode_operations ramfs_dir_inode_operations; + +static struct backing_dev_info ramfs_backing_dev_info = { + .ra_pages = 0, /* No readahead */ + .capabilities = BDI_CAP_NO_ACCT_DIRTY | BDI_CAP_NO_WRITEBACK | + BDI_CAP_MAP_DIRECT | BDI_CAP_MAP_COPY | + BDI_CAP_READ_MAP | BDI_CAP_WRITE_MAP | BDI_CAP_EXEC_MAP, +}; + +struct inode *ramfs_get_inode(struct super_block *sb, int mode, dev_t dev) +{ + struct inode * inode = new_inode(sb); + + if (inode) { + inode->i_mode = mode; + inode->i_uid = current->fsuid; + inode->i_gid = current->fsgid; + inode->i_blksize = PAGE_CACHE_SIZE; + inode->i_blocks = 0; + inode->i_mapping->a_ops = &ramfs_aops; + inode->i_mapping->backing_dev_info = &ramfs_backing_dev_info; + inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME; + switch (mode & S_IFMT) { + default: + init_special_inode(inode, mode, dev); + break; + case S_IFREG: + inode->i_op = &ramfs_file_inode_operations; + inode->i_fop = &ramfs_file_operations; + break; + case S_IFDIR: + inode->i_op = &ramfs_dir_inode_operations; + inode->i_fop = &simple_dir_operations; + + /* directory inodes start off with i_nlink == 2 (for "." entry) */ + inode->i_nlink++; + break; + case S_IFLNK: + inode->i_op = &page_symlink_inode_operations; + break; + } + } + return inode; +} + +/* + * File creation. Allocate an inode, and we're done.. + */ +/* SMP-safe */ +static int +ramfs_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev) +{ + struct inode * inode = ramfs_get_inode(dir->i_sb, mode, dev); + int error = -ENOSPC; + + if (inode) { + if (dir->i_mode & S_ISGID) { + inode->i_gid = dir->i_gid; + if (S_ISDIR(mode)) + inode->i_mode |= S_ISGID; + } + d_instantiate(dentry, inode); + dget(dentry); /* Extra count - pin the dentry in core */ + error = 0; + } + return error; +} + +static int ramfs_mkdir(struct inode * dir, struct dentry * dentry, int mode) +{ + int retval = ramfs_mknod(dir, dentry, mode | S_IFDIR, 0); + if (!retval) + dir->i_nlink++; + return retval; +} + +static int ramfs_create(struct inode *dir, struct dentry *dentry, int mode, struct nameidata *nd) +{ + return ramfs_mknod(dir, dentry, mode | S_IFREG, 0); +} + +static int ramfs_symlink(struct inode * dir, struct dentry *dentry, const char * symname) +{ + struct inode *inode; + int error = -ENOSPC; + + inode = ramfs_get_inode(dir->i_sb, S_IFLNK|S_IRWXUGO, 0); + if (inode) { + int l = strlen(symname)+1; + error = page_symlink(inode, symname, l); + if (!error) { + if (dir->i_mode & S_ISGID) + inode->i_gid = dir->i_gid; + d_instantiate(dentry, inode); + dget(dentry); + } else + iput(inode); + } + return error; +} + +static struct address_space_operations ramfs_aops = { + .readpage = simple_readpage, + .prepare_write = simple_prepare_write, + .commit_write = simple_commit_write +}; + +struct file_operations ramfs_file_operations = { + .read = generic_file_read, + .write = generic_file_write, + .mmap = generic_file_mmap, + .fsync = simple_sync_file, + .sendfile = generic_file_sendfile, + .llseek = generic_file_llseek, +}; + +static struct inode_operations ramfs_file_inode_operations = { + .getattr = simple_getattr, +}; + +static struct inode_operations ramfs_dir_inode_operations = { + .create = ramfs_create, + .lookup = simple_lookup, + .link = simple_link, + .unlink = simple_unlink, + .symlink = ramfs_symlink, + .mkdir = ramfs_mkdir, + .rmdir = simple_rmdir, + .mknod = ramfs_mknod, + .rename = simple_rename, +}; + +static struct super_operations ramfs_ops = { + .statfs = simple_statfs, + .drop_inode = generic_delete_inode, +}; + +static int ramfs_fill_super(struct super_block * sb, void * data, int silent) +{ + struct inode * inode; + struct dentry * root; + + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_blocksize = PAGE_CACHE_SIZE; + sb->s_blocksize_bits = PAGE_CACHE_SHIFT; + sb->s_magic = RAMFS_MAGIC; + sb->s_op = &ramfs_ops; + sb->s_time_gran = 1; + inode = ramfs_get_inode(sb, S_IFDIR | 0755, 0); + if (!inode) + return -ENOMEM; + + root = d_alloc_root(inode); + if (!root) { + iput(inode); + return -ENOMEM; + } + sb->s_root = root; + return 0; +} + +struct super_block *ramfs_get_sb(struct file_system_type *fs_type, + int flags, const char *dev_name, void *data) +{ + return get_sb_nodev(fs_type, flags, data, ramfs_fill_super); +} + +static struct super_block *rootfs_get_sb(struct file_system_type *fs_type, + int flags, const char *dev_name, void *data) +{ + return get_sb_nodev(fs_type, flags|MS_NOUSER, data, ramfs_fill_super); +} + +static struct file_system_type ramfs_fs_type = { + .name = "ramfs", + .get_sb = ramfs_get_sb, + .kill_sb = kill_litter_super, +}; +static struct file_system_type rootfs_fs_type = { + .name = "rootfs", + .get_sb = rootfs_get_sb, + .kill_sb = kill_litter_super, +}; + +static int __init init_ramfs_fs(void) +{ + return register_filesystem(&ramfs_fs_type); +} + +static void __exit exit_ramfs_fs(void) +{ + unregister_filesystem(&ramfs_fs_type); +} + +module_init(init_ramfs_fs) +module_exit(exit_ramfs_fs) + +int __init init_rootfs(void) +{ + return register_filesystem(&rootfs_fs_type); +} + +MODULE_LICENSE("GPL"); diff --git a/pool/shard003/C/0069040_sbinfo.c b/pool/shard003/C/0069040_sbinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..7af9bee0e4473b5d880b835e6b05d7e1d6538eb6 --- /dev/null +++ b/pool/shard003/C/0069040_sbinfo.c @@ -0,0 +1,272 @@ +/* + * Copyright (C) 2005-2010 Junjiro R. Okajima + * + * This program, aufs 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 + */ + +/* + * superblock private data + */ + +#include +#include "aufs.h" + +/* + * they are necessary regardless sysfs is disabled. + */ +void au_si_free(struct kobject *kobj) +{ + struct au_sbinfo *sbinfo; + struct super_block *sb; + char *locked __maybe_unused; /* debug only */ + + sbinfo = container_of(kobj, struct au_sbinfo, si_kobj); + AuDebugOn(!list_empty(&sbinfo->si_plink.head)); + AuDebugOn(sbinfo->si_plink_maint); + + sb = sbinfo->si_sb; + si_write_lock(sb); + au_xino_clr(sb); + au_br_free(sbinfo); + si_write_unlock(sb); + + AuDebugOn(radix_tree_gang_lookup + (&sbinfo->au_si_pid.tree, (void **)&locked, + /*first_index*/PID_MAX_DEFAULT - 1, + /*max_items*/sizeof(locked)/sizeof(*locked))); + + kfree(sbinfo->si_branch); + kfree(sbinfo->au_si_pid.bitmap); + mutex_destroy(&sbinfo->si_xib_mtx); + AuRwDestroy(&sbinfo->si_rwsem); + + kfree(sbinfo); +} + +int au_si_alloc(struct super_block *sb) +{ + int err; + struct au_sbinfo *sbinfo; + static struct lock_class_key aufs_si; + + err = -ENOMEM; + sbinfo = kzalloc(sizeof(*sbinfo), GFP_NOFS); + if (unlikely(!sbinfo)) + goto out; + + BUILD_BUG_ON(sizeof(unsigned long) != + sizeof(*sbinfo->au_si_pid.bitmap)); + sbinfo->au_si_pid.bitmap = kcalloc(BITS_TO_LONGS(PID_MAX_DEFAULT), + sizeof(*sbinfo->au_si_pid.bitmap), + GFP_NOFS); + if (unlikely(!sbinfo->au_si_pid.bitmap)) + goto out_sbinfo; + + /* will be reallocated separately */ + sbinfo->si_branch = kzalloc(sizeof(*sbinfo->si_branch), GFP_NOFS); + if (unlikely(!sbinfo->si_branch)) + goto out_pidmap; + + err = sysaufs_si_init(sbinfo); + if (unlikely(err)) + goto out_br; + + au_nwt_init(&sbinfo->si_nowait); + au_rw_init_wlock(&sbinfo->si_rwsem); + au_rw_class(&sbinfo->si_rwsem, &aufs_si); + spin_lock_init(&sbinfo->au_si_pid.tree_lock); + INIT_RADIX_TREE(&sbinfo->au_si_pid.tree, GFP_ATOMIC | __GFP_NOFAIL); + + sbinfo->si_bend = -1; + + sbinfo->si_wbr_copyup = AuWbrCopyup_Def; + sbinfo->si_wbr_create = AuWbrCreate_Def; + sbinfo->si_wbr_copyup_ops = au_wbr_copyup_ops + sbinfo->si_wbr_copyup; + sbinfo->si_wbr_create_ops = au_wbr_create_ops + sbinfo->si_wbr_create; + + sbinfo->si_mntflags = AuOpt_Def; + + mutex_init(&sbinfo->si_xib_mtx); + sbinfo->si_xino_brid = -1; + /* leave si_xib_last_pindex and si_xib_next_bit */ + + sbinfo->si_rdcache = msecs_to_jiffies(AUFS_RDCACHE_DEF * MSEC_PER_SEC); + sbinfo->si_rdblk = AUFS_RDBLK_DEF; + sbinfo->si_rdhash = AUFS_RDHASH_DEF; + sbinfo->si_dirwh = AUFS_DIRWH_DEF; + + au_spl_init(&sbinfo->si_plink); + init_waitqueue_head(&sbinfo->si_plink_wq); + spin_lock_init(&sbinfo->si_plink_maint_lock); + + /* leave other members for sysaufs and si_mnt. */ + sbinfo->si_sb = sb; + sb->s_fs_info = sbinfo; + si_pid_set(sb); + au_debug_sbinfo_init(sbinfo); + return 0; /* success */ + +out_br: + kfree(sbinfo->si_branch); +out_pidmap: + kfree(sbinfo->au_si_pid.bitmap); +out_sbinfo: + kfree(sbinfo); +out: + return err; +} + +int au_sbr_realloc(struct au_sbinfo *sbinfo, int nbr) +{ + int err, sz; + struct au_branch **brp; + + AuRwMustWriteLock(&sbinfo->si_rwsem); + + err = -ENOMEM; + sz = sizeof(*brp) * (sbinfo->si_bend + 1); + if (unlikely(!sz)) + sz = sizeof(*brp); + brp = au_kzrealloc(sbinfo->si_branch, sz, sizeof(*brp) * nbr, GFP_NOFS); + if (brp) { + sbinfo->si_branch = brp; + err = 0; + } + + return err; +} + +/* ---------------------------------------------------------------------- */ + +unsigned int au_sigen_inc(struct super_block *sb) +{ + unsigned int gen; + + SiMustWriteLock(sb); + + gen = ++au_sbi(sb)->si_generation; + au_update_digen(sb->s_root); + au_update_iigen(sb->s_root->d_inode); + sb->s_root->d_inode->i_version++; + return gen; +} + +aufs_bindex_t au_new_br_id(struct super_block *sb) +{ + aufs_bindex_t br_id; + int i; + struct au_sbinfo *sbinfo; + + SiMustWriteLock(sb); + + sbinfo = au_sbi(sb); + for (i = 0; i <= AUFS_BRANCH_MAX; i++) { + br_id = ++sbinfo->si_last_br_id; + if (br_id && au_br_index(sb, br_id) < 0) + return br_id; + } + + return -1; +} + +/* ---------------------------------------------------------------------- */ + +/* dentry and super_block lock. call at entry point */ +void aufs_read_lock(struct dentry *dentry, int flags) +{ + si_read_lock(dentry->d_sb, flags); + if (au_ftest_lock(flags, DW)) + di_write_lock_child(dentry); + else + di_read_lock_child(dentry, flags); +} + +void aufs_read_unlock(struct dentry *dentry, int flags) +{ + if (au_ftest_lock(flags, DW)) + di_write_unlock(dentry); + else + di_read_unlock(dentry, flags); + si_read_unlock(dentry->d_sb); +} + +void aufs_write_lock(struct dentry *dentry) +{ + si_write_lock(dentry->d_sb); + di_write_lock_child(dentry); +} + +void aufs_write_unlock(struct dentry *dentry) +{ + di_write_unlock(dentry); + si_write_unlock(dentry->d_sb); +} + +void aufs_read_and_write_lock2(struct dentry *d1, struct dentry *d2, int flags) +{ + si_read_lock(d1->d_sb, flags); + di_write_lock2_child(d1, d2, au_ftest_lock(flags, DIR)); +} + +void aufs_read_and_write_unlock2(struct dentry *d1, struct dentry *d2) +{ + di_write_unlock2(d1, d2); + si_read_unlock(d1->d_sb); +} + +/* ---------------------------------------------------------------------- */ + +int si_pid_test_slow(struct super_block *sb) +{ + void *p; + + rcu_read_lock(); + p = radix_tree_lookup(&au_sbi(sb)->au_si_pid.tree, current->pid); + rcu_read_unlock(); + + return (long)p; +} + +void si_pid_set_slow(struct super_block *sb) +{ + int err; + struct au_sbinfo *sbinfo; + + AuDebugOn(si_pid_test_slow(sb)); + + sbinfo = au_sbi(sb); + err = radix_tree_preload(GFP_NOFS | __GFP_NOFAIL); + AuDebugOn(err); + spin_lock(&sbinfo->au_si_pid.tree_lock); + err = radix_tree_insert(&sbinfo->au_si_pid.tree, current->pid, + (void *)1); + spin_unlock(&sbinfo->au_si_pid.tree_lock); + AuDebugOn(err); + radix_tree_preload_end(); +} + +void si_pid_clr_slow(struct super_block *sb) +{ + void *p; + struct au_sbinfo *sbinfo; + + AuDebugOn(!si_pid_test_slow(sb)); + + sbinfo = au_sbi(sb); + spin_lock(&sbinfo->au_si_pid.tree_lock); + p = radix_tree_delete(&sbinfo->au_si_pid.tree, current->pid); + spin_unlock(&sbinfo->au_si_pid.tree_lock); + AuDebugOn(1 != (long)p); +} diff --git a/pool/shard003/C/0069047_test-malloc.c b/pool/shard003/C/0069047_test-malloc.c new file mode 100644 index 0000000000000000000000000000000000000000..e8b9380ea7075ae160e6470b5385f4ce3c55e9f0 --- /dev/null +++ b/pool/shard003/C/0069047_test-malloc.c @@ -0,0 +1,38 @@ +#include +#include +#include +#include + +int main(int argc, char* argv[]) +{ + uint8_t* mallocme, *mallocme2, *mallocme3; + fprintf(stdout, "-- malloc test by Wolfgang Richter --" + "\n"); + + mallocme = malloc(4096); + mallocme2 = malloc(4096); + mallocme3 = malloc(4096); + + memset(mallocme, 0, 4096); + memset(mallocme2, 0xff, 4096); + memset(mallocme3, 0xee, 4096); + + free(mallocme); + free(mallocme2); + free(mallocme3); + + mallocme = malloc(4096); + mallocme2 = malloc(4096); + mallocme3 = malloc(4096); + + memset(mallocme, 0, 4096); + memset(mallocme2, 0xff, 4096); + memset(mallocme3, 0xee, 4096); + + free(mallocme3); + free(mallocme2); + free(mallocme); + + + return EXIT_SUCCESS; +} diff --git a/pool/shard003/C/0069060_maq2sam.c b/pool/shard003/C/0069060_maq2sam.c new file mode 100644 index 0000000000000000000000000000000000000000..2645f7328620c76d249d4bf5ccb74d24f6522d8c --- /dev/null +++ b/pool/shard003/C/0069060_maq2sam.c @@ -0,0 +1,197 @@ +/* maq2sam.c -- convert MAQ output to SAM. + + Copyright (C) 2008, 2009 Genome Research Ltd. + + Author: Heng Li + +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 +#include +#include + +#define PACKAGE_VERSION "r439" + +//#define MAQ_LONGREADS + +#ifdef MAQ_LONGREADS +# define MAX_READLEN 128 +#else +# define MAX_READLEN 64 +#endif + +#define MAX_NAMELEN 36 +#define MAQMAP_FORMAT_OLD 0 +#define MAQMAP_FORMAT_NEW -1 + +#define PAIRFLAG_FF 0x01 +#define PAIRFLAG_FR 0x02 +#define PAIRFLAG_RF 0x04 +#define PAIRFLAG_RR 0x08 +#define PAIRFLAG_PAIRED 0x10 +#define PAIRFLAG_DIFFCHR 0x20 +#define PAIRFLAG_NOMATCH 0x40 +#define PAIRFLAG_SW 0x80 + +typedef struct +{ + uint8_t seq[MAX_READLEN]; /* the last base is the single-end mapping quality. */ + uint8_t size, map_qual, info1, info2, c[2], flag, alt_qual; + uint32_t seqid, pos; + int dist; + char name[MAX_NAMELEN]; +} maqmap1_t; + +typedef struct +{ + int format, n_ref; + char **ref_name; + uint64_t n_mapped_reads; + maqmap1_t *mapped_reads; +} maqmap_t; + +maqmap_t *maq_new_maqmap(void) +{ + maqmap_t *mm = (maqmap_t*)calloc(1, sizeof(maqmap_t)); + mm->format = MAQMAP_FORMAT_NEW; + return mm; +} +void maq_delete_maqmap(maqmap_t *mm) +{ + int i; + if (mm == 0) return; + for (i = 0; i < mm->n_ref; ++i) + free(mm->ref_name[i]); + free(mm->ref_name); + free(mm->mapped_reads); + free(mm); +} +maqmap_t *maqmap_read_header(gzFile fp) +{ + maqmap_t *mm; + int k, len; + mm = maq_new_maqmap(); + gzread(fp, &mm->format, sizeof(int)); + if (mm->format != MAQMAP_FORMAT_NEW) { + if (mm->format > 0) { + fprintf(stderr, "** Obsolete map format is detected. Please use 'mapass2maq' command to convert the format.\n"); + exit(3); + } + assert(mm->format == MAQMAP_FORMAT_NEW); + } + gzread(fp, &mm->n_ref, sizeof(int)); + mm->ref_name = (char**)calloc(mm->n_ref, sizeof(char*)); + for (k = 0; k != mm->n_ref; ++k) { + gzread(fp, &len, sizeof(int)); + mm->ref_name[k] = (char*)malloc(len * sizeof(char)); + gzread(fp, mm->ref_name[k], len); + } + /* read number of mapped reads */ + gzread(fp, &mm->n_mapped_reads, sizeof(uint64_t)); + return mm; +} + +void maq2tam_core(gzFile fp, const char *rg) +{ + maqmap_t *mm; + maqmap1_t mm1, *m1; + int ret; + m1 = &mm1; + mm = maqmap_read_header(fp); + while ((ret = gzread(fp, m1, sizeof(maqmap1_t))) == sizeof(maqmap1_t)) { + int j, flag = 0, se_mapq = m1->seq[MAX_READLEN-1]; + if (m1->flag) flag |= 1; + if ((m1->flag&PAIRFLAG_PAIRED) || ((m1->flag&PAIRFLAG_SW) && m1->flag != 192)) flag |= 2; + if (m1->flag == 192) flag |= 4; + if (m1->flag == 64) flag |= 8; + if (m1->pos&1) flag |= 0x10; + if ((flag&1) && m1->dist != 0) { + int c; + if (m1->dist > 0) { + if (m1->flag&(PAIRFLAG_FF|PAIRFLAG_RF)) c = 0; + else if (m1->flag&(PAIRFLAG_FR|PAIRFLAG_RR)) c = 1; + else c = m1->pos&1; + } else { + if (m1->flag&(PAIRFLAG_FF|PAIRFLAG_FR)) c = 0; + else if (m1->flag&(PAIRFLAG_RF|PAIRFLAG_RR)) c = 1; + else c = m1->pos&1; + } + if (c) flag |= 0x20; + } + if (m1->flag) { + int l = strlen(m1->name); + if (m1->name[l-2] == '/') { + flag |= (m1->name[l-1] == '1')? 0x40 : 0x80; + m1->name[l-2] = '\0'; + } + } + printf("%s\t%d\t", m1->name, flag); + printf("%s\t%d\t", mm->ref_name[m1->seqid], (m1->pos>>1)+1); + if (m1->flag == 130) { + int c = (int8_t)m1->seq[MAX_READLEN-1]; + printf("%d\t", m1->alt_qual); + if (c == 0) printf("%dM\t", m1->size); + else { + if (c > 0) printf("%dM%dI%dM\t", m1->map_qual, c, m1->size - m1->map_qual - c); + else printf("%dM%dD%dM\t", m1->map_qual, -c, m1->size - m1->map_qual); + } + se_mapq = 0; // zero SE mapQ for reads aligned by SW + } else { + if (flag&4) printf("0\t*\t"); + else printf("%d\t%dM\t", m1->map_qual, m1->size); + } + printf("*\t0\t%d\t", m1->dist); + for (j = 0; j != m1->size; ++j) { + if (m1->seq[j] == 0) putchar('N'); + else putchar("ACGT"[m1->seq[j]>>6&3]); + } + putchar('\t'); + for (j = 0; j != m1->size; ++j) + putchar((m1->seq[j]&0x3f) + 33); + putchar('\t'); + if (rg) printf("RG:Z:%s\t", rg); + if (flag&4) { // unmapped + printf("MF:i:%d\n", m1->flag); + } else { + printf("MF:i:%d\t", m1->flag); + if (m1->flag) printf("AM:i:%d\tSM:i:%d\t", m1->alt_qual, se_mapq); + printf("NM:i:%d\tUQ:i:%d\tH0:i:%d\tH1:i:%d\n", m1->info1&0xf, m1->info2, m1->c[0], m1->c[1]); + } + } + if (ret > 0) + fprintf(stderr, "Truncated! Continue anyway.\n"); + maq_delete_maqmap(mm); +} + +int main(int argc, char *argv[]) +{ + gzFile fp; + if (argc == 1) { + fprintf(stderr, "Version: %s\n", PACKAGE_VERSION); + fprintf(stderr, "Usage: maq2sam []\n"); + return 1; + } + fp = strcmp(argv[1], "-")? gzopen(argv[1], "r") : gzdopen(fileno(stdin), "r"); + maq2tam_core(fp, argc > 2? argv[2] : 0); + gzclose(fp); + return 0; +} diff --git a/pool/shard003/C/0069061_combobox.c b/pool/shard003/C/0069061_combobox.c new file mode 100644 index 0000000000000000000000000000000000000000..9e22c42cf893d23d78462d8563eead5451529324 --- /dev/null +++ b/pool/shard003/C/0069061_combobox.c @@ -0,0 +1,259 @@ +#include +#include +#include + +static rt_bool_t rtgui_combobox_pulldown_hide(struct rtgui_widget* widget, struct rtgui_event* event); +const static rt_uint8_t down_arrow[] = {0xff, 0x7e, 0x3c, 0x18}; + +static void _rtgui_combobox_constructor(rtgui_combobox_t *box) +{ + rtgui_rect_t rect = {0, 0, RTGUI_COMBOBOX_WIDTH, RTGUI_COMBOBOX_HEIGHT}; + + /* init widget and set event handler */ + rtgui_widget_set_event_handler(RTGUI_WIDGET(box), rtgui_combobox_event_handler); + rtgui_widget_set_rect(RTGUI_WIDGET(box), &rect); + + RTGUI_WIDGET_TEXTALIGN(RTGUI_WIDGET(box)) = RTGUI_ALIGN_CENTER_VERTICAL; + + box->pd_pressed = RT_FALSE; + box->current_item = 0; + box->on_selected = RT_NULL; + box->pd_win = RT_NULL; +} + +static void _rtgui_combobox_destructor(rtgui_combobox_t *box) +{ + /* destroy pull down window */ + rtgui_win_destroy(box->pd_win); + + /* reset box field */ + box->pd_win = RT_NULL; +} + +void rtgui_combobox_pdwin_onitem(struct rtgui_widget* widget, struct rtgui_event* event) +{ + rtgui_win_t* pd_win; + rtgui_combobox_t* combo; + rtgui_listbox_t* list; + + list = RTGUI_LISTBOX(widget); + pd_win = RTGUI_WIN(rtgui_widget_get_toplevel(widget)); + combo = RTGUI_COMBOBOX(pd_win->user_data); + combo->current_item = list->current_item; + + if (combo->on_selected != RT_NULL) + combo->on_selected(RTGUI_WIDGET(combo), RT_NULL); + + rtgui_win_hiden(pd_win); + rtgui_widget_update(RTGUI_WIDGET(combo)); + + return ; +} + +rt_bool_t rtgui_combobox_pdwin_ondeactive(struct rtgui_widget* widget, struct rtgui_event* event) +{ + rtgui_win_hiden(RTGUI_WIN(widget)); + return RT_TRUE; +} + +DEFINE_CLASS_TYPE(combobox, "combobox", + RTGUI_WIDGET_TYPE, + _rtgui_combobox_constructor, + _rtgui_combobox_destructor, + sizeof(struct rtgui_combobox)); + +rtgui_combobox_t *rtgui_combobox_create(struct rtgui_listbox_item* items, rt_uint16_t count, struct rtgui_rect* rect) +{ + rtgui_combobox_t *box; + + box = (rtgui_combobox_t*)rtgui_widget_create(RTGUI_COMBOBOX_TYPE); + box->items_count = count; + box->items = items; + rtgui_widget_set_rect(RTGUI_WIDGET(box), rect); + + box->pd_win = RT_NULL; + + return box; +} + +void rtgui_combobox_destroy(rtgui_combobox_t* box) +{ + rtgui_widget_destroy(RTGUI_WIDGET(box)); +} + +static void rtgui_combobox_ondraw(struct rtgui_combobox* box) +{ + /* draw button */ + rtgui_color_t bc; + struct rtgui_dc* dc; + struct rtgui_rect rect, r; + + /* begin drawing */ + dc = rtgui_dc_begin_drawing(RTGUI_WIDGET(box)); + if (dc == RT_NULL) return; + + bc = RTGUI_WIDGET_BACKGROUND(RTGUI_WIDGET(box)); + + /* get widget rect */ + rtgui_widget_get_rect(RTGUI_WIDGET(box), &rect); + RTGUI_WIDGET_BACKGROUND(RTGUI_WIDGET(box)) = white; + + /* fill widget rect with background color */ + rtgui_dc_fill_rect(dc, &rect); + rtgui_dc_draw_rect(dc, &rect); + + /* draw current item */ + if (box->current_item < box->items_count) + { + rect.x1 += 5; + rtgui_dc_draw_text(dc, box->items[box->current_item].name, &rect); + } + + /* restore background color */ + RTGUI_WIDGET_BACKGROUND(RTGUI_WIDGET(box)) = bc; + + /* draw pull down button */ + rect.x1 = rect.x2 - RTGUI_COMBOBOX_BUTTON_WIDTH; + rtgui_rect_inflate(&rect, -1); + rtgui_dc_fill_rect(dc, &rect); + if (box->pd_pressed == RT_TRUE) rtgui_dc_draw_border(dc, &rect, RTGUI_BORDER_SUNKEN); + else rtgui_dc_draw_border(dc, &rect, RTGUI_BORDER_RAISE); + + r.x1 = 0; r.y1 = 0; r.x2 = 8; r.y2 = 4; + rtgui_rect_moveto_align(&rect, &r, RTGUI_ALIGN_CENTER_HORIZONTAL | RTGUI_ALIGN_CENTER_VERTICAL); + rtgui_dc_draw_byte(dc, r.x1, r.y1, 4, down_arrow); + + /* end drawing */ + rtgui_dc_end_drawing(dc); + return; +} + +static rt_bool_t rtgui_combobox_onmouse_button(struct rtgui_combobox* box, struct rtgui_event_mouse* event) +{ + struct rtgui_rect rect; + + /* get widget rect */ + rect = RTGUI_WIDGET(box)->extent; + + /* move to the pull down button */ + rect.x1 = rect.x2 - RTGUI_COMBOBOX_BUTTON_WIDTH; + if (rtgui_rect_contains_point(&rect, event->x, event->y) == RT_EOK) + { + /* handle mouse button on pull down button */ + if (event->button & RTGUI_MOUSE_BUTTON_LEFT && + event->button & RTGUI_MOUSE_BUTTON_DOWN) + { + box->pd_pressed = RT_TRUE; + rtgui_widget_update(RTGUI_WIDGET(box)); + } + else if (event->button & RTGUI_MOUSE_BUTTON_LEFT && + event->button & RTGUI_MOUSE_BUTTON_UP) + { + box->pd_pressed = RT_FALSE; + rtgui_widget_update(RTGUI_WIDGET(box)); + + /* pop pull down window */ + if (box->pd_win == RT_NULL) + { + rtgui_listbox_t *list; + + /* create pull down window */ + rect = RTGUI_WIDGET(box)->extent; + rect.y1 = rect.y2; + rect.y2 = rect.y1 + 5 * (2 + rtgui_theme_get_selected_height()); + box->pd_win = rtgui_win_create(RT_NULL, "combo", &rect, RTGUI_WIN_STYLE_NO_TITLE); + rtgui_win_set_ondeactivate(RTGUI_WIN(box->pd_win), rtgui_combobox_pulldown_hide); + /* set user data to parent combobox */ + box->pd_win->user_data = (rt_uint32_t)box; + + /* create list box */ + rtgui_rect_inflate(&rect, -1); + list = rtgui_listbox_create(box->items, box->items_count, &rect); + rtgui_container_add_child(RTGUI_CONTAINER(box->pd_win), RTGUI_WIDGET(list)); + rtgui_widget_focus(RTGUI_WIDGET(list)); + + rtgui_listbox_set_onitem(list, rtgui_combobox_pdwin_onitem); + rtgui_win_set_ondeactivate(box->pd_win, rtgui_combobox_pdwin_ondeactive); + } + + /* show combo box pull down window */ + rtgui_win_show(RTGUI_WIN(box->pd_win), RT_FALSE); + } + + return RT_TRUE; + } + + return RT_FALSE; +} + +rt_bool_t rtgui_combobox_event_handler(struct rtgui_widget* widget, struct rtgui_event* event) +{ + struct rtgui_combobox* box = (struct rtgui_combobox*)widget; + + switch (event->type) + { + case RTGUI_EVENT_PAINT: +#ifndef RTGUI_USING_SMALL_SIZE + if (widget->on_draw != RT_NULL) widget->on_draw(widget, event); + else +#endif + rtgui_combobox_ondraw(box); + + break; + + case RTGUI_EVENT_MOUSE_BUTTON: + return rtgui_combobox_onmouse_button(box, (struct rtgui_event_mouse*)event); + + case RTGUI_EVENT_FOCUSED: + { + /* item focused */ + struct rtgui_event_focused* focused; + + focused = (struct rtgui_event_focused*) event; + + if (focused->widget != RT_NULL) + { + /* hide pull down window */ + rtgui_win_hiden(RTGUI_WIN(box->pd_win)); + rtgui_combobox_ondraw(box); + } + } + break; + } + + return RT_FALSE; +} + +static rt_bool_t rtgui_combobox_pulldown_hide(struct rtgui_widget* widget, struct rtgui_event* event) +{ + struct rtgui_combobox* box; + + if (widget == RT_NULL) return RT_TRUE; + + box = (struct rtgui_combobox*) (((struct rtgui_win*)widget)->user_data); + if (box == RT_NULL) return RT_TRUE; + + /* hide pull down window */ + rtgui_win_hiden(RTGUI_WIN(box->pd_win)); + + /* clear pull down button state */ + box->pd_pressed = RT_FALSE; + rtgui_widget_update(RTGUI_WIDGET(box)); + + return RT_TRUE; +} + +struct rtgui_listbox_item* rtgui_combox_get_select(struct rtgui_combobox* box) +{ + if ((box != RT_NULL) && (box->current_item < box->items_count)) + { + return &(box->items[box->current_item]); + } + + return RT_NULL; +} + +void rtgui_combobox_set_onselected(struct rtgui_combobox* box, rtgui_onitem_func_t func) +{ + box->on_selected = func; +} diff --git a/pool/shard003/C/0069075_scm-boot.c b/pool/shard003/C/0069075_scm-boot.c new file mode 100644 index 0000000000000000000000000000000000000000..f653217ae4425bb64797c3d6678ed702e19c6a7e --- /dev/null +++ b/pool/shard003/C/0069075_scm-boot.c @@ -0,0 +1,74 @@ +/* Copyright (c) 2010, Code Aurora Forum. 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 version 2 and + * only 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., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include +#include + +#include +#include + +#define SCM_FLAG_WARMBOOT_CPU0 0x04 +#define SCM_FLAG_WARMBOOT_CPU1 0x02 +#define SCM_FLAG_WARMBOOT_CPU2 0x10 +#define SCM_FLAG_WARMBOOT_CPU3 0x40 + +struct scm_warmboot { + int flag; + void *entry; +}; + +static struct scm_warmboot scm_flags[] = { + { .flag = SCM_FLAG_WARMBOOT_CPU0 }, + { .flag = SCM_FLAG_WARMBOOT_CPU1 }, + { .flag = SCM_FLAG_WARMBOOT_CPU2 }, + { .flag = SCM_FLAG_WARMBOOT_CPU3 }, +}; + +/* + * Set the cold/warm boot address for one of the CPU cores. + */ +int scm_set_boot_addr(phys_addr_t addr, int flags) +{ + struct { + unsigned int flags; + phys_addr_t addr; + } cmd; + + cmd.addr = addr; + cmd.flags = flags; + return scm_call(SCM_SVC_BOOT, SCM_BOOT_ADDR, + &cmd, sizeof(cmd), NULL, 0); +} +EXPORT_SYMBOL(scm_set_boot_addr); + +int scm_set_warm_boot_addr(void *entry, int cpu) +{ + int ret; + + /* + * Reassign only if we are switching from hotplug entry point + * to cpuidle entry point or vice versa. + */ + if (entry == scm_flags[cpu].entry) + return 0; + + ret = scm_set_boot_addr(virt_to_phys(entry), scm_flags[cpu].flag); + if (!ret) + scm_flags[cpu].entry = entry; + + return ret; +} diff --git a/pool/shard003/C/0069089_mpfc-ce.c b/pool/shard003/C/0069089_mpfc-ce.c new file mode 100644 index 0000000000000000000000000000000000000000..6cd47484359cc2460bcf8db505e1c9ec8f8aa38a --- /dev/null +++ b/pool/shard003/C/0069089_mpfc-ce.c @@ -0,0 +1,284 @@ +/* + + mplayer font creator for central-europe (latin-1 etc) charset + + This program uses gd & freetype2 library to draw each characters then + write the image to stdout. + + Written by Sunjin Yang May 03, 2001. + Modified by Arpad Gereoffy Jun 18, 2001. + +*/ + +#include +#include +#include +#include + +#define UPSCALE_FACTOR 2 + +#define X_ALIGN (8*UPSCALE_FACTOR) +#define ALIGNED(x) (((x)+(X_ALIGN-1))&(~(X_ALIGN-1))) + +#define DEF_FONT_SIZE 16.0 + +#define DEF_CHAR_GAP 6 +#define CHAR_SKIP(gap) (gap / 4) + +#define AUTHOR "Sunjin Yang " +#define VERSION "0.1" + +struct code_range { + int start, end; +}; + +/* basic alphabet character range */ +//static struct code_range ascii_range = { 0x21, 0x7E }; +static struct code_range ascii_range = { 0x20, 0x1FF }; + +#ifdef USE_UNIFIED_KOREAN + +/* Unified Hangul Code Encoding */ +static struct code_range first_byte_range[] = { + { 0x81, 0xFE }, { 0, 0 } +}; +static struct code_range second_byte_range[] = { + { 0x41, 0x5A }, { 0x61, 0x7A }, { 0x81, 0x9F }, { 0xA0, 0xBF }, + { 0xC0, 0xDF }, { 0xE0, 0xFE }, { 0, 0 } +}; + +#else + +/* KSX 1001:1992 */ +static struct code_range first_byte_range[] = { + { 0xA1, 0xAC }, { 0xB0, 0xFD }, { 0, 0 } +}; +static struct code_range second_byte_range[] = { + { 0xA1, 0xAF }, { 0xB0, 0xBF }, { 0xC0, 0xCF }, { 0xD0, 0xDF }, + { 0xE0, 0xEF }, { 0xF0, 0xFE }, { 0, 0 } +}; + +#endif + +#define _output(msg...) fprintf(stdout, ##msg) + +/* debugging macros */ +#define _print(msg...) fprintf(stderr, ##msg) +#define _info(msg...) { _print("mpfc: "); _print(##msg); _print("\n"); } +#define _abort(msg...) { _info(##msg); exit(1); } + +static double size; +static int gap,vgap; +static char *name, *font, *eng_font, *kor_font; +static int file_index; +static char filename[20]; + +static int base_x, char_count; +static gdImagePtr char_image[65536]; + +static gdImagePtr concat_char_images(void) +{ + gdImagePtr ret; + int width, height, i, x,black, white; + + /* get image's width & height */ + height = size + (vgap * 2); + for (width = 0, i = 0; i < char_count; i++) + width += ALIGNED(char_image[i]->sx); + + ret = gdImageCreate(width, height); + + /* background color (first allocated) */ + black = gdImageColorResolve(ret, 0, 0, 0); +// white = gdImageColorResolve(ret, 255, 255, 255); + for(x=1;x<=255;x++) + white = gdImageColorResolve(ret, x,x,x); + + width = 0; + for (i = 0; i < char_count; i++) { + gdImageCopy(ret, char_image[i], /* dst, src */ + width + 0, 0, /* dstX, dstY */ + 0, 0, /* srcX, srcY */ + char_image[i]->sx, char_image[i]->sy); /* size */ + width += ALIGNED(char_image[i]->sx); + gdImageDestroy(char_image[i]); + } + char_count = 0; + + return ret; +} + +static gdImagePtr create_char_image(int code) +{ + gdImagePtr im; + int rect[8], black, white, width, height, x, y; + char *err; + char s[10]; + +#if 1 + sprintf(s,"&#%d;",code); +#else + if(code>=0x100){ + s[0]=code>>8; + s[1]=code&0xFF; + s[2]=0; + } else { + s[0]=code; + s[1]=0; + } +#endif + + /* obtain border rectangle so that we can size the image. */ + err = gdImageStringTTF(NULL, &rect[0], 0, font, size, .0, 0, 0, s); + if (err) + _abort("%s\n", err); + + /* create an image big enough for a string plus a little whitespace. */ + width = rect[2] - rect[6] + gap; + height = size + (vgap * 2); + im = gdImageCreate(width, height); + + /* background color (first allocated) */ + black = gdImageColorResolve(im, 0, 0, 0); + for(x=1;x<=255;x++) + white = gdImageColorResolve(im, x,x,x); +// white = gdImageColorResolve(im, 255, 255, 255); + + /* render the string, offset origin to center string. + note that we use top-left coordinate for adjustment + since gd origin is in top-left with y increasing downwards. */ + x = (gap / 2) - rect[6]; + y = (vgap) - rect[7] + (size + rect[7]); + err = gdImageStringTTF(im, &rect[0], white, font, size, .0, x, y, s); + if (err) + _abort("%s\n", err); + + //if (*s == '"') _output("'%s' ", s); else _output("\"%s\" ", s); + _output("0x%x %d %d\n", code, + (base_x + CHAR_SKIP(gap))/UPSCALE_FACTOR -1, + (base_x + width - CHAR_SKIP(gap))/UPSCALE_FACTOR - 0); + base_x += ALIGNED(width); +// base_x = (base_x+width+7)&(~7); // align to 8-pixel boundary for fast MMX code + + return im; +} + +void make_charset_font(struct code_range *first, struct code_range *second) +{ + gdImagePtr im; + FILE *fd; + int i, j; + + base_x = 0; + char_count = 0; + + _output("[files]\n"); + //_output("alpha %s%d_a.raw\n", name, file_index); + _output("alpha %s%02d_a.raw\n", name, file_index); + _output("bitmap %s%02d_b.raw\n\n", name, file_index); + _output("[characters]\n"); + + for (i = first->start; i <= first->end; i++) { + if (!second) { + char_image[char_count++] = create_char_image(i); + } else + for (j = second->start; j <= second->end; j++) { + char_image[char_count++]= create_char_image((i<<8)|j); + } + } + + _output("\n"); + + /* concatenate each character images into one image. */ + im = concat_char_images(); + + /* get filename and create one with it. */ + sprintf(filename, "%s%02d_b.png", name, file_index++); + fd = fopen(filename, "w+"); + if (!fd) + _abort(strerror(errno)); + + /* write image to the PNG file. */ + gdImagePng(im, fd); + + fclose(fd); + + /* destroy it */ + gdImageDestroy(im); +} + +int main(int argc, char **argv) +{ + int i, j; + + if (argc < 4) + _abort("usage:%s name eng-ttf kor-ttf [size gap vgap]",argv[0]); + + /* get program parameter like font names, size... */ + name = argv[1]; + eng_font = argv[2]; + kor_font = argv[3]; + size = DEF_FONT_SIZE; + gap = DEF_CHAR_GAP; + vgap = DEF_CHAR_GAP; + if (argc > 4) { + float __s; sscanf(argv[4], "%f", &__s); + size = (double)__s; + } + if (argc > 5) + sscanf(argv[5], "%d", &gap); + if (argc > 6) + sscanf(argv[6], "%d", &vgap); + + /* write basic font information. */ + _output("[info]\n"); + _output("name \"%s version %s - created by %s\"\n", + name, VERSION, AUTHOR); + _output("descversion 1\n"); + _output("spacewidth %d\n", (int)(size / 2)); + _output("charspace -%d\n", CHAR_SKIP(gap) + 1); + _output("; height %d\n\n", (int)size + DEF_CHAR_GAP); + + /* write general OSD fonts information. */ + _output("[files]\n"); + _output("alpha arpi_osd_a.raw\n"); + _output("bitmap arpi_osd_b.raw\n\n"); + _output("[characters]\n"); + _output("0x01 0 36\n"); + _output("0x02 35 71\n"); + _output("0x03 70 106\n"); + _output("0x04 116 152\n"); + _output("0x05 164 200\n"); + _output("0x06 209 245\n"); + _output("0x07 256 292\n"); + _output("0x08 305 342\n"); + _output("0x09 354 400\n"); + _output("0x0A 407 442\n"); + _output("0x0B 457 494\n"); + _output("[files]\n"); + _output("alpha arpi_progress_a.raw\n"); + _output("bitmap arpi_progress_b.raw\n\n"); + _output("[characters]\n"); + _output("0x10 4 21\n"); + _output("0x11 30 41\n"); + _output("0x12 50 66\n"); + _output("0x13 74 85\n\n"); + + + file_index = 0; + + /* create basic alphabet character set. */ + font = eng_font; + make_charset_font(&ascii_range, NULL); + +#if 0 + /* create korean character set. */ + font = kor_font; + for (i = 0; first_byte_range[i].start != 0; i++) + for (j = 0; second_byte_range[j].start != 0; j++) + make_charset_font(&first_byte_range[i], &second_byte_range[j]); +#endif + + return 0; +} + diff --git a/pool/shard003/C/0069090_mphconv.c b/pool/shard003/C/0069090_mphconv.c new file mode 100644 index 0000000000000000000000000000000000000000..4e95c19713cb6270e1cdf8acf3874338b5a01502 --- /dev/null +++ b/pool/shard003/C/0069090_mphconv.c @@ -0,0 +1,27 @@ +#include + +void displayUsage() { + printf("usage: mphconv \n"); +} + +double milesToMinutes(double miles, double mph) { + return miles * 60 / mph; +} + +int main(int numArgs, char *args[]) { + if(numArgs != 3) { + displayUsage(); + return -1; + } + double miles = 0; + double mph = 0; + sscanf(args[1], "%lf", &miles); + sscanf(args[2], "%lf", &mph); + if(miles == 0 || mph == 0) { + displayUsage(); + return -2; + } + double minutes = milesToMinutes(miles, mph); + printf("%.1f\n", minutes); + return 0; +} diff --git a/pool/shard003/C/0069098_FLA_task_partitioning.c b/pool/shard003/C/0069098_FLA_task_partitioning.c new file mode 100644 index 0000000000000000000000000000000000000000..8d4074a8f8bcf5492ec57fa7a2886e3bc3d94e9d --- /dev/null +++ b/pool/shard003/C/0069098_FLA_task_partitioning.c @@ -0,0 +1,162 @@ +/* + + 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" +#include "FLA_queue_omp.h" +#include "FLA_task_partitioning.h" + +#if FLA_MULTITHREADING_MODEL == FLA_OPENMP + +#define NUM_THREADS_MAX 128 +#define NUM_TAGS_MAX 5 + +int factors[NUM_THREADS_MAX+1][NUM_TAGS_MAX]; + +void FLA_Task_partitioning_init() +{ + int i; + + for( i = 0; i < NUM_THREADS_MAX; ++i ) + FLA_Task_partitioning_set( i, -1, -1, -1, -1, -1 ); +} + +void FLA_Task_partitioning_set( int n_threads, int tag0_val, int tag1_val, int tag2_val, int tag3_val, int tag4_val ) +{ + factors[n_threads][0] = tag0_val; + factors[n_threads][1] = tag1_val; + factors[n_threads][2] = tag2_val; + factors[n_threads][3] = tag3_val; + factors[n_threads][4] = tag4_val; +} + +int FLA_task_get_num_partitions( int n_threads, int tag ) +{ + return factors[n_threads][tag]; +} + +int FLA_Task_compute_blocksize( int tag, FLA_Obj A, FLA_Obj A_proc, FLA_Quadrant from ) +{ + int n_threads = FLA_Queue_get_num_threads(); + int A_size, A_proc_size; + int n_part; + int b; + + // Determine the sizes of the matrix partitions. + A_size = FLA_task_determine_matrix_size( A, from ); + A_proc_size = FLA_task_determine_matrix_size( A_proc, from ); + + // Determine the raw blocksize value. + n_part = FLA_task_get_num_partitions( n_threads, tag ); + + // Determine the blocksize based on the sign of the value from + // _get_num_partitions(). + if( n_part > 0 ) + { + b = FLA_task_determine_absolute_blocksize( A_size, + A_proc_size, + n_part ); + } + else if( n_part < 0 ) + { + b = FLA_task_determine_relative_blocksize( A_size, + A_proc_size, + abs(n_part) ); + } + else + { + FLA_Print_message( "Detected blocksize of 0!", __FILE__, __LINE__ ); + FLA_Abort(); + } + + return b; +} + +int FLA_task_determine_matrix_size( FLA_Obj A, FLA_Quadrant from ) +{ + int r_val = 0; + + // Determine the size of the matrix dimension along which we are moving. + switch( from ) + { + case FLA_TOP: + case FLA_BOTTOM: + { + r_val = FLA_Obj_length( A ); + break; + } + case FLA_LEFT: + case FLA_RIGHT: + { + r_val = FLA_Obj_width( A ); + break; + } + case FLA_TL: + case FLA_TR: + case FLA_BL: + case FLA_BR: + { + // If A happens to be the full object, we need to use min_dim() here + // because the matrix might be rectangular. If A is the processed + // partition, it is very probably square, and min_dim() doesn't hurt. + r_val = FLA_Obj_min_dim( A ); + break; + } + default: + FLA_Print_message( "Unexpected default in switch statement!", __FILE__, __LINE__ ); + FLA_Abort(); + } + + return r_val; +} + + +int FLA_task_determine_relative_blocksize( int A_size, int A_proc_size, int n_part ) +{ + int b, i, z; + + // Return early if the size is zero (scenario (A)). + if( A_size == 0 ) return 0; + + // Compute the base blocksize (according to (1) above). + b = A_size / n_part; + + // If the base blocksize is zero (because A_size < n_part), then override + // n_part and proceed as if only one partition was requested (scenario (B)). + if( b == 0 ) + { + n_part = 1; + b = A_size; + } + + // Compute partition index i. + i = A_proc_size / b; + + // Compute the index z below which we will use the base blocksize. + z = n_part - (A_size % n_part); + + // If the current partition index i is at least z, then increment the + // base blocksize (according to (2) above). + if( z <= i ) b++; + + // Return the blocksize. + return b; +} + +int FLA_task_determine_absolute_blocksize( int A_size, int A_proc_size, int nb_alg ) +{ + int A_unproc_size = A_size - A_proc_size; + int b; + + b = min( A_unproc_size, nb_alg ); + + return b; +} + +#endif diff --git a/pool/shard003/C/0069114_xddinfo.c b/pool/shard003/C/0069114_xddinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..3658a8653841e9dfc51ddd382ef6abfa713bf26f --- /dev/null +++ b/pool/shard003/C/0069114_xddinfo.c @@ -0,0 +1,59 @@ +/* xddinfo - description + * + * Purpose: + * + * Written by: R. Mortensen + * Date: + * + * Calling Sequence: + * + * STATUS = xddinfo( parameters ) + * + * Parameter List: + * + * Unit: Display device unit number + * + * Possible Error Codes: + * + */ + +#include "xvmaininc.h" +#include "ftnbridge.h" +#include "xdexterns.h" +#include "xdroutines.h" +#include "xderrors.h" +#include "xdfuncs.h" + +FUNCTION FTN_NAME(xddinfo)( Unit, Start, Number, Array ) +INTEGER Unit, Start, Number, Array; + { + return ( zddinfo( *Unit, *Start, *Number, Array )); + } + +FUNCTION zddinfo( unit, start, number, array ) +int unit, start, number, *array; + { + int status, i; + + xd_current_call = DINFO; + + if (!ZCHECK_UNIT_NUMBER) { + status = UNIT_OUT_OF_RANGE; + } + else if (!ZCHECK_DEVICE_OPEN) { + status = DEVICE_NOT_OPEN; + } + else if ((start < 0) || ((start+number-1) > DCB_SIZE)) { + status = INVALID_INFO_REQUEST; + } + else { + status = SUCCESS; + + for ( i = 0; i < (number); i++ ) { + array[i] = *(((int *)DCB[unit])+start+i); + } + } + + xd_error_handler( &unit, status ); + return (status); + } diff --git a/pool/shard003/C/0069123_gdevdjet.c b/pool/shard003/C/0069123_gdevdjet.c new file mode 100644 index 0000000000000000000000000000000000000000..f3e7c7721f31725156777f832066562ec5b28123 --- /dev/null +++ b/pool/shard003/C/0069123_gdevdjet.c @@ -0,0 +1,228 @@ +/* Copyright (C) 1989, 1990, 1991 Aladdin Enterprises. All rights reserved. + Distributed by Free Software Foundation, Inc. + +This file is part of Ghostscript. + +Ghostscript is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY. No author or distributor accepts responsibility +to anyone for the consequences of using it or for whether it serves any +particular purpose or works at all, unless he says so in writing. Refer +to the Ghostscript General Public License for full details. + +Everyone is granted permission to copy, modify and redistribute +Ghostscript, but only under the conditions described in the Ghostscript +General Public License. A copy of this license is supposed to have been +given to you along with Ghostscript so you can know your rights and +responsibilities. It should be in a file named COPYING. Among other +things, the copyright notice and this notice must be preserved on all +copies. */ + +/* gdevdjet.c */ +/* H-P DeskJet/LaserJet driver for GhostScript */ + +/* Define whether we are writing to a DeskJet (which can do bitmap */ +/* compression) or a LaserJet (which can't). */ +/* Normally this is defined in the compiler command line -- */ +/* see the DeskJet and LaserJet entries in gdevs.mak. */ +#ifndef LASER +# define LASER 0 +#endif + +#if LASER +# define GS_PRN_DEVICE gs_laserjet_device +# define DEVICE_NAME "laserjet" +#else +# define GS_PRN_DEVICE gs_deskjet_device +# define DEVICE_NAME "deskjet" +#endif +#define PAGE_WIDTH_10THS 80 /* not quite a full page */ +#define PAGE_HEIGHT_10THS 105 /* ditto */ +/* Normally we set up at 300 DPI; however, on MS-DOS systems with */ +/* virtual memory disabled, we can't do more than 60 DPI */ +/* because the maximum buffer is only 64K. */ +#define X_DPI 300 +#define Y_DPI 300 +#ifdef __MSDOS__ +# if !VMEM_SPACE +# undef X_DPI +# define X_DPI 60 +# undef Y_DPI +# define Y_DPI 60 +# endif +#endif +#define PRN_OPEN gdev_prn_open +#define PRN_CLOSE gdev_prn_close +#define PRN_OUTPUT_PAGE djet_output_page +#define DRIVER /* see gdevprn.h */ +#include "gdevprn.h" + +/* Forward references */ +private int djet_print_page(P2(gx_device_printer *, FILE *)); + +/* Send the page to the printer. */ +private int +djet_output_page(gx_device *dev) +{ int code = gdev_prn_open_printer(dev); + if ( code < 0 ) return code; + + /* print the accumulated page description */ + djet_print_page(prn_dev, prn_dev->file); + + gdev_prn_close_printer(dev); + return 0; +} + +/* ------ Internal routines ------ */ + +/* Send the page to the printer. For the DeskJet, compress each scan line, */ +/* since computer-to-printer communication time is often a bottleneck. */ +private int +djet_print_page(gx_device_printer *pdev, FILE *prn_stream) +{ char data[LINE_SIZE + 4]; + +#define escape_print(str) fprintf(prn_stream, str, 27) +#define escape_print_1(str,arg) fprintf(prn_stream, str, 27, arg) + + /* ends raster graphics to set raster graphics resolution */ + escape_print("%c*rB"); + + /* set raster graphics resolution -- 75 or 300 dpi */ +#if X_DPI == 300 + escape_print("%c*t300R"); +#else + escape_print("%c*t75R"); +#endif + + /* move to top left of page */ + escape_print("%c*p0x0Y"); + + /* start raster graphics */ + escape_print("%c*r0A"); + + /* select the most compressed mode available */ +#if !LASER /* LaserJet can't handle it */ + escape_print("%c*b2M"); +#endif + + /* Send each scan line in turn */ + { int lnum; + int line_size = mem_bytes_per_scan_line(&pdev->mem); + int num_blank_lines = 0; + for ( lnum = 0; lnum < pdev->height; lnum++ ) + { char *end_data = data + LINE_SIZE; + mem_copy_scan_lines(&pdev->mem, lnum, + (byte *)data, line_size); + /* Mask off 1-bits beyond LINE_WIDTH. */ +#if (LINE_WIDTH & 7) + end_data[-1] &= (byte)(0xff00 >> (LINE_WIDTH & 7)); +#endif + /* Remove trailing 0s. */ + while ( end_data > data && end_data[-1] == 0 ) + end_data--; + if ( end_data == data ) + { /* Blank line */ + num_blank_lines++; + } + else + { +#if LASER /* no compression */ + char *out_data = data; + int out_count = end_data - data; +#else + char out_data[LINE_SIZE + LINE_SIZE / 127 + 1]; + int out_count = + compress_row(data, end_data, out_data); +#endif + + /* Skip blank lines if any */ + if ( num_blank_lines > 0 ) + { /* move down from current position */ + escape_print_1("%c*p+%dY", + num_blank_lines); + num_blank_lines = 0; + } + + /* transfer raster graphics */ + escape_print_1("%c*b%dW", out_count); + + /* send the row */ + fwrite(out_data, sizeof(char), + out_count, prn_stream); + } + } + } + + /* end raster graphics */ + escape_print("%c*rB"); + + /* eject page */ + escape_print("%c&l0H"); + + return 0; +} + +#if !LASER + +/* Row compression routine for the HP DeskJet. */ +/* Compresses data from row up to end_row, storing the result */ +/* starting at compressed. Returns the number of bytes stored. */ +/* Runs of K<=127 literal bytes are encoded as K-1 followed by */ +/* the bytes; runs of 2<=K<=127 identical bytes are encoded as */ +/* 257-K followed by the byte. */ +/* In the worst case, the result is N+(N/127)+1 bytes long, */ +/* where N is the original byte count (end_row - row). */ +int +compress_row(char *row, char *end_row, char *compressed) +{ register char *i_exam = row; /* byte being examined in the row to compress */ + char *stop_exam = end_row - 4; /* stop scanning for similar bytes here */ + register char *cptr = compressed; /* output pointer into compressed bytes */ + + while ( i_exam < end_row ) + { /* Search ahead in the input looking for a run */ + /* of at least 4 identical bytes. */ + char *i_compr = i_exam; + char *i_next; /* end of run */ + char byte_value; + while ( i_exam <= stop_exam && + ((byte_value = *i_exam) != i_exam[1] || + byte_value != i_exam[2] || + byte_value != i_exam[3]) ) + i_exam++; + + /* Find out how long the run is */ + if ( i_exam > stop_exam ) /* no run */ + i_next = i_exam = end_row; + else + { i_next = i_exam + 4; + while ( i_next < end_row && *i_next == byte_value ) + i_next++; + } + + /* Now [i_compr..i_exam) should be encoded as dissimilar, */ + /* and [i_exam..i_next) should be encoded as similar. */ + /* Note that either of these ranges may be empty. */ + + while ( i_compr < i_exam ) + { /* Encode up to 127 dissimilar bytes */ + int count = i_exam - i_compr; + if ( count > 127 ) count = 127; + *cptr++ = count - 1; + while ( count > 0 ) + { *cptr++ = *i_compr++; + count--; + } + } + + while ( i_exam < i_next ) + { /* Encode up to 127 similar bytes */ + int count = i_next - i_exam; + if ( count > 127 ) count = 127; + *cptr++ = 1 - count; + *cptr++ = byte_value; + i_exam += count; + } + } + return (cptr - compressed); +} + +#endif /* !LASER */ diff --git a/pool/shard003/C/0069127_16_.c b/pool/shard003/C/0069127_16_.c new file mode 100644 index 0000000000000000000000000000000000000000..52073f9db3c40b9ad2cb52e7f0b8f2754ad3d1af --- /dev/null +++ b/pool/shard003/C/0069127_16_.c @@ -0,0 +1,39 @@ +#include +void F(int,int,int); +int main() +{ + int year, month, day; + + printf("Please enter the year:\n"); + scanf("%d", &year); + printf("Please enter the month(1 ~ 12):\n"); + scanf("%d", &month); + printf("Please enter the day(1 ~ 31):\n"); + scanf("%d", &day); + + F(year, month, day); + + return 0; +} + +void F(int Y, int M, int D) +{ + int m, d, sum1 = 0, sum2 = 0; + if ((Y % 4 == 0 && Y % 100 != 0) || (Y % 400 == 0)) + { + int MONTH1[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + for (m = 0; m < (M - 1); m++) + sum1 += MONTH1[m]; + sum1 += D; + printf("The day is %dth of the year.\n", sum1); + } + else + { + int MONTH2[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + for (m = 0; m < (M - 1); m++) + sum2 += MONTH2[m]; + sum2 += D; + printf("The day is %dth of the year.\n", sum2); + } + return; +} diff --git a/pool/shard003/C/0069128_printLongInt.c b/pool/shard003/C/0069128_printLongInt.c new file mode 100644 index 0000000000000000000000000000000000000000..479229e4fb5fb272f00023acabdddf3d5d38f2be --- /dev/null +++ b/pool/shard003/C/0069128_printLongInt.c @@ -0,0 +1,38 @@ +#include "mobilereminder.h" + +void printLongInt(long int number, char* buffer) +{ + #ifdef Debug + printf("Printing Long: %ld\r\n", number); + #endif + char output[11] = {0}; + int length = 0; + while(number != 0) + { + output[length] = (char)((number - (((int)(number/10))*10))+48); + + #ifdef Debug + printf("%s", &output[length]); + #endif + length++; + number /= 10; + } + #ifdef Debug + printf("\r\n"); + #endif + int x; + for(x = length; x > -1; x--) + { + strncat(buffer, &output[x], 1); + #ifdef Debug + printf("Buffer So Far: %s\r\n", buffer); + printf("Character Added: %c\r\n", output[x]); + #endif + } + + strcat(buffer, "\0"); + + #ifdef Debug + printf("\r\n"); + #endif +} diff --git a/pool/shard003/C/0069129_Stack.c b/pool/shard003/C/0069129_Stack.c new file mode 100644 index 0000000000000000000000000000000000000000..4979d93c9d6dc6728c23ad138db5935ae30027ec --- /dev/null +++ b/pool/shard003/C/0069129_Stack.c @@ -0,0 +1,41 @@ +#include +#include +#include +#include "Stack.h" + +void init(Stack* s) +{ + s->top = 0; + s->size = STACKSIZE; + s->dane = (int*)malloc(sizeof(int)*STACKSIZE); +} + +void destroy(Stack* s) +{ + free(s->dane); +} + +void push(Stack* s, int element) +{ + s->dane[s->top++] = element; + if(s->top == s->size) + { + s->dane = (int*)realloc(s->dane, (s->size*=2)*sizeof(int)); + } +} + +int pop(Stack* s) +{ + assert(s->top > 0); + return s->dane[--s->top]; +} + +void clear(Stack* s) +{ + s->top = 0; +} + +bool isEmpty(Stack* s) +{ + return s->top > 0 ? false : true; +} diff --git a/pool/shard003/C/0069139_RGBtoRGBA.c b/pool/shard003/C/0069139_RGBtoRGBA.c new file mode 100644 index 0000000000000000000000000000000000000000..bd9b6b205e05f2b7d2e2ca0e919cd0ff3b8a53f6 --- /dev/null +++ b/pool/shard003/C/0069139_RGBtoRGBA.c @@ -0,0 +1,59 @@ +#define FALSE 0 +#define TRUE 1 +#define ALPHA_VALUE 128 + +#include +#include +#include + +int main(int argc, char **argv) { + FILE *lut = NULL; + char RGBAfile[1024]; + uint8_t lutBufferRGB[768]; + uint8_t lutBufferRGBA[1024]; + int32_t readBytes = 0, i = 0; + + printf("Reading LUT at %s\n", argv[1]); + + lut = fopen(argv[1], "rb"); + if(lut == NULL) { + printf("Unable to open LUT at %s\n", argv[1]); + return FALSE; + } + + readBytes = (int32_t)fread(lutBufferRGB, 1, 768, lut); + if(readBytes != 768) { + printf("File %s does not have 768 bytes.\n", argv[1]); + if(fclose(lut) != 0) { + printf("Additionally, an error occured closing the file"); + } + return FALSE; + } + + memcpy(lutBufferRGBA, lutBufferRGB, 768); + for(i = 768; i < 1024; i++) + lutBufferRGBA[i] = 0x80; + + if(fclose(lut) != 0) { + printf("Error closing LUT file.\n"); + return FALSE; + } + + sprintf(RGBAfile, "%s.rgba", argv[1]); + + lut = fopen(RGBAfile, "w+b"); + if(lut == NULL) { + printf("Unable to open RGBA file at %s\n", RGBAfile); + return FALSE; + } + if(fwrite(lutBufferRGBA, 1, 1024, lut) != 1024) { + printf("Unable to write RGBA file.\n"); + if(fclose(lut) != 0) + printf("Additionally, an error occured closing the file.\n"); + return FALSE; + } + if(fclose(lut) != 0) + printf("Error closing the RGBA file\n"); + + return TRUE; +} diff --git a/pool/shard003/C/0069141_wintip.c b/pool/shard003/C/0069141_wintip.c new file mode 100644 index 0000000000000000000000000000000000000000..8f8b3ce4846a655b690c13f653014a58798abcb5 --- /dev/null +++ b/pool/shard003/C/0069141_wintip.c @@ -0,0 +1,120 @@ +// wintip.c (part of mintty) +// Copyright 2008-10 Andy Koppe +// Adapted from code from PuTTY-0.60 by Simon Tatham and team. +// Licensed under the terms of the GNU General Public License v3 or later. + +#include "winpriv.h" + +static ATOM tip_class; +static HFONT tip_font; +static COLORREF tip_bg; +static COLORREF tip_text; +static HWND tip_wnd; + +static LRESULT CALLBACK +tip_proc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam) +{ + switch (nMsg) { + when WM_DESTROY: + DeleteObject(tip_font); + tip_font = null; + when WM_ERASEBKGND: return true; + when WM_NCHITTEST: return HTTRANSPARENT; + when WM_SETTEXT: { + LPCTSTR str = (LPCTSTR) lParam; + HDC dc = CreateCompatibleDC(null); + SelectObject(dc, tip_font); + SIZE sz; + GetTextExtentPoint32(dc, str, strlen(str), &sz); + SetWindowPos(hWnd, null, 0, 0, sz.cx + 6, sz.cy + 6, + SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE); + InvalidateRect(hWnd, null, false); + DeleteDC(dc); + } + when WM_PAINT: { + PAINTSTRUCT ps; + HDC dc = BeginPaint(hWnd, &ps); + + SelectObject(dc, tip_font); + SelectObject(dc, GetStockObject(BLACK_PEN)); + + HBRUSH hbr = CreateSolidBrush(tip_bg); + HGDIOBJ holdbr = SelectObject(dc, hbr); + + RECT cr; + GetClientRect(hWnd, &cr); + Rectangle(dc, cr.left, cr.top, cr.right, cr.bottom); + + int wtlen = GetWindowTextLength(hWnd); + TCHAR wt[wtlen + 1]; + GetWindowText(hWnd, wt, wtlen + 1); + + SetTextColor(dc, tip_text); + SetBkColor(dc, tip_bg); + + TextOut(dc, cr.left + 3, cr.top + 3, wt, wtlen); + + SelectObject(dc, holdbr); + DeleteObject(hbr); + + EndPaint(hWnd, &ps); + return 0; + } + } + return DefWindowProc(hWnd, nMsg, wParam, lParam); +} + +void +win_show_tip(int x, int y, int cols, int rows) +{ + if (!tip_wnd) { + NONCLIENTMETRICS nci; + + /* First make sure the window class is registered */ + if (!tip_class) { + WNDCLASS wc; + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.lpfnWndProc = tip_proc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = inst; + wc.hIcon = null; + wc.hCursor = null; + wc.hbrBackground = null; + wc.lpszMenuName = null; + wc.lpszClassName = "SizeTipClass"; + tip_class = RegisterClass(&wc); + } + + /* Prepare other GDI objects and drawing info */ + tip_bg = GetSysColor(COLOR_INFOBK); + tip_text = GetSysColor(COLOR_INFOTEXT); + memset(&nci, 0, sizeof (NONCLIENTMETRICS)); + nci.cbSize = sizeof (NONCLIENTMETRICS); + SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof (NONCLIENTMETRICS), + &nci, 0); + tip_font = CreateFontIndirect(&nci.lfStatusFont); + tip_wnd = + CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TOPMOST, + MAKEINTRESOURCE(tip_class), null, WS_POPUP, x, y, 1, 1, + null, null, inst, null); + ShowWindow(tip_wnd, SW_SHOWNOACTIVATE); + } + else { + SetWindowPos(tip_wnd, null, x, y, 0, 0, + SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE); + } + + char str[32]; + sprintf(str, "%dx%d", cols, rows); + SetWindowText(tip_wnd, str); +} + +void +win_destroy_tip(void) +{ + if (tip_wnd) { + DestroyWindow(tip_wnd); + tip_wnd = null; + } +} diff --git a/pool/shard003/C/0069145_bspstart.c b/pool/shard003/C/0069145_bspstart.c new file mode 100644 index 0000000000000000000000000000000000000000..b3a17e774ddb9b880b95148abb304a21ca101d3c --- /dev/null +++ b/pool/shard003/C/0069145_bspstart.c @@ -0,0 +1,389 @@ +/* + * This routine starts the application. It includes application, + * board, and monitor specific initialization and configuration. + * The generic CPU dependent initialization has been performed + * before this routine is invoked. + * + * COPYRIGHT (c) 1989-1998. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.OARcorp.com/rtems/license.html. + * + * Modified to support the MCP750. + * Modifications Copyright (C) 1999 Eric Valette. valette@crf.canon.fr + * + * Modified to support the Synergy VGM & Motorola PowerPC boards. + * (C) by Till Straumann, , 2002, 2004, 2005 + * + * Modified to support the mvme5500 BSP + * (C) by Kate Feng , 2003, 2004 + * under the contract DE-AC02-98CH10886 with the Deaprtment of Energy + * + * T. Straumann: 2005-2007; stolen again for 'beatnik'... + */ +#include +#include +#include + +#include +#include +#include +#include +#include +/*#include */ +#include /* registers.h is included here */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* for RTEMS_VERSION :-( I dont like the preassembled string */ +#include + +#ifdef __RTEMS_APPLICATION__ +#undef __RTEMS_APPLICATION__ +#endif + +#define SHOW_MORE_INIT_SETTINGS + +BSP_output_char_function_type BSP_output_char = BSP_output_char_via_serial; +BSP_polling_getchar_function_type BSP_poll_char = NULL; + +extern Triv121PgTbl BSP_pgtbl_setup(unsigned int *); +extern void BSP_pgtbl_activate(Triv121PgTbl); +extern void BSP_motload_pci_fixup(void); + +extern unsigned long __rtems_end[]; + +/* We really shouldn't use these since MMUoff also sets IP; + * nevertheless, during early init I don't care for now + */ +extern void MMUoff(void); +extern void MMUon(void); + +extern uint32_t probeMemoryEnd(void); + +SPR_RW(SPRG0) +SPR_RW(SPRG1) +SPR_RO(HID1) + +/* Table of PLL multipliers for 7455/7457: +01000 2 00010 7.5 00000 11.5 00001 17 +10000 3 11000 8 10111 12 00101 18 +10100 4 01100 8.5 11111 12.5 00111 20 +10110 5 01111 9 01011 13 01001 21 +10010 5.5 01110 9.5 11100 13.5 01101 24 +11010 6 10101 10 11001 14 11101 28 +01010 6.5 10001 10.5 00011 15 00110 bypass +00100 7 10011 11 11011 16 11110 off +*/ + +/* Sorted according to CFG bits and multiplied by 2 it looks + * like this (note that this is in sequential order, not + * tabulated as above) + */ +signed char mpc7450PllMultByTwo[32] = { +23, 34, 15, 30, +14, 36, 2/*bypass*/, 40, +4, 42, 13, 26, +17, 48, 19, 18, +6, 21, 11, 22, +8, 20, 10, 24, +16, 28, 12, 32, +27, 56, 0/*off*/, 25, +}; + +uint32_t bsp_clicks_per_usec = 0; + +/* + * Total memory using probing. + */ +unsigned int BSP_mem_size; + +/* + * PCI Bus Frequency + */ +unsigned int BSP_bus_frequency = 0xdeadbeef; +/* + * processor clock frequency + */ +unsigned int BSP_processor_frequency = 0xdeadbeef; + +/* + * Time base divisior (bus freq / TB clock) + */ +unsigned int BSP_time_base_divisor = 4000; /* most 604+ CPUs seem to use this */ + +/* Board identification string */ +char BSP_productIdent[20] = {0}; +char BSP_serialNumber[20] = {0}; + +/* VPD appends an extra char -- what for ? */ +char BSP_enetAddr0[7] = {0}; +char BSP_enetAddr1[7] = {0}; + +char *rtems_progname; + +/* + * Use the shared implementations of the following routines + */ + +extern void bsp_pretasking_hook(void); + +#define CMDLINE_BUF_SIZE 2048 + +static char cmdline_buf[CMDLINE_BUF_SIZE]; +char *BSP_commandline_string = cmdline_buf; + +/* this routine is called early and must be safe with a not properly + * aligned stack + */ +char * +save_boot_params(void *r3, void *r4, void* r5, char *cmdline_start, char *cmdline_end) +{ +int i=cmdline_end-cmdline_start; + if ( i >= CMDLINE_BUF_SIZE ) + i = CMDLINE_BUF_SIZE-1; + else if ( i < 0 ) + i = 0; + memmove(cmdline_buf, cmdline_start, i); + cmdline_buf[i]=0; + return cmdline_buf; +} + +static BSP_BoardType board_type = Unknown; + +BSP_BoardType +BSP_getBoardType( void ) +{ + return board_type; +} + +/* + * bsp_start + * + * This routine does the bulk of the system initialization. + */ + +void bsp_start( void ) +{ + unsigned char *stack; + char *chpt; + uint32_t intrStackStart; + uint32_t intrStackSize; + + Triv121PgTbl pt=0; + + VpdBufRec vpdData [] = { + { key: ProductIdent, instance: 0, buf: BSP_productIdent, buflen: sizeof(BSP_productIdent) - 1 }, + { key: SerialNumber, instance: 0, buf: BSP_serialNumber, buflen: sizeof(BSP_serialNumber) - 1 }, + { key: CpuClockHz, instance: 0, buf: &BSP_processor_frequency, buflen: sizeof(BSP_processor_frequency) }, + { key: BusClockHz, instance: 0, buf: &BSP_bus_frequency, buflen: sizeof(BSP_bus_frequency) }, + { key: EthernetAddr, instance: 0, buf: BSP_enetAddr0, buflen: sizeof(BSP_enetAddr0) }, + { key: EthernetAddr, instance: 1, buf: BSP_enetAddr1, buflen: sizeof(BSP_enetAddr1) }, + VPD_END + }; + + /* T. Straumann: 4/2005 + * + * Need to map the system registers early, so we can printk... + * (otherwise we silently die) + */ + /* map the PCI 0, 1 Domain I/O space, GT64260B registers + * and the reserved area so that the size is the power of 2. + */ + setdbat(7, BSP_DEV_AND_PCI_IO_BASE, BSP_DEV_AND_PCI_IO_BASE, BSP_DEV_AND_PCI_IO_SIZE, IO_PAGE); + + /* Intersperse messages with actions to help locate problems */ + printk("-----------------------------------------\n"); + + /* + * Get CPU identification dynamically. Note that the get_ppc_cpu_type() & friends functions + * store the result in global variables so that it can be used latter... + * This also verifies that we run on a known CPU. + */ + get_ppc_cpu_type(); + get_ppc_cpu_revision(); + + /* Make sure we detect a known host bridge */ + BSP_getDiscoveryVersion(/* assert detection */ 1); + + printk("Welcome to RTEMS %s\n", _RTEMS_version ); + + /* Leave all caches as MotLoad left them. Seems to be fine */ + + /* + * the initial stack has aready been set to this value in start.S + * so there is no need to set it in r1 again... It is just for info + * so that it can be printed without accessing R1. + */ + __asm__ volatile("mr %0, 1":"=r"(stack)); + + /* tag the bottom (T. Straumann 6/36/2001 ) */ + + *((uint32_t *)stack) = 0; + + /* + * Initialize the interrupt related settings + * SPRG0 = interrupt nesting level count + * SPRG1 = software managed IRQ stack + * + * This could be done latter (e.g in IRQ_INIT) but it helps to understand + * some settings below... + */ + intrStackStart = (uint32_t)__rtems_end; + intrStackSize = rtems_configuration_get_interrupt_stack_size(); + + /* + * Initialize default raw exception handlers. See vectors/vectors_init.c + */ + ppc_exc_initialize( + PPC_INTERRUPT_DISABLE_MASK_DEFAULT, + intrStackStart, + intrStackSize + ); + + printk("CPU: %s\n", get_ppc_cpu_type_name(current_ppc_cpu)); + + /* + * Initialize RTEMS IRQ system + */ + BSP_rtems_irq_mng_init(0); + + BSP_vpdRetrieveFields(vpdData); + + if ( !strncmp(BSP_productIdent,"MVME5500",8) ) + board_type = MVME5500; + else if ( !strncmp(BSP_productIdent,"MVME6100",8) ) + board_type = MVME6100; + + printk("Board Type: %s (S/N %s)\n", + BSP_productIdent[0] ? BSP_productIdent : "n/a", + BSP_serialNumber[0] ? BSP_serialNumber : "n/a"); + + if ( 0xdeadbeef == BSP_bus_frequency ) { + BSP_bus_frequency = 133333333; + printk("Bus Clock Freq NOT FOUND in VPD; using %10u Hz\n", + BSP_bus_frequency); + } else { + printk("Bus Clock Freq: %10u Hz\n", + BSP_bus_frequency); + } + + if ( 0xdeadbeef == BSP_processor_frequency ) { + BSP_processor_frequency = BSP_bus_frequency/2; + BSP_processor_frequency *= mpc7450PllMultByTwo[ (_read_HID1() >> (31-19)) & 31 ]; + } + printk("CPU Clock Freq: %10u Hz\n", BSP_processor_frequency); + + /* probe real memory size; if it's more than 256M we can't currently access it + * since at this point only BAT-0 maps 0..256M + */ + BSP_mem_size = probeMemoryEnd(); + + if ( (chpt = strstr(BSP_commandline_string,"MEMSZ=")) ) { + char *endp; + uint32_t sz; + chpt+=6 /* strlen("MEMSZ=") */; + sz = strtoul(chpt, &endp, 0); + if ( endp != chpt ) + BSP_mem_size = sz; + } + + printk("Memory: %10u bytes\n", BSP_mem_size); + + if ( BSP_mem_size > 0x10000000 ) { + uint32_t s; + if ( BSP_mem_size > 0x80000000 ) { + BSP_mem_size = 0x80000000; + printk("Memory clipped to 0x%08x for now, sorry\n", BSP_mem_size); + } + for ( s = 0x20000000; s < BSP_mem_size ; s<<=1) + ; + MMUoff(); + /* since it's currently in use we must first surrender it */ + setdbat(0, 0, 0, 0, 0); + setdbat(0, 0, 0, s, _PAGE_RW); + MMUon(); + } + + printk("-----------------------------------------\n"); + + /* Maybe not setup yet because of the warning message */ + + /* Allocate and set up the page table mappings + * This is only available on >604 CPUs. + * + * NOTE: This setup routine may modify the available memory + * size. It is essential to call it before + * calculating the workspace etc. + */ + pt = BSP_pgtbl_setup(&BSP_mem_size); + if (!pt) + printk("WARNING: unable to setup page tables.\n"); + +#ifdef SHOW_MORE_INIT_SETTINGS + printk("Now BSP_mem_size = 0x%x\n",BSP_mem_size); +#endif + + /* + * Set up our hooks + * Make sure libc_init is done before drivers initialized so that + * they can use atexit() + */ + + bsp_clicks_per_usec = BSP_bus_frequency/(BSP_time_base_divisor * 1000); + +#ifdef SHOW_MORE_INIT_SETTINGS + printk( + "Configuration.work_space_size = %x\n", + rtems_configuration_get_work_space_size() + ); +#endif + + /* Activate the page table mappings only after + * initializing interrupts because the irq_mng_init() + * routine needs to modify the text + */ + if ( pt ) { +#ifdef SHOW_MORE_INIT_SETTINGS + printk("Page table setup finished; will activate it NOW...\n"); +#endif + BSP_pgtbl_activate(pt); + } + +#ifdef SHOW_MORE_INIT_SETTINGS + printk("Going to start PCI buses scanning and initialization\n"); +#endif + BSP_pci_initialize(); + + /* need to tweak the motload setup */ + BSP_motload_pci_fixup(); + + /* map 512M, 256 for PCI 256 for VME */ + setdbat(5,BSP_PCI_HOSE0_MEM_BASE, BSP_PCI_HOSE0_MEM_BASE, BSP_PCI_HOSE0_MEM_SIZE, IO_PAGE); + setdbat(6,BSP_PCI_HOSE1_MEM_BASE, BSP_PCI_HOSE1_MEM_BASE, 0x10000000, IO_PAGE); + +#ifdef SHOW_MORE_INIT_SETTINGS + printk("Number of PCI buses found is : %d\n", pci_bus_count()); +#endif + + /* + * Initialize hardware timer facility (not used by BSP itself) + * Needs PCI to identify discovery version... + */ + BSP_timers_initialize(); + +#ifdef SHOW_MORE_INIT_SETTINGS + printk("MSR %x \n", _read_MSR()); + printk("Exit from bspstart\n"); +#endif +} diff --git a/pool/shard003/C/0069164_equisols.c b/pool/shard003/C/0069164_equisols.c new file mode 100644 index 0000000000000000000000000000000000000000..4c8c3685ca08e9de233c9cc0549c81c8ec81885a --- /dev/null +++ b/pool/shard003/C/0069164_equisols.c @@ -0,0 +1,100 @@ +/* + * equisols.c - Equinox and solstice calculations. + * Copyright (C) 2016 Shiva Iyer + * + * 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 . + */ + +/* + * References: Chapter 27 in Meeus. This implementation interpolates + * the apparent geocentric longitude of the Sun from the full VSOP87 + * theory to time equinoxes and solstices. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Calculate the time of the equinox or solstice in the specified year + * and month. + * + * year -- Year number using astronomical reckoning and after 4800BC. + * month -- 3 for March equinox, 6 for June solstice, 9 for September + * equinox, or 12 for December solstice. + * + * Return: Dynamical time in JDE form at which the requested equinox + * or solstice occurs; -1 if the input parameters are invalid. + */ +double equisols(int year, int month) +{ + int steps,i; + double X,w,nutl,nuto,df[24/TIME_STEP+1],lon[24/TIME_STEP+1], + prec[3][3]; + struct julian_date jd0,jd; + struct rectangular_coordinates ear,sun = {0,0,0}; + struct ecliptic_coordinates ecl; + struct equatorial_coordinates equ; + + if (month == 3) + X = TWO_PI; + else if (month == 6) + X = 0.5*PI; + else if (month == 9) + X = 1.0*PI; + else if (month == 12) + X = 1.5*PI; + else + return(-1); + + calendar_to_julian_date(year, month, 20, &jd0); + jd = jd0; + + steps = sizeof(df)/sizeof(double); + for (i = 0; i < steps; i++) { + df[i] = (double)i*TIME_STEP/24; + jd.date2 = jd0.date2 + df[i]; + vsop87_coordinates(EARTH, &jd, &ear); + + lightcor(EARTH, &jd, &ear, NULL); + + vsop87_ecliptic_to_equator(&ear); + + iau2006_precession_matrix(&jd, 0, prec); + rotate_rectangular(prec, &ear); + + rectangular_to_spherical(&sun, &ear, &equ.right_ascension, + &equ.declination, &w); + + iau2000a_nutation(&jd, &nutl, &nuto); + equatorial_to_ecliptic(&equ, iau2000a_mean_obliquity(&jd)+nuto, + &ecl); + lon[i] = ecl.longitude + nutl; + } + + w = 0; + for (i = 1; i < steps; i++) { + if (lon[i-1] > 1.5*PI && lon[i] < 0.5*PI) + w = TWO_PI; + lon[i] += w; + } + + return(jd0.date1 + jd0.date2 + interpolate(steps, lon, df, X)); +} diff --git a/pool/shard003/C/0069166_cxa_finalize.c b/pool/shard003/C/0069166_cxa_finalize.c new file mode 100644 index 0000000000000000000000000000000000000000..b410270f2e298e360d470d4d721f1452d8fb0017 --- /dev/null +++ b/pool/shard003/C/0069166_cxa_finalize.c @@ -0,0 +1,85 @@ +/* Copyright (C) 1999-2016 Free Software Foundation, Inc. + + NOTE: This source is derived from an old version taken from the GNU C + Library (glibc). + +This file is part of GCC. + +GCC 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. + +GCC 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. + +Under Section 7 of GPL version 3, you are granted additional +permissions described in the GCC Runtime Library Exception, version +3.1, as published by the Free Software Foundation. + +You should have received a copy of the GNU General Public License and +a copy of the GCC Runtime Library Exception along with this program; +see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +. */ + +#include +#include +#include "exit.h" + + +static boolean_t +catomic_compare_and_exchange_bool_acq (long *mem, long newval, long oldval) +{ + return ! __atomic_compare_exchange (mem, &oldval, &newval, 0, + __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE); +} + +/* If D is non-NULL, call all functions registered with `__cxa_atexit' + with the same dso handle. Otherwise, if D is NULL, call all of the + registered handlers. */ +void +__cxa_finalize (void *d) +{ + struct exit_function_list *funcs; + + restart: + for (funcs = __exit_funcs; funcs; funcs = funcs->next) + { + struct exit_function *f; + + for (f = &funcs->fns[funcs->idx - 1]; f >= &funcs->fns[0]; --f) + { + void (*cxafn) (void *arg, int status); + void *cxaarg; + + if ((d == NULL || d == f->func.cxa.dso_handle) + /* We don't want to run this cleanup more than once. */ + && (cxafn = f->func.cxa.fn, + cxaarg = f->func.cxa.arg, + ! catomic_compare_and_exchange_bool_acq (&f->flavor, ef_free, + ef_cxa))) + { + uint64_t check = __new_exitfn_called; + +#ifdef PTR_DEMANGLE + PTR_DEMANGLE (cxafn); +#endif + cxafn (cxaarg, 0); + + /* It is possible that that last exit function registered + more exit functions. Start the loop over. */ + if (__builtin_expect (check != __new_exitfn_called, 0)) + goto restart; + } + } + } + + /* Remove the registered fork handlers. We do not have to + unregister anything if the program is going to terminate anyway. */ +#ifdef UNREGISTER_ATFORK + if (d != NULL) + UNREGISTER_ATFORK (d); +#endif +} diff --git a/pool/shard003/C/0069178_timer-gp.c b/pool/shard003/C/0069178_timer-gp.c new file mode 100644 index 0000000000000000000000000000000000000000..02bfb4006b1fe74c9d724381190eece5e649542c --- /dev/null +++ b/pool/shard003/C/0069178_timer-gp.c @@ -0,0 +1,77 @@ +/* + * linux/arch/arm/mach-omap2/timer-gp.c + * + * OMAP2 GP timer support. + * + * Copyright (C) 2005 Nokia Corporation + * Author: Paul Mundt + * Juha Yrjölä + * OMAP Dual-mode timer framework support by Timo Teras + * + * Some parts based off of TI's 24xx code: + * + * Copyright (C) 2004 Texas Instruments, Inc. + * + * Roughly modelled after the OMAP1 MPU timer code. + * + * This file is subject to the terms and conditions of the GNU General Public + * License. See the file "COPYING" in the main directory of this archive + * for more details. + */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +static struct omap_dm_timer *gptimer; + +static inline void omap2_gp_timer_start(unsigned long load_val) +{ + omap_dm_timer_set_load(gptimer, 1, 0xffffffff - load_val); + omap_dm_timer_set_int_enable(gptimer, OMAP_TIMER_INT_OVERFLOW); + omap_dm_timer_start(gptimer); +} + +static irqreturn_t omap2_gp_timer_interrupt(int irq, void *dev_id) +{ + write_seqlock(&xtime_lock); + + omap_dm_timer_write_status(gptimer, OMAP_TIMER_INT_OVERFLOW); + timer_tick(); + + write_sequnlock(&xtime_lock); + + return IRQ_HANDLED; +} + +static struct irqaction omap2_gp_timer_irq = { + .name = "gp timer", + .flags = IRQF_DISABLED | IRQF_TIMER, + .handler = omap2_gp_timer_interrupt, +}; + +static void __init omap2_gp_timer_init(void) +{ + u32 tick_period; + + omap_dm_timer_init(); + gptimer = omap_dm_timer_request_specific(1); + BUG_ON(gptimer == NULL); + + omap_dm_timer_set_source(gptimer, OMAP_TIMER_SRC_SYS_CLK); + tick_period = clk_get_rate(omap_dm_timer_get_fclk(gptimer)) / HZ; + tick_period -= 1; + + setup_irq(omap_dm_timer_get_irq(gptimer), &omap2_gp_timer_irq); + omap2_gp_timer_start(tick_period); +} + +struct sys_timer omap_timer = { + .init = omap2_gp_timer_init, +}; diff --git a/pool/shard003/C/0069185_xc_save.c b/pool/shard003/C/0069185_xc_save.c new file mode 100644 index 0000000000000000000000000000000000000000..adbcb9214122c1655a0129b6b6e70dd95de422b9 --- /dev/null +++ b/pool/shard003/C/0069185_xc_save.c @@ -0,0 +1,328 @@ +/* + * This file is subject to the terms and conditions of the GNU General + * Public License. See the file "COPYING" in the main directory of + * this archive for more details. + * + * Copyright (C) 2005 by Christian Limpach + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +static struct suspendinfo { + int xce; /* event channel handle */ + int suspend_evtchn; +} si; + +/** + * Issue a suspend request through stdout, and receive the acknowledgement + * from stdin. This is handled by XendCheckpoint in the Python layer. + */ +static int compat_suspend(void) +{ + char ans[30]; + + printf("suspend\n"); + fflush(stdout); + + return (fgets(ans, sizeof(ans), stdin) != NULL && + !strncmp(ans, "done\n", 5)); +} + +static int suspend_evtchn_release(void) +{ + if (si.suspend_evtchn >= 0) { + xc_evtchn_unbind(si.xce, si.suspend_evtchn); + si.suspend_evtchn = -1; + } + if (si.xce >= 0) { + xc_evtchn_close(si.xce); + si.xce = -1; + } + + return 0; +} + +static int await_suspend(void) +{ + int rc; + + do { + rc = xc_evtchn_pending(si.xce); + if (rc < 0) { + warnx("error polling suspend notification channel: %d", rc); + return -1; + } + } while (rc != si.suspend_evtchn); + + /* harmless for one-off suspend */ + if (xc_evtchn_unmask(si.xce, si.suspend_evtchn) < 0) + warnx("failed to unmask suspend notification channel: %d", rc); + + return 0; +} + +static int suspend_evtchn_init(int xc, int domid) +{ + struct xs_handle *xs; + char path[128]; + char *portstr; + unsigned int plen; + int port; + int rc; + + si.xce = -1; + si.suspend_evtchn = -1; + + xs = xs_daemon_open(); + if (!xs) { + warnx("failed to get xenstore handle"); + return -1; + } + sprintf(path, "/local/domain/%d/device/suspend/event-channel", domid); + portstr = xs_read(xs, XBT_NULL, path, &plen); + xs_daemon_close(xs); + + if (!portstr || !plen) { + warnx("could not read suspend event channel"); + return -1; + } + + port = atoi(portstr); + free(portstr); + + si.xce = xc_evtchn_open(); + if (si.xce < 0) { + warnx("failed to open event channel handle"); + goto cleanup; + } + + si.suspend_evtchn = xc_evtchn_bind_interdomain(si.xce, domid, port); + if (si.suspend_evtchn < 0) { + warnx("failed to bind suspend event channel: %d", si.suspend_evtchn); + goto cleanup; + } + + rc = xc_domain_subscribe_for_suspend(xc, domid, port); + if (rc < 0) { + warnx("failed to subscribe to domain: %d", rc); + goto cleanup; + } + + /* event channel is pending immediately after binding */ + await_suspend(); + + return 0; + + cleanup: + suspend_evtchn_release(); + + return -1; +} + +/** + * Issue a suspend request to a dedicated event channel in the guest, and + * receive the acknowledgement from the subscribe event channel. */ +static int evtchn_suspend(void) +{ + int rc; + + rc = xc_evtchn_notify(si.xce, si.suspend_evtchn); + if (rc < 0) { + warnx("failed to notify suspend request channel: %d", rc); + return 0; + } + + if (await_suspend() < 0) { + warnx("suspend failed"); + return 0; + } + + /* notify xend that it can do device migration */ + printf("suspended\n"); + fflush(stdout); + + return 1; +} + +static int suspend(void) +{ + if (si.suspend_evtchn >= 0) + return evtchn_suspend(); + + return compat_suspend(); +} + +/* For HVM guests, there are two sources of dirty pages: the Xen shadow + * log-dirty bitmap, which we get with a hypercall, and qemu's version. + * The protocol for getting page-dirtying data from qemu uses a + * double-buffered shared memory interface directly between xc_save and + * qemu-dm. + * + * xc_save calculates the size of the bitmaps and notifies qemu-dm + * through the store that it wants to share the bitmaps. qemu-dm then + * starts filling in the 'active' buffer. + * + * To change the buffers over, xc_save writes the other buffer number to + * the store and waits for qemu to acknowledge that it is now writing to + * the new active buffer. xc_save can then process and clear the old + * active buffer. */ + +static char *qemu_active_path; +static char *qemu_next_active_path; +static int qemu_shmid = -1; +static struct xs_handle *xs; + + +/* Mark the shared-memory segment for destruction */ +static void qemu_destroy_buffer(void) +{ + if (qemu_shmid != -1) + shmctl(qemu_shmid, IPC_RMID, NULL); + qemu_shmid = -1; +} + +/* Get qemu to change buffers. */ +static void qemu_flip_buffer(int domid, int next_active) +{ + char digit = '0' + next_active; + unsigned int len; + char *active_str, **watch; + struct timeval tv; + fd_set fdset; + + /* Tell qemu that we want it to start writing log-dirty bits to the + * other buffer */ + if (!xs_write(xs, XBT_NULL, qemu_next_active_path, &digit, 1)) + errx(1, "can't write next-active to store path (%s)\n", + qemu_next_active_path); + + /* Wait a while for qemu to signal that it has switched to the new + * active buffer */ + read_again: + tv.tv_sec = 5; + tv.tv_usec = 0; + FD_ZERO(&fdset); + FD_SET(xs_fileno(xs), &fdset); + if ((select(xs_fileno(xs) + 1, &fdset, NULL, NULL, &tv)) != 1) + errx(1, "timed out waiting for qemu to switch buffers\n"); + watch = xs_read_watch(xs, &len); + free(watch); + + active_str = xs_read(xs, XBT_NULL, qemu_active_path, &len); + if (active_str == NULL || active_str[0] - '0' != next_active) + /* Watch fired but value is not yet right */ + goto read_again; +} + +static void *init_qemu_maps(int domid, unsigned int bitmap_size) +{ + key_t key; + char key_ascii[17] = {0,}; + void *seg; + char *path, *p; + + /* Make a shared-memory segment */ + do { + key = rand(); /* No security, just a sequence of numbers */ + qemu_shmid = shmget(key, 2 * bitmap_size, + IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR); + if (qemu_shmid == -1 && errno != EEXIST) + errx(1, "can't get shmem to talk to qemu-dm"); + } while (qemu_shmid == -1); + + /* Remember to tidy up after ourselves */ + atexit(qemu_destroy_buffer); + + /* Map it into our address space */ + seg = shmat(qemu_shmid, NULL, 0); + if (seg == (void *) -1) + errx(1, "can't map shmem to talk to qemu-dm"); + memset(seg, 0, 2 * bitmap_size); + + /* Write the size of it into the first 32 bits */ + *(uint32_t *)seg = bitmap_size; + + /* Tell qemu about it */ + if ((xs = xs_daemon_open()) == NULL) + errx(1, "Couldn't contact xenstore"); + if (!(path = strdup("/local/domain/0/device-model/"))) + errx(1, "can't get domain path in store"); + if (!(path = realloc(path, strlen(path) + + 10 + + strlen("/logdirty/next-active") + 1))) + errx(1, "no memory for constructing xenstore path"); + snprintf(path + strlen(path), 11, "%i", domid); + strcat(path, "/logdirty/"); + p = path + strlen(path); + + strcpy(p, "key"); + snprintf(key_ascii, 17, "%16.16llx", (unsigned long long) key); + if (!xs_write(xs, XBT_NULL, path, key_ascii, 16)) + errx(1, "can't write key (%s) to store path (%s)\n", key_ascii, path); + + /* Watch for qemu's indication of the active buffer, and request it + * to start writing to buffer 0 */ + strcpy(p, "active"); + if (!xs_watch(xs, path, "qemu-active-buffer")) + errx(1, "can't set watch in store (%s)\n", path); + if (!(qemu_active_path = strdup(path))) + errx(1, "no memory for copying xenstore path"); + + strcpy(p, "next-active"); + if (!(qemu_next_active_path = strdup(path))) + errx(1, "no memory for copying xenstore path"); + + qemu_flip_buffer(domid, 0); + + free(path); + return seg; +} + + +int +main(int argc, char **argv) +{ + unsigned int domid, maxit, max_f, flags; + int xc_fd, io_fd, ret; + + if (argc != 6) + errx(1, "usage: %s iofd domid maxit maxf flags", argv[0]); + + xc_fd = xc_interface_open(); + if (xc_fd < 0) + errx(1, "failed to open control interface"); + + io_fd = atoi(argv[1]); + domid = atoi(argv[2]); + maxit = atoi(argv[3]); + max_f = atoi(argv[4]); + flags = atoi(argv[5]); + + if (suspend_evtchn_init(xc_fd, domid) < 0) + warnx("suspend event channel initialization failed, using slow path"); + + ret = xc_domain_save(xc_fd, io_fd, domid, maxit, max_f, flags, + &suspend, !!(flags & XCFLAGS_HVM), + &init_qemu_maps, &qemu_flip_buffer); + + suspend_evtchn_release(); + + xc_interface_close(xc_fd); + + return ret; +} diff --git a/pool/shard003/C/0069188_wakeup_fd_eventfd.c b/pool/shard003/C/0069188_wakeup_fd_eventfd.c new file mode 100644 index 0000000000000000000000000000000000000000..f67379e4fcfaf709bf9964e4eebd58b7e2481c13 --- /dev/null +++ b/pool/shard003/C/0069188_wakeup_fd_eventfd.c @@ -0,0 +1,85 @@ +/* + * + * Copyright 2015, Google 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 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 + +#ifdef GPR_LINUX_EVENTFD + +#include +#include +#include + +#include + +#include "src/core/iomgr/wakeup_fd_posix.h" +#include "src/core/profiling/timers.h" + +static void eventfd_create(grpc_wakeup_fd* fd_info) { + int efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); + /* TODO(klempner): Handle failure more gracefully */ + GPR_ASSERT(efd >= 0); + fd_info->read_fd = efd; + fd_info->write_fd = -1; +} + +static void eventfd_consume(grpc_wakeup_fd* fd_info) { + eventfd_t value; + int err; + do { + err = eventfd_read(fd_info->read_fd, &value); + } while (err < 0 && errno == EINTR); +} + +static void eventfd_wakeup(grpc_wakeup_fd* fd_info) { + int err; + GPR_TIMER_BEGIN("eventfd_wakeup", 0); + do { + err = eventfd_write(fd_info->read_fd, 1); + } while (err < 0 && errno == EINTR); + GPR_TIMER_END("eventfd_wakeup", 0); +} + +static void eventfd_destroy(grpc_wakeup_fd* fd_info) { + if (fd_info->read_fd != 0) close(fd_info->read_fd); +} + +static int eventfd_check_availability(void) { + /* TODO(klempner): Actually check if eventfd is available */ + return 1; +} + +const grpc_wakeup_fd_vtable grpc_specialized_wakeup_fd_vtable = { + eventfd_create, eventfd_consume, eventfd_wakeup, eventfd_destroy, + eventfd_check_availability}; + +#endif /* GPR_LINUX_EVENTFD */ diff --git a/pool/shard003/C/0069198_test-distrib.c b/pool/shard003/C/0069198_test-distrib.c new file mode 100644 index 0000000000000000000000000000000000000000..b404c8230d17d8fa64a1864e136f48070b17f4de --- /dev/null +++ b/pool/shard003/C/0069198_test-distrib.c @@ -0,0 +1,87 @@ +/* test-distrib.c --- testing distribution of nonprinting chars + +Copyright (C) 1987, 1993-1995, 1999, 2001-2012 Free Software Foundation, Inc. + +This file is part of GNU Emacs. + +GNU Emacs 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. + +GNU Emacs 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 GNU Emacs. If not, see . */ + + +#include +#include +#include +#include + +/* Break string in two parts to avoid buggy C compilers that ignore characters + after nulls in strings. */ + +static char string1[] = "Testing distribution of nonprinting chars:\n\ +Should be 0177: \177 Should be 0377: \377 Should be 0212: \212.\n\ +Should be 0000: "; + +static char string2[] = ".\n\ +This file is read by the `test-distribution' program.\n\ +If you change it, you will make that program fail.\n"; + +/* Like `read' but keeps trying until it gets SIZE bytes or reaches eof. */ +static int +cool_read (int fd, char *buf, size_t size) +{ + ssize_t num; + ssize_t sofar = 0; + + while (1) + { + if ((num = read (fd, buf + sofar, size - sofar)) == 0) + return sofar; + else if (num < 0) + return num; + sofar += num; + } +} + +int +main (int argc, char **argv) +{ + int fd; + char buf[300]; + + if (argc != 2) + { + fprintf (stderr, "Usage: %s testfile\n", argv[0]); + exit (EXIT_FAILURE); + } + fd = open (argv[1], O_RDONLY); + if (fd < 0) + { + perror (argv[1]); + exit (EXIT_FAILURE); + } + if (cool_read (fd, buf, sizeof string1) != sizeof string1 || + strcmp (buf, string1) || + cool_read (fd, buf, sizeof string2) != sizeof string2 - 1 || + strncmp (buf, string2, sizeof string2 - 1)) + { + fprintf (stderr, "Data in file `%s' has been damaged.\n\ +Most likely this means that many nonprinting characters\n\ +have been corrupted in the files of Emacs, and it will not work.\n", + argv[1]); + exit (EXIT_FAILURE); + } + close (fd); + return EXIT_SUCCESS; +} + + +/* test-distrib.c ends here */ diff --git a/pool/shard003/C/0069200_2016-8-20-B.c b/pool/shard003/C/0069200_2016-8-20-B.c new file mode 100644 index 0000000000000000000000000000000000000000..52ce75019882c1847b2151e801f13ca55dac7c1d --- /dev/null +++ b/pool/shard003/C/0069200_2016-8-20-B.c @@ -0,0 +1,29 @@ +#include +#include + +long long shit[1000024]; +long long fuck(int n) { + long long ans = shit[0]; + int i; + for(i = 0; i < n; i++) + if(shit[i] > 1) + ans += (shit[i] * (shit[i] - 1)) / 2; + return ans; +} +int main() { + int a, num, sum, n, d, i; + scanf("%d", &a); + while(a--) { + sum = 0; + memset(shit, 0, sizeof(shit)); + scanf("%d %d", &d, &n); + for(i = 0; i < n; i++) { + scanf("%d", &num); + sum = (sum + num) % d; + shit[sum]++; + } + printf("%I64d\n", fuck(d)); + } + return 0; +} + diff --git a/pool/shard003/C/0069216_CWE190_Integer_Overflow__int_fscanf_preinc_67a.c b/pool/shard003/C/0069216_CWE190_Integer_Overflow__int_fscanf_preinc_67a.c new file mode 100644 index 0000000000000000000000000000000000000000..2d0173d74d042061261eeefe6f2168f669534a20 --- /dev/null +++ b/pool/shard003/C/0069216_CWE190_Integer_Overflow__int_fscanf_preinc_67a.c @@ -0,0 +1,108 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE190_Integer_Overflow__int_fscanf_preinc_67a.c +Label Definition File: CWE190_Integer_Overflow__int.label.xml +Template File: sources-sinks-67a.tmpl.c +*/ +/* + * @description + * CWE: 190 Integer Overflow + * BadSource: fscanf Read data from the console using fscanf() + * GoodSource: Set data to a small, non-zero number (two) + * Sinks: increment + * GoodSink: Ensure there will not be an overflow before incrementing data + * BadSink : Increment data, which can cause an overflow + * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +typedef struct _CWE190_Integer_Overflow__int_fscanf_preinc_67_structType +{ + int structFirst; +} CWE190_Integer_Overflow__int_fscanf_preinc_67_structType; + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE190_Integer_Overflow__int_fscanf_preinc_67b_badSink(CWE190_Integer_Overflow__int_fscanf_preinc_67_structType myStruct); + +void CWE190_Integer_Overflow__int_fscanf_preinc_67_bad() +{ + int data; + CWE190_Integer_Overflow__int_fscanf_preinc_67_structType myStruct; + /* Initialize data */ + data = 0; + /* POTENTIAL FLAW: Read data from the console using fscanf() */ + fscanf(stdin, "%d", &data); + myStruct.structFirst = data; + CWE190_Integer_Overflow__int_fscanf_preinc_67b_badSink(myStruct); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE190_Integer_Overflow__int_fscanf_preinc_67b_goodG2BSink(CWE190_Integer_Overflow__int_fscanf_preinc_67_structType myStruct); + +static void goodG2B() +{ + int data; + CWE190_Integer_Overflow__int_fscanf_preinc_67_structType myStruct; + /* Initialize data */ + data = 0; + /* FIX: Use a small, non-zero value that will not cause an integer overflow in the sinks */ + data = 2; + myStruct.structFirst = data; + CWE190_Integer_Overflow__int_fscanf_preinc_67b_goodG2BSink(myStruct); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void CWE190_Integer_Overflow__int_fscanf_preinc_67b_goodB2GSink(CWE190_Integer_Overflow__int_fscanf_preinc_67_structType myStruct); + +static void goodB2G() +{ + int data; + CWE190_Integer_Overflow__int_fscanf_preinc_67_structType myStruct; + /* Initialize data */ + data = 0; + /* POTENTIAL FLAW: Read data from the console using fscanf() */ + fscanf(stdin, "%d", &data); + myStruct.structFirst = data; + CWE190_Integer_Overflow__int_fscanf_preinc_67b_goodB2GSink(myStruct); +} + +void CWE190_Integer_Overflow__int_fscanf_preinc_67_good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE190_Integer_Overflow__int_fscanf_preinc_67_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE190_Integer_Overflow__int_fscanf_preinc_67_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard003/C/0069217_anyauthput.c b/pool/shard003/C/0069217_anyauthput.c new file mode 100644 index 0000000000000000000000000000000000000000..eb91d991b5675954479cb163f0b9aeaeeee813f3 --- /dev/null +++ b/pool/shard003/C/0069217_anyauthput.c @@ -0,0 +1,168 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2017, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +/* + * HTTP PUT upload with authentiction using "any" method. libcurl picks the + * one the server supports/wants. + * + */ +#include +#include +#ifdef WIN32 +# include +#else +# include +#endif +#include +#include + +#include + +#if LIBCURL_VERSION_NUM < 0x070c03 +#error "upgrade your libcurl to no less than 7.12.3" +#endif + +/* + * This example shows a HTTP PUT operation with authentiction using "any" + * type. It PUTs a file given as a command line argument to the URL also given + * on the command line. + * + * Since libcurl 7.12.3, using "any" auth and POST/PUT requires a set ioctl + * function. + * + * This example also uses its own read callback. + */ + +/* ioctl callback function */ +static curlioerr my_ioctl(CURL *handle, curliocmd cmd, void *userp) +{ + int *fdp = (int *)userp; + int fd = *fdp; + + (void)handle; /* not used in here */ + + switch(cmd) { + case CURLIOCMD_RESTARTREAD: + /* mr libcurl kindly asks as to rewind the read data stream to start */ + if(-1 == lseek(fd, 0, SEEK_SET)) + /* couldn't rewind */ + return CURLIOE_FAILRESTART; + + break; + + default: /* ignore unknown commands */ + return CURLIOE_UNKNOWNCMD; + } + return CURLIOE_OK; /* success! */ +} + +/* read callback function, fread() look alike */ +static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream) +{ + ssize_t retcode; + curl_off_t nread; + + int *fdp = (int *)stream; + int fd = *fdp; + + retcode = read(fd, ptr, size * nmemb); + + nread = (curl_off_t)retcode; + + fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T + " bytes from file\n", nread); + + return retcode; +} + +int main(int argc, char **argv) +{ + CURL *curl; + CURLcode res; + int hd; + struct stat file_info; + + char *file; + char *url; + + if(argc < 3) + return 1; + + file = argv[1]; + url = argv[2]; + + /* get the file size of the local file */ + hd = open(file, O_RDONLY); + fstat(hd, &file_info); + + /* In windows, this will init the winsock stuff */ + curl_global_init(CURL_GLOBAL_ALL); + + /* get a curl handle */ + curl = curl_easy_init(); + if(curl) { + /* we want to use our own read function */ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* which file to upload */ + curl_easy_setopt(curl, CURLOPT_READDATA, (void *)&hd); + + /* set the ioctl function */ + curl_easy_setopt(curl, CURLOPT_IOCTLFUNCTION, my_ioctl); + + /* pass the file descriptor to the ioctl callback as well */ + curl_easy_setopt(curl, CURLOPT_IOCTLDATA, (void *)&hd); + + /* enable "uploading" (which means PUT when doing HTTP) */ + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* specify target URL, and note that this URL should also include a file + name, not only a directory (as you can do with GTP uploads) */ + curl_easy_setopt(curl, CURLOPT_URL, url); + + /* and give the size of the upload, this supports large file sizes + on systems that have general support for it */ + curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, + (curl_off_t)file_info.st_size); + + /* tell libcurl we can use "any" auth, which lets the lib pick one, but it + also costs one extra round-trip and possibly sending of all the PUT + data twice!!! */ + curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_ANY); + + /* set user name and password for the authentication */ + curl_easy_setopt(curl, CURLOPT_USERPWD, "user:password"); + + /* Now run off and do what you've been told! */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + close(hd); /* close the local file */ + + curl_global_cleanup(); + return 0; +} diff --git a/pool/shard003/C/0069221_parsepkg-py.c b/pool/shard003/C/0069221_parsepkg-py.c new file mode 100644 index 0000000000000000000000000000000000000000..bd6cc46c1bdd3e20538531ebdbb2560ad682d452 --- /dev/null +++ b/pool/shard003/C/0069221_parsepkg-py.c @@ -0,0 +1,103 @@ +/* createrepo_c - Library of routines for manipulation with repodata + * Copyright (C) 2013 Tomas Mlcoch + * + * 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 "src/createrepo_c.h" + +#include "typeconversion.h" +#include "parsepkg-py.h" +#include "package-py.h" +#include "exception-py.h" + +PyObject * +py_package_from_rpm(PyObject *self, PyObject *args) +{ + CR_UNUSED(self); + + PyObject *ret; + cr_Package *pkg; + int checksum_type, changelog_limit; + char *filename, *location_href, *location_base; + GError *tmp_err = NULL; + + if (!PyArg_ParseTuple(args, "sizzi:py_package_from_rpm", + &filename, + &checksum_type, + &location_href, + &location_base, + &changelog_limit)) { + return NULL; + } + + pkg = cr_package_from_rpm(filename, checksum_type, location_href, + location_base, changelog_limit, NULL, &tmp_err); + if (tmp_err) { + nice_exception(&tmp_err, "Cannot load %s: ", filename); + return NULL; + } + + ret = Object_FromPackage(pkg, 1); + return ret; +} + +PyObject * +py_xml_from_rpm(PyObject *self, PyObject *args) +{ + CR_UNUSED(self); + + PyObject *tuple; + int checksum_type, changelog_limit; + char *filename, *location_href, *location_base; + struct cr_XmlStruct xml_res; + GError *tmp_err = NULL; + + if (!PyArg_ParseTuple(args, "sizzi:py_xml_from_rpm", + &filename, + &checksum_type, + &location_href, + &location_base, + &changelog_limit)) { + return NULL; + } + + xml_res = cr_xml_from_rpm(filename, checksum_type, location_href, + location_base, changelog_limit, NULL, &tmp_err); + if (tmp_err) { + nice_exception(&tmp_err, "Cannot load %s: ", filename); + return NULL; + } + + if ((tuple = PyTuple_New(3)) == NULL) + goto py_xml_from_rpm_end; // Free xml_res and return NULL + + PyTuple_SetItem(tuple, 0, PyStringOrNone_FromString(xml_res.primary)); + PyTuple_SetItem(tuple, 1, PyStringOrNone_FromString(xml_res.filelists)); + PyTuple_SetItem(tuple, 2, PyStringOrNone_FromString(xml_res.other)); + +py_xml_from_rpm_end: + free(xml_res.primary); + free(xml_res.filelists); + free(xml_res.other); + + return tuple; +} + diff --git a/pool/shard003/C/0069222_readstd.c b/pool/shard003/C/0069222_readstd.c new file mode 100644 index 0000000000000000000000000000000000000000..b38485b40b227ae467fa85ba5d4f431e33c76d25 --- /dev/null +++ b/pool/shard003/C/0069222_readstd.c @@ -0,0 +1,49 @@ +/* +* Parser +* -- Beispiel aus 185.A48 Uebersetzerbau +* -- Author: Peter Nirschl (#1025647) +* -- E-Mail: e1025647@student.tuwien.ac.at +*/ + +#include "readstd.h" +#include +#include +#include + +#define READ_STD_BUFFER_SIZE 1024 + +char *readFromStdin(void) +{ + char buffer[READ_STD_BUFFER_SIZE]; + size_t contentSize = 1; + + char *content = malloc(sizeof(char) * READ_STD_BUFFER_SIZE); + if(content == NULL) + { + fprintf(stderr, "FATAL ERROR: failed to allocate memory\n"); + exit(-1); + } + content[0] = '\0'; + while(fgets(buffer, READ_STD_BUFFER_SIZE, stdin)) + { + char *old = content; + contentSize += strlen(buffer); + content = realloc(content, contentSize); + if(content == NULL) + { + fprintf(stderr, "FATAL ERROR: failed to allocate memory\n"); + free(old); + exit(-1); + } + strcat(content, buffer); + } + + if(ferror(stdin)) + { + free(content); + fprintf(stderr, "Input error while reading from stdin\n"); + exit(-1); + } + return content; +} +