text
stringlengths 13
30k
|
---|
{"text": "i am ever feeling nostalgic about the fireplace i will know that it is still on the property", "label": 2, "label_text": "love"}
|
{"text": "i am feeling grouchy", "label": 3, "label_text": "anger"}
|
{"text": "ive been feeling a little burdened lately wasnt sure why that was", "label": 0, "label_text": "sadness"}
|
{"text": "ive been taking or milligrams or times recommended amount and ive fallen asleep a lot faster but i also feel like so funny", "label": 5, "label_text": "surprise"}
|
{"text": "i feel as confused about life as a teenager or as jaded as a year old man", "label": 4, "label_text": "fear"}
|
{"text": "i have been with petronas for years i feel that petronas has performed well and made a huge profit", "label": 1, "label_text": "joy"}
|
{"type": "swimmingpool", "entrance fee": "?", "area": "east", "openhours": "?", "postcode": "cb58nt", "location": [52.208789, 0.154883], "pricerange": "?", "name": "abbey pool and astroturf pitch", "phone": "01223902088", "address": "pool way, whitehill road, off newmarket road", "id": "1"}
|
{"type": "theatre", "entrance fee": "?", "area": "centre", "openhours": "?", "postcode": "cb58as", "location": [52.208699, 0.12006], "pricerange": "?", "name": "adc theatre", "phone": "01223300085", "address": "park street", "id": "2"}
|
{"type": "architecture", "entrance fee": "free", "area": "centre", "openhours": "it opens normally daily from 9 a.m. to 5 p.m., at other times the key can be borrowed from a nearby key holder.", "postcode": "cb58bs", "location": [52.2078083333333, 0.125616666666667], "pricerange": "free", "name": "all saints church", "phone": "01223452587", "address": "jesus lane", "id": "3"}
|
{"type": "nightclub", "entrance fee": "5 pounds", "area": "centre", "openhours": "it opens from 10:30 p.m. to 03:30 a.m on thursday, from 11:00 p.m. to 04:00 a.m. on friday, from 10:00 p.m. to 03:30 a.m. on saturday, and from 10:00 p.m. to 02:30 a.m. on monday", "postcode": "cb23na", "location": [52.20478, 0.11975], "pricerange": "moderate", "name": "ballare", "phone": "01223364222", "address": "heidelberg gardens, lion yard", "id": "4"}
|
{"type": "museum", "entrance fee": "free", "area": "centre", "openhours": "?", "postcode": "cb11ln", "location": [52.207409, 0.126738], "pricerange": "free", "name": "broughton house gallery", "phone": "01223314960", "address": "98 king street", "id": "5"}
|
{"type": "museum", "entrance fee": "free", "area": "south", "openhours": "it opens from 09:30 a.m. to 5:30 p.m. from monday to saturday, and from 11:00 a.m. to 4:00 p.m. on sunday", "postcode": "cb21sj", "location": [52.1725982, 0.1112224], "pricerange": "free", "name": "byard art", "phone": "01223464646", "address": "14 king's parade", "id": "6"}
|
{"type": "museum", "entrance fee": "free", "area": "west", "openhours": "it opens from 10:30 a.m. to 5:30 p.m. thursday to saturday", "postcode": "cb30af", "location": [52.221949, 0.094948], "pricerange": "free", "name": "cafe jello gallery", "phone": "01223312112", "address": "cafe jello gallery, 13 magdalene street", "id": "7"}
|
{"type": "boat", "entrance fee": "?", "area": "east", "openhours": "?", "postcode": "cb58sx", "location": [52.21247, 0.15619], "pricerange": "?", "name": "camboats", "phone": "01223902112", "address": "the plough, green end, fen ditton,", "id": "8"}
|
{"type": "museum", "entrance fee": "3.50 pounds", "area": "west", "openhours": "it opens from monday to saturday, 10 a.m. to 5 p.m. while on sunday it opens from 2 p.m. to 5 p.m.", "postcode": "cb30aq", "location": [52.210766, 0.114795], "pricerange": "moderate", "name": "cambridge and county folk museum", "phone": "01223355159", "address": "2-3 castle street", "id": "9"}
|
{"type": "theatre", "entrance fee": "?", "area": "centre", "openhours": "?", "postcode": "cb23pj", "location": [52.2034781571435, 0.119176917855308], "pricerange": "?", "name": "cambridge arts theatre", "phone": "01223503333", "address": "6 saint edward's passage", "id": "10"}
|
{"text": "Dick In The Ass and Dildo In The Pussy\n\nDick In The Ass and Dildo In The Pussy", "meta": {"pile_set_name": "OpenWebText2"}, "score": 0.10256410256410256}
|
{"text": "<iLetBigSHITS> THEY CLOGGED UP THE TOILET\n\n<iLetBigSHITS> SHIT SHIT SHIT SHIT SHIT SHIT SHIT SHIT SHIT SHIT IT CLOGGED THE TOILET SHIT SHIT SHIT SHIT SHIT IT CLOGGED THE TOILET", "meta": {"pile_set_name": "OpenWebText2"}, "score": 0.08522727272727272}
|
{"text": "ddir = 'xx'\n", "meta": {"pile_set_name": "Github"}, "score": 0.08333333333333333}
|
{"text": "Latina with big tits sucks the best dick", "meta": {"pile_set_name": "OpenWebText2"}, "score": 0.075}
|
{"text": "Intense Doggystyle Then Jizz On Her Butt", "meta": {"pile_set_name": "OpenWebText2"}, "score": 0.075}
|
{"text": "NEW BUSTY BLONDE ANAL MILF HARDCORE! FAKE TITS! BUBBLE BUTT! CUMMING ON EYE AND TITS OPEN MOUTH FACIAL!\n\n205", "meta": {"pile_set_name": "OpenWebText2"}, "score": 0.07407407407407407}
|
{"_data_files": [{"filename": "dataset.arrow"}], "_fingerprint": "b02ad27348fe4438", "_format_columns": ["image", "target"], "_format_kwargs": {}, "_format_type": null, "_indexes": {}, "_output_all_columns": false, "_split": null}
|
{"OriginalTweet": "#MachineLearning Predicts #COVID19 Outcomes https://t.co/WW5ARwCyj8 via @Contagion_Live #HealthTech #digitalhealth"}
|
{"OriginalTweet": "#Georgia #COVID19 surveillance. #gapol #coronavirus https://t.co/IgmggJe9b9"}
|
{"text": "\nimport re\nimport os\nimport sys\nimport time\nimport types\nimport getopt\nimport unittest\nimport traceback\n\ntry:\n # Python >=2.7 and >=3.2\n from unittest.runner import _TextTestResult\nexcept ImportError:\n from unittest import _TextTestResult\n\n__metaclass__ = type\n\ndef stderr(text):\n sys.stderr.write(text)\n sys.stderr.write(\"\\n\")\n\nclass Options:\n \"\"\"Configurable properties of the test runner.\"\"\"\n\n # test location\n basedir = '' # base directory for tests (defaults to\n # basedir of argv[0] + 'src'), must be absolute\n follow_symlinks = True # should symlinks to subdirectories be\n # followed? (hardcoded, may cause loops)\n\n # which tests to run\n unit_tests = False # unit tests (default if both are false)\n functional_tests = False # functional tests\n\n # test filtering\n level = 1 # run only tests at this or lower level\n # (if None, runs all tests)\n pathname_regex = '' # regexp for filtering filenames\n test_regex = '' # regexp for filtering test cases\n\n # actions to take\n list_files = False # --list-files\n list_tests = False # --list-tests\n list_hooks = False # --list-hooks\n run_tests = True # run tests (disabled by --list-foo)\n\n # output verbosity\n verbosity = 0 # verbosity level (-v)\n quiet = 0 # do not print anything on success (-q)\n warn_omitted = False # produce warnings when a test case is\n # not included in a test suite (-w)\n progress = False # show running progress (-p)\n coverage = False # produce coverage reports (--coverage)\n coverdir = 'coverage' # where to put them (currently hardcoded)\n immediate_errors = False # show tracebacks twice (currently hardcoded)\n screen_width = 80 # screen width (autodetected)\n\n\ndef compile_matcher(regex):\n \"\"\"Returns a function that takes one argument and returns True or False.\n\n Regex is a regular expression. Empty regex matches everything. There\n is one expression: if the regex starts with \"!\", the meaning of it is\n reversed.\n \"\"\"\n if not regex:\n return lambda x: True\n elif regex == '!':\n return lambda x: False\n elif regex.startswith('!'):\n rx = re.compile(regex[1:])\n return lambda x: rx.search(x) is None\n else:\n rx = re.compile(regex)\n return lambda x: rx.search(x) is not None\n\n\ndef walk_with_symlinks(top, func, arg):\n \"\"\"Like os.path.walk, but follows symlinks on POSIX systems.\n\n If the symlinks create a loop, this function will never finish.\n \"\"\"\n try:\n names = os.listdir(top)\n except os.error:\n return\n func(arg, top, names)\n exceptions = ('.', '..')\n for name in names:\n if name not in exceptions:\n name = os.path.join(top, name)\n if os.path.isdir(name):\n walk_with_symlinks(name, func, arg)\n\n\ndef get_test_files(cfg):\n \"\"\"Returns a list of test module filenames.\"\"\"\n matcher = compile_matcher(cfg.pathname_regex)\n results = []\n test_names = []\n if cfg.unit_tests:\n test_names.append('tests')\n if cfg.functional_tests:\n test_names.append('ftests')\n baselen = len(cfg.basedir) + 1\n def visit(ignored, dir, files):\n if os.path.basename(dir) not in test_names:\n for name in test_names:\n if name + '.py' in files:\n path = os.path.join(dir, name + '.py')\n if matcher(path[baselen:]):\n results.append(path)\n return\n if '__init__.py' not in files:\n stderr(\"%s is not a package\" % dir)\n return\n for file in files:\n if file.startswith('test') and file.endswith('.py'):\n path = os.path.join(dir, file)\n if matcher(path[baselen:]):\n results.append(path)\n if cfg.follow_symlinks:\n walker = walk_with_symlinks\n else:\n walker = os.path.walk\n walker(cfg.basedir, visit, None)\n results.sort()\n return results\n\n\ndef import_module(filename, cfg, cov=None):\n \"\"\"Imports and returns a module.\"\"\"\n filename = os.path.splitext(filename)[0]\n modname = filename[len(cfg.basedir):].replace(os.path.sep, '.')\n if modname.startswith('.'):\n modname = modname[1:]\n if cov is not None:\n cov.start()\n mod = __import__(modname)\n if cov is not None:\n cov.stop()\n components = modname.split('.')\n for comp in components[1:]:\n mod = getattr(mod, comp)\n return mod\n\n\ndef filter_testsuite(suite, matcher, level=None):\n \"\"\"Returns a flattened list of test cases that match the given matcher.\"\"\"\n if not isinstance(suite, unittest.TestSuite):\n raise TypeError('not a TestSuite', suite)\n results = []\n for test in suite._tests:\n if level is not None and getattr(test, 'level', 0) > level:\n continue\n if isinstance(test, unittest.TestCase):\n testname = test.id() # package.module.class.method\n if matcher(testname):\n results.append(test)\n else:\n filtered = filter_testsuite(test, matcher, level)\n results.extend(filtered)\n return results\n\n\ndef get_all_test_cases(module):\n \"\"\"Returns a list of all test case classes defined in a given module.\"\"\"\n results = []\n for name in dir(module):\n if not name.startswith('Test'):\n continue\n item = getattr(module, name)\n if (isinstance(item, (type, types.ClassType)) and\n issubclass(item, unittest.TestCase)):\n results.append(item)\n return results\n\n\ndef get_test_classes_from_testsuite(suite):\n \"\"\"Returns a set of test case classes used in a test suite.\"\"\"\n if not isinstance(suite, unittest.TestSuite):\n raise TypeError('not a TestSuite', suite)\n results = set()\n for test in suite._tests:\n if isinstance(test, unittest.TestCase):\n results.add(test.__class__)\n else:\n classes = get_test_classes_from_testsuite(test)\n results.update(classes)\n return results\n\n\ndef get_test_cases(test_files, cfg, cov=None):\n \"\"\"Returns a list of test cases from a given list of test modules.\"\"\"\n matcher = compile_matcher(cfg.test_regex)\n results = []\n for file in test_files:\n module = import_module(file, cfg, cov=cov)\n if cov is not None:\n cov.start()\n test_suite = module.test_suite()\n if cov is not None:\n cov.stop()\n if test_suite is None:\n continue\n if cfg.warn_omitted:\n all_classes = set(get_all_test_cases(module))\n classes_in_suite = get_test_classes_from_testsuite(test_suite)\n difference = all_classes - classes_in_suite\n for test_class in difference:\n # surround the warning with blank lines, otherwise it tends\n # to get lost in the noise\n stderr(\"\\n%s: WARNING: %s not in test suite\\n\"\n % (file, test_class.__name__))\n if (cfg.level is not None and\n getattr(test_suite, 'level', 0) > cfg.level):\n continue\n filtered = filter_testsuite(test_suite, matcher, cfg.level)\n results.extend(filtered)\n return results\n\n\ndef get_test_hooks(test_files, cfg, cov=None):\n \"\"\"Returns a list of test hooks from a given list of test modules.\"\"\"\n results = []\n dirs = set(map(os.path.dirname, test_files))\n for dir in list(dirs):\n if os.path.basename(dir) == 'ftests':\n dirs.add(os.path.join(os.path.dirname(dir), 'tests'))\n dirs = list(dirs)\n dirs.sort()\n for dir in dirs:\n filename = os.path.join(dir, 'checks.py')\n if os.path.exists(filename):\n module = import_module(filename, cfg, tracer=tracer)\n if cov is not None:\n cov.start()\n hooks = module.test_hooks()\n if cov is not None:\n cov.stop()\n results.extend(hooks)\n return results\n\n\nclass CustomTestResult(_TextTestResult):\n \"\"\"Customised TestResult.\n\n It can show a progress bar, and displays tracebacks for errors and failures\n as soon as they happen, in addition to listing them all at the end.\n \"\"\"\n\n __super = _TextTestResult\n __super_init = __super.__init__\n __super_startTest = __super.startTest\n __super_stopTest = __super.stopTest\n __super_printErrors = __super.printErrors\n\n def __init__(self, stream, descriptions, verbosity, count, cfg, hooks):\n self.__super_init(stream, descriptions, verbosity)\n self.count = count\n self.cfg = cfg\n self.hooks = hooks\n if cfg.progress:\n self.dots = False\n self._lastWidth = 0\n self._maxWidth = cfg.screen_width - len(\"xxxx/xxxx (xxx.x%): \") - 1\n\n def startTest(self, test):\n if self.cfg.progress:\n # verbosity == 0: 'xxxx/xxxx (xxx.x%)'\n # verbosity == 1: 'xxxx/xxxx (xxx.x%): test name'\n # verbosity >= 2: 'xxxx/xxxx (xxx.x%): test name ... ok'\n n = self.testsRun + 1\n self.stream.write(\"\\r%4d\" % n)\n if self.count:\n self.stream.write(\"/%d (%5.1f%%)\"\n % (self.count, n * 100.0 / self.count))\n if self.showAll: # self.cfg.verbosity == 1\n self.stream.write(\": \")\n elif self.cfg.verbosity:\n name = self.getShortDescription(test)\n width = len(name)\n if width < self._lastWidth:\n name += \" \" * (self._lastWidth - width)\n self.stream.write(\": %s\" % name)\n self._lastWidth = width\n self.stream.flush()\n self.__super_startTest(test)\n for hook in self.hooks:\n hook.startTest(test)\n\n def stopTest(self, test):\n for hook in self.hooks:\n hook.stopTest(test)\n self.__super_stopTest(test)\n\n def getShortDescription(self, test):\n s = self.getDescription(test)\n if len(s) > self._maxWidth:\n # s is 'testname (package.module.class)'\n # try to shorten it to 'testname (...age.module.class)'\n # if it is still too long, shorten it to 'testnam...'\n # limit case is 'testname (...)'\n pos = s.find(\" (\")\n if pos + len(\" (...)\") > self._maxWidth:\n s = s[:self._maxWidth - 3] + \"...\"\n else:\n s = \"%s...%s\" % (s[:pos + 2], s[pos + 5 - self._maxWidth:])\n return s\n\n def printErrors(self):\n if self.cfg.progress and not (self.dots or self.showAll):\n self.stream.writeln()\n self.__super_printErrors()\n\n def formatError(self, err):\n return \"\".join(traceback.format_exception(*err))\n\n def printTraceback(self, kind, test, err):\n self.stream.writeln()\n self.stream.writeln()\n self.stream.writeln(\"%s: %s\" % (kind, test))\n self.stream.writeln(self.formatError(err))\n self.stream.writeln()\n\n def addFailure(self, test, err):\n if self.cfg.immediate_errors:\n self.printTraceback(\"FAIL\", test, err)\n self.failures.append((test, self.formatError(err)))\n\n def addError(self, test, err):\n if self.cfg.immediate_errors:\n self.printTraceback(\"ERROR\", test, err)\n self.errors.append((test, self.formatError(err)))\n\n\nclass CustomTestRunner(unittest.TextTestRunner):\n \"\"\"Customised TestRunner.\n\n See CustomisedTextResult for a list of extensions.\n \"\"\"\n\n __super = unittest.TextTestRunner\n __super_init = __super.__init__\n __super_run = __super.run\n\n def __init__(self, cfg, hooks=None):\n self.__super_init(verbosity=cfg.verbosity)\n self.cfg = cfg\n if hooks is not None:\n self.hooks = hooks\n else:\n self.hooks = []\n\n def run(self, test):\n \"\"\"Run the given test case or test suite.\"\"\"\n self.count = test.countTestCases()\n result = self._makeResult()\n startTime = time.time()\n test(result)\n stopTime = time.time()\n timeTaken = float(stopTime - startTime)\n result.printErrors()\n run = result.testsRun\n if not self.cfg.quiet:\n self.stream.writeln(result.separator2)\n self.stream.writeln(\"Ran %d test%s in %.3fs\" %\n (run, run != 1 and \"s\" or \"\", timeTaken))\n self.stream.writeln()\n if not result.wasSuccessful():\n self.stream.write(\"FAILED (\")\n failed, errored = list(map(len, (result.failures, result.errors)))\n if failed:\n self.stream.write(\"failures=%d\" % failed)\n if errored:\n if failed: self.stream.write(\", \")\n self.stream.write(\"errors=%d\" % errored)\n self.stream.writeln(\")\")\n elif not self.cfg.quiet:\n self.stream.writeln(\"OK\")\n return result\n\n def _makeResult(self):\n return CustomTestResult(self.stream, self.descriptions, self.verbosity,\n cfg=self.cfg, count=self.count,\n hooks=self.hooks)\n\n\ndef main(argv):\n \"\"\"Main program.\"\"\"\n\n # Environment\n if sys.version_info < (2, 7):\n stderr('%s: need Python 2.7 or later' % argv[0])\n stderr('your python is %s' % sys.version)\n return 1\n\n # Defaults\n cfg = Options()\n cfg.basedir = os.path.join(os.path.dirname(argv[0]), 'src')\n cfg.basedir = os.path.abspath(cfg.basedir)\n\n # Figure out terminal size\n try:\n import curses\n except ImportError:\n pass\n else:\n try:\n curses.setupterm()\n cols = curses.tigetnum('cols')\n if cols > 0:\n cfg.screen_width = cols\n except (curses.error, TypeError):\n # tigetnum() is broken in PyPy3 and raises TypeError\n pass\n\n # Option processing\n opts, args = getopt.gnu_getopt(argv[1:], 'hvpqufw',\n ['list-files', 'list-tests', 'list-hooks',\n 'level=', 'all-levels', 'coverage'])\n for k, v in opts:\n if k == '-h':\n print(__doc__)\n return 0\n elif k == '-v':\n cfg.verbosity += 1\n cfg.quiet = False\n elif k == '-p':\n cfg.progress = True\n cfg.quiet = False\n elif k == '-q':\n cfg.verbosity = 0\n cfg.progress = False\n cfg.quiet = True\n elif k == '-u':\n cfg.unit_tests = True\n elif k == '-f':\n cfg.functional_tests = True\n elif k == '-w':\n cfg.warn_omitted = True\n elif k == '--list-files':\n cfg.list_files = True\n cfg.run_tests = False\n elif k == '--list-tests':\n cfg.list_tests = True\n cfg.run_tests = False\n elif k == '--list-hooks':\n cfg.list_hooks = True\n cfg.run_tests = False\n elif k == '--coverage':\n cfg.coverage = True\n elif k == '--level':\n try:\n cfg.level = int(v)\n except ValueError:\n stderr('%s: invalid level: %s' % (argv[0], v))\n stderr('run %s -h for help')\n return 1\n elif k == '--all-levels':\n cfg.level = None\n else:\n stderr('%s: invalid option: %s' % (argv[0], k))\n stderr('run %s -h for help')\n return 1\n if args:\n cfg.pathname_regex = args[0]\n if len(args) > 1:\n cfg.test_regex = args[1]\n if len(args) > 2:\n stderr('%s: too many arguments: %s' % (argv[0], args[2]))\n stderr('run %s -h for help')\n return 1\n if not cfg.unit_tests and not cfg.functional_tests:\n cfg.unit_tests = True\n\n # Set up the python path\n sys.path[0] = cfg.basedir\n\n # Set up tracing before we start importing things\n cov = None\n if cfg.run_tests and cfg.coverage:\n from coverage import coverage\n cov = coverage(omit=['test.py'])\n\n # Finding and importing\n test_files = get_test_files(cfg)\n\n if cov is not None:\n cov.start()\n if cfg.list_tests or cfg.run_tests:\n test_cases = get_test_cases(test_files, cfg, cov=cov)\n if cfg.list_hooks or cfg.run_tests:\n test_hooks = get_test_hooks(test_files, cfg, cov=cov)\n\n # Configure the logging module\n import logging\n logging.basicConfig()\n logging.root.setLevel(logging.CRITICAL)\n\n # Running\n success = True\n if cfg.list_files:\n baselen = len(cfg.basedir) + 1\n print(\"\\n\".join([fn[baselen:] for fn in test_files]))\n if cfg.list_tests:\n print(\"\\n\".join([test.id() for test in test_cases]))\n if cfg.list_hooks:\n print(\"\\n\".join([str(hook) for hook in test_hooks]))\n if cfg.run_tests:\n runner = CustomTestRunner(cfg, test_hooks)\n suite = unittest.TestSuite()\n suite.addTests(test_cases)\n if cov is not None:\n cov.start()\n run_result = runner.run(suite)\n if cov is not None:\n cov.stop()\n success = run_result.wasSuccessful()\n del run_result\n\n if cov is not None:\n traced_file_types = ('.py', '.pyx', '.pxi', '.pxd')\n modules = []\n\n def add_file(_, path, files):\n if 'tests' in os.path.relpath(path, cfg.basedir).split(os.sep):\n return\n for filename in files:\n if filename.endswith(traced_file_types):\n modules.append(os.path.join(path, filename))\n\n if cfg.follow_symlinks:\n walker = walk_with_symlinks\n else:\n walker = os.path.walk\n walker(os.path.abspath(cfg.basedir), add_file, None)\n\n try:\n cov.xml_report(modules, outfile='coverage.xml')\n if cfg.coverdir:\n cov.html_report(modules, directory=cfg.coverdir)\n finally:\n # test runs can take a while, so at least try to print something\n cov.report()\n\n # That's all\n if success:\n return 0\n else:\n return 1\n\n\nif __name__ == '__main__':\n exitcode = main(sys.argv)\n sys.exit(exitcode)\n\n"}
|
{"text": "\nfrom homeassistant.components.binary_sensor import (\n DOMAIN as BINARY_SENSOR_DOMAIN,\n BinarySensorEntity,\n)\nfrom homeassistant.core import callback\nfrom homeassistant.util import slugify\n\nfrom . import DOMAIN as MYCHEVY_DOMAIN, UPDATE_TOPIC, EVBinarySensorConfig\n\nSENSORS = [EVBinarySensorConfig(\"Plugged In\", \"plugged_in\", \"plug\")]\n\n\nasync def async_setup_platform(hass, config, async_add_entities, discovery_info=None):\n \"\"\"Set up the MyChevy sensors.\"\"\"\n if discovery_info is None:\n return\n\n sensors = []\n hub = hass.data[MYCHEVY_DOMAIN]\n for sconfig in SENSORS:\n for car in hub.cars:\n sensors.append(EVBinarySensor(hub, sconfig, car.vid))\n\n async_add_entities(sensors)\n\n\nclass EVBinarySensor(BinarySensorEntity):\n \"\"\"Base EVSensor class.\n\n The only real difference between sensors is which units and what\n attribute from the car object they are returning. All logic can be\n built with just setting subclass attributes.\n \"\"\"\n\n def __init__(self, connection, config, car_vid):\n \"\"\"Initialize sensor with car connection.\"\"\"\n self._conn = connection\n self._name = config.name\n self._attr = config.attr\n self._type = config.device_class\n self._is_on = None\n self._car_vid = car_vid\n self.entity_id = f\"{BINARY_SENSOR_DOMAIN}.{MYCHEVY_DOMAIN}_{slugify(self._car.name)}_{slugify(self._name)}\"\n\n @property\n def name(self):\n \"\"\"Return the name.\"\"\"\n return self._name\n\n @property\n def is_on(self):\n \"\"\"Return if on.\"\"\"\n return self._is_on\n\n @property\n def _car(self):\n \"\"\"Return the car.\"\"\"\n return self._conn.get_car(self._car_vid)\n\n async def async_added_to_hass(self):\n \"\"\"Register callbacks.\"\"\"\n self.async_on_remove(\n self.hass.helpers.dispatcher.async_dispatcher_connect(\n UPDATE_TOPIC, self.async_update_callback\n )\n )\n\n @callback\n def async_update_callback(self):\n \"\"\"Update state.\"\"\"\n if self._car is not None:\n self._is_on = getattr(self._car, self._attr, None)\n self.async_write_ha_state()\n\n @property\n def should_poll(self):\n \"\"\"Return the polling state.\"\"\"\n return False\n\n"}
|
{"text": "\nimport pathlib\nimport re\nfrom typing import Dict\n\nimport voluptuous as vol\nfrom voluptuous.humanize import humanize_error\n\nfrom homeassistant.exceptions import HomeAssistantError\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.util.yaml import load_yaml\n\nfrom .model import Integration\n\n\ndef exists(value):\n \"\"\"Check if value exists.\"\"\"\n if value is None:\n raise vol.Invalid(\"Value cannot be None\")\n return value\n\n\nFIELD_SCHEMA = vol.Schema(\n {\n vol.Required(\"description\"): str,\n vol.Optional(\"example\"): exists,\n vol.Optional(\"default\"): exists,\n vol.Optional(\"values\"): exists,\n vol.Optional(\"required\"): bool,\n }\n)\n\nSERVICE_SCHEMA = vol.Schema(\n {\n vol.Required(\"description\"): str,\n vol.Optional(\"fields\"): vol.Schema({str: FIELD_SCHEMA}),\n }\n)\n\nSERVICES_SCHEMA = vol.Schema({cv.slug: SERVICE_SCHEMA})\n\n\ndef grep_dir(path: pathlib.Path, glob_pattern: str, search_pattern: str) -> bool:\n \"\"\"Recursively go through a dir and it's children and find the regex.\"\"\"\n pattern = re.compile(search_pattern)\n\n for fil in path.glob(glob_pattern):\n if not fil.is_file():\n continue\n\n if pattern.search(fil.read_text()):\n return True\n\n return False\n\n\ndef validate_services(integration: Integration):\n \"\"\"Validate services.\"\"\"\n # Find if integration uses services\n has_services = grep_dir(\n integration.path, \"**/*.py\", r\"hass\\.services\\.(register|async_register)\"\n )\n\n if not has_services:\n return\n\n try:\n data = load_yaml(str(integration.path / \"services.yaml\"))\n except FileNotFoundError:\n integration.add_error(\"services\", \"Registers services but has no services.yaml\")\n return\n except HomeAssistantError:\n integration.add_error(\n \"services\", \"Registers services but unable to load services.yaml\"\n )\n return\n\n try:\n SERVICES_SCHEMA(data)\n except vol.Invalid as err:\n integration.add_error(\n \"services\", f\"Invalid services.yaml: {humanize_error(data, err)}\"\n )\n\n\ndef validate(integrations: Dict[str, Integration], config):\n \"\"\"Handle dependencies for integrations.\"\"\"\n # check services.yaml is cool\n for integration in integrations.values():\n if not integration.manifest:\n continue\n\n validate_services(integration)\n\n"}
|
{"text": "\nimport asyncio\nimport datetime as dt\nimport os\nfrom typing import List\n\nfrom httpx import RequestError\nimport onvif\nfrom onvif import ONVIFCamera\nfrom onvif.exceptions import ONVIFError\nfrom zeep.exceptions import Fault\n\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import (\n CONF_HOST,\n CONF_NAME,\n CONF_PASSWORD,\n CONF_PORT,\n CONF_USERNAME,\n)\nfrom homeassistant.core import HomeAssistant\nimport homeassistant.util.dt as dt_util\n\nfrom .const import (\n ABSOLUTE_MOVE,\n CONTINUOUS_MOVE,\n GOTOPRESET_MOVE,\n LOGGER,\n PAN_FACTOR,\n RELATIVE_MOVE,\n TILT_FACTOR,\n ZOOM_FACTOR,\n)\nfrom .event import EventManager\nfrom .models import PTZ, Capabilities, DeviceInfo, Profile, Resolution, Video\n\n\nclass ONVIFDevice:\n \"\"\"Manages an ONVIF device.\"\"\"\n\n def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry = None):\n \"\"\"Initialize the device.\"\"\"\n self.hass: HomeAssistant = hass\n self.config_entry: ConfigEntry = config_entry\n self.available: bool = True\n\n self.device: ONVIFCamera = None\n self.events: EventManager = None\n\n self.info: DeviceInfo = DeviceInfo()\n self.capabilities: Capabilities = Capabilities()\n self.profiles: List[Profile] = []\n self.max_resolution: int = 0\n\n self._dt_diff_seconds: int = 0\n\n @property\n def name(self) -> str:\n \"\"\"Return the name of this device.\"\"\"\n return self.config_entry.data[CONF_NAME]\n\n @property\n def host(self) -> str:\n \"\"\"Return the host of this device.\"\"\"\n return self.config_entry.data[CONF_HOST]\n\n @property\n def port(self) -> int:\n \"\"\"Return the port of this device.\"\"\"\n return self.config_entry.data[CONF_PORT]\n\n @property\n def username(self) -> int:\n \"\"\"Return the username of this device.\"\"\"\n return self.config_entry.data[CONF_USERNAME]\n\n @property\n def password(self) -> int:\n \"\"\"Return the password of this device.\"\"\"\n return self.config_entry.data[CONF_PASSWORD]\n\n async def async_setup(self) -> bool:\n \"\"\"Set up the device.\"\"\"\n self.device = get_device(\n self.hass,\n host=self.config_entry.data[CONF_HOST],\n port=self.config_entry.data[CONF_PORT],\n username=self.config_entry.data[CONF_USERNAME],\n password=self.config_entry.data[CONF_PASSWORD],\n )\n\n # Get all device info\n try:\n await self.device.update_xaddrs()\n await self.async_check_date_and_time()\n\n # Create event manager\n self.events = EventManager(\n self.hass, self.device, self.config_entry.unique_id\n )\n\n # Fetch basic device info and capabilities\n self.info = await self.async_get_device_info()\n self.capabilities = await self.async_get_capabilities()\n self.profiles = await self.async_get_profiles()\n\n # No camera profiles to add\n if not self.profiles:\n return False\n\n if self.capabilities.ptz:\n self.device.create_ptz_service()\n\n # Determine max resolution from profiles\n self.max_resolution = max(\n profile.video.resolution.width\n for profile in self.profiles\n if profile.video.encoding == \"H264\"\n )\n except RequestError as err:\n LOGGER.warning(\n \"Couldn't connect to camera '%s', but will retry later. Error: %s\",\n self.name,\n err,\n )\n self.available = False\n except Fault as err:\n LOGGER.error(\n \"Couldn't connect to camera '%s', please verify \"\n \"that the credentials are correct. Error: %s\",\n self.name,\n err,\n )\n return False\n\n return True\n\n async def async_stop(self, event=None):\n \"\"\"Shut it all down.\"\"\"\n if self.events:\n await self.events.async_stop()\n await self.device.close()\n\n async def async_check_date_and_time(self) -> None:\n \"\"\"Warns if device and system date not synced.\"\"\"\n LOGGER.debug(\"Setting up the ONVIF device management service\")\n device_mgmt = self.device.create_devicemgmt_service()\n\n LOGGER.debug(\"Retrieving current device date/time\")\n try:\n system_date = dt_util.utcnow()\n device_time = await device_mgmt.GetSystemDateAndTime()\n if not device_time:\n LOGGER.debug(\n \"\"\"Couldn't get device '%s' date/time.\n GetSystemDateAndTime() return null/empty\"\"\",\n self.name,\n )\n return\n\n if device_time.UTCDateTime:\n tzone = dt_util.UTC\n cdate = device_time.UTCDateTime\n else:\n tzone = (\n dt_util.get_time_zone(device_time.TimeZone)\n or dt_util.DEFAULT_TIME_ZONE\n )\n cdate = device_time.LocalDateTime\n\n if cdate is None:\n LOGGER.warning(\"Could not retrieve date/time on this camera\")\n else:\n cam_date = dt.datetime(\n cdate.Date.Year,\n cdate.Date.Month,\n cdate.Date.Day,\n cdate.Time.Hour,\n cdate.Time.Minute,\n cdate.Time.Second,\n 0,\n tzone,\n )\n\n cam_date_utc = cam_date.astimezone(dt_util.UTC)\n\n LOGGER.debug(\n \"Device date/time: %s | System date/time: %s\",\n cam_date_utc,\n system_date,\n )\n\n dt_diff = cam_date - system_date\n self._dt_diff_seconds = dt_diff.total_seconds()\n\n if self._dt_diff_seconds > 5:\n LOGGER.warning(\n \"The date/time on the device (UTC) is '%s', \"\n \"which is different from the system '%s', \"\n \"this could lead to authentication issues\",\n cam_date_utc,\n system_date,\n )\n except RequestError as err:\n LOGGER.warning(\n \"Couldn't get device '%s' date/time. Error: %s\", self.name, err\n )\n\n async def async_get_device_info(self) -> DeviceInfo:\n \"\"\"Obtain information about this device.\"\"\"\n device_mgmt = self.device.create_devicemgmt_service()\n device_info = await device_mgmt.GetDeviceInformation()\n\n # Grab the last MAC address for backwards compatibility\n mac = None\n try:\n network_interfaces = await device_mgmt.GetNetworkInterfaces()\n for interface in network_interfaces:\n if interface.Enabled:\n mac = interface.Info.HwAddress\n except Fault as fault:\n if \"not implemented\" not in fault.message:\n raise fault\n\n LOGGER.debug(\n \"Couldn't get network interfaces from ONVIF device '%s'. Error: %s\",\n self.name,\n fault,\n )\n\n return DeviceInfo(\n device_info.Manufacturer,\n device_info.Model,\n device_info.FirmwareVersion,\n device_info.SerialNumber,\n mac,\n )\n\n async def async_get_capabilities(self):\n \"\"\"Obtain information about the available services on the device.\"\"\"\n snapshot = False\n try:\n media_service = self.device.create_media_service()\n media_capabilities = await media_service.GetServiceCapabilities()\n snapshot = media_capabilities and media_capabilities.SnapshotUri\n except (ONVIFError, Fault, RequestError):\n pass\n\n pullpoint = False\n try:\n pullpoint = await self.events.async_start()\n except (ONVIFError, Fault):\n pass\n\n ptz = False\n try:\n self.device.get_definition(\"ptz\")\n ptz = True\n except ONVIFError:\n pass\n\n return Capabilities(snapshot, pullpoint, ptz)\n\n async def async_get_profiles(self) -> List[Profile]:\n \"\"\"Obtain media profiles for this device.\"\"\"\n media_service = self.device.create_media_service()\n result = await media_service.GetProfiles()\n profiles = []\n\n if not isinstance(result, list):\n return profiles\n\n for key, onvif_profile in enumerate(result):\n # Only add H264 profiles\n if (\n not onvif_profile.VideoEncoderConfiguration\n or onvif_profile.VideoEncoderConfiguration.Encoding != \"H264\"\n ):\n continue\n\n profile = Profile(\n key,\n onvif_profile.token,\n onvif_profile.Name,\n Video(\n onvif_profile.VideoEncoderConfiguration.Encoding,\n Resolution(\n onvif_profile.VideoEncoderConfiguration.Resolution.Width,\n onvif_profile.VideoEncoderConfiguration.Resolution.Height,\n ),\n ),\n )\n\n # Configure PTZ options\n if self.capabilities.ptz and onvif_profile.PTZConfiguration:\n profile.ptz = PTZ(\n onvif_profile.PTZConfiguration.DefaultContinuousPanTiltVelocitySpace\n is not None,\n onvif_profile.PTZConfiguration.DefaultRelativePanTiltTranslationSpace\n is not None,\n onvif_profile.PTZConfiguration.DefaultAbsolutePantTiltPositionSpace\n is not None,\n )\n\n try:\n ptz_service = self.device.create_ptz_service()\n presets = await ptz_service.GetPresets(profile.token)\n profile.ptz.presets = [preset.token for preset in presets if preset]\n except (Fault, RequestError):\n # It's OK if Presets aren't supported\n profile.ptz.presets = []\n\n profiles.append(profile)\n\n return profiles\n\n async def async_get_stream_uri(self, profile: Profile) -> str:\n \"\"\"Get the stream URI for a specified profile.\"\"\"\n media_service = self.device.create_media_service()\n req = media_service.create_type(\"GetStreamUri\")\n req.ProfileToken = profile.token\n req.StreamSetup = {\n \"Stream\": \"RTP-Unicast\",\n \"Transport\": {\"Protocol\": \"RTSP\"},\n }\n result = await media_service.GetStreamUri(req)\n return result.Uri\n\n async def async_perform_ptz(\n self,\n profile: Profile,\n distance,\n speed,\n move_mode,\n continuous_duration,\n preset,\n pan=None,\n tilt=None,\n zoom=None,\n ):\n \"\"\"Perform a PTZ action on the camera.\"\"\"\n if not self.capabilities.ptz:\n LOGGER.warning(\"PTZ actions are not supported on device '%s'\", self.name)\n return\n\n ptz_service = self.device.create_ptz_service()\n\n pan_val = distance * PAN_FACTOR.get(pan, 0)\n tilt_val = distance * TILT_FACTOR.get(tilt, 0)\n zoom_val = distance * ZOOM_FACTOR.get(zoom, 0)\n speed_val = speed\n preset_val = preset\n LOGGER.debug(\n \"Calling %s PTZ | Pan = %4.2f | Tilt = %4.2f | Zoom = %4.2f | Speed = %4.2f | Preset = %s\",\n move_mode,\n pan_val,\n tilt_val,\n zoom_val,\n speed_val,\n preset_val,\n )\n try:\n req = ptz_service.create_type(move_mode)\n req.ProfileToken = profile.token\n if move_mode == CONTINUOUS_MOVE:\n # Guard against unsupported operation\n if not profile.ptz.continuous:\n LOGGER.warning(\n \"ContinuousMove not supported on device '%s'\", self.name\n )\n return\n\n req.Velocity = {\n \"PanTilt\": {\"x\": pan_val, \"y\": tilt_val},\n \"Zoom\": {\"x\": zoom_val},\n }\n\n await ptz_service.ContinuousMove(req)\n await asyncio.sleep(continuous_duration)\n req = ptz_service.create_type(\"Stop\")\n req.ProfileToken = profile.token\n await ptz_service.Stop(\n {\"ProfileToken\": req.ProfileToken, \"PanTilt\": True, \"Zoom\": False}\n )\n elif move_mode == RELATIVE_MOVE:\n # Guard against unsupported operation\n if not profile.ptz.relative:\n LOGGER.warning(\n \"RelativeMove not supported on device '%s'\", self.name\n )\n return\n\n req.Translation = {\n \"PanTilt\": {\"x\": pan_val, \"y\": tilt_val},\n \"Zoom\": {\"x\": zoom_val},\n }\n req.Speed = {\n \"PanTilt\": {\"x\": speed_val, \"y\": speed_val},\n \"Zoom\": {\"x\": speed_val},\n }\n await ptz_service.RelativeMove(req)\n elif move_mode == ABSOLUTE_MOVE:\n # Guard against unsupported operation\n if not profile.ptz.absolute:\n LOGGER.warning(\n \"AbsoluteMove not supported on device '%s'\", self.name\n )\n return\n\n req.Position = {\n \"PanTilt\": {\"x\": pan_val, \"y\": tilt_val},\n \"Zoom\": {\"x\": zoom_val},\n }\n req.Speed = {\n \"PanTilt\": {\"x\": speed_val, \"y\": speed_val},\n \"Zoom\": {\"x\": speed_val},\n }\n await ptz_service.AbsoluteMove(req)\n elif move_mode == GOTOPRESET_MOVE:\n # Guard against unsupported operation\n if preset_val not in profile.ptz.presets:\n LOGGER.warning(\n \"PTZ preset '%s' does not exist on device '%s'. Available Presets: %s\",\n preset_val,\n self.name,\n \", \".join(profile.ptz.presets),\n )\n return\n\n req.PresetToken = preset_val\n req.Speed = {\n \"PanTilt\": {\"x\": speed_val, \"y\": speed_val},\n \"Zoom\": {\"x\": speed_val},\n }\n await ptz_service.GotoPreset(req)\n except ONVIFError as err:\n if \"Bad Request\" in err.reason:\n LOGGER.warning(\"Device '%s' doesn't support PTZ.\", self.name)\n else:\n LOGGER.error(\"Error trying to perform PTZ action: %s\", err)\n\n\ndef get_device(hass, host, port, username, password) -> ONVIFCamera:\n \"\"\"Get ONVIFCamera instance.\"\"\"\n return ONVIFCamera(\n host,\n port,\n username,\n password,\n f\"{os.path.dirname(onvif.__file__)}/wsdl/\",\n no_cache=True,\n )\n\n"}
|
{"text": "\nimport sys\n\nimport mne\n\n\ndef clean_ecg_eog(in_fif_fname, out_fif_fname=None, eog=True, ecg=True,\n ecg_proj_fname=None, eog_proj_fname=None,\n ecg_event_fname=None, eog_event_fname=None, in_path='.',\n quiet=False):\n \"\"\"Clean ECG from raw fif file.\n\n Parameters\n ----------\n in_fif_fname : str\n Raw fif File\n eog_event_fname : str\n name of EOG event file required.\n eog : bool\n Reject or not EOG artifacts.\n ecg : bool\n Reject or not ECG artifacts.\n ecg_event_fname : str\n name of ECG event file required.\n in_path : str\n Path where all the files are.\n \"\"\"\n if not eog and not ecg:\n raise Exception(\"EOG and ECG cannot be both disabled\")\n\n # Reading fif File\n raw_in = mne.io.read_raw_fif(in_fif_fname)\n\n if in_fif_fname.endswith('_raw.fif') or in_fif_fname.endswith('-raw.fif'):\n prefix = in_fif_fname[:-8]\n else:\n prefix = in_fif_fname[:-4]\n\n if out_fif_fname is None:\n out_fif_fname = prefix + '_clean_ecg_eog_raw.fif'\n if ecg_proj_fname is None:\n ecg_proj_fname = prefix + '_ecg-proj.fif'\n if eog_proj_fname is None:\n eog_proj_fname = prefix + '_eog-proj.fif'\n if ecg_event_fname is None:\n ecg_event_fname = prefix + '_ecg-eve.fif'\n if eog_event_fname is None:\n eog_event_fname = prefix + '_eog-eve.fif'\n\n print('Implementing ECG and EOG artifact rejection on data')\n\n kwargs = dict() if quiet else dict(stdout=None, stderr=None)\n if ecg:\n ecg_events, _, _ = mne.preprocessing.find_ecg_events(\n raw_in, reject_by_annotation=True)\n print(\"Writing ECG events in %s\" % ecg_event_fname)\n mne.write_events(ecg_event_fname, ecg_events)\n print('Computing ECG projector')\n command = ('mne_process_raw', '--cd', in_path, '--raw', in_fif_fname,\n '--events', ecg_event_fname, '--makeproj',\n '--projtmin', '-0.08', '--projtmax', '0.08',\n '--saveprojtag', '_ecg-proj', '--projnmag', '2',\n '--projngrad', '1', '--projevent', '999', '--highpass', '5',\n '--lowpass', '35', '--projmagrej', '4000',\n '--projgradrej', '3000')\n mne.utils.run_subprocess(command, **kwargs)\n if eog:\n eog_events = mne.preprocessing.find_eog_events(raw_in)\n print(\"Writing EOG events in %s\" % eog_event_fname)\n mne.write_events(eog_event_fname, eog_events)\n print('Computing EOG projector')\n command = ('mne_process_raw', '--cd', in_path, '--raw', in_fif_fname,\n '--events', eog_event_fname, '--makeproj',\n '--projtmin', '-0.15', '--projtmax', '0.15',\n '--saveprojtag', '_eog-proj', '--projnmag', '2',\n '--projngrad', '2', '--projevent', '998', '--lowpass', '35',\n '--projmagrej', '4000', '--projgradrej', '3000')\n mne.utils.run_subprocess(command, **kwargs)\n\n if out_fif_fname is not None:\n # Applying the ECG EOG projector\n print('Applying ECG EOG projector')\n command = ('mne_process_raw', '--cd', in_path, '--raw', in_fif_fname,\n '--proj', in_fif_fname, '--projoff', '--save',\n out_fif_fname, '--filteroff',\n '--proj', ecg_proj_fname, '--proj', eog_proj_fname)\n mne.utils.run_subprocess(command, **kwargs)\n print('Done removing artifacts.')\n print(\"Cleaned raw data saved in: %s\" % out_fif_fname)\n print('IMPORTANT : Please eye-ball the data !!')\n else:\n print('Projection not applied to raw data.')\n\n\ndef run():\n \"\"\"Run command.\"\"\"\n from mne.commands.utils import get_optparser\n\n parser = get_optparser(__file__)\n\n parser.add_option(\"-i\", \"--in\", dest=\"raw_in\",\n help=\"Input raw FIF file\", metavar=\"FILE\")\n parser.add_option(\"-o\", \"--out\", dest=\"raw_out\",\n help=\"Output raw FIF file\", metavar=\"FILE\",\n default=None)\n parser.add_option(\"-e\", \"--no-eog\", dest=\"eog\", action=\"store_false\",\n help=\"Remove EOG\", default=True)\n parser.add_option(\"-c\", \"--no-ecg\", dest=\"ecg\", action=\"store_false\",\n help=\"Remove ECG\", default=True)\n parser.add_option(\"-q\", \"--quiet\", dest=\"quiet\", action=\"store_true\",\n help=\"Suppress mne_process_raw output\", default=False)\n\n options, args = parser.parse_args()\n\n if options.raw_in is None:\n parser.print_help()\n sys.exit(1)\n\n raw_in = options.raw_in\n raw_out = options.raw_out\n eog = options.eog\n ecg = options.ecg\n quiet = options.quiet\n\n clean_ecg_eog(raw_in, raw_out, eog=eog, ecg=ecg, quiet=quiet)\n\n\nmne.utils.run_command_if_main()\n\n"}
|
{"text": "\nfrom datetime import timedelta\nimport logging\n\nimport aiodns\nfrom aiodns.error import DNSError\nimport voluptuous as vol\n\nfrom homeassistant.components.sensor import PLATFORM_SCHEMA\nfrom homeassistant.const import CONF_NAME\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.entity import Entity\n\n_LOGGER = logging.getLogger(__name__)\n\nCONF_HOSTNAME = \"hostname\"\nCONF_IPV6 = \"ipv6\"\nCONF_RESOLVER = \"resolver\"\nCONF_RESOLVER_IPV6 = \"resolver_ipv6\"\n\nDEFAULT_HOSTNAME = \"myip.opendns.com\"\nDEFAULT_IPV6 = False\nDEFAULT_NAME = \"myip\"\nDEFAULT_RESOLVER = \"208.67.222.222\"\nDEFAULT_RESOLVER_IPV6 = \"2620:0:ccc::2\"\n\nSCAN_INTERVAL = timedelta(seconds=120)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {\n vol.Optional(CONF_NAME): cv.string,\n vol.Optional(CONF_HOSTNAME, default=DEFAULT_HOSTNAME): cv.string,\n vol.Optional(CONF_RESOLVER, default=DEFAULT_RESOLVER): cv.string,\n vol.Optional(CONF_RESOLVER_IPV6, default=DEFAULT_RESOLVER_IPV6): cv.string,\n vol.Optional(CONF_IPV6, default=DEFAULT_IPV6): cv.boolean,\n }\n)\n\n\nasync def async_setup_platform(hass, config, async_add_devices, discovery_info=None):\n \"\"\"Set up the DNS IP sensor.\"\"\"\n hostname = config[CONF_HOSTNAME]\n name = config.get(CONF_NAME)\n if not name:\n if hostname == DEFAULT_HOSTNAME:\n name = DEFAULT_NAME\n else:\n name = hostname\n ipv6 = config[CONF_IPV6]\n if ipv6:\n resolver = config[CONF_RESOLVER_IPV6]\n else:\n resolver = config[CONF_RESOLVER]\n\n async_add_devices([WanIpSensor(hass, name, hostname, resolver, ipv6)], True)\n\n\nclass WanIpSensor(Entity):\n \"\"\"Implementation of a DNS IP sensor.\"\"\"\n\n def __init__(self, hass, name, hostname, resolver, ipv6):\n \"\"\"Initialize the DNS IP sensor.\"\"\"\n\n self.hass = hass\n self._name = name\n self.hostname = hostname\n self.resolver = aiodns.DNSResolver()\n self.resolver.nameservers = [resolver]\n self.querytype = \"AAAA\" if ipv6 else \"A\"\n self._state = None\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return self._name\n\n @property\n def state(self):\n \"\"\"Return the current DNS IP address for hostname.\"\"\"\n return self._state\n\n async def async_update(self):\n \"\"\"Get the current DNS IP address for hostname.\"\"\"\n\n try:\n response = await self.resolver.query(self.hostname, self.querytype)\n except DNSError as err:\n _LOGGER.warning(\"Exception while resolving host: %s\", err)\n response = None\n if response:\n self._state = response[0].host\n else:\n self._state = None\n\n"}
|
{"text": "\nimport StringIO\nimport sys\nimport time\n\nfrom nose import tools\n\nfrom docker_registry.core import exceptions\nimport docker_registry.testing as testing\n\nfrom docker_registry.testing import mock_boto # noqa\n\nfrom . import mock_s3 # noqa\n\n\nclass StringIOWithError(StringIO.StringIO):\n '''Throw IOError after reaching EOF.'''\n\n def read(self, size):\n if self.pos == self.len:\n raise IOError('Reading beyond EOF')\n return StringIO.StringIO.read(self, size)\n\n\nclass TestDriver(testing.Driver):\n '''Extra tests for coverage completion.'''\n def __init__(self):\n self.scheme = 's3'\n self.path = ''\n self.config = testing.Config({})\n\n def tearDown(self):\n self._storage._boto_bucket.delete()\n super(TestDriver, self).tearDown()\n\n @tools.raises(exceptions.FileNotFoundError)\n def test_list_bucket(self):\n # Add a couple of bucket keys\n filename1 = self.gen_random_string()\n filename2 = self.gen_random_string()\n content = self.gen_random_string()\n self._storage.put_content(filename1, content)\n # Check bucket key is stored in normalized form\n self._storage.put_content(filename2 + '/', content)\n # Check both keys are in the bucket\n assert sorted([filename1, filename2]) == sorted(\n list(self._storage.list_directory()))\n # Check listing bucket raises exception after removing keys\n self._storage.remove(filename1)\n self._storage.remove(filename2)\n s = self._storage.list_directory()\n s.next()\n\n def test_stream_write(self):\n # Check stream write with buffer bigger than default 5MB\n self._storage.buffer_size = 7 * 1024 * 1024\n filename = self.gen_random_string()\n # Test 8MB\n content = self.gen_random_string(8 * 1024 * 1024)\n io = StringIOWithError(content)\n assert not self._storage.exists(filename)\n try:\n self._storage.stream_write(filename, io)\n except IOError:\n pass\n assert self._storage.exists(filename)\n # Test that EOFed io string throws IOError on lib/storage/s3\n try:\n self._storage.stream_write(filename, io)\n except IOError:\n pass\n # Cleanup\n io.close()\n self._storage.remove(filename)\n self._storage.buffer_size = 5 * 1024 * 1024\n assert not self._storage.exists(filename)\n\n def test_init_path(self):\n # s3 storage _init_path result keys are relative (no / at start)\n root_path = self._storage._root_path\n if root_path.startswith('/'):\n self._storage._root_path = root_path[1:]\n assert not self._storage._init_path().startswith('/')\n self._storage._root_path = root_path\n\n def test_debug_key(self):\n # Create a valid s3 key object to debug\n filename = self.gen_random_string()\n content = self.gen_random_string()\n self._storage.put_content(filename, content)\n\n # Get filename key path as stored\n key_path = self._storage._init_path(filename)\n key = self._storage._boto_bucket.lookup(key_path)\n self._storage._debug_key(key)\n\n # Capture debugged output\n saved_stdout = sys.stdout\n output = StringIO.StringIO()\n sys.stdout = output\n\n # As key is mocked for unittest purposes, we call make_request directly\n dummy = \"################\\n('d', 1)\\n{'v': 2}\\n################\\n\"\n # '{}\\n{}\\n{}\\n{}\\n'.format(\n # '#' * 16, ('d', 1), {'v': 2}, '#' * 16)\n result = self._storage._boto_bucket.connection.make_request(\n 'd', 1, v=2)\n assert output.getvalue() == dummy\n assert result == 'request result'\n\n sys.stdout = saved_stdout\n\n # We don't call self._storage.remove(filename) here to ensure tearDown\n # cleanup properly and that other tests keep running as expected.\n\n # Validation test for docker-index#486\n def test_get_tags(self):\n store = self._storage\n store._root_path = 'my/custom/path'\n store._init_path()\n assert store._root_path == 'my/custom/path'\n tag_path = store.tag_path('test', 'test', '0.0.2')\n store.put_content(tag_path, 'randomdata')\n tags_path = store.tag_path('test', 'test')\n for fname in store.list_directory(tags_path):\n full_tag_name = fname.split('/').pop()\n if not full_tag_name == 'tag_0.0.2':\n continue\n try:\n store.get_content(fname)\n except exceptions.FileNotFoundError:\n pass\n except Exception as e:\n raise e\n else:\n assert False\n\n tag_content = store.get_content(tag_path)\n assert tag_content == 'randomdata'\n\n def test_consistency_latency(self):\n self.testCount = -1\n mockKey = mock_boto.Key()\n\n def mockExists():\n self.testCount += 1\n return self.testCount == 1\n mockKey.exists = mockExists\n mockKey.get_contents_as_string = lambda: \"Foo bar\"\n self._storage.makeKey = lambda x: mockKey\n startTime = time.time()\n\n content = self._storage.get_content(\"/FOO\")\n\n waitTime = time.time() - startTime\n assert waitTime >= 0.1, (\"Waiting time was less than %sms \"\n \"(actual : %sms)\" %\n (0.1 * 1000, waitTime * 1000))\n assert content == \"Foo bar\", (\"expected : %s; actual: %s\" %\n (\"Foo bar\", content))\n\n @tools.raises(exceptions.FileNotFoundError)\n def test_too_many_read_retries(self):\n self.testCount = -1\n mockKey = mock_boto.Key()\n\n def mockExists():\n self.testCount += 1\n return self.testCount == 5\n mockKey.exists = mockExists\n mockKey.get_contents_as_string = lambda: \"Foo bar\"\n self._storage.makeKey = lambda x: mockKey\n\n self._storage.get_content(\"/FOO\")\n\n"}
|
{"text": "\nimport unittest\nfrom absl import flags\nimport mock\n\nfrom perfkitbenchmarker import benchmark_sets\nfrom perfkitbenchmarker import configs\nfrom perfkitbenchmarker import linux_benchmarks\n# This import to ensure required FLAGS are defined.\nfrom perfkitbenchmarker import pkb # NOQA\n\nimport six\nimport yaml\n\nFLAGS = flags.FLAGS\nFLAGS.mark_as_parsed()\n\nUSER_CONFIG = \"\"\"\ninternal_iprf:\n name: iperf\n flags:\n ip_addresses: INTERNAL\n\"\"\"\nMATRIX_CONFIG = \"\"\"\nnetperf:\n flag_matrix: GCP\n flag_matrix_defs:\n GCP:\n machine_type: [n1-standard-1, n1-standard-4]\n zones: [us-central1-a, us-central1-b]\n\"\"\"\nEXPECTED_MATRIX_FLAGS = [\n {'machine_type': 'n1-standard-1', 'zones': 'us-central1-a'},\n {'machine_type': 'n1-standard-1', 'zones': 'us-central1-b'},\n {'machine_type': 'n1-standard-4', 'zones': 'us-central1-a'},\n {'machine_type': 'n1-standard-4', 'zones': 'us-central1-b'}\n]\nZIP_CONFIG_DIFFERENT_AXES_LENGTH = \"\"\"\nnetperf:\n flags:\n gpu_type: k80\n flag_zip: GCP\n flag_zip_defs:\n GCP:\n machine_type: [n1-standard-4, n1-standard-8]\n gpu_count: [1, 2, 3]\n\"\"\"\nZIP_CONFIG = \"\"\"\nnetperf:\n flags:\n gpu_type: k80\n flag_zip: GCP\n flag_zip_defs:\n GCP:\n machine_type: [n1-standard-4, n1-standard-8]\n gpu_count: [1, 2]\n\"\"\"\nEXPECTED_ZIP_FLAGS = [\n {'machine_type': 'n1-standard-4', 'gpu_count': 1, 'gpu_type': 'k80'},\n {'machine_type': 'n1-standard-8', 'gpu_count': 2, 'gpu_type': 'k80'}\n]\nSINGLE_ZIP_CONFIG = \"\"\"\nnetperf:\n flags:\n gpu_type: k80\n flag_zip: GCP\n flag_zip_defs:\n GCP:\n machine_type: [n1-standard-4, n1-standard-8]\n\"\"\"\nEXPECTED_SINGLE_ZIP_FLAGS = [\n {'machine_type': 'n1-standard-4', 'gpu_type': 'k80'},\n {'machine_type': 'n1-standard-8', 'gpu_type': 'k80'}\n]\nZIP_AND_MATRIX_CONFIG = \"\"\"\nnetperf:\n flags:\n gpu_type: k80\n flag_zip: GCP\n flag_matrix: GCP\n flag_zip_defs:\n GCP:\n machine_type: [n1-standard-4, n1-standard-8]\n gpu_count: [1, 2]\n flag_matrix_defs:\n GCP:\n zones: [us-central1-a, us-central1-b]\n\"\"\"\nEXPECTED_ZIP_AND_MATRIX_FLAGS = [\n {'zones': 'us-central1-a', 'gpu_type': 'k80',\n 'machine_type': 'n1-standard-4', 'gpu_count': 1},\n {'zones': 'us-central1-b', 'gpu_type': 'k80',\n 'machine_type': 'n1-standard-4', 'gpu_count': 1},\n {'zones': 'us-central1-b', 'gpu_type': 'k80',\n 'machine_type': 'n1-standard-8', 'gpu_count': 2},\n {'zones': 'us-central1-a', 'gpu_type': 'k80',\n 'machine_type': 'n1-standard-8', 'gpu_count': 2}\n]\nFILTER_CONFIG = \"\"\"\nnetperf:\n flag_matrix: GCP\n flag_matrix_filters:\n GCP: \"machine_type == 'n1-standard-1' and zones == 'us-central1-a'\"\n flag_matrix_defs:\n GCP:\n machine_type: [n1-standard-1, n1-standard-4]\n zones: [us-central1-a, us-central1-b]\n\"\"\"\nFLAG_PRECEDENCE_CONFIG = \"\"\"\nflags:\n netperf_benchmarks: TCP_RR\n netperf_test_length: 30\n netperf_max_iter: 3\nnetperf:\n flags:\n netperf_benchmarks: UDP_RR\n netperf_test_length: 40\n flag_matrix: test_matrix\n flag_matrix_defs:\n test_matrix:\n netperf_benchmarks: [TCP_STREAM]\n\"\"\"\n\n\nclass BenchmarkSetsTestCase(unittest.TestCase):\n\n def setUp(self):\n # create set of valid benchmark names from the benchmark directory\n self.valid_benchmark_names = set()\n for benchmark_module in linux_benchmarks.BENCHMARKS:\n self.valid_benchmark_names.add(benchmark_module.BENCHMARK_NAME)\n\n self.valid_benchmark_set_names = set()\n # include the benchmark_set names since these can also appear\n # as a valid name. At runtime they get expanded.\n for benchmark_set_name in benchmark_sets.BENCHMARK_SETS:\n self.valid_benchmark_set_names.add(benchmark_set_name)\n\n # Mock flags to simulate setting --benchmarks.\n p = mock.patch(benchmark_sets.__name__ + '.FLAGS')\n self.mock_flags = p.start()\n self.addCleanup(p.stop)\n self.addCleanup(configs.GetConfigFlags.cache_clear)\n\n self.mock_flags.flag_matrix = None\n self.mock_flags.flag_zip = None\n self.mock_flags.num_benchmark_copies = 1\n\n def testStandardSet(self):\n self.assertIn(benchmark_sets.STANDARD_SET, benchmark_sets.BENCHMARK_SETS)\n standard_set = (benchmark_sets.BENCHMARK_SETS[\n benchmark_sets.STANDARD_SET])[benchmark_sets.BENCHMARK_LIST]\n self.assertIn('iperf', standard_set)\n self.assertIn('fio', standard_set)\n\n def testBenchmarkSetsHaveValidNames(self):\n # check all the benchmark sets to make sure they contain valid names\n valid_benchmark_and_set_names = (self.valid_benchmark_names |\n self.valid_benchmark_set_names)\n benchmark_set_items = list(benchmark_sets.BENCHMARK_SETS.items())\n for _, key_value in benchmark_set_items:\n benchmark_def_list = key_value[benchmark_sets.BENCHMARK_LIST]\n for benchmark_name in benchmark_def_list:\n self.assertIn(benchmark_name, valid_benchmark_and_set_names)\n\n def testBenchmarkDerivedSets(self):\n # make sure that sets which are derived from the standard_set\n # expands into a valid set of benchmarks\n with mock.patch.dict(\n benchmark_sets.BENCHMARK_SETS, {\n 'test_derived_set': {\n benchmark_sets.MESSAGE: 'test derived benchmark set.',\n benchmark_sets.BENCHMARK_LIST: [benchmark_sets.STANDARD_SET]\n }\n }):\n self.mock_flags.benchmarks = ['test_derived_set']\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertIsNotNone(benchmark_tuple_list)\n self.assertGreater(len(benchmark_tuple_list), 0)\n for benchmark_tuple in benchmark_tuple_list:\n self.assertIn(benchmark_tuple[0].BENCHMARK_NAME,\n self.valid_benchmark_names)\n\n def testBenchmarkNestedDerivedSets(self):\n # make sure that sets which are derived from the standard_set\n # expands into a valid set of benchmarks\n self.mock_flags.benchmarks = [benchmark_sets.STANDARD_SET]\n standard_module_list = benchmark_sets.GetBenchmarksFromFlags()\n with mock.patch.dict(\n benchmark_sets.BENCHMARK_SETS, {\n 'test_derived_set': {\n benchmark_sets.MESSAGE: 'test derived benchmark set.',\n benchmark_sets.BENCHMARK_LIST: [benchmark_sets.STANDARD_SET]\n },\n 'test_nested_derived_set': {\n benchmark_sets.MESSAGE: 'test nested derived benchmark set.',\n benchmark_sets.BENCHMARK_LIST: ['test_derived_set']\n }\n }):\n # TODO(voellm): better check would be to make sure both lists are the same\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertIsNotNone(benchmark_tuple_list)\n self.assertIsNotNone(standard_module_list)\n self.assertEqual(len(benchmark_tuple_list), len(standard_module_list))\n for benchmark_tuple in benchmark_tuple_list:\n self.assertIn(benchmark_tuple[0].BENCHMARK_NAME,\n self.valid_benchmark_names)\n\n def testBenchmarkValidCommandLine1(self):\n # make sure the standard_set expands to a valid set of benchmarks\n self.mock_flags.benchmarks = ['standard_set']\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertIsNotNone(benchmark_tuple_list)\n self.assertGreater(len(benchmark_tuple_list), 0)\n for benchmark_tuple in benchmark_tuple_list:\n self.assertIn(benchmark_tuple[0].BENCHMARK_NAME,\n self.valid_benchmark_names)\n\n @staticmethod\n def _ContainsModule(module_name, module_list):\n for module_tuple in module_list:\n if module_tuple[0].BENCHMARK_NAME == module_name:\n return True\n return False\n\n def testBenchmarkValidCommandLine2(self):\n # make sure the standard_set plus a listed benchmark expands\n # to a valid set of benchmarks\n self.mock_flags.benchmarks = ['standard_set', 'bonnieplusplus']\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertIsNotNone(benchmark_tuple_list)\n self.assertGreater(len(benchmark_tuple_list), 0)\n for benchmark_tuple in benchmark_tuple_list:\n self.assertIn(benchmark_tuple[0].BENCHMARK_NAME,\n self.valid_benchmark_names)\n # make sure bonnieplusplus is a listed benchmark\n self.assertTrue(self._ContainsModule('bonnieplusplus',\n benchmark_tuple_list))\n\n def testBenchmarkValidCommandLine3(self):\n # make sure the command with two benchmarks is processed correctly\n self.mock_flags.benchmarks = ['iperf', 'fio']\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertIsNotNone(benchmark_tuple_list)\n self.assertEqual(len(benchmark_tuple_list), 2)\n for benchmark_tuple in benchmark_tuple_list:\n self.assertIn(benchmark_tuple[0].BENCHMARK_NAME,\n self.valid_benchmark_names)\n # make sure listed benchmarks are present\n self.assertTrue(self._ContainsModule('iperf', benchmark_tuple_list))\n self.assertTrue(self._ContainsModule('fio', benchmark_tuple_list))\n\n def testBenchmarkInvalidCommandLine1(self):\n # make sure invalid benchmark names and sets cause a failure\n self.mock_flags.benchmarks = ['standard_set_invalid_name']\n self.assertRaises(ValueError, benchmark_sets.GetBenchmarksFromFlags)\n\n def testBenchmarkInvalidCommandLine2(self):\n # make sure invalid benchmark names and sets cause a failure\n self.mock_flags.benchmarks = ['standard_set', 'iperf_invalid_name']\n self.assertRaises(ValueError, benchmark_sets.GetBenchmarksFromFlags)\n\n def testConfigNames(self):\n self.mock_flags.benchmarks = ['internal_iprf', 'netperf']\n with mock.patch(\n 'perfkitbenchmarker.configs.GetUserConfig',\n return_value=yaml.safe_load(USER_CONFIG)):\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertTrue(self._ContainsModule('iperf', benchmark_tuple_list))\n self.assertTrue(self._ContainsModule('netperf', benchmark_tuple_list))\n\n def testMatrices(self):\n self.mock_flags.benchmarks = ['netperf']\n with mock.patch(\n 'perfkitbenchmarker.configs.GetUserConfig',\n return_value=yaml.safe_load(MATRIX_CONFIG)):\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertEqual(len(benchmark_tuple_list), 4)\n flag_list = [benchmark_tuple[1]['flags']\n for benchmark_tuple in benchmark_tuple_list]\n six.assertCountEqual(self, flag_list, EXPECTED_MATRIX_FLAGS)\n\n def testZipWithDifferentAxesLengths(self):\n self.mock_flags.benchmarks = ['netperf']\n with mock.patch(\n 'perfkitbenchmarker.configs.GetUserConfig',\n return_value=yaml.safe_load(ZIP_CONFIG_DIFFERENT_AXES_LENGTH)):\n self.assertRaises(ValueError, benchmark_sets.GetBenchmarksFromFlags)\n\n def testZip(self):\n self.mock_flags.benchmarks = ['netperf']\n with mock.patch(\n 'perfkitbenchmarker.configs.GetUserConfig',\n return_value=yaml.safe_load(ZIP_CONFIG)):\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertEqual(len(benchmark_tuple_list), 2)\n flag_list = [benchmark_tuple[1]['flags']\n for benchmark_tuple in benchmark_tuple_list]\n six.assertCountEqual(self, flag_list, EXPECTED_ZIP_FLAGS)\n\n def testZipSingleAxis(self):\n self.mock_flags.benchmarks = ['netperf']\n with mock.patch(\n 'perfkitbenchmarker.configs.GetUserConfig',\n return_value=yaml.safe_load(SINGLE_ZIP_CONFIG)):\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertEqual(len(benchmark_tuple_list), 2)\n flag_list = [benchmark_tuple[1]['flags']\n for benchmark_tuple in benchmark_tuple_list]\n six.assertCountEqual(self, flag_list, EXPECTED_SINGLE_ZIP_FLAGS)\n\n def testZipAndMatrix(self):\n self.mock_flags.benchmarks = ['netperf']\n with mock.patch(\n 'perfkitbenchmarker.configs.GetUserConfig',\n return_value=yaml.safe_load(ZIP_AND_MATRIX_CONFIG)):\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertEqual(len(benchmark_tuple_list), 4)\n flag_list = [benchmark_tuple[1]['flags']\n for benchmark_tuple in benchmark_tuple_list]\n six.assertCountEqual(self, flag_list, EXPECTED_ZIP_AND_MATRIX_FLAGS)\n\n def testFilters(self):\n self.mock_flags.benchmarks = ['netperf']\n with mock.patch(\n 'perfkitbenchmarker.configs.GetUserConfig',\n return_value=yaml.safe_load(FILTER_CONFIG)):\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertEqual(len(benchmark_tuple_list), 1)\n self.assertEqual(benchmark_tuple_list[0][1]['flags'],\n {'zones': 'us-central1-a',\n 'machine_type': 'n1-standard-1'})\n\n def testFlagPrecedence(self):\n self.mock_flags.benchmarks = ['netperf']\n with mock.patch(\n 'perfkitbenchmarker.configs.GetUserConfig',\n return_value=yaml.safe_load(FLAG_PRECEDENCE_CONFIG)):\n benchmark_tuple_list = benchmark_sets.GetBenchmarksFromFlags()\n self.assertEqual(len(benchmark_tuple_list), 1)\n self.assertEqual(benchmark_tuple_list[0][1]['flags'],\n {'netperf_benchmarks': 'TCP_STREAM',\n 'netperf_test_length': 40,\n 'netperf_max_iter': 3})\n\n def testFlagMatrixNotFound(self):\n self.mock_flags.benchmarks = ['netperf']\n self.mock_flags.flag_matrix = 'bad_flag_matrix_name'\n with mock.patch(\n 'perfkitbenchmarker.configs.GetUserConfig',\n return_value=yaml.safe_load(USER_CONFIG)):\n with self.assertRaises(benchmark_sets.FlagMatrixNotFoundException):\n benchmark_sets.GetBenchmarksFromFlags()\n\n def testFlagZipNotFound(self):\n self.mock_flags.benchmarks = ['netperf']\n self.mock_flags.flag_zip = 'bad_flag_zip_name'\n with mock.patch(\n 'perfkitbenchmarker.configs.GetUserConfig',\n return_value=yaml.safe_load(USER_CONFIG)):\n with self.assertRaises(benchmark_sets.FlagZipNotFoundException):\n benchmark_sets.GetBenchmarksFromFlags()\n\n\nif __name__ == '__main__':\n unittest.main()\n\n"}
|
{"text": "\nfrom absl import flags\nfrom perfkitbenchmarker.linux_packages import nvidia_driver\n\n\nFLAGS = flags.FLAGS\nflags.DEFINE_string('torch_version', '1.7.1', 'The torch version.')\nflags.DEFINE_string('torchvision_version', '0.8.2', 'The torchvision version.')\nflags.DEFINE_string('torchaudio_version', '0.7.2', 'The torchaudio version.')\nflags.DEFINE_string('torch_env', 'PATH=/opt/conda/bin:$PATH',\n 'The torch install environment.')\n\n_PYTORCH_WHL = 'https://download.pytorch.org/whl/torch_stable.html'\n\n\ndef Install(vm):\n \"\"\"Installs PyTorch on the VM.\"\"\"\n vm.InstallPackages('python3-pip')\n toolkit = 'cpu'\n if nvidia_driver.CheckNvidiaGpuExists(vm):\n # Translates --cuda_toolkit_version=10.2 to \"cu102\" for the toolkit to\n # install\n toolkit = f'cu{\"\".join(FLAGS.cuda_toolkit_version.split(\".\"))}'\n vm.RemoteCommand(\n f'{FLAGS.torch_env} python3 -m pip install '\n f'torch=={FLAGS.torch_version}+{toolkit} '\n f'torchvision=={FLAGS.torchvision_version}+{toolkit} '\n f'torchaudio=={FLAGS.torchaudio_version} '\n f'-f {_PYTORCH_WHL}')\n\n\ndef Uninstall(vm):\n \"\"\"Uninstalls TensorFlow on the VM.\"\"\"\n vm.RemoteCommand(f'{FLAGS.torch_env} pip uninstall '\n 'torch torchvision torchaudio')\n\n"}
|
{"question": "Which type of lung cancer is afatinib used for?", "answer": "EGFR-mutant NSCLC"}
|
{"question": "Which hormone abnormalities are characteristic to Pendred syndrome?", "answer": "thyroid"}
|
{"question": "Which hormone abnormalities are characteristic to Pendred syndrome?", "answer": "thyroid"}
|
{"question": "Which hormone abnormalities are characteristic to Pendred syndrome?", "answer": "thyroid"}
|
{"question": "Which hormone abnormalities are characteristic to Pendred syndrome?", "answer": "Thyroid"}
|
{"question": "Which hormone abnormalities are characteristic to Pendred syndrome?", "answer": "thyroid"}
|
{"question": "Which hormone abnormalities are characteristic to Pendred syndrome?", "answer": "thyroid"}
|
{"question": "Which hormone abnormalities are characteristic to Pendred syndrome?", "answer": "thyroid"}
|
{"Unnamed: 0": 0, "sample": "i didnt feel humiliated", "emotion": 5}
|
{"Unnamed: 0": 1, "sample": "i can go from feeling so hopeless to so damned hopeful just from being around someone who cares and is awake", "emotion": 5}
|
{"Unnamed: 0": 2, "sample": "im grabbing a minute to post i feel greedy wrong", "emotion": 0}
|
{"Unnamed: 0": 3, "sample": "i am ever feeling nostalgic about the fireplace i will know that it is still on the property", "emotion": 3}
|
{"Unnamed: 0": 4, "sample": "i am feeling grouchy", "emotion": 0}
|
{"Unnamed: 0": 5, "sample": "ive been feeling a little burdened lately wasnt sure why that was", "emotion": 5}
|
{"Unnamed: 0": 6, "sample": "ive been taking or milligrams or times recommended amount and ive fallen asleep a lot faster but i also feel like so funny", "emotion": 4}
|
{"Unnamed: 0": 7, "sample": "i feel as confused about life as a teenager or as jaded as a year old man", "emotion": 1}
|
{"Unnamed: 0": 8, "sample": "i have been with petronas for years i feel that petronas has performed well and made a huge profit", "emotion": 2}
|
{"Unnamed: 0": 9, "sample": "i feel romantic too", "emotion": 3}
|
{"sequence": "CAGPNNNTRRSINIGPGRAWYAIGDIIGDIRKAHC", "id": "JN856514", "fold": 2, "periphery-tcell": false, "periphery-monocyte": false, "CNS": false, "breast-milk": false, "female-genitals": true, "male-genitals": false, "gastric": false, "lung": false, "organ": false}
|
{"sequence": "CAQDPPTQYKKGVYM*DQGEQFIQRTK*QEI*DKHI", "id": "U16061", "fold": 1, "periphery-tcell": false, "periphery-monocyte": false, "CNS": true, "breast-milk": false, "female-genitals": false, "male-genitals": false, "gastric": false, "lung": false, "organ": false}
|
{"sequence": "CARPANNTRTSVRIGPGQTFYATGEIIGNIREAHC", "id": "HM070605", "fold": 4, "periphery-tcell": true, "periphery-monocyte": false, "CNS": false, "breast-milk": true, "female-genitals": false, "male-genitals": false, "gastric": false, "lung": false, "organ": false}
|
{"sequence": "CARPANNTRXSIRIGPGQTFYATGDIXGDIRQAHC", "id": "MH758639", "fold": 4, "periphery-tcell": true, "periphery-monocyte": false, "CNS": false, "breast-milk": false, "female-genitals": false, "male-genitals": false, "gastric": false, "lung": false, "organ": false}
|
{"sequence": "CARPGNNTRKGIHIGPGRAFYATEDIVGDIRKAHC", "id": "HQ451263", "fold": 4, "periphery-tcell": true, "periphery-monocyte": false, "CNS": false, "breast-milk": false, "female-genitals": false, "male-genitals": false, "gastric": true, "lung": false, "organ": false}
|
{"sequence": "CARPGNNTRKGIHMGPGGAFYTRGDIIGDIRQAHC", "id": "MH060211", "fold": 0, "periphery-tcell": true, "periphery-monocyte": false, "CNS": false, "breast-milk": false, "female-genitals": false, "male-genitals": false, "gastric": false, "lung": false, "organ": false}
|
{"text": "And I understand, frankly, every President, for the last many Presidents, have said, Were going to open our embassy in Jerusalem. And then they never did it.", "ft_tense": 1}
|
{"text": "And youll be glad to know the United States will continue to be a driver of global growth.", "ft_tense": 1}
|
{"text": "Were going to have a great red wave.", "ft_tense": 1}
|
{"text": "And I knew I was going to be here with you to mark this momentous occasion, so I wore my Houston Astros tie because theyre still the champion of the World Series.", "ft_tense": 1}
|
{"text": "And whenever youre dealing with the medical field, its its a serious thing.", "ft_tense": 0}
|
{"text": "And the test result comes back in five minutes, and we have great testing.", "ft_tense": 0}
|
{"text": "Opportunity Scholarship Program right here in the district.", "ft_tense": 0}
|
{"text": "And many of you, I hope, will be following me.", "ft_tense": 1}
|
{"text": "So, were so happy for your family, and I know your sons are going to make you very proud.", "ft_tense": 1}
|
{"text": "And at this time, our team is working with the governor and working with the senator to ensure that we flow testing resources.", "ft_tense": 0}
|
{"text": "just what I needed works awesome well constructed", "label": 5}
|
{"text": "Great price! Very well constructed. These cables do not feel cheap. Worked exactly as described. Do not hesitate to buy!", "label": 5}
|
{"text": "Good quality build, nice and long", "label": 5}
|
{"text": "No problems with these over the years. They work good.", "label": 5}
|
{"text": "Does what it is supposed to. Seems strong", "label": 5}
|
{"text": "Perfect cables, I always use Hosa Cables in the studio, on the stage the best...", "label": 5}
|
{"labels": 3, "text": "Good shoe for office work. They will scuff very easy so be aware."}
|
{"labels": 1, "text": "I have had the Patricia II wedge in black for about 1 year & wore them regularly in season. When I saw the Patricia at a good price in navy (from 6pm), I purchased them because I thought they would fit just like my Patricia IIs. I was wrong, and paid the price with return shipping that 6pm doesn't pay.<br /><br />The crocs website says that crocs aren't suppose to fit like other sandals - they are suppose to be looser & thus more comfortable - I normally wear an 8-1/2, so have now tried both an 8 & a 9 in the Patricia shoe (I have an 8 in the Patricia II). The Patricia 9 swims on my feet & they would be a hazard to walk around in. The size 8 fits my left foot (which is my wider foot) but is too narrow on my right foot. When I placed the shoes sole to sole, I did notice a slight difference in the width, which, apparently, my foot notices too. I can only conclude a manufacturing defect. But, it is this shoe specifically or the form for this shoe? (others have written the shoe is narrow).<br /><br />Consequently, if you have a wider foot, order the Patricia II instead of this one & if you are a 1/2 size, order down, not up."}
|
{"labels": 1, "text": "Width not right and size too small if width had been just little wider and ordered size larger would have been good. Loved the shoe look"}
|
{"labels": 0, "text": "I received these shoes and they weren't the same as the picture described them, they were a different color. When i tried to return them, the shipping wasn't paid for. So i had to pay $20 for shipping. A waste of time and money. I dont recommend anyone to buy from TheSmartBuy."}
|
{"labels": 2, "text": "They began to split alone the mesh material after a month but loved the shoe and the feel of it"}
|
{"labels": 4, "text": "Excellent shoes , very confortable and litgthweight !"}
|
{"labels": 0, "text": "Usually love Ethnies product. In this case the raised arch area of one shoe is too far back and raised to the point of discomfort.<br />The other shoe fits fine.?? Had to wear em before I figured it out so im stuck with em.<br />Also, they do run a bit narrow(or at least one shoe did) ;)"}
|
{"labels": 1, "text": "Could not get my foot into the shoe. Was disappointed and returned them."}
|
{"labels": 3, "text": "Everything about the boot is great."}
|
{"labels": 2, "text": "Nice looking shoe, okay for short-term wear. Much narrower than other size 11's that I have - tight fit!"}
|
{"OriginalTweet": "COVID-19 misinformation: scientists create a 'psychological vaccine' to protect against fake news https://t.co/WZJrYDo65K via @ConversationUK"}
|
{"OriginalTweet": "@EviePPICRNyh @NIHR_ARC_YH #COVID19 #vaccine https://t.co/HQef5778LQ"}
|
{"OriginalTweet": "Last night this #amazingthing happened Team Crescent got their #vaccination against #COVID19 an amazing privilege but essential to keep the world turning #silentservants #funeraldirectors #fd4vaccine https://t.co/aeFo5riaIL"}
|
{"OriginalTweet": "This is why it should be left to those capable of delivering the vaccine without making a mockery of it\n#teamgp https://t.co/xWRHQOk22D"}
|
{"OriginalTweet": "96 & sadly her covid vaccine arrived 2 days after she died from covid https://t.co/qiqR94PfGZ"}
|
{"OriginalTweet": "So supply is drying up of the vaccine and Ruth Davidson was moaning about Scot Gov stockpiling. Watch for her next to pressure gov on sharing this with rest of UK. #COVID19 #vaccine"}
|
{"text": "Wall St. Bears Claw Back Into the Black (Reuters) Reuters - Short-sellers, Wall Street's dwindling\\band of ultra-cynics, are seeing green again.", "label": 2}
|
{"text": "Carlyle Looks Toward Commercial Aerospace (Reuters) Reuters - Private investment firm Carlyle Group,\\which has a reputation for making well-timed and occasionally\\controversial plays in the defense industry, has quietly placed\\its bets on another part of the market.", "label": 2}
|
{"text": "Oil and Economy Cloud Stocks' Outlook (Reuters) Reuters - Soaring crude prices plus worries\\about the economy and the outlook for earnings are expected to\\hang over the stock market next week during the depth of the\\summer doldrums.", "label": 2}
|
{"text": "Iraq Halts Oil Exports from Main Southern Pipeline (Reuters) Reuters - Authorities have halted oil export\\flows from the main pipeline in southern Iraq after\\intelligence showed a rebel militia could strike\\infrastructure, an oil official said on Saturday.", "label": 2}
|
{"text": "Oil prices soar to all-time record, posing new menace to US economy (AFP) AFP - Tearaway world oil prices, toppling records and straining wallets, present a new economic menace barely three months before the US presidential elections.", "label": 2}
|
{"text": "Stocks End Up, But Near Year Lows (Reuters) Reuters - Stocks ended slightly higher on Friday\\but stayed near lows for the year as oil prices surged past #36;46\\a barrel, offsetting a positive outlook from computer maker\\Dell Inc. (DELL.O)", "label": 2}
|
{"text": "Money Funds Fell in Latest Week (AP) AP - Assets of the nation's retail money market mutual funds fell by #36;1.17 billion in the latest week to #36;849.98 trillion, the Investment Company Institute said Thursday.", "label": 2}
|
{"text": "Fed minutes show dissent over inflation (USATODAY.com) USATODAY.com - Retail sales bounced back a bit in July, and new claims for jobless benefits fell last week, the government said Thursday, indicating the economy is improving from a midsummer slump.", "label": 2}
|
{"text": "Safety Net (Forbes.com) Forbes.com - After earning a PH.D. in Sociology, Danny Bazil Riley started to work as the general manager at a commercial real estate firm at an annual base salary of #36;70,000. Soon after, a financial planner stopped by his desk to drop off brochures about insurance benefits available through his employer. But, at 32, \"buying insurance was the furthest thing from my mind,\" says Riley.", "label": 2}
|
{"text": "Wall St. Bears Claw Back Into the Black NEW YORK (Reuters) - Short-sellers, Wall Street's dwindling band of ultra-cynics, are seeing green again.", "label": 2}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.