content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
from setuptools import setup from distutils.util import convert_path main_ns = {} ver_path = convert_path('mudslide/version.py') with open(ver_path) as ver_file: exec(ver_file.read(), main_ns) setup( name='mudslide', packages=['mudslide'], version=main_ns['__version__'], license='MIT', description='Package to simulate nonadiabatic molecular dynamics using trajectory methods', author='Shane M. Parker', author_email='shane.parker@case.edu', url='https://github.com/smparker/mudslide', download_url='https://github.com/smparker/mudslide/archive/v0.9.tar.gz', keywords= ['science', 'chemistry', 'nonadiabatic dynamics'], install_requires=[ 'numpy>=1.19', 'scipy', 'typing_extensions' ], test_suite='nose.collector', tests_require=['nose'], entry_points={ 'console_scripts': [ 'mudslide = mudslide.__main__:main', 'mudslide-surface = mudslide.surface:main' ] }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Chemistry', 'Topic :: Scientific/Engineering :: Physics', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8' ] )
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 6738, 1233, 26791, 13, 22602, 1330, 10385, 62, 6978, 198, 198, 12417, 62, 5907, 796, 23884, 198, 332, 62, 6978, 796, 10385, 62, 6978, 10786, 41650, 6649, 485, 14, 9641, 13, 9078, 11537, 198, 4...
2.433775
604
import csv import joblib from sklearn.metrics import accuracy_score data = [] features = [] targets = [] feature_names = [] users = [] with open('satisfaction_feature_names.csv') as name_file: column_name_file = csv.reader(name_file) feature_names = next(column_name_file)[2:394] with open('cza_satisfaction_train_0922.csv') as data_file: csv_file = csv.reader(data_file) idx = 0 for content in csv_file: idx = idx + 1 if idx <= 10000: continue if idx > 50000: break content = content[:2] + list(map(float, content[2:])) if len(content) != 0: data.append(content) features.append(content[2:394]) targets.append(content[-1]) users.append(content[1]) clf, sorted_feature_scores = joblib.load("cza_rf.pkl") predict_result = clf.predict(features) print(sorted_feature_scores) print(accuracy_score(predict_result, targets)) result = list(zip(users, predict_result)) print(result[:10]) print(sum(predict_result)) print(sum([flag[1] for flag in result])) with open("rf_predict_result.csv", "w", encoding="UTF-8") as w_file: result_file = csv.writer(w_file) for idx, row in enumerate(result): if idx > 10: break row = list(row) row.insert(0, 20200928) result_file.writerow(row)
[ 11748, 269, 21370, 198, 11748, 1693, 8019, 198, 6738, 1341, 35720, 13, 4164, 10466, 1330, 9922, 62, 26675, 198, 198, 7890, 796, 17635, 198, 40890, 796, 17635, 198, 83, 853, 1039, 796, 17635, 198, 30053, 62, 14933, 796, 17635, 198, 18417...
2.249587
605
print("Hello World") # test = TestClass()
[ 198, 4798, 7203, 15496, 2159, 4943, 198, 2, 1332, 796, 6208, 9487, 3419, 198 ]
3.071429
14
"""Utilities for managing child processes within a scope - this ensures tests run cleanly even on failure and also gives us a mechanism to get debug info for our children. """ import logging import os import sys from contextlib import contextmanager from typing import ContextManager, List import psutil import process_tracker process_tracker.install() logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) __all__ = [ "active_children", "contained_children", "disable_child_tracking", "kill_children", ] def _get_create_time(create_time): """Given basic process create time, return one that would match psutil. """ boot_time = psutil.boot_time() clock_ticks = os.sysconf("SC_CLK_TCK") return boot_time + (create_time / clock_ticks) def active_children() -> List[psutil.Process]: """Returns the active child processes. """ out = [] children = process_tracker.children() for pid, create_time in children: try: process = psutil.Process(pid) except psutil.NoSuchProcess: continue else: if process.create_time() == _get_create_time(create_time): out.append(process) return out def kill_children(timeout=1) -> List[psutil.Process]: """ Kill any active children, returning any that were not terminated within timeout. Args: timeout: time to wait before killing. Returns: list of processes that had to be killed forcefully. """ procs = active_children() for p in procs: try: p.terminate() except psutil.NoSuchProcess: pass gone, alive = psutil.wait_procs(procs, timeout=timeout) for p in alive: logger.warning("Cleaning up child: %d", p.pid) p.kill() return alive
[ 37811, 18274, 2410, 329, 11149, 1200, 7767, 1626, 257, 8354, 532, 428, 19047, 198, 41989, 1057, 3424, 306, 772, 319, 5287, 290, 635, 3607, 514, 257, 9030, 284, 198, 1136, 14257, 7508, 329, 674, 1751, 13, 198, 37811, 198, 11748, 18931, ...
2.64622
701
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2016 Carlos Segura. 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 os import sys import gzip parents = {} conversations = [] samples = {} comentario_id = None parent_id = [] with gzip.open(sys.argv[1]) as f: for line in f: try: line = line.decode('utf-8').strip() #print(line) splitted_line = line.split() if len(splitted_line) == 0: continue head = splitted_line[0] rest = splitted_line[1:] if head == 'comentario_id:': comentario_id = rest[0] parent_id = [] if head == 'parent_id:': parent_id.append(rest[0]) if head == 'comentario:': comentario = rest if len(comentario) == 0: comentario_id = None parent_id = [] continue #Store this comment in parents dictionary if comentario_id is not None: sample = Sample() sample.comentario_id = comentario_id sample.parent_id = parent_id sample.comentario = comentario samples[comentario_id] = sample comentario_id = None parent_id = [] except: continue for k in samples: sample = samples[k] for parent in sample.parent_id: if parent in samples: qa = [samples[parent].comentario, sample.comentario] conversations.append(qa) for conversation in conversations: print('********************************************') for frase in conversation: print(*frase)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 1584, 17409, 31220, 5330, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, ...
2.201984
1,109
import unittest import pandas as pd import git import os from dfstools import get_dataset_dtypes from dfstools import find_related_cols_by_name from dfstools import find_related_cols_by_content from dfstools import find_parent_child_relationships from dfstools import pecan_cookies_load_data if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 17606, 198, 11748, 28686, 198, 6738, 47764, 301, 10141, 1330, 651, 62, 19608, 292, 316, 62, 67, 19199, 198, 6738, 47764, 301, 10141, 1330, 1064, 62, 5363, 62, 403...
2.948276
116
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout,QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox from PyQt5.QtGui import QIcon from PyQt5.QtCore import pyqtSlot if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_())
[ 11748, 25064, 201, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1195, 23416, 11, 1195, 38300, 11, 1195, 49222, 21864, 11, 1195, 39, 14253, 32517, 11, 1195, 13247, 14253, 11, 1195, 44204, 11, 1195, 53, 14253, 32517, ...
2.490446
157
# // ########################################################################### # // Queries # // ########################################################################### # -> get a single cell of a df (use `iloc` with `row` + `col` as arguments) df.iloc[0]['staticContextId'] # -> get one column as a list allFunctionNames = staticContexts[['displayName']].to_numpy().flatten().tolist() # -> get all rows that match a condition callLinked = staticTraces[~staticTraces['callId'].isin([0])] # -> exclude columns df.drop(['A', 'B'], axis=1) # -> complex queries staticTraces.query(f'callId == {callId} or resultCallId == {callId}') # -> join queries (several examples) # https://stackoverflow.com/a/40869861 df.set_index('key').join(other.set_index('key')) B.query('client_id not in @A.client_id') B[~B.client_id.isin(A.client_id)] # merging dfs # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html pd.merge(df1, df2, on=['A', 'B']) df1.merge(df2, left_on='lkey', right_on='rkey') # // ########################################################################### # // Display # // ########################################################################### # -> display a groupby object (https://stackoverflow.com/questions/22691010/how-to-print-a-groupby-object) groups = df.groupby('A') for key, item in groups: group = groups.get_group(key) display(group) # .to_numpy().flatten().tolist()
[ 2, 3373, 1303, 29113, 29113, 7804, 2235, 198, 2, 3373, 2264, 10640, 198, 2, 3373, 1303, 29113, 29113, 7804, 2235, 198, 198, 2, 4613, 651, 257, 2060, 2685, 286, 257, 47764, 357, 1904, 4600, 346, 420, 63, 351, 4600, 808, 63, 1343, 460...
3.083156
469
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: v3/diff/UniversalDiff.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from v3.diff import Transaction_pb2 as v3_dot_diff_dot_Transaction__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='v3/diff/UniversalDiff.proto', package='v3.diff', syntax='proto3', serialized_pb=_b('\n\x1bv3/diff/UniversalDiff.proto\x12\x07v3.diff\x1a\x19v3/diff/Transaction.proto\";\n\rUniversalDiff\x12*\n\x0ctransactions\x18\x01 \x03(\x0b\x32\x14.v3.diff.Transactionb\x06proto3') , dependencies=[v3_dot_diff_dot_Transaction__pb2.DESCRIPTOR,]) _UNIVERSALDIFF = _descriptor.Descriptor( name='UniversalDiff', full_name='v3.diff.UniversalDiff', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='transactions', full_name='v3.diff.UniversalDiff.transactions', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=67, serialized_end=126, ) _UNIVERSALDIFF.fields_by_name['transactions'].message_type = v3_dot_diff_dot_Transaction__pb2._TRANSACTION DESCRIPTOR.message_types_by_name['UniversalDiff'] = _UNIVERSALDIFF _sym_db.RegisterFileDescriptor(DESCRIPTOR) UniversalDiff = _reflection.GeneratedProtocolMessageType('UniversalDiff', (_message.Message,), dict( DESCRIPTOR = _UNIVERSALDIFF, __module__ = 'v3.diff.UniversalDiff_pb2' # @@protoc_insertion_point(class_scope:v3.diff.UniversalDiff) )) _sym_db.RegisterMessage(UniversalDiff) # @@protoc_insertion_point(module_scope)
[ 2, 2980, 515, 416, 262, 8435, 11876, 17050, 13, 220, 8410, 5626, 48483, 0, 198, 2, 2723, 25, 410, 18, 14, 26069, 14, 38747, 28813, 13, 1676, 1462, 198, 198, 11748, 25064, 198, 62, 65, 28, 17597, 13, 9641, 62, 10951, 58, 15, 60, ...
2.65
860
#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ from __future__ import annotations import numpy as np import torch from torch import Tensor from onevision.data.augment.base import BaseAugment from onevision.data.augment.utils import apply_transform_op from onevision.data.data_class import ObjectAnnotation from onevision.factory import AUGMENTS __all__ = [ "ImageBoxAugment", ] # MARK: - Modules
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 37811, 198, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 299, 32152, 355, 45941, 198, 1...
3.021898
137
from pudzu.charts import * from pudzu.sandbox.bamboo import * import seaborn as sns # generate map df = pd.read_csv("datasets/euvotes.csv").set_index('country') palette = tmap(RGBA, sns.cubehelix_palette(11, start=0.2, rot=-0.75)) ranges = [20000000,10000000,5000000,2000000,1000000,500000,200000,100000,0] map = map_chart("maps/Europe.png", colorfn, labelfn) # legend vote_arr = Image.from_array([ [box(votecolfn(n)), Image.from_text("<0.1M" if n < 100000 else ">{:.2g}M".format(n/1000000), arial(16), padding=(10,0))] for n in ranges ], bg="white", xalign=0) vote_leg = Image.from_column([Image.from_text("# votes", arial(16, bold=True)), vote_arr], bg="white", xalign=0, padding=(0,5)) note_leg = Image.from_text("Multi-party national elections for executive head or party.", arial(16), max_width=100, bg="white", padding=(0,2)) legend = Image.from_column([vote_leg, note_leg], bg="white", xalign=0, padding=5).pad(1, "black") chart = map.place(legend, align=(1,0), padding=10) title = Image.from_column([ Image.from_text("EUROPEAN POPULAR VOTE RECORDS", arial(48, bold=True)), Image.from_text("candidate or party with the highest absolute popular vote", arial(36))], bg="white") img = Image.from_column([title, chart], bg="white", padding=2) img.place(Image.from_text("/u/Udzu", font("arial", 16), fg="black", bg="white", padding=5).pad((1,1,0,0), "black"), align=1, padding=10, copy=False) img.save("output/euvotes.png")
[ 6738, 279, 463, 27624, 13, 354, 5889, 1330, 1635, 198, 6738, 279, 463, 27624, 13, 38142, 3524, 13, 65, 27708, 1330, 1635, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 198, 2, 7716, 3975, 198, 7568, 796, 279, 67, 13, 961, 62, 40...
2.586643
554
import pandas as pd import numpy as np from copy import * from bisect import * from scipy.optimize import curve_fit from sklearn.metrics import * from collections import defaultdict as defd import datetime,pickle from DemandHelper import * import warnings warnings.filterwarnings("ignore") ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# # Export a fitted model to text file: # These filenames normally end in '.pkl' def ExportModel(filename,model_object): pickle.dump(model_object, open(filename, 'wb')) print('Model Saved TO: '+filename) # Import a fitted model from text file: # These filenames normally end in '.pkl' ################################################################# ################################################################# ################################################################# short2long = { 'H&G' : 'Home & Garden', 'L&G' : 'Lawn & Garden', 'SPORTS' : 'Sports & Outdoors', 'HI' : 'Home Improvement', 'TOY' : 'Toys & Games', 'KIT' : 'Home & Kitchen', } long2short = {} for short in sorted(short2long): long2short[short2long[short]] = short Shorts = sorted(short2long) Longs = sorted(long2short) Models2 = {} for SH in Shorts: fn = 'MODELS/'+SH+'/DFM2.pkl' model = ImportModel(fn) Models2[SH] = model AllDates = sorted(set([str(a)[:10] for a in Models2['H&G'].alldates])) ################################################################# ################################################################# # Returns a list of valid category names: # SPREETAIL DEMAND PREDICTION: # cat : Category (String or List) # rank : Sales Rank (Integer, 2-List, Long-List) # date1 : First Date of Forecast ("2018-09-03") # date2 : Final Date of Forecast OR # Days Forward ("2018-10-03" or 30) # bb_ratio : BuyBox Percent (100.0) # md_ratio : Marketplace Distribution Percent ################################################################# ################################################################# # [END]
[ 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 220, 355, 45941, 198, 6738, 4866, 1330, 1635, 198, 6738, 47457, 478, 1330, 1635, 220, 198, 6738, 629, 541, 88, 13, 40085, 1096, 1330, 12133, 62, 11147, 198, 6738, 1341...
3.591528
661
import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Flatten from keras.layers import Conv2D, MaxPooling2D model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(128, 128, 1))) model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(128, 128, 1))) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(10000, activation='relu')) model.add(Dense(1000, activation='relu')) model.add(Dense(num_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='sgd') model.fit(x_train, y_train, epochs=100, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test)
[ 11748, 41927, 292, 198, 6738, 41927, 292, 13, 19608, 292, 1039, 1330, 285, 77, 396, 198, 6738, 41927, 292, 13, 27530, 1330, 24604, 1843, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 360, 1072, 11, 1610, 41769, 198, 6738, 41927, 292, 13,...
2.202429
494
# AUTOGENERATED FILE! PLEASE DON'T EDIT """ This module is for selecting a subnetwork using CSS so that you can do special things to them. Checkout the tutorial section for a walkthrough. This is exposed automatically with:: from k1lib.imports import * selector.select # exposed """ from torch import nn; import k1lib, re, torch from typing import List, Tuple, Dict, Union, Any, Iterator, Callable from contextlib import contextmanager; from functools import partial __all__ = ["ModuleSelector", "preprocess", "select"] def preprocess(selectors:str, defaultProp="*") -> List[str]: r"""Removes all quirkly features allowed by the css language, and outputs nice lines. Example:: # returns ["a:f", "a:g,h", "b:g,h", "t:*"] selector.preprocess("a:f; a, b: g,h; t") :param selectors: single css selector string. Statements separated by "\\n" or ";" :param defaultProp: default property, if statement doesn't have one""" # filtering unwanted characters and quirky spaces lines = [e for l in selectors.split("\n") for e in l.split(";")] selectors = [re.sub("(^\s+)|(\s+$)", "", re.sub("\s\s+", " ", line)).replace(" >", ">").replace("> ", ">").replace(" :", ":").replace(": ", ":").replace(" ,", ",").replace(", ", ",").replace(";", "\n").replace(" \n", "\n").replace("\n ", "\n") for line in lines if line != ""] # adding "*" to all selectors with no props specified selectors = [selector if ":" in selector else f"{selector}:{defaultProp}" for selector in selectors] # expanding comma-delimited selectors return [f"{segment}:{selector.split(':')[1]}" for selector in selectors for segment in selector.split(":")[0].split(",")] _idxAuto = k1lib.AutoIncrement() def _strTensor(t): return "None" if t is None else f"{t.shape}" from contextlib import ExitStack
[ 2, 47044, 7730, 1677, 1137, 11617, 45811, 0, 37795, 23917, 6, 51, 48483, 198, 37811, 198, 1212, 8265, 318, 329, 17246, 257, 850, 27349, 1262, 17391, 523, 326, 345, 460, 466, 2041, 198, 27971, 284, 606, 13, 6822, 448, 262, 11808, 2665,...
3.037037
594
''' Created on 22 fvr. 2022 @author: slinux ''' from .wxRavenGeneralDesign import wxRavenWebBrowser from wxRavenGUI.application.wxcustom.CustomLoading import * from wxRavenGUI.application.wxcustom import * import wx.html2 as webview import sys import logging from wxRavenGUI.application.wxcustom.CustomUserIO import UserAdvancedMessage
[ 7061, 6, 198, 41972, 319, 2534, 277, 37020, 13, 33160, 198, 198, 31, 9800, 25, 1017, 259, 2821, 198, 7061, 6, 628, 198, 6738, 764, 49345, 49098, 12218, 23067, 1330, 266, 87, 49098, 13908, 46532, 198, 6738, 266, 87, 49098, 40156, 13, ...
3.016807
119
# Copyright 2017 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. from ebcli.objects.platform import PlatformVersion from ..resources.strings import prompts from ..resources.statics import namespaces, option_names from ..core import io from ..lib import elasticbeanstalk from . import commonops
[ 2, 15069, 2177, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 11074, 921, 198, 2, 743, 407, 779, 428, 2393, ...
3.965
200
''' Perimeterator - Enumerator for AWS ELBs (Public IPs). ''' import logging import boto3 from perimeterator.helper import aws_elb_arn from perimeterator.helper import dns_lookup
[ 7061, 6, 2448, 16912, 1352, 532, 2039, 6975, 1352, 329, 30865, 17852, 37000, 357, 15202, 6101, 82, 737, 705, 7061, 198, 198, 11748, 18931, 198, 11748, 275, 2069, 18, 198, 198, 6738, 25317, 1352, 13, 2978, 525, 1330, 3253, 82, 62, 417,...
3.084746
59
"""Module to help guess whether a file is binary or text. Requirements: Python 2.7+ Recommended: Python 3 """ def is_binary_file(fname): """Attempt to guess if 'fname' is a binary file heuristically. This algorithm has many flaws. Use with caution. It assumes that if a part of the file has NUL bytes or has more control characters than text characters, it is a binary file. Additionally, an ASCII compatible character set is assumed. Returns True if 'fname' appears to be a binary file. """ with open(fname, 'rb') as fh: chunk = fh.read(1024) if not chunk: # Empty file return False if b'\x00' in chunk: # Has NUL bytes return True ncontrol = control_char_count(chunk) ntext = len(chunk) - ncontrol return ncontrol > ntext def is_control_char(c): """Return True if 'c' is a control character. c is considered a control character if it is outside of the extended ASCII set or has a code below 32 with some exclusions. An ASCII compatible character set is assumed. """ charcode = 0 # The following assignment # should make this module compatible with # at least Python 2.7 (tested on 2.7.9). try: charcode = ord(c) except TypeError: charcode = c excludes = ("\t", "\r", "\n") if charcode in [ord(char) for char in excludes]: return False return (charcode < 32 or charcode > 255) def control_char_count(data): """Return the count of control characters in 'data'.""" n = 0 for c in data: if is_control_char(c): n += 1 return n
[ 37811, 26796, 284, 1037, 4724, 1771, 257, 2393, 318, 13934, 393, 2420, 13, 198, 198, 42249, 25, 198, 220, 220, 220, 11361, 362, 13, 22, 10, 198, 198, 36171, 25, 198, 220, 220, 220, 11361, 513, 198, 37811, 198, 198, 4299, 318, 62, ...
2.632813
640
import numpy as np import spikemetrics.metrics as metrics from .utils.thresholdcurator import ThresholdCurator from .quality_metric import QualityMetric import spiketoolkit as st from spikemetrics.utils import Epoch, printProgressBar from collections import OrderedDict from .parameter_dictionaries import get_recording_gui_params, get_feature_gui_params def _compute_template_SNR(template, channel_noise_levels, max_channel_idx): """ Computes SNR on the channel with largest amplitude Parameters ---------- template: np.array Template (n_elec, n_timepoints) channel_noise_levels: list Noise levels for the different channels max_channel_idx: int Index of channel with largest templaye Returns ------- snr: float Signal-to-noise ratio for the template """ snr = ( np.max(np.abs(template[max_channel_idx])) / channel_noise_levels[max_channel_idx] ) return snr def _compute_channel_noise_levels(recording, mode, noise_duration, seed): """ Computes noise level channel-wise Parameters ---------- recording: RecordingExtractor The recording ectractor object mode: str 'std' or 'mad' (default noise_duration: float Number of seconds to compute SNR from Returns ------- moise_levels: list Noise levels for each channel """ M = recording.get_num_channels() n_frames = int(noise_duration * recording.get_sampling_frequency()) if n_frames >= recording.get_num_frames(): start_frame = 0 end_frame = recording.get_num_frames() else: start_frame = np.random.RandomState(seed=seed).randint( 0, recording.get_num_frames() - n_frames ) end_frame = start_frame + n_frames X = recording.get_traces(start_frame=start_frame, end_frame=end_frame) noise_levels = [] for ch in range(M): if mode == "std": noise_level = np.std(X[ch, :]) elif mode == "mad": noise_level = np.median(np.abs(X[ch, :]) / 0.6745) else: raise Exception("'mode' can be 'std' or 'mad'") noise_levels.append(noise_level) return noise_levels
[ 11748, 299, 32152, 355, 45941, 198, 11748, 20240, 4164, 10466, 13, 4164, 10466, 355, 20731, 198, 6738, 764, 26791, 13, 400, 10126, 22019, 1352, 1330, 536, 10126, 26628, 1352, 198, 6738, 764, 13237, 62, 4164, 1173, 1330, 14156, 9171, 1173,...
2.508989
890
# This is a sample Python script. # Press Mays+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import Gramatica as g import interprete as Inter import ts as TS import jsonMode as JSON_INGE import jsonMode as json import Instruccion as INST import Interfaz.Interfaz as Gui import os import glob from os import path from os import remove if __name__ == '__main__': Gui.principal cadena= "goto" # for n in cadena: # in print("ELIMINANDO...") files = glob.glob('data/json/*') for ele in files: os.remove(ele)
[ 2, 770, 318, 257, 6291, 11361, 4226, 13, 198, 198, 2, 4332, 337, 592, 10, 37, 940, 284, 12260, 340, 393, 6330, 340, 351, 534, 2438, 13, 198, 2, 4332, 11198, 15576, 284, 2989, 8347, 329, 6097, 11, 3696, 11, 2891, 9168, 11, 4028, ...
2.822034
236
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Test spparser.py module, which uses spark.py. .. note:: Only testing to see if the parser makes the right kind of objects. Quality of the data is tested in other modules. """ # STDLIB import os # THIRD-PARTY import pytest from astropy import units as u from astropy.tests.helper import assert_quantity_allclose from astropy.utils.exceptions import AstropyUserWarning from numpy.testing import assert_allclose # SYNPHOT from synphot import exceptions as synexceptions from synphot import units from synphot.models import (BlackBodyNorm1D, Box1D, ConstFlux1D, Empirical1D, GaussianFlux1D, PowerLawFlux1D) from synphot.reddening import ExtinctionCurve from synphot.spectrum import SourceSpectrum, SpectralElement # LOCAL from .. import catalog, exceptions, observationmode, spectrum, spparser from ..config import conf from ..stio import resolve_filename def _compare_spectra(sp1, sp2): """Test that two spectra are basically equivalent.""" if sp1.waveset is None: assert sp2.waveset is None w = [100, 5000, 11000] * u.AA else: w = sp1.waveset assert_quantity_allclose(w, sp2.waveset) assert_quantity_allclose(sp1(w), sp2(w)) assert_quantity_allclose(sp1.integrate(wavelengths=w), sp2.integrate(wavelengths=w)) assert type(sp1.model.__class__) == type(sp2.model.__class__) # noqa if hasattr(sp1, 'z'): assert sp1.z == sp2.z def test_z_null(): """ETC junk spectrum results in flat spectrum with no redshift.""" sp1 = spparser.parse_spec('z(null, 0.1)') _single_functioncall(sp1, SourceSpectrum, ConstFlux1D, 'z(null,0.1)') sp2 = SourceSpectrum(ConstFlux1D, amplitude=1 * units.PHOTLAM) _compare_spectra(sp1, sp2) class TestTokens: """Test underlying parser engine.""" def teardown_module(): """Clear all cache.""" catalog.reset_cache() observationmode.reset_cache() spectrum.reset_cache()
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 198, 37811, 14402, 264, 381, 28198, 13, 9078, 8265, 11, 543, 3544, 9009, 13, 9078, 13, 198, 198, 492, 3465, 3712, 628, 220, 220, 2...
2.604798
792
from __future__ import absolute_import import os from tornado.web import StaticFileHandler from rsbroker.views import websocket from rsbroker.views.error import NotFoundErrorHandler settings = dict( template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static") ) handlers = [ # Http api # Events WebSocket API (r"/api/ws", websocket.BrokerServerHandler), # Static (r"/static/(.*)", StaticFileHandler), # Error (r".*", NotFoundErrorHandler) ]
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 28686, 198, 198, 6738, 33718, 13, 12384, 1330, 36125, 8979, 25060, 198, 198, 6738, 44608, 7957, 6122, 13, 33571, 1330, 2639, 5459, 198, 6738, 44608, 7957, 6122, 13, 33571, ...
2.77
200
# -*- coding: utf-8 -*- """ Unit testing for command flags. This tests the various command flags and there helper methods. """ import argparse import typing import uuid import pytest from pheweb.load.command_flags import ( FLAG_CHROMOSOME, add_chromosome_flag, OUTPUT_COLUMN_CHROMOSOME, FLAG_POSITION, add_position_flag, FLAG_REFERENCE, add_reference_flag, FLAG_ALTERNATIVE, add_alternate_flag, OUTPUT_COLUMN_REFERENCE, OUTPUT_COLUMN_ALTERNATIVE, FLAG_P_VALUE, add_p_value_flag, OUTPUT_COLUMN_P_VALUE, FLAG_M_LOG_P_VALUE, add_m_log_p_value_flag, OUTPUT_COLUMN_M_LOG_P_VALUE, add_beta_value_flag, FLAG_BETA, OUTPUT_COLUMN_BETA, FLAG_SE_BETA, add_se_beta_value_flag, OUTPUT_COLUMN_SE_BETA, OUTPUT_COLUMN_POSITION, add_in_file_value_flag, DEFAULT_IN_FILE, add_out_file_value_flag, DEFAULT_OUT_FILE, add_rename_value_flag, DEFAULT_RENAME, add_exclude_value_flag, FLAG_EXCLUDE, FLAG_RENAME, DEFAULT_EXCLUDE, parse_exclude_args, parse_rename_args, ) def test_exclude_args() -> None: """ Test exclude args. @return: None """ assert parse_exclude_args("") == set() assert parse_exclude_args("a") == {"a"} assert parse_exclude_args("a,b") == {"a", "b"} assert parse_exclude_args("a,b,c") == {"a", "b", "c"} def test_rename_args() -> None: """ Test rename args. @return: None """ assert not parse_rename_args("") assert parse_rename_args("a:b") == {"a": "b"} assert parse_rename_args("a:b,c:d") == {"a": "b", "c": "d"} with pytest.raises(ValueError): assert parse_rename_args("a") def parse_harness( cli_argv: typing.List[str], parse_method: typing.Callable[[argparse.ArgumentParser], None], ): """ Parse harness. Calls the argument parser with the parse method. Then calls the argument parse with the cli argv. @param cli_argv: arguments to pass to parser @param parse_method: parse set up method @return: result of the parse """ parser = argparse.ArgumentParser(description=f"test : {parse_method}") parse_method(parser) return parser.parse_args(cli_argv) def test_add_chromosome() -> None: """ Test arguments for chromosome column. @return: None """ chromosome = str(uuid.uuid4()) arguments = parse_harness([FLAG_CHROMOSOME, chromosome], add_chromosome_flag) assert arguments.chromosome == chromosome assert parse_harness([], add_chromosome_flag).chromosome is OUTPUT_COLUMN_CHROMOSOME def test_add_position(): """ Test arguments for position column. @return: None """ position = str(uuid.uuid4()) arguments = parse_harness([FLAG_POSITION, position], add_position_flag) assert arguments.position == position assert parse_harness([], add_position_flag).position is OUTPUT_COLUMN_POSITION def test_add_ref() -> None: """ Test arguments for alternative column. @return: None """ reference = str(uuid.uuid4()) arguments = parse_harness([FLAG_REFERENCE, reference], add_reference_flag) assert arguments.reference == reference assert parse_harness([], add_reference_flag).reference is OUTPUT_COLUMN_REFERENCE def test_add_alt() -> None: """ Test arguments for alternative column. @return: None """ alternative = str(uuid.uuid4()) arguments = parse_harness([FLAG_ALTERNATIVE, alternative], add_alternate_flag) assert arguments.alternative == alternative assert ( parse_harness([], add_alternate_flag).alternative is OUTPUT_COLUMN_ALTERNATIVE ) def test_add_p_value() -> None: """ Test arguments for p-value column. @return: None """ p_value = str(uuid.uuid4()) arguments = parse_harness([FLAG_P_VALUE, p_value], add_p_value_flag) assert arguments.p_value == p_value assert parse_harness([], add_p_value_flag).p_value == OUTPUT_COLUMN_P_VALUE def test_add_m_log_p_value() -> None: """ Test arguments for m log p value column. @return: None """ m_log_p_value = str(uuid.uuid4()) arguments = parse_harness( [FLAG_M_LOG_P_VALUE, m_log_p_value], add_m_log_p_value_flag ) assert arguments.m_log_p_value == m_log_p_value arguments = parse_harness([], add_m_log_p_value_flag) assert arguments.m_log_p_value == OUTPUT_COLUMN_M_LOG_P_VALUE def test_add_beta() -> None: """ Test arguments for beta column. @return: None """ beta = str(uuid.uuid4()) arguments = parse_harness([FLAG_BETA, beta], add_beta_value_flag) assert arguments.beta == beta assert parse_harness([], add_beta_value_flag).beta == OUTPUT_COLUMN_BETA def test_add_se_beta() -> None: """ Test arguments for beta column. @return: None """ se_beta = str(uuid.uuid4()) arguments = parse_harness([FLAG_SE_BETA, se_beta], add_se_beta_value_flag) assert arguments.se_beta == se_beta assert parse_harness([], add_se_beta_value_flag).se_beta == OUTPUT_COLUMN_SE_BETA def test_add_exclude() -> None: """ Test argument for columns to exclude. @return: None """ exclude = str(uuid.uuid4()) arguments = parse_harness([FLAG_EXCLUDE, exclude], add_exclude_value_flag) assert arguments.exclude == exclude assert parse_harness([], add_exclude_value_flag).exclude == DEFAULT_EXCLUDE def test_add_rename() -> None: """ Test arguments for rename. @return: None """ new_name = str(uuid.uuid4()) old_name = str(uuid.uuid4()) rename = f"{old_name}:{new_name}" arguments = parse_harness([FLAG_RENAME, rename], add_rename_value_flag) assert arguments.rename == rename assert parse_harness([], add_rename_value_flag).rename == DEFAULT_RENAME def test_parse_out_file() -> None: """ Test arguments for out file. @return: None """ out_file = str(uuid.uuid4()) arguments = parse_harness(["--out-file", out_file], add_out_file_value_flag) assert arguments.out_file == out_file assert parse_harness([], add_out_file_value_flag).out_file == DEFAULT_OUT_FILE def test_add_in_file() -> None: """ Test arguments for input file. @return: None """ in_file = str(uuid.uuid4()) assert parse_harness([in_file], add_in_file_value_flag).in_file == in_file assert parse_harness([], add_in_file_value_flag).in_file == DEFAULT_IN_FILE
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 26453, 4856, 329, 3141, 9701, 13, 198, 198, 1212, 5254, 262, 2972, 3141, 9701, 198, 392, 612, 31904, 5050, 13, 198, 198, 37811, 198, 11748, 1822, 29572, 198,...
2.463796
2,624
#! /usr/bin/env python # This file is part of khmer, https://github.com/dib-lab/khmer/, and is # Copyright (C) 2011-2015, Michigan State University. # Copyright (C) 2015, The Regents of the University of California. # # 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 Michigan State 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 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. # # Contact: khmer-project@idyll.org """ Error correct reads based on a counting hash from a diginorm step. Output sequences will be put in inputfile.corr. % python scripts/error-correct-pass2 <counting.ct> <data1> [ <data2> <...> ] Use '-h' for parameter help. """ import sys import os import screed import khmer from khmer import Countgraph from khmer import khmer_args from khmer.khmer_args import FileType as khFileType DEFAULT_CUTOFF = 2 if __name__ == '__main__': main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 770, 2393, 318, 636, 286, 44081, 647, 11, 3740, 1378, 12567, 13, 785, 14, 67, 571, 12, 23912, 14, 14636, 647, 47454, 290, 318, 198, 2, 15069, 357, 34, 8, 2813, 12, 4626, 11,...
3.245665
692
import json import pathlib from unittest.mock import patch from freezegun import freeze_time from datahub.ingestion.run.pipeline import Pipeline from datahub.ingestion.source.identity.azure_ad import AzureADConfig from tests.test_helpers import mce_helpers FROZEN_TIME = "2021-08-24 09:00:00" def load_test_resources(test_resources_dir): azure_ad_users_json_file = test_resources_dir / "azure_ad_users.json" azure_ad_groups_json_file = test_resources_dir / "azure_ad_groups.json" with azure_ad_users_json_file.open() as azure_ad_users_json: reference_users = json.loads(azure_ad_users_json.read()) with azure_ad_groups_json_file.open() as azure_ad_groups_json: reference_groups = json.loads(azure_ad_groups_json.read()) return reference_users, reference_groups def mocked_functions( test_resources_dir, mock_token, mock_users, mock_groups, mock_groups_users ): # mock token response mock_token.return_value = "xxxxxxxx" # mock users and groups response users, groups = load_test_resources(test_resources_dir) mock_users.return_value = iter(list([users])) mock_groups.return_value = iter(list([groups])) # For simplicity, each user is placed in ALL groups. # Create a separate response mock for each group in our sample data. r = [] for _ in groups: r.append(users) mock_groups_users.return_value = iter(r)
[ 11748, 33918, 198, 11748, 3108, 8019, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 8529, 198, 198, 6738, 1479, 89, 1533, 403, 1330, 16611, 62, 2435, 198, 198, 6738, 4818, 993, 549, 13, 278, 395, 295, 13, 5143, 13, 79, 541, 4470, 1...
2.738372
516
from .builder import build_optimizers, MGE_OPTIMIZERS, build_gradmanagers from .default_constructor import DefaultOptimizerConstructor
[ 6738, 764, 38272, 1330, 1382, 62, 40085, 11341, 11, 337, 8264, 62, 3185, 51, 3955, 14887, 4877, 11, 1382, 62, 9744, 805, 10321, 198, 6738, 764, 12286, 62, 41571, 273, 1330, 15161, 27871, 320, 7509, 42316, 273, 628, 628 ]
3.538462
39
#!/usr/bin/env python3 import unittest from config.parser.parsing import Parser
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 555, 715, 395, 198, 6738, 4566, 13, 48610, 13, 79, 945, 278, 1330, 23042, 263, 628, 628, 198 ]
2.833333
30
## Requires Python v3 and pandas (pip install pandas) ## This script takes the newcastle membership csv and attempts ## to reduce the file size as much as possible through aggregation and lookups ## Two lookup files to provide library names and dates are also created. import csv import os import re from datetime import datetime import pandas MEMBERDATA = '..\\data\\dashboard_newcastle_members.csv' run()
[ 2235, 26848, 11361, 410, 18, 290, 19798, 292, 357, 79, 541, 2721, 19798, 292, 8, 198, 2235, 770, 4226, 2753, 262, 649, 18676, 9931, 269, 21370, 290, 6370, 198, 2235, 284, 4646, 262, 2393, 2546, 355, 881, 355, 1744, 832, 46500, 290, ...
3.858491
106
"""Interface contract object""" from __future__ import absolute_import import six import sys import logging from contracts.interface import ContractException, ContractNotRespected from .extension import ID from ..declarations import implementer from ..verify import verifyObject from ..interface import InterfaceClass __all__ = ( 'InterfaceContract', 'MethodContract', 'AttributeContract', 'ContractNotRespected') def method_wrapper(element): return func def construct_class(iface, elements): attrs = {'__module__': iface.__module__} slots = {'__context__', '__logger__'} for name, element in elements.items(): slots.add(name) if isinstance(element, AttributeContract): attrs[name] = AttributeDescriptor(element) else: attrs[name] = method_wrapper(element) name = '%sBoundContract' % iface.__name__ cls = type(name, (BoundInterfaceContract,), attrs) cls.__slots__ = tuple(slots) return implementer(iface)(cls)
[ 37811, 39317, 2775, 2134, 37811, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 11748, 2237, 198, 11748, 25064, 198, 11748, 18931, 198, 6738, 8592, 13, 39994, 1330, 17453, 16922, 11, 17453, 3673, 4965, 7254, 198, 198, 6738, 764...
2.933526
346
import numpy as np import torch import torchvision.transforms as transforms from dataloader.dataloader_hourglass import heatmap_Dataloader import os from network import KFSGNet import torchvision.transforms as transforms os.environ['CUDA_VISIBLE_DEVICES'] = '2' # Device configuration device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Hyper-parameters num_epochs = 200 learning_rate = 0.001 transform = transforms.Compose([ transforms.ToTensor()]) params = dict() params['data_normalize_factor'] = 256 params['dataset_dir'] = "./" params['rgb2gray'] = False params['dataset'] = "heatmap_dataset_all" params['train_batch_sz'] = 16 params['val_batch_sz'] = 1 params['sigma'] = 3 dataloaders, dataset_sizes = heatmap_Dataloader(params) train_loader = dataloaders['train'] test_loader = dataloaders['val'] # Define your model model = KFSGNet() # model.load_state_dict(torch.load( # '/media/home_bak/ziqi/park/hourglass/10heatmap5.ckpt')) # move model to the right device model.to(device) model.train() # Loss and optimizer loss_fn = torch.nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) # # # milestones[0. 200] # [200, 300][300, 320].....[340, 400] # gammagamma # torch.optim.lr_scheduler.MultiStepLR(optimizer, # milestones=[30, 60, 80, 100, 120, 140], gamma=0.5) print(optimizer.state_dict()['param_groups'][0]['lr']) # For updating learning rate # Train the model total_step = len(train_loader) curr_lr = learning_rate print("start") def calculate_mask(heatmaps_target): """ :param heatmaps_target: Variable (N,15,96,96) :return: Variable (N,15,96,96) """ N, C, _, _ = heatmaps_targets.size() N_idx = [] C_idx = [] for n in range(N): for c in range(C): max_v = heatmaps_targets[n, c, :, :].max().data if max_v != 0.0: N_idx.append(n) C_idx.append(c) mask = torch.zeros(heatmaps_targets.size()) mask[N_idx, C_idx, :, :] = 1. mask = mask.float().cuda() return mask, [N_idx, C_idx] # def MSE(y_pred, gt): # loss = 0 # loss += 0.5 * np.sum((y_pred - gt)**2) # vec_gt = [[0]*3] * 5 # for w in range(4): # vec_gt[w] = np.array([gt[w][0], # gt[w][1]]) # vector_gt = vec_gt[1]-vec_gt[0] # vec_pred = [[0]*3] * 5 # for v in range(4): # vec_pred[w] = np.array([y_pred[w][0], # y_pred[w][1]]) # vector_pred = vec_pred[1]-vec_pred[0] # loss += (vector_gt[0]*vector_pred[1]-vector_pred[0]*vector_gt[1])**0.5 for epoch in range(num_epochs): tmp = 0 for i, (data, gt, mask, item, imgPath, heatmaps_targets) in enumerate(train_loader): # print(i) data = data.to(device) gt = gt.to(device) mask = mask.to(device) gt = gt.view(-1, 8) heatmaps_targets = heatmaps_targets.to(device) mask, indices_valid = calculate_mask(heatmaps_targets) # print(heatmaps_targets.shape) # Forward pass outputs = model(data) outputs = outputs * mask heatmaps_targets = heatmaps_targets * mask # print(outputs.shape) loss = loss_fn(outputs, heatmaps_targets) tmp += loss.item() # exit() # Backward and optimize optimizer.zero_grad() loss.backward() optimizer.step() if i % 10 == 0: print("Epoch [{}/{}], Step [{}/{}] Loss: {:.4f}, average_loss: {:.4f}, learning_rate: {}".format( epoch + 1, num_epochs, i + 1, total_step, loss.item(), tmp / (i+1), optimizer.state_dict()['param_groups'][0]['lr'])) if (epoch + 1) % 10 == 0: torch.save(model.state_dict(), '{}heatmap4.ckpt'.format(epoch + 1)) # card2 heatmap 26688 # card0 heatmap2 29009
[ 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 28034, 10178, 13, 7645, 23914, 355, 31408, 198, 6738, 4818, 282, 1170, 263, 13, 67, 10254, 1170, 263, 62, 9769, 20721, 1330, 4894, 8899, 62, 35, 10254, 1170, 263, 198, 11748,...
2.122192
1,825
#!/usr/bin/env python3 import sys from argparse import ArgumentParser from getpass import getpass from hashlib import pbkdf2_hmac from signal import signal, SIGINT signal = signal(SIGINT, die) iwd = """[Security] PreSharedKey={psk}""" supplicant = """network={{ ssid={ssid} #psk={passphrase} psk={psk} }}""" parser = ArgumentParser( description="%(prog)s pre-computes PSK entries for network configuration blocks of wpa_supplicant or iwd config. An ASCII passphrase and SSID are used to generate a 256-bit PSK." ) parser.add_argument("ssid", help="The SSID whose passphrase should be derived.") parser.add_argument( "passphrase", help="The passphrase to use. If not included on the command line, passphrase will be read from standard input.", nargs="?", ) parser.add_argument( "--iwd", "-i", dest="template", action="store_const", const=iwd, default=supplicant, help="Generate for iwd (default: generate for wpa_supplicant).", ) args = parser.parse_args() if not args.passphrase: print("# reading passphrase from stdin", file=sys.stderr) args.passphrase = getpass(prompt="") if not 8 <= len(args.passphrase) <= 63: print("Passphrase must be 8..63 characters", file=sys.stderr) sys.exit(1) passphrase = args.passphrase.encode() if any(b < 32 or b == 127 for b in passphrase): print("Invalid passphrase character", file=sys.stderr) sys.exit(1) ssid = args.ssid.encode() psk = pbkdf2_hmac("sha1", passphrase, ssid, iterations=4096, dklen=32) print(args.template.format(ssid=args.ssid, passphrase=args.passphrase, psk=psk.hex()))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 11748, 25064, 198, 6738, 1822, 29572, 1330, 45751, 46677, 198, 6738, 651, 6603, 1330, 651, 6603, 198, 6738, 12234, 8019, 1330, 279, 65, 74, 7568, 17, 62, 71, 20285, 198, 6738,...
2.729272
591
# -*- coding: utf-8 -*- from optparse import make_option from django.conf import settings from django.core.management.base import BaseCommand, CommandError from cms.api import copy_plugins_to_language from cms.models import Title, Page from cms.utils.i18n import get_language_list
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 2172, 29572, 1330, 787, 62, 18076, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 27604, 13, 8692, 1330, 7308, 21...
3.202247
89
# Generated by Django 2.1.2 on 2018-10-14 18:37 from django.db import migrations import picklefield.fields
[ 2, 2980, 515, 416, 37770, 362, 13, 16, 13, 17, 319, 2864, 12, 940, 12, 1415, 1248, 25, 2718, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 198, 11748, 2298, 293, 3245, 13, 25747, 628 ]
2.945946
37
# -*- coding: utf-8 -*- from adsrefpipe.refparsers.CrossRefXML import CrossReftoREFs from adsrefpipe.refparsers.ElsevierXML import ELSEVIERtoREFs from adsrefpipe.refparsers.JATSxml import JATStoREFs from adsrefpipe.refparsers.IOPxml import IOPtoREFs from adsrefpipe.refparsers.SpringerXML import SPRINGERtoREFs from adsrefpipe.refparsers.APSxml import APStoREFs from adsrefpipe.refparsers.NatureXML import NATUREtoREFs from adsrefpipe.refparsers.AIPxml import AIPtoREFs from adsrefpipe.refparsers.WileyXML import WILEYtoREFs from adsrefpipe.refparsers.NLM3xml import NLMtoREFs from adsrefpipe.refparsers.AGUxml import AGUtoREFs from adsrefpipe.refparsers.arXivTXT import ARXIVtoREFs def verify(parser_name): """ :param parser_name: parser name from db :return: """ # based on parser name return the parser class, if it is an xml if parser_name == 'CrossRef': return CrossReftoREFs if parser_name == 'ELSEVIER': return ELSEVIERtoREFs if parser_name == 'JATS': return JATStoREFs if parser_name == 'IOP': return IOPtoREFs if parser_name == 'SPRINGER': return SPRINGERtoREFs if parser_name == 'APS': return APStoREFs if parser_name == 'NATURE': return NATUREtoREFs if parser_name == 'AIP': return AIPtoREFs if parser_name == 'WILEY': return WILEYtoREFs if parser_name == 'NLM': return NLMtoREFs if parser_name == 'AGU': return AGUtoREFs if parser_name == 'arXiv': return ARXIVtoREFs return None
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 9011, 5420, 34360, 13, 5420, 79, 945, 364, 13, 21544, 8134, 55, 5805, 1330, 6372, 3041, 701, 78, 31688, 82, 198, 6738, 9011, 5420, 34360, 13, 5420, 79, 945,...
2.343328
667
from cached_property import cached_property from purl import URL from onegov.translator_directory import _ from onegov.core.elements import Block, Link, LinkGroup, Confirm, Intercooler from onegov.core.utils import linkify from onegov.org.layout import DefaultLayout as BaseLayout from onegov.translator_directory.collections.documents import \ TranslatorDocumentCollection from onegov.translator_directory.collections.language import LanguageCollection from onegov.translator_directory.collections.translator import \ TranslatorCollection from onegov.translator_directory.constants import member_can_see, \ editor_can_see, GENDERS, ADMISSIONS, PROFESSIONAL_GUILDS, \ INTERPRETING_TYPES def format_boolean(self, val): assert isinstance(val, bool) return self.request.translate((_('Yes') if val else _('No'))) def format_admission(self, val): return self.request.translate(ADMISSIONS[val]) def show(self, attribute_name): """Some attributes on the translator are hidden for less privileged users""" if self.request.is_member: return attribute_name in member_can_see if self.request.is_editor: return attribute_name in editor_can_see return True def color_class(self, count): """ Depending how rare a language is offered by translators, apply a color code using the returned css class """ if count <= 5: return 'text-orange' class TranslatorLayout(DefaultLayout): class LanguageCollectionLayout(DefaultLayout):
[ 6738, 39986, 62, 26745, 1330, 39986, 62, 26745, 198, 6738, 1308, 75, 1330, 10289, 198, 198, 6738, 530, 9567, 13, 7645, 41880, 62, 34945, 1330, 4808, 198, 6738, 530, 9567, 13, 7295, 13, 68, 3639, 1330, 9726, 11, 7502, 11, 7502, 13247, ...
2.933579
542
import pandas as pd import numpy as np import io
[ 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 33245 ]
3.2
15
# Copyright (c) nexB Inc. and others. All rights reserved. # ScanCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/scancode-toolkit for support or download. # See https://aboutcode.org for more information about nexB OSS projects. # import logging import re import attr from packageurl import PackageURL import toml from commoncode import filetype from commoncode import fileutils from packagedcode import models """ Handle Rust cargo crates """ TRACE = False logger = logging.getLogger(__name__) if TRACE: import sys logging.basicConfig(stream=sys.stdout) logger.setLevel(logging.DEBUG) def party_mapper(party, party_role): """ Yields a Party object with party of `party_role`. https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field-optional """ for person in party: name, email = parse_person(person) yield models.Party( type=models.party_person, name=name, role=party_role, email=email) def parse_person(person): """ https://doc.rust-lang.org/cargo/reference/manifest.html#the-authors-field-optional A "person" is an object with an optional "name" or "email" field. A person can be in the form: "author": "Isaac Z. Schlueter <i@izs.me>" For example: >>> p = parse_person('Barney Rubble <b@rubble.com>') >>> assert p == ('Barney Rubble', 'b@rubble.com') >>> p = parse_person('Barney Rubble') >>> assert p == ('Barney Rubble', None) >>> p = parse_person('<b@rubble.com>') >>> assert p == (None, 'b@rubble.com') """ parsed = person_parser(person) if not parsed: name = None parsed = person_parser_no_name(person) else: name = parsed.group('name') email = parsed.group('email') if name: name = name.strip() if email: email = email.strip('<> ') return name, email person_parser = re.compile( r'^(?P<name>[^\(<]+)' r'\s?' r'(?P<email><([^>]+)>)?' ).match person_parser_no_name = re.compile( r'(?P<email><([^>]+)>)?' ).match
[ 198, 2, 15069, 357, 66, 8, 497, 87, 33, 3457, 13, 290, 1854, 13, 1439, 2489, 10395, 13, 198, 2, 20937, 10669, 318, 257, 16028, 286, 497, 87, 33, 3457, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 1...
2.495506
890
#!/usr/bin/env python2.7 # # Copyright (c) 2016 ARM Limited # All rights reserved # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Andreas Sandberg from abc import ABCMeta, abstractmethod from datetime import datetime import difflib import functools import os import re import subprocess import sys import traceback from results import UnitResult from helpers import * _test_base = os.path.join(os.path.dirname(__file__), "..")
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 13, 22, 198, 2, 198, 2, 15069, 357, 66, 8, 1584, 20359, 15302, 198, 2, 1439, 2489, 10395, 198, 2, 198, 2, 383, 5964, 2174, 14582, 691, 284, 6634, 287, 262, 3788, 290, 2236, 198, 2...
3.890145
619
from app import ( mythic, links, nginx_port, listen_port, mythic_admin_password, mythic_admin_user, default_operation_name, mythic_db ) import app import asyncpg import redis from peewee_async import Manager from sanic.response import json from sanic import response from sanic.exceptions import ( NotFound, Unauthorized, MethodNotSupported, SanicException, RequestTimeout, ) import sys from jinja2 import Environment, PackageLoader from app.database_models.model import ( Operator, Operation, OperatorOperation, ATTACK, Artifact, ) import datetime import app.crypto as crypto from sanic_jwt import BaseEndpoint, utils, exceptions from sanic_jwt.decorators import scoped, inject_user import ujson as js from ipaddress import ip_address from app.routes.authentication import invalidate_refresh_token import app.database_models.model as db_model from sanic.log import logger from uuid import uuid4 import asyncio env = Environment(loader=PackageLoader("app", "templates"), autoescape=True) class Login(BaseEndpoint): # /static serves out static images and files mythic.static("/static", "./app/static", name="shared_files") mythic.static("/favicon.ico", "./app/static/favicon.ico", name="favicon") mythic.static("/strict_time.png", "./app/static/strict_time.png", name="strict_time") mythic.static( "/grouped_output.png", "./app/static/grouped_output.png", name="grouped_output" ) mythic.static( "/no_cmd_output.png", "./app/static/no_cmd_output.png", name="no_cmd_output" ) mythic.static("/add_comment.png", "./app/static/add_comment.png", name="add_comment") # add links to the routes in this file at the bottom links["index"] = mythic.url_for("index") links["login"] = links["WEB_BASE"] + "/login" links["logout"] = mythic.url_for("logout") links["settings"] = mythic.url_for("settings")
[ 6738, 598, 1330, 357, 201, 198, 220, 220, 220, 7918, 291, 11, 201, 198, 220, 220, 220, 6117, 11, 201, 198, 220, 220, 220, 299, 42822, 62, 634, 11, 201, 198, 220, 220, 220, 6004, 62, 634, 11, 201, 198, 220, 220, 220, 7918, 291, ...
2.592398
763
from ctypes import c_int from .dll import _bind __all__ = [ # Enums "SDL_BlendMode", "SDL_BLENDMODE_NONE", "SDL_BLENDMODE_BLEND", "SDL_BLENDMODE_ADD", "SDL_BLENDMODE_MOD", "SDL_BLENDMODE_MUL", "SDL_BLENDMODE_INVALID", "SDL_BlendOperation", "SDL_BLENDOPERATION_ADD", "SDL_BLENDOPERATION_SUBTRACT", "SDL_BLENDOPERATION_REV_SUBTRACT", "SDL_BLENDOPERATION_MINIMUM", "SDL_BLENDOPERATION_MAXIMUM", "SDL_BlendFactor", "SDL_BLENDFACTOR_ZERO", "SDL_BLENDFACTOR_ONE", "SDL_BLENDFACTOR_SRC_COLOR", "SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR", "SDL_BLENDFACTOR_SRC_ALPHA", "SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA", "SDL_BLENDFACTOR_DST_COLOR", "SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR", "SDL_BLENDFACTOR_DST_ALPHA", "SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA", # Functions "SDL_ComposeCustomBlendMode" ] SDL_BlendMode = c_int SDL_BLENDMODE_NONE = 0x00000000 SDL_BLENDMODE_BLEND = 0x00000001 SDL_BLENDMODE_ADD = 0x00000002 SDL_BLENDMODE_MOD = 0x00000004 SDL_BLENDMODE_MUL = 0x00000008 SDL_BLENDMODE_INVALID = 0x7FFFFFFF SDL_BlendOperation = c_int SDL_BLENDOPERATION_ADD = 0x1 SDL_BLENDOPERATION_SUBTRACT = 0x2 SDL_BLENDOPERATION_REV_SUBTRACT = 0x3 SDL_BLENDOPERATION_MINIMUM = 0x4 SDL_BLENDOPERATION_MAXIMUM = 0x5 SDL_BlendFactor = c_int SDL_BLENDFACTOR_ZERO = 0x1 SDL_BLENDFACTOR_ONE = 0x2 SDL_BLENDFACTOR_SRC_COLOR = 0x3 SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = 0x4 SDL_BLENDFACTOR_SRC_ALPHA = 0x5 SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = 0x6 SDL_BLENDFACTOR_DST_COLOR = 0x7 SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = 0x8 SDL_BLENDFACTOR_DST_ALPHA = 0x9 SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = 0xA SDL_ComposeCustomBlendMode = _bind("SDL_ComposeCustomBlendMode", [SDL_BlendFactor, SDL_BlendFactor, SDL_BlendOperation, SDL_BlendFactor, SDL_BlendFactor, SDL_BlendOperation], SDL_BlendMode, added='2.0.6')
[ 6738, 269, 19199, 1330, 269, 62, 600, 198, 6738, 764, 12736, 1330, 4808, 21653, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 1303, 2039, 5700, 198, 220, 220, 220, 366, 10305, 43, 62, 3629, 437, 19076, 1600, 198, 220, 220, ...
1.91483
998
from .vizutils import viz_overlaymask, display_side2side, display_side2sidev1, stack_patches, figure2image, get_heatmap, visualize_probmaps from .vizutils import get_heatmap_multiple, figure2image_save
[ 6738, 764, 85, 528, 26791, 1330, 48569, 62, 2502, 10724, 27932, 11, 3359, 62, 1589, 17, 1589, 11, 220, 3359, 62, 1589, 17, 1589, 85, 16, 11, 8931, 62, 8071, 2052, 11, 3785, 17, 9060, 11, 651, 62, 25080, 8899, 11, 38350, 62, 1676, ...
3.044776
67
#!/usr/bin/env python """ site configuration for larch: init_files: list of larch files run (in order) on startup module_path: list of directories to search for larch code history_file: """ from __future__ import print_function import sys import os from os.path import exists, abspath, join from .utils import get_homedir, nativepath from .version import __version__ as larch_version ## # set system-wide and local larch folders # larchdir = sys.exec_prefix + 'share' + 'larch' # usr_larchdir = get_homedir() + '.larch' (#unix) # = get_homedir() + 'larch' (#win) ## larchdir = pjoin(sys.exec_prefix, 'share', 'larch') home_dir = get_homedir() usr_larchdir = pjoin(home_dir, '.larch') if os.name == 'nt': usr_larchdir = pjoin(home_dir, 'larch') if 'LARCHDIR' in os.environ: usr_larchdir = nativepath(os.environ['LARCHDIR']) ## ## names (and loading order) for core plugin modules core_plugins = ('std', 'math', 'io', 'wx', 'xray', 'xrf', 'xafs') # frozen executables, as from cx_freeze, will have # these paths to be altered... if hasattr(sys, 'frozen'): if os.name == 'nt': try: tdir, exe = os.path.split(sys.executable) toplevel, bindir = os.path.split(tdir) larchdir = os.path.abspath(toplevel) except: pass elif sys.platform.lower().startswith('darwin'): tdir, exe = os.path.split(sys.executable) toplevel, bindir = os.path.split(tdir) larchdir = pjoin(toplevel, 'Resources', 'larch') modules_path = [] plugins_path = [] _path = [usr_larchdir, larchdir] if 'LARCHPATH' in os.environ: _path.extend([nativepath(s) for s in os.environ['LARCHPATH'].split(':')]) for pth in _path: mdir = pjoin(pth, 'modules') if exists(mdir) and mdir not in modules_path: modules_path.append(mdir) pdir = pjoin(pth, 'plugins') if exists(pdir) and pdir not in plugins_path: plugins_path.append(pdir) # initialization larch files to be run on startup init_files = [pjoin(usr_larchdir, 'init.lar')] if 'LARCHSTARTUP' in os.environ: startup = os.environ['LARCHSTARTUP'] if exists(startup): init_files = [nativepath(startup)] # history file: history_file = pjoin(usr_larchdir, 'history.lar') def make_user_larchdirs(): """create user's larch directories""" files = {'init.lar': 'put custom startup larch commands:', 'history.lar': 'history of larch commands:', 'history_larchgui.lar': 'history of larch_gui commands:', } subdirs = {'matplotlib': 'matplotlib may put files here', 'dlls': 'put dlls here', 'modules': 'put custom larch or python modules here', 'plugins': 'put custom larch plugins here'} make_dir(usr_larchdir) for fname, text in files.items(): write_file(pjoin(usr_larchdir, fname), text) for sdir, text in subdirs.items(): sdir = pjoin(usr_larchdir, sdir) make_dir(sdir) write_file(pjoin(sdir, 'README'), text) def system_settings(): """set system-specific Environmental Variables, and make sure that the user larchdirs exist. This is run by the interpreter on startup.""" # ubuntu / unity hack if sys.platform.lower().startswith('linux'): if 'ubuntu' in os.uname()[3].lower(): os.environ['UBUNTU_MENUPROXY'] = '0' make_user_larchdirs() if __name__ == '__main__': show_site_config()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 198, 15654, 8398, 329, 300, 998, 25, 628, 220, 220, 2315, 62, 16624, 25, 220, 1351, 286, 300, 998, 3696, 1057, 357, 259, 1502, 8, 319, 13693, 198, 220, 220, 8265, 62, 6978, ...
2.330013
1,506
#!/usr/bin/env python # -*- coding: utf-8 -*- ############## # GPathFinder: Identification of ligand pathways by a multi-objective # genetic algorithm # # https://github.com/insilichem/gpathfinder # # Copyright 2019 Jos-Emilio Snchez Aparicio, Giuseppe Sciortino, # Daniel Villadrich Herrmannsdoerfer, Pablo Orenes Chueca, # Jaime Rodrguez-Guerra Pedregal and Jean-Didier Marchal # # 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 contains the similarity functions that are used to discard individuals that are not different enough. This criterion of similarity will be applied in the case of two ``pathways`` individuals with the same score. Then, if they are similar enough according to this module, one of them will be discarded. """ from __future__ import print_function, division import logging import numpy as np logger = logging.getLogger(__name__) def pathways_rmsd(ind1, ind2, subject, threshold, *args, **kwargs): """ Calculates the RMSD between the positions of the ``pathways`` genes belonging two the two individuals object of study. If the squared RMSD is less or equal than the squared threshold, we consider that the two pathways are identical and one of them will be discarded. Parameters ---------- ind1 : gpath.base.Individual ind2 : gpath.base.Individual subject: str Name of Gpath ``pathway`` gene instance to measure. threshold : float Maximum RMSD value in Angstroms to consider two individuals as similar. If ``rmsd > threshold``, they are considered different. Returns ------- bool True if ``rmsd`` is within threshold, False otherwise. It will always return False if number of points of the pathway is not equal in the two Individuals. """ coords1 = np.array([elem[:] for elem in \ ind1.genes[subject].allele['positions']]) coords2 = np.array([elem[:] for elem in \ ind2.genes[subject].allele['positions']]) if coords1.shape[0] != coords2.shape[0]: return False rmsd_squared = _rmsd_squared(coords1, coords2) if rmsd_squared > threshold*threshold: return False return True
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 7804, 4242, 2235, 198, 2, 14714, 776, 37, 5540, 25, 38657, 286, 26106, 392, 22963, 416, 257, 5021, 12, 15252, 42...
2.929325
948
from django.conf.urls import url, include from .views import (GroupListAPIView, GroupCreateAPIView, AgendaListAPIView, AgendaDetailAPIView, AgendaCreateAPIView, AgendaPostAPIView, agenda_create, AgendaRefreshAPIView, NumberInGroupAPIView, GroupProfileDetailAPIView, GroupProfileUpdateAPIView, number_in_group) urlpatterns = [ url(r'^group/$', GroupListAPIView.as_view(), name="group_list"), url(r'^group/create/$', GroupCreateAPIView.as_view(), name="group_create"), url(r'agenda-list/$', AgendaListAPIView.as_view(), name="agenda_list"), url(r'^(?P<group_id>\d+)/(?P<pk>\d+)/detail/$', AgendaDetailAPIView.as_view(), name='agenda_detail'), # url(r'^create/$', AgendaCreateAPIView.as_view(), name='agenda_create'), url(r'^(?P<group_id>\d+)/post2/$', AgendaPostAPIView.as_view(), name='agenda_create2'), # recommended api url(r'^(?P<group_id>\d+)/post/$', agenda_create, name='agenda_create'), url(r'^(?P<group_id>\d+)/(?P<pk>\d+)/refresh/$', AgendaRefreshAPIView.as_view(), name='agenda_refresh'), url(r'^(?P<id>\d+)/number/$', NumberInGroupAPIView.as_view(), name="number"), url(r'^(?P<group_id>\d+)/(?P<date>\d{4}-\d{2}-\d{2})/number/$', number_in_group, name="number2"), url(r'^(?P<group_id>\d+)/group-profile/$', GroupProfileDetailAPIView.as_view(), name="group_profile"), url(r'^(?P<group_id>\d+)/group-profile/update/$', GroupProfileUpdateAPIView.as_view(), name="group_profile_update"), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 11, 2291, 198, 6738, 764, 33571, 1330, 357, 13247, 8053, 2969, 3824, 769, 11, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
2.031707
820
from django.contrib import admin # Register your models here. #models Shop from .models import Shop from .models import Parsed_data from .models import Img_data from .models import Other admin.site.register(Shop) admin.site.register(Parsed_data) admin.site.register(Img_data) admin.site.register(Other)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 198, 2, 17296, 534, 4981, 994, 13, 198, 198, 2, 27530, 13705, 220, 198, 6738, 764, 27530, 1330, 13705, 198, 6738, 764, 27530, 1330, 23042, 276, 62, 7890, 198, 6738, 764, 27530, 1330...
3.1875
96
import torch from models.gta import GraphTemporalEmbedding if __name__ == '__main__': device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') x = torch.randn(32, 96, 122) model = GraphTemporalEmbedding(122, 96, 3) y = model(x) print(y.size()) # model = AdaGraphSage(num_nodes=10, seq_len=96, label_len=48, out_len=24) # model = model.double().to(device) # x = torch.randn(32, 96, 10, requires_grad=True).double().to(device) # y = torch.randn(32, 48, 10, requires_grad=True).double().to(device) # # print(out.size()) # out = model(x, y, None, None) # print(out.size())
[ 11748, 28034, 198, 6738, 4981, 13, 70, 8326, 1330, 29681, 12966, 35738, 31567, 6048, 278, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 3335, 796, 28034, 13, 25202, 10786, 66, 15339, 6, 611, 2...
2.40458
262
''' Auteur : Jol Dendaletche But : trac une figure gomtrique l'aide de la bibliothque Turtle Le projet utilise l'objet file pour itrer le calcul de chaque nouveau point Les coordonnes des points d'un polygone sont placs dans une file l'algorithme consiste calculer les coordonnes d'un point pour tracer une droite qui part du premier points de la file et passe par le deuxime en prolongeant le segment d'une fraction dtermine de la longueur entre les deux points. Le deuxime point est remplac par le nouveau. A la prochaine itration, le segment va partir du nouveau point pour passer par le suivant dans la file, qui sera remplac par le nouveau point et ainsi de suite. ''' import turtle board = turtle.Turtle() listePoints = [(0,0),(10,0),(5, int(10*75**.5)] print(listePoints) for x, y in listePoints : board.goto(x, y) turtle.done()
[ 7061, 6, 201, 198, 220, 220, 220, 220, 220, 220, 220, 317, 1133, 333, 1058, 39329, 360, 437, 282, 316, 2395, 201, 198, 220, 220, 220, 220, 220, 220, 220, 887, 1058, 491, 330, 17809, 3785, 308, 296, 28461, 4188, 220, 300, 6, 64, ...
2.463158
380
# -*- coding:utf-8 -*- # author: Xinge # @file: spconv_unet.py # @time: 2020/06/22 15:01 import time import numpy as np import spconv import torch import torch.nn.functional as F from torch import nn
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 1772, 25, 1395, 11912, 198, 2, 2488, 7753, 25, 599, 42946, 62, 403, 316, 13, 9078, 198, 2, 2488, 2435, 25, 12131, 14, 3312, 14, 1828, 1315, 25, 486, 198, 198, 11748,...
2.620253
79
from .model import DummyModel, ImageNetModel
[ 6738, 764, 19849, 1330, 360, 13513, 17633, 11, 7412, 7934, 17633, 198 ]
3.75
12
import numpy as np from prml.dimreduction.pca import PCA
[ 11748, 299, 32152, 355, 45941, 198, 6738, 778, 4029, 13, 27740, 445, 8110, 13, 79, 6888, 1330, 4217, 32, 628 ]
2.9
20
# Authors : Alexandre Gramfort, alexandre.gramfort@telecom-paristech.fr (2011) # Denis A. Engemann <denis.engemann@gmail.com> # License : BSD 3-clause import numpy as np from ..parallel import parallel_func from ..io.pick import _pick_data_channels from ..utils import logger, verbose, _time_mask from ..fixes import get_spectrogram from .multitaper import psd_array_multitaper def _psd_func(epoch, noverlap, n_per_seg, nfft, fs, freq_mask, func): """Aux function.""" return func(epoch, fs=fs, nperseg=n_per_seg, noverlap=noverlap, nfft=nfft, window='hamming')[2][..., freq_mask, :] def _check_nfft(n, n_fft, n_per_seg, n_overlap): """Ensure n_fft, n_per_seg and n_overlap make sense.""" if n_per_seg is None and n_fft > n: raise ValueError(('If n_per_seg is None n_fft is not allowed to be > ' 'n_times. If you want zero-padding, you have to set ' 'n_per_seg to relevant length. Got n_fft of %d while' ' signal length is %d.') % (n_fft, n)) n_per_seg = n_fft if n_per_seg is None or n_per_seg > n_fft else n_per_seg n_per_seg = n if n_per_seg > n else n_per_seg if n_overlap >= n_per_seg: raise ValueError(('n_overlap cannot be greater than n_per_seg (or ' 'n_fft). Got n_overlap of %d while n_per_seg is ' '%d.') % (n_overlap, n_per_seg)) return n_fft, n_per_seg, n_overlap def _check_psd_data(inst, tmin, tmax, picks, proj, reject_by_annotation=False): """Check PSD data / pull arrays from inst.""" from ..io.base import BaseRaw from ..epochs import BaseEpochs from ..evoked import Evoked if not isinstance(inst, (BaseEpochs, BaseRaw, Evoked)): raise ValueError('epochs must be an instance of Epochs, Raw, or' 'Evoked. Got type {0}'.format(type(inst))) time_mask = _time_mask(inst.times, tmin, tmax, sfreq=inst.info['sfreq']) if picks is None: picks = _pick_data_channels(inst.info, with_ref_meg=False) if proj: # Copy first so it's not modified inst = inst.copy().apply_proj() sfreq = inst.info['sfreq'] if isinstance(inst, BaseRaw): start, stop = np.where(time_mask)[0][[0, -1]] rba = 'NaN' if reject_by_annotation else None data = inst.get_data(picks, start, stop + 1, reject_by_annotation=rba) elif isinstance(inst, BaseEpochs): data = inst.get_data()[:, picks][:, :, time_mask] else: # Evoked data = inst.data[picks][:, time_mask] return data, sfreq
[ 2, 46665, 1058, 21000, 260, 20159, 3319, 11, 257, 2588, 49078, 13, 4546, 3319, 31, 46813, 785, 12, 1845, 396, 3055, 13, 8310, 357, 9804, 8, 198, 2, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 33089, 317, 13, 1985, 368, 1236,...
2.133225
1,231
from zope.interface import implementer from sqlalchemy import ( Column, String, Integer, Float, ForeignKey, CheckConstraint, ) from sqlalchemy.orm import relationship, backref from clld import interfaces from clld.db.meta import Base, CustomModelMixin from clld.db.versioned import Versioned from clld.db.models.common import ( Contribution, Parameter, IdNameDescriptionMixin, Language ) from clld_glottologfamily_plugin.models import HasFamilyMixin, Family from .interfaces import IDependency, ITransition, IStability, IDeepFamily, ISupport, IHasSupport
[ 6738, 1976, 3008, 13, 39994, 1330, 3494, 263, 198, 6738, 44161, 282, 26599, 1330, 357, 198, 220, 220, 220, 29201, 11, 198, 220, 220, 220, 10903, 11, 198, 220, 220, 220, 34142, 11, 198, 220, 220, 220, 48436, 11, 198, 220, 220, 220, ...
2.917476
206
import torch import torch.nn as nn
[ 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77 ]
3.4
10
""" Twisted adapter for Kanone """ from twisted.python.failure import Failure from twisted.internet import defer from ..lib import Invalid from ..util import varargs2kwargs import logging, sys log = logging.getLogger( __name__ ) # hacky and redundant, but it'll do for now .. # TODO: move to proper twisted specific classes under .tx.* # and get rid of the monkey _python3 = sys.version_info[0]>=3 def monkeyPatch(): """ Patches Kanone so that any validation returns a Deferred, thus one can write asynchronous validators using Twisted's non-blocking API. Schema and ForEach fields are validated concurrently. """ if getattr( monkeyPatch,'_isMonkeyPatched',False): return from ..lib import Context, PASS, MISSING from ..validator.core import Tag, Compose, Tmp, Item, Not, And, Or, Call, If from ..validator.check import Match from ..validator.schema import Schema, ForEach, Field from ..validator.web import MXLookup from twisted.names import client from twisted.names.dns import Record_MX from twisted.names.error import DNSNameError from twisted.internet.defer import TimeoutError mxLookup_resolver = client.Resolver('/etc/resolv.conf') Context.validate = context_validate Tag.validate = tag_validate Compose.valdate = compose_validate Tmp.validate = tmp_validate Item.validate = item_validate Not.validate = not_validate And.validate = and_validate Or.validate = or_validate Call.validate = call_validate Match.on_value = match_on_value If.validate = if_validate Schema._on_value = schema__on_value Schema._createContextChildren_on_value = schema__createContextChildren_on_value ForEach._on_value = forEach__on_value ForEach._createContextChildren_on_value = forEach__createContextChildren_on_value Field.validate = field_validate MXLookup.on_value = mxLookup_on_value monkeyPatch._isMonkeyPatched = True from ..util import getArgSpec, getParameterNames
[ 37811, 40006, 21302, 329, 14248, 505, 37227, 198, 198, 6738, 19074, 13, 29412, 13, 32165, 495, 1330, 25743, 198, 6738, 19074, 13, 37675, 1330, 29135, 198, 6738, 11485, 8019, 1330, 17665, 198, 6738, 11485, 22602, 1330, 1401, 22046, 17, 462...
2.932761
699
#! /usr/bin/env python2 # # This file is part of khmer, http://github.com/ged-lab/khmer/, and is # Copyright (C) Michigan State University, 2009-2013. It is licensed under # the three-clause BSD license; see doc/LICENSE.txt. # Contact: khmer-project@idyll.org # import khmer import sys import screed import os.path from khmer.thread_utils import ThreadedSequenceProcessor, verbose_fasta_iter K = 32 HASHTABLE_SIZE = int(4e9) THRESHOLD = 500 N_HT = 4 WORKER_THREADS = 5 ### GROUPSIZE = 100 ### if __name__ == '__main__': main()
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 2, 198, 2, 770, 2393, 318, 636, 286, 44081, 647, 11, 2638, 1378, 12567, 13, 785, 14, 2004, 12, 23912, 14, 14636, 647, 47454, 290, 318, 198, 2, 15069, 357, 34, 8, 7055, 1812...
2.658416
202
""" Fetches demand statistics. Modified from Dan Zhao Original article: https://yaledailynews.com/blog/2020/01/10/yales-most-popular-courses/ Github: https://github.com/iamdanzhao/yale-popular-classes README: https://github.com/iamdanzhao/yale-popular-classes/blob/master/data-guide/course_data_guide.md """ import argparse from multiprocessing import Pool from typing import List, Tuple import ujson from ferry import config from ferry.crawler.common_args import add_seasons_args, parse_seasons_arg from ferry.includes.demand_processing import fetch_season_subject_demand, get_dates from ferry.includes.tqdm import tqdm def handle_season_subject_demand(demand_args: Tuple[str, str, List[str], List[str]]): """ Handler for fetching subject codes to be passed into Pool() """ demand_season, demand_subject_code, demand_subject_codes, demand_dates = demand_args courses = fetch_season_subject_demand( demand_season, demand_subject_code, demand_subject_codes, demand_dates ) return courses if __name__ == "__main__": # Set season # Pass using command line arguments # Examples: 202001 = 2020 Spring, 201903 = 2019 Fall # If no season is provided, the program will scrape all available seasons parser = argparse.ArgumentParser(description="Import demand stats") add_seasons_args(parser) args = parser.parse_args() # list of seasons previously from fetch_seasons.py with open(f"{config.DATA_DIR}/demand_seasons.json", "r") as f: all_viable_seasons = ujson.load(f) seasons = parse_seasons_arg(args.seasons, all_viable_seasons) print("Retrieving subjects list... ", end="") with open(f"{config.DATA_DIR}/demand_subjects.json", "r") as f: subjects = ujson.load(f) subject_codes = sorted(list(subjects.keys())) print("ok") # set up parallel processing pool with Pool(processes=64) as pool: for season in seasons: print(f"Retrieving demand by subject for season {season}") dates = get_dates(season) pool_args = [ (season, subject_code, subject_codes, dates) for subject_code in subject_codes ] season_courses = [] # use imap_unordered to report to tqdm with tqdm(total=len(pool_args), desc="Subjects retrieved") as pbar: for i, result in enumerate( pool.imap_unordered(handle_season_subject_demand, pool_args) ): pbar.update() season_courses.append(result) # flatten season courses season_courses = [x for y in season_courses for x in y] # sort courses by title (for consistency with ferry-data) season_courses = sorted(season_courses, key=lambda x: x["title"]) with open(f"{config.DATA_DIR}/demand_stats/{season}_demand.json", "w") as f: ujson.dump(season_courses, f, indent=4)
[ 37811, 198, 37, 316, 2052, 3512, 7869, 13, 198, 198, 5841, 1431, 422, 6035, 29436, 198, 198, 20556, 2708, 25, 198, 5450, 1378, 88, 3021, 3079, 10827, 13, 785, 14, 14036, 14, 42334, 14, 486, 14, 940, 14, 88, 2040, 12, 1712, 12, 475...
2.512927
1,199
from flask import Flask from flask_sqlalchemy import SQLAlchemy from qxf2_scheduler import models from qxf2_scheduler import db from qxf2_scheduler.__init__ import app from flask_script import Manager from flask_migrate import Migrate,MigrateCommand migrate=Migrate(app, db,render_as_batch=True) manager=Manager(app) manager.add_command('db',MigrateCommand) if __name__ == "__main__": manager.run()
[ 6738, 42903, 1330, 46947, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 6738, 10662, 26152, 17, 62, 1416, 704, 18173, 1330, 4981, 198, 6738, 10662, 26152, 17, 62, 1416, 704, 18173, 1330, 20613, 198, 6738, 10662, ...
3.052632
133
# import packages import requests import pandas as pd import time from functions import * # limit per sity max_results_per_city = 100 # db of city city_set = ['New+York','Toronto','Las+Vegas'] # job roles job_set = ['business+analyst','data+scientist'] # file num file = 1 # from where to skip SKIPPER = 0 # loop on all cities for city in city_set: # for each job role for job_qry in job_set: # count cnt = 0 startTime = time.time() # skipper if(file > SKIPPER): # dataframe df = pd.DataFrame(columns = ['unique_id', 'city', 'job_qry','job_title', 'company_name', 'location', 'summary', 'salary', 'link', 'date', 'full_text']) # for results for start in range(0, max_results_per_city, 10): # get dom page = requests.get('http://www.indeed.com/jobs?q=' + job_qry +'&l=' + str(city) + '&start=' + str(start)) #ensuring at least 1 second between page grabs time.sleep(1) #fetch data soup = get_soup(page.text) divs = soup.find_all(name="div", attrs={"class":"row"}) # if results exist if(len(divs) == 0): break # for all jobs on a page for div in divs: #specifying row num for index of job posting in dataframe num = (len(df) + 1) cnt = cnt + 1 #job data after parsing job_post = [] #append unique id job_post.append(div['id']) #append city name job_post.append(city) #append job qry job_post.append(job_qry) #grabbing job title job_post.append(extract_job_title(div)) #grabbing company job_post.append(extract_company(div)) #grabbing location name job_post.append(extract_location(div)) #grabbing summary text job_post.append(extract_summary(div)) #grabbing salary job_post.append(extract_salary(div)) #grabbing link link = extract_link(div) job_post.append(link) #grabbing date job_post.append(extract_date(div)) #grabbing full_text job_post.append(extract_fulltext(link)) #appending list of job post info to dataframe at index num df.loc[num] = job_post #debug add write_logs(('Completed =>') + '\t' + city + '\t' + job_qry + '\t' + str(cnt) + '\t' + str(start) + '\t' + str(time.time() - startTime) + '\t' + ('file_' + str(file))) #saving df as a local csv file df.to_csv('jobs_' + str(file) + '.csv', encoding='utf-8') else: #debug add write_logs(('Skipped =>') + '\t' + city + '\t' + job_qry + '\t' + str(-1) + '\t' + str(-1) + '\t' + str(time.time() - startTime) + '\t' + ('file_' + str(file))) # increment file file = file + 1
[ 2, 1330, 10392, 198, 11748, 7007, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 640, 220, 198, 6738, 5499, 1330, 1635, 628, 198, 2, 4179, 583, 264, 414, 198, 9806, 62, 43420, 62, 525, 62, 19205, 796, 1802, 198, 198, 2, 20613, ...
1.789907
1,942
# Import Libraries import numpy as np import cv2 import argparse import time # Import User Libraries import L0_helpers # Image File Path image_r = "images/flowers.jpg" image_w = "out_serial.png" # L0 minimization parameters kappa = 2.0 _lambda = 2e-2 # Verbose output verbose = False if __name__ == '__main__': # Parse arguments parser = argparse.ArgumentParser( description="Serial implementation of image smoothing via L0 gradient minimization") parser.add_argument('image_r', help="input image file") parser.add_argument('image_w', help="output image file") parser.add_argument('-k', type=float, default=2.0, metavar='kappa', help='updating weight (default 2.0)') parser.add_argument('-l', type=float, default=2e-2, metavar='lambda', help='smoothing weight (default 2e-2)') parser.add_argument('-v', '--verbose', action='store_true', help='enable verbose logging for each iteration') args = parser.parse_args() L0_smooth(args.image_r, args.image_w, args.k, args.l, args.verbose)
[ 2, 17267, 46267, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 269, 85, 17, 198, 11748, 1822, 29572, 198, 11748, 640, 198, 198, 2, 17267, 11787, 46267, 198, 11748, 406, 15, 62, 16794, 364, 198, 198, 2, 7412, 9220, 10644, 198, 9060, ...
2.848066
362
### Interpretable cnn for big five personality traits using audio data ### ### This script downsamples 41000 kz signal into 4000 kz signal ### from __future__ import absolute_import, division, print_function import pathlib import random import csv import numpy as np from scipy.io import wavfile import tensorflow as tf import itertools from scipy import stats ### functions for mapping ### ### down sample the data ### data = [] labels = [] folder_path = '/...path/to/wav/data/folder/' folder_path = pathlib.Path(folder_path) files_path = list(folder_path.glob('*.wav')) files_path = [str(path) for path in files_path] no_of_samples = len(files_path) ### load data labels ### with open('/...path/to/.csv/labels/file', 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') for row in spamreader: data.append(row) for i in range(len(files_path)): file_1 = files_path[i] file_1 = file_1.split("/")[5] file_name_1 = file_1[:-4] new_filename_1 = file_name_1 + '.mp4' label_1 = [] label_2 = [] matching = [s for s in data if new_filename_1 in s] label_1= np.delete(matching,[0],axis=1) label_2 = label_1[0,:] label_2 = [float(i) for i in label_2] labels.append(label_2) ### dataset pipeline ### ds = tf.data.Dataset.from_tensor_slices((files_path, labels)) data_ds = ds.map(get_wav) ds = data_ds.shuffle(buffer_size=wavfiles_count) ds = ds.repeat() ds = ds.batch(1) ### prefetch the data batches in the background ### ds = ds.prefetch(buffer_size=1) iterator = ds.make_one_shot_iterator() next_ele = iterator.get_next() features_4k = [] labels_4k = [] with tf.Session() as sess: for _ in range(len(files_path)): t_features, t_labels = sess.run(next_ele) features_4k.append(t_features) labels_4k.append(t_labels) np.save('.../save/path/',features_4k) np.save('.../save/path/',labels_4k) print('Completed')
[ 21017, 48907, 540, 269, 20471, 329, 1263, 1936, 8806, 12796, 1262, 6597, 1366, 44386, 198, 21017, 770, 4226, 21838, 12629, 6073, 830, 479, 89, 6737, 656, 30123, 479, 89, 6737, 44386, 628, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11...
2.372664
856
# # Copyright 2022 The AI Flow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import pprint from abc import abstractmethod class _ModelRepoObjectPrinter(object):
[ 2, 198, 2, 15069, 33160, 383, 9552, 27782, 46665, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 1...
3.740331
181
# Copyright 2020 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. # Lint as: python3 """Tests for model_search.search.common.""" from absl.testing import parameterized from model_search.search import common import tensorflow.compat.v2 as tf if __name__ == "__main__": tf.enable_v2_behavior() tf.test.main()
[ 2, 15069, 12131, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
3.5
236
import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" newFunc.__name__ = func.__name__ newFunc.__doc__ = func.__doc__ newFunc.__dict__.update(func.__dict__) return newFunc
[ 11748, 14601, 628, 198, 4299, 39224, 7, 20786, 2599, 198, 220, 220, 220, 37227, 1212, 318, 257, 11705, 1352, 543, 460, 307, 973, 284, 1317, 5499, 198, 220, 220, 220, 355, 39224, 13, 632, 481, 1255, 287, 257, 6509, 852, 795, 3291, 19...
2.87069
116
from torchvision.models import resnet18 import torch.nn.functional as F import torch.nn as nn import numpy as np import torch import pdb ############################## # Encoder ############################## ############################## # Generator ############################## ############################## # Discriminator ##############################
[ 6738, 28034, 10178, 13, 27530, 1330, 581, 3262, 1507, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 279, 9945, 198, 198,...
3.558559
111
from oem_framework.models.core import ModelRegistry from oem_framework.plugin import Plugin from oem_framework.storage import ProviderStorage from oem_storage_file.core.base import BaseFileStorage from oem_storage_file.database import DatabaseFileStorage import appdirs import os # # Index methods # # # Item methods # # # Private methods #
[ 6738, 267, 368, 62, 30604, 13, 27530, 13, 7295, 1330, 9104, 8081, 4592, 198, 6738, 267, 368, 62, 30604, 13, 33803, 1330, 42636, 198, 6738, 267, 368, 62, 30604, 13, 35350, 1330, 32549, 31425, 198, 6738, 267, 368, 62, 35350, 62, 7753, ...
3.031746
126
# 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 DEPS CONFIG_CTX = DEPS['gclient'].CONFIG_CTX ChromiumGitURL = DEPS['gclient'].config.ChromiumGitURL
[ 2, 15069, 2211, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043, 287, 262, 38559, 24290, 2393, 13, 198, 198, 11748...
3.055556
90
from models.instructions.shared import Instruction from models.Other.ambito import Ambito from controllers.three_address_code import ThreeAddressCode from controllers.procedures import Procedures from models.instructions.Expression.expression import DATA_TYPE, PrimitiveData
[ 6738, 4981, 13, 259, 7249, 507, 13, 28710, 1330, 46486, 198, 6738, 4981, 13, 6395, 13, 321, 2545, 78, 1330, 1703, 2545, 78, 198, 6738, 20624, 13, 15542, 62, 21975, 62, 8189, 1330, 7683, 20231, 10669, 198, 6738, 20624, 13, 1676, 771, ...
4.134328
67
import typing import urllib.error import urllib.request from podcast.files import download_location from podcast.info import build_info_content from podcast.info import InfoContent from podcast.models import Channel from podcast.models import get_podcast_audio_link from podcast.models import NewStatus from podcast.models import Podcast from podcast.models import Radio from podcast.models import RadioDirectory
[ 11748, 19720, 198, 11748, 2956, 297, 571, 13, 18224, 198, 11748, 2956, 297, 571, 13, 25927, 198, 198, 6738, 9905, 13, 16624, 1330, 4321, 62, 24886, 198, 6738, 9905, 13, 10951, 1330, 1382, 62, 10951, 62, 11299, 198, 6738, 9905, 13, 109...
4.265306
98
from tests.base import TestCase, main, assets from ocrd_models.ocrd_page import ( AlternativeImageType, PcGtsType, PageType, TextRegionType, TextLineType, WordType, GlyphType, parseString, parse, to_xml ) simple_page = """\ <PcGts xmlns="http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15 http://schema.primaresearch.org/PAGE/gts/pagecontent/2013-07-15/pagecontent.xsd"> <Metadata> <Creator>OCR-D</Creator> <Created>2016-09-20T11:09:27.041+02:00</Created> <LastChange>2018-04-25T17:44:49.605+01:00</LastChange> </Metadata> <Page imageFilename="https://github.com/OCR-D/assets/raw/master/data/kant_aufklaerung_1784/data/OCR-D-IMG/INPUT_0017.tif" imageWidth="1457" imageHeight="2083" type="content"> <TextRegion type="heading" id="r_1_1" custom="readingOrder {index:0;} structure {type:heading;}"> <Coords points="113,365 919,365 919,439 113,439"/> <TextLine id="tl_1" primaryLanguage="German" custom="readingOrder {index:0;} textStyle {offset:0; length:26;fontFamily:Arial; fontSize:17.0; bold:true;}"> <Coords points="114,366 918,366 918,438 114,438"/> <Baseline points="114,429 918,429"/> <Word id="w_w1aab1b1b2b1b1ab1" language="German" custom="readingOrder {index:0;} textStyle {offset:0; length:11;fontFamily:Arial; fontSize:17.0; bold:true;}"> <Coords points="114,368 442,368 442,437 114,437"/> <TextEquiv conf="0.987654321"> <Unicode>Berliniche</Unicode> </TextEquiv> </Word> </TextLine> </TextRegion> </Page> </PcGts> """ # pylint: disable=protected-access if __name__ == '__main__': main()
[ 6738, 5254, 13, 8692, 1330, 6208, 20448, 11, 1388, 11, 6798, 198, 198, 6738, 267, 66, 4372, 62, 27530, 13, 1696, 67, 62, 7700, 1330, 357, 198, 220, 220, 220, 27182, 5159, 6030, 11, 198, 220, 220, 220, 350, 66, 38, 912, 6030, 11, ...
2.073607
951
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*- """ Created on Wed Aug 13 15:35:50 2014 @author: rich """ import networkx as nx # assign component IDs to graph components, id=0 is giant component
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 3300, 2447, 1511, 1315, 25, 2327, 25, 1120, 1946, 198, 198, 31, 9800, 25,...
2.582278
79
#!/usr/bin/python """composes the config from user definitions.""" import argparse import os import users import users.__config__ import importlib import csv # file indicators IND_DELIM = "_" USER_INDICATOR = "user" + IND_DELIM VLAN_INDICATOR = "vlan" + IND_DELIM AUTH_PHASE_ONE = "PEAP" AUTH_PHASE_TWO = "MSCHAPV2" def _get_mod(name): """import the module dynamically.""" return importlib.import_module("users." + name) def _get_by_indicator(indicator): """get by a file type indicator.""" return [x for x in sorted(users.__all__) if x.startswith(indicator)] def _common_call(common, method, entity): """make a common mod call.""" obj = entity if common is not None and method in dir(common): call = getattr(common, method) if call is not None: obj = call(obj) return obj def check_object(obj): """Check an object.""" return obj.check() def _process(output): """process the composition of users.""" common_mod = None try: common_mod = _get_mod("common") print("loaded common definitions...") except Exception as e: print("defaults only...") vlans = None meta = ConfigMeta() for v_name in _get_by_indicator(VLAN_INDICATOR): print("loading vlan..." + v_name) for obj in _load_objs(v_name, users.__config__.VLAN): if vlans is None: vlans = {} if not check_object(obj): exit(-1) num_str = str(obj.num) for vk in vlans.keys(): if num_str == vlans[vk]: print("vlan number defined multiple times...") exit(-1) vlans[obj.name] = num_str if obj.initiate is not None and len(obj.initiate) > 0: for init_to in obj.initiate: meta.vlan_to_vlan(init_to) if vlans is None: raise Exception("missing required config settings...") meta.all_vlans = vlans.keys() store = Store() for f_name in _get_by_indicator(USER_INDICATOR): print("composing..." + f_name) for obj in _load_objs(f_name, users.__config__.Assignment): obj = _common_call(common_mod, 'ready', obj) key = f_name.replace(USER_INDICATOR, "") if not key.isalnum(): print("does not meet naming requirements...") exit(-1) vlan = obj.vlan if vlan not in vlans: raise Exception("no vlan defined for " + key) store.add_vlan(vlan, vlans[vlan]) meta.vlan_user(vlan, key) fqdn = vlan + "." + key if not check_object(obj): print("did not pass check...") exit(-1) if obj.disabled: print("account is disabled") continue macs = sorted(obj.macs) password = obj.password bypassed = sorted(obj.bypassed()) owned = sorted(obj.owns) # meta checks meta.user_macs(macs) if not obj.inherits: meta.password(password) meta.extra(bypassed) meta.extra(owned) store.add_user(fqdn, macs, password) if obj.mab_only: store.set_mab(fqdn) if len(bypassed) > 0: for m in bypassed: store.add_mab(m, obj.bypass_vlan(m)) user_all = [] for l in [obj.macs, obj.owns, bypassed]: user_all += list(l) store.add_audit(fqdn, sorted(set(user_all))) meta.verify() # audit outputs with open(output + "audit.csv", 'w') as f: csv_writer = csv.writer(f, lineterminator=os.linesep) for a in sorted(store.get_tag(store.audit)): p = a[0].split(".") for m in a[1]: csv_writer.writerow([p[1], p[0], m]) # eap_users and preauth manifest = [] with open(output + "eap_users", 'w') as f: for u in store.get_eap_user(): f.write('"{}" {}\n\n'.format(u[0], AUTH_PHASE_ONE)) f.write('"{}" {} hash:{} [2]\n'.format(u[0], AUTH_PHASE_TWO, u[1])) write_vlan(f, u[2]) for u in store.get_eap_mab(): up = u[0].upper() f.write('"{}" MD5 "{}"\n'.format(up, up)) write_vlan(f, u[1]) manifest.append((u[0], u[0])) for u in store.get_tag(store.umac): manifest.append((u[0], u[1])) with open(output + "manifest", 'w') as f: for m in sorted(manifest): f.write("{}.{}\n".format(m[0], m[1]).lower()) def write_vlan(f, vlan_id): """Write vlan assignment for login.""" f.write('radius_accept_attr=64:d:13\n') f.write('radius_accept_attr=65:d:6\n') f.write('radius_accept_attr=81:s:{}\n\n'.format(vlan_id)) def main(): """main entry.""" success = False try: parser = argparse.ArgumentParser() parser.add_argument("--output", type=str, required=True) args = parser.parse_args() _process(args.output) success = True except Exception as e: print('unable to compose') print(str(e)) if success: print("success") exit(0) else: print("failure") exit(1) if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 37811, 785, 4832, 262, 4566, 422, 2836, 17336, 526, 15931, 198, 11748, 1822, 29572, 198, 11748, 28686, 198, 11748, 2985, 198, 11748, 2985, 13, 834, 11250, 834, 198, 11748, 1330, 8019, 198, 1174...
1.979397
2,718
# Import the Twython class from twython import Twython, TwythonStreamer import json # import pandas as pd import csv import datetime # Create a class that inherits TwythonStreamer if __name__ == "__main__": main()
[ 2, 17267, 262, 1815, 7535, 1398, 198, 6738, 665, 7535, 1330, 1815, 7535, 11, 1815, 7535, 28696, 198, 11748, 33918, 198, 2, 1330, 19798, 292, 355, 279, 67, 198, 11748, 269, 21370, 198, 11748, 4818, 8079, 628, 198, 198, 2, 13610, 257, ...
3.264706
68
#!/usr/bin/env python2 import sys; from yaml import load, dump, load_all from cassandra_attributes import * if __name__ == "__main__": main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 198, 11748, 25064, 26, 198, 6738, 331, 43695, 1330, 3440, 11, 10285, 11, 3440, 62, 439, 198, 6738, 30606, 15918, 62, 1078, 7657, 1330, 1635, 198, 198, 361, 11593, 3672, 834, 6624, ...
2.740741
54
import pytest import itertools # Cartesian product of file names and extensions # e.g. README.txt, README.md, CHANGELOG.txt, CHANGELOG.md ... file_extensions = ['txt', 'md'] names = ['README', 'CHANGELOG', 'CONTRIBUTING', 'LICENSE', 'CODE_OF_CONDUCT'] exempt_files = [('.'.join(x)) for x in itertools.product(names, file_extensions)]
[ 11748, 12972, 9288, 198, 11748, 340, 861, 10141, 198, 198, 2, 13690, 35610, 1720, 286, 2393, 3891, 290, 18366, 198, 2, 304, 13, 70, 13, 20832, 11682, 13, 14116, 11, 20832, 11682, 13, 9132, 11, 5870, 15567, 3698, 7730, 13, 14116, 11, ...
2.65873
126
import sys import unittest sys.path.append("../main") from sshtransport import *
[ 11748, 25064, 198, 11748, 555, 715, 395, 198, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 12417, 4943, 198, 198, 6738, 26678, 7645, 634, 1330, 1635, 198 ]
3.074074
27
import random import time from pathlib import Path from typing import Dict, List, Tuple import numpy as np import torch from torch.utils import data from torch.utils.tensorboard import SummaryWriter import utils_graph import utils_io import utils_nn from feed_forward import FeedForward from hyperparameters import Hyperparameters from signal_data import SignalData from signal_dataset import SignalDataset PLOTS_FOLDER = 'plots' USE_CUDA = torch.cuda.is_available() def _train_ff_network(hyperparameter_dict: dict, data: SignalData) -> Tuple[FeedForward, List, List, List, List]: """Trains a feed-forward network using the specified hyperparameters. """ # Ensure reproducibility by giving PyTorch the same seed every time we train. torch.manual_seed(1) # Print hyperparameters. print(f'Hyperparameters: {hyperparameter_dict}') # Get hyperparameters. learning_rate = hyperparameter_dict['learning_rate'] batch_size = hyperparameter_dict['batch_size'] optimizer_str = hyperparameter_dict['optimizer'] # There are 6 labels, and Pytorch expects them to go from 0 to 5. full_train_labels = data.train_labels - 1 # Get generators. signal_dataset = SignalDataset(data.train_signals, full_train_labels) (training_generator, validation_generator) = utils_nn.get_trainval_generators( signal_dataset, batch_size, num_workers=0, training_fraction=0.8) # Crete feed forward network. input_size = data.num_timesteps * data.num_components feed_forward = FeedForward(input_size, input_size, data.num_activity_labels) print(feed_forward) # Parameters should be moved to GPU before constructing the optimizer. device = torch.device('cuda:0' if USE_CUDA else 'cpu') feed_forward = feed_forward.to(device) # Get optimizer. optimizer = None if optimizer_str == 'adam': optimizer = torch.optim.Adam(feed_forward.parameters(), lr=learning_rate) elif optimizer_str == 'sgd': optimizer = torch.optim.SGD(feed_forward.parameters(), lr=learning_rate) else: raise Exception(f'Specified optimizer not valid: {optimizer_str}') training_accuracy_list = [] training_loss_list = [] validation_accuracy_list = [] validation_loss_list = [] max_epochs = 10 for epoch in range(max_epochs): print(f'Epoch {epoch}') # Training data. (training_accuracy, training_loss) = utils_nn.fit(feed_forward, training_generator, optimizer, USE_CUDA) training_accuracy_list.append(training_accuracy) training_loss_list.append(training_loss) # Validation data. (validation_accuracy, validation_loss) = utils_nn.evaluate(feed_forward, validation_generator, 'Validation', USE_CUDA) validation_accuracy_list.append(validation_accuracy) validation_loss_list.append(validation_loss) return (feed_forward, training_accuracy_list, training_loss_list, validation_accuracy_list, validation_loss_list) def _get_ff_hyperparameters() -> Hyperparameters: """Returns hyperparameters used to tune the feed-forward network. """ # First pass: hyperparameter_values = Hyperparameters({ 'learning_rate': [0.1, 0.01, 0.001], 'batch_size': [32, 64, 128], 'optimizer': ['adam', 'sgd'] }) # Best: # optimizer: sgd, batch size: 64, learning rate: 0.1 # Second pass: hyperparameter_values = Hyperparameters({ 'learning_rate': [0.05, 0.1, 0.2], 'batch_size': [16, 32, 64], 'optimizer': ['sgd'] }) # Best: # optimizer: sgd, batch size: 16, learning rate: 0.1 return hyperparameter_values def _tune_ff_hyperparameters(data: SignalData) -> None: """Classifies temporal signals using a feed-forward network. """ print(' Tuning hyperparameters.') start_time = time.time() # Hyperparameters to tune. hyperparameter_values = _get_ff_hyperparameters() hyperparameter_combinations = hyperparameter_values.sample_combinations() # Create Tensorboard writer. with SummaryWriter(f'runs/signals', filename_suffix='') as writer: # Hyperparameter loop. for hyperparameter_dict in hyperparameter_combinations: (_, _, _, validation_accuracy_list, _) = _train_ff_network( hyperparameter_dict, data) writer.add_hparams(hyperparameter_dict, {'hparam/signals/validation_accuracy': validation_accuracy_list[-1]}) utils_io.print_elapsed_time(start_time, time.time()) def _test_ff_network(feed_forward: FeedForward, signal_data: SignalData, hyperparameter_dict: dict) -> Tuple[float, float]: """Returns accuracy and loss of specified network for specified test data and specified hyperparameters. """ # There are 6 labels, and Pytorch expects them to go from 0 to 5. test_labels = signal_data.test_labels - 1 # Get test generator. batch_size = hyperparameter_dict['batch_size'] test_data = SignalDataset(signal_data.test_signals, test_labels) params = {'batch_size': batch_size, 'shuffle': True, 'num_workers': 0} test_generator = data.DataLoader(test_data, **params) (test_avg_accuracy, test_avg_loss) = utils_nn.evaluate(feed_forward, test_generator, 'Test', USE_CUDA) return (test_avg_accuracy, test_avg_loss) def _test_best_ff_hyperparameters(data: SignalDataset) -> None: """Use network with best hyperparameters to predict labels for test data. Produces accuracy and loss graphs for training and validation data, as well as accuracy and loss values for test data. """ hyperparameter_dict = { 'learning_rate': 0.1, 'batch_size': 16, 'optimizer': 'sgd', } (feed_forward, training_accuracy_list, training_loss_list, validation_accuracy_list, validation_loss_list) = _train_ff_network(hyperparameter_dict, data) utils_graph.graph_nn_results(training_accuracy_list, validation_accuracy_list, f'Training and validation accuracy of classification of temporal signals', 'Accuracy', PLOTS_FOLDER, f'signals_accuracy.html') utils_graph.graph_nn_results(training_loss_list, validation_loss_list, f'Training and validation loss of classification of temporal signals', 'Loss', PLOTS_FOLDER, f'signals_loss.html') _test_ff_network(feed_forward, data, hyperparameter_dict) with SummaryWriter(f'runs/signals', filename_suffix='') as writer: num_epochs_train_val = len(training_accuracy_list) for i in range(num_epochs_train_val): writer.add_scalars(f'signals/accuracy', { 'training': training_accuracy_list[i], 'validation': validation_accuracy_list[i] }, i) writer.add_scalars(f'signals/loss', { 'training': training_loss_list[i], 'validation': validation_loss_list[i] }, i) # Test accuracy: 87.25% # Test loss: 0.45 def scenario1(data: SignalData) -> None: """Uses a simple feed forward network to classify the raw signal. """ print('Scenario 1: feed forward network on raw signal') # _tune_ff_hyperparameters(data) _test_best_ff_hyperparameters(data)
[ 11748, 4738, 198, 11748, 640, 198, 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 11, 309, 29291, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 13, 26791, 1330, 1366, 198, 6738...
2.581404
2,850
input = """ ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 hcl:#cfa07d byr:1929 hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm hcl:#cfa07d eyr:2025 pid:166559648 iyr:2011 ecl:brn hgt:59in """ count = 0 for i in input.strip().split("\n\n"): if validate(i): count += 1 print(count)
[ 15414, 796, 37227, 198, 68, 565, 25, 70, 563, 46514, 25, 4521, 405, 20370, 1983, 1926, 81, 25, 42334, 289, 565, 43922, 12927, 16344, 198, 1525, 81, 25, 1129, 2718, 1312, 2417, 25, 5539, 269, 312, 25, 20198, 289, 13655, 25, 24839, 11...
1.9375
208
import os.path as osp from unittest import TestCase import pytest from flit_core.common import ( Module, get_info_from_module, InvalidVersion, NoVersionError, check_version, normalize_file_permissions, Metadata ) samples_dir = osp.join(osp.dirname(__file__), 'samples')
[ 11748, 28686, 13, 6978, 355, 267, 2777, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 11748, 12972, 9288, 198, 198, 6738, 781, 270, 62, 7295, 13, 11321, 1330, 357, 198, 220, 220, 220, 19937, 11, 651, 62, 10951, 62, 6738, 62, 214...
2.886598
97
import datetime import logging from typing import Optional from betfairlightweight.resources.bettingresources import MarketBook, MarketCatalogue from .blotter import Blotter from ..events import events logger = logging.getLogger(__name__)
[ 11748, 4818, 8079, 198, 11748, 18931, 198, 6738, 19720, 1330, 32233, 198, 6738, 731, 22043, 2971, 6551, 13, 37540, 13, 11181, 889, 37540, 1330, 5991, 10482, 11, 5991, 39075, 5119, 198, 198, 6738, 764, 2436, 313, 353, 1330, 1086, 313, 35...
3.84127
63
import pytest from fastapi.testclient import TestClient from {{cookiecutter.project_name}}.app import app
[ 11748, 12972, 9288, 198, 6738, 3049, 15042, 13, 9288, 16366, 1330, 6208, 11792, 198, 198, 6738, 22935, 44453, 8968, 353, 13, 16302, 62, 3672, 11709, 13, 1324, 1330, 598, 628 ]
3.6
30
import itertools import multiprocessing import json import numpy as np from tqdm import tqdm from lp_generators.features import coeff_features, solution_features from lp_generators.performance import clp_simplex_performance from search_operators import lp_column_neighbour, lp_row_neighbour from seeds import cli_seeds from search_common import condition, objective, start_instance run()
[ 198, 11748, 340, 861, 10141, 198, 11748, 18540, 305, 919, 278, 198, 11748, 33918, 198, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 6738, 300, 79, 62, 8612, 2024, 13, 40890, 1330, 763,...
3.327731
119
import unittest from iterable_collections import collect
[ 11748, 555, 715, 395, 198, 198, 6738, 11629, 540, 62, 4033, 26448, 1330, 2824, 628, 198 ]
3.75
16
from parcels import FieldSet, ParticleSet, ScipyParticle, JITParticle, Variable from parcels import AdvectionRK4, AdvectionEE, AdvectionRK45 from argparse import ArgumentParser import numpy as np import math # NOQA import pytest from datetime import timedelta as delta ptype = {'scipy': ScipyParticle, 'jit': JITParticle} method = {'RK4': AdvectionRK4, 'EE': AdvectionEE, 'RK45': AdvectionRK45} def peninsula_fieldset(xdim, ydim, mesh='flat'): """Construct a fieldset encapsulating the flow field around an idealised peninsula. :param xdim: Horizontal dimension of the generated fieldset :param xdim: Vertical dimension of the generated fieldset :param mesh: String indicating the type of mesh coordinates and units used during velocity interpolation: 1. spherical: Lat and lon in degree, with a correction for zonal velocity U near the poles. 2. flat (default): No conversion, lat/lon are assumed to be in m. The original test description can be found in Fig. 2.2.3 in: North, E. W., Gallego, A., Petitgas, P. (Eds). 2009. Manual of recommended practices for modelling physical - biological interactions during fish early life. ICES Cooperative Research Report No. 295. 111 pp. http://archimer.ifremer.fr/doc/00157/26792/24888.pdf To avoid accuracy problems with interpolation from A-grid to C-grid, we return NetCDF files that are on an A-grid. """ # Set Parcels FieldSet variables # Generate the original test setup on A-grid in m domainsizeX, domainsizeY = (1.e5, 5.e4) dx, dy = domainsizeX / xdim, domainsizeY / ydim La = np.linspace(dx, 1.e5-dx, xdim, dtype=np.float32) Wa = np.linspace(dy, 5.e4-dy, ydim, dtype=np.float32) u0 = 1 x0 = domainsizeX / 2 R = 0.32 * domainsizeX / 2 # Create the fields x, y = np.meshgrid(La, Wa, sparse=True, indexing='xy') P = (u0*R**2*y/((x-x0)**2+y**2)-u0*y) / 1e3 U = u0-u0*R**2*((x-x0)**2-y**2)/(((x-x0)**2+y**2)**2) V = -2*u0*R**2*((x-x0)*y)/(((x-x0)**2+y**2)**2) # Set land points to NaN landpoints = P >= 0. P[landpoints] = np.nan U[landpoints] = np.nan V[landpoints] = np.nan # Convert from m to lat/lon for spherical meshes lon = La / 1852. / 60. if mesh == 'spherical' else La lat = Wa / 1852. / 60. if mesh == 'spherical' else Wa data = {'U': U, 'V': V, 'P': P} dimensions = {'lon': lon, 'lat': lat} return FieldSet.from_data(data, dimensions, mesh=mesh) else: x = 3. * (1. / 1.852 / 60) # 3 km offset from boundary y = (fieldset.U.lat[0] + x, fieldset.U.lat[-1] - x) # latitude range, including offsets pset = ParticleSet.from_line(fieldset, size=npart, pclass=MyParticle, start=(x, y[0]), finish=(x, y[1]), time=0) if verbose: print("Initial particle positions:\n%s" % pset) # Advect the particles for 24h time = delta(hours=24) dt = delta(minutes=5) k_adv = pset.Kernel(method) k_p = pset.Kernel(UpdateP) out = pset.ParticleFile(name="MyParticle", outputdt=delta(hours=1)) if output else None print("Peninsula: Advecting %d particles for %s" % (npart, str(time))) pset.execute(k_adv + k_p, runtime=time, dt=dt, output_file=out) if verbose: print("Final particle positions:\n%s" % pset) return pset def fieldsetfile(mesh): """Generate fieldset files for peninsula test""" filename = 'peninsula' fieldset = peninsula_fieldset(100, 50, mesh=mesh) fieldset.write(filename) return filename if __name__ == "__main__": p = ArgumentParser(description=""" Example of particle advection around an idealised peninsula""") p.add_argument('mode', choices=('scipy', 'jit'), nargs='?', default='jit', help='Execution mode for performing RK4 computation') p.add_argument('-p', '--particles', type=int, default=20, help='Number of particles to advect') p.add_argument('-d', '--degree', type=int, default=1, help='Degree of spatial interpolation') p.add_argument('-v', '--verbose', action='store_true', default=False, help='Print particle information before and after execution') p.add_argument('-o', '--nooutput', action='store_true', default=False, help='Suppress trajectory output') p.add_argument('--profiling', action='store_true', default=False, help='Print profiling information after run') p.add_argument('-f', '--fieldset', type=int, nargs=2, default=None, help='Generate fieldset file with given dimensions') p.add_argument('-m', '--method', choices=('RK4', 'EE', 'RK45'), default='RK4', help='Numerical method used for advection') args = p.parse_args() if args.fieldset is not None: filename = 'peninsula' fieldset = peninsula_fieldset(args.fieldset[0], args.fieldset[1], mesh='flat') fieldset.write(filename) # Open fieldset file set fieldset = FieldSet.from_parcels('peninsula', extra_fields={'P': 'P'}, allow_time_extrapolation=True) if args.profiling: from cProfile import runctx from pstats import Stats runctx("pensinsula_example(fieldset, args.particles, mode=args.mode,\ degree=args.degree, verbose=args.verbose,\ output=not args.nooutput, method=method[args.method])", globals(), locals(), "Profile.prof") Stats("Profile.prof").strip_dirs().sort_stats("time").print_stats(10) else: pensinsula_example(fieldset, args.particles, mode=args.mode, degree=args.degree, verbose=args.verbose, output=not args.nooutput, method=method[args.method])
[ 6738, 49796, 1330, 7663, 7248, 11, 2142, 1548, 7248, 11, 1446, 541, 88, 7841, 1548, 11, 449, 2043, 7841, 1548, 11, 35748, 198, 6738, 49796, 1330, 1215, 303, 596, 49, 42, 19, 11, 1215, 303, 596, 6500, 11, 1215, 303, 596, 49, 42, 22...
2.388326
2,467
from httprunner import HttpRunner import time kwargs = { "failfast":False, #"dot_env_path": "/path/to/.env" } runner = HttpRunner(**kwargs) # runner.run("/Users/wangjianqing/PycharmProjects/HttpRunner-master/tests/testcases/Release/-.yml") runner.gen_html_report(html_report_name="reportTestForBetaYunZS",html_report_template="/Users/wangjianqing/PycharmProjects/HttpRunner-master/httprunner/templates/default_report_template.html")
[ 6738, 1841, 1050, 403, 1008, 1330, 367, 29281, 49493, 198, 11748, 640, 628, 198, 46265, 22046, 796, 1391, 198, 220, 220, 220, 366, 32165, 7217, 1298, 25101, 11, 198, 220, 220, 220, 1303, 1, 26518, 62, 24330, 62, 6978, 1298, 12813, 697...
2.676647
167
''' Manage sensitivity classification recommendations. ''' from ...... pyaz_utils import _call_az def list(name, resource_group, workspace_name, filter=None, included_disabled=None, skip_token=None): ''' List the recommended sensitivity classifications of a given SQL pool. Required Parameters: - name -- The SQL pool name. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` - workspace_name -- The workspace name. Optional Parameters: - filter -- An OData filter expression that filters elements in the collection. - included_disabled -- Indicates whether the result should include disabled recommendations - skip_token -- An OData query option to indicate how many elements to skip in the collection. ''' return _call_az("az synapse sql pool classification recommendation list", locals()) def enable(column, name, resource_group, schema, table, workspace_name): ''' Enable sensitivity recommendations for a given column(recommendations are enabled by default on all columns). Required Parameters: - column -- The name of column. - name -- The SQL pool name. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` - schema -- The name of schema. - table -- The name of table. - workspace_name -- The workspace name. ''' return _call_az("az synapse sql pool classification recommendation enable", locals()) def disable(column, name, resource_group, schema, table, workspace_name): ''' Disable sensitivity recommendations for a given column(recommendations are enabled by default on all columns). Required Parameters: - column -- The name of column. - name -- The SQL pool name. - resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>` - schema -- The name of schema. - table -- The name of table. - workspace_name -- The workspace name. ''' return _call_az("az synapse sql pool classification recommendation disable", locals())
[ 7061, 6, 198, 5124, 496, 14233, 17923, 10763, 13, 198, 7061, 6, 198, 6738, 47082, 12972, 1031, 62, 26791, 1330, 4808, 13345, 62, 1031, 198, 198, 4299, 1351, 7, 3672, 11, 8271, 62, 8094, 11, 44573, 62, 3672, 11, 8106, 28, 14202, 11, ...
3.67395
595
""" Testing array utilities """ import sys import numpy as np from ..arrfuncs import as_native_array, pinv, eigh from numpy.testing import (assert_array_almost_equal, assert_array_equal) from nose.tools import assert_true, assert_false, assert_equal, assert_raises NATIVE_ORDER = '<' if sys.byteorder == 'little' else '>' SWAPPED_ORDER = '>' if sys.byteorder == 'little' else '<'
[ 37811, 23983, 7177, 20081, 198, 37811, 198, 198, 11748, 25064, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 11485, 3258, 12543, 6359, 1330, 355, 62, 30191, 62, 18747, 11, 6757, 85, 11, 304, 394, 198, 198, 6738, 299, 32152, ...
2.616352
159
# -*- coding: utf-8 -*- import time import sys import math #HOMEMADE WITHOUT ONLINE CODE by Aris #LIENCE BY ARIS
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 640, 198, 11748, 25064, 198, 11748, 10688, 198, 198, 2, 39, 2662, 3620, 19266, 42881, 6177, 24027, 42714, 416, 943, 271, 198, 2, 31271, 18310, 11050, 5923, 1797, ...
2.590909
44
"""Rail network map """ import os import sys from collections import OrderedDict import cartopy.crs as ccrs import cartopy.io.shapereader as shpreader import matplotlib.pyplot as plt from vtra.utils import * if __name__ == '__main__': main()
[ 37811, 44631, 3127, 3975, 198, 37811, 198, 11748, 28686, 198, 11748, 25064, 198, 6738, 17268, 1330, 14230, 1068, 35, 713, 198, 198, 11748, 6383, 11081, 13, 66, 3808, 355, 36624, 3808, 198, 11748, 6383, 11081, 13, 952, 13, 43358, 46862, ...
3.012048
83
# Generated by Django 3.1.1 on 2020-09-27 20:02 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 16, 319, 12131, 12, 2931, 12, 1983, 1160, 25, 2999, 201, 198, 201, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 201, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2...
2.58
50
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import numpy as np import os from astropy.tests.helper import raises from astropy.utils.data import get_pkg_data_filename from .. import Pydlspec2dException from ..spec1d import (HMF, findspec, spec_append, spec_path, template_metadata, wavevector)
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 38559, 24290, 13, 81, 301, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 6738, 6...
2.727273
132
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os from absl import flags import numpy as np import skimage.io as io import cv2 import matplotlib.pyplot as plt # import tensorflow as tf # from psbody.mesh import Mesh from smpl_webuser.serialization import load_model import pyrender import trimesh from util import renderer as vis_util from util import image as img_util from flame import FLAME from flame_config import get_config import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init import torch.optim as optim import MyRingnet # Input size: 2048 + 159, fc1_size: 512, fc2_size: 512, out_size: 159 config_img_size = 244 if __name__ == '__main__': # read images and scale #input_img_path = "./training_set/NoW_Dataset/final_release_version/iphone_pictures/FaMoS_180424_03335_TA/multiview_neutral/IMG_0101.jpg" #input_img_path = "./training_set/NoW_Dataset/final_release_version/iphone_pictures/FaMoS_180704_03355_TA/multiview_expressions/IMG_1948.jpg" input_img_path = "./training_set/NoW_Dataset/final_release_version/iphone_pictures/FaMoS_180427_03338_TA/multiview_expressions/IMG_0230.jpg" #input_img_path = "./training_set/NoW_Dataset/final_release_version/iphone_pictures/FaMoS_180502_00145_TA/multiview_expressions/IMG_0407.jpg" openpose = np.load(input_img_path.replace("iphone_pictures", "openpose").replace("jpg", "npy"), allow_pickle=True, encoding='latin1') img = io.imread(input_img_path) if np.max(img.shape[:2]) != config_img_size: # print('Resizing so the max image size is %d..' % self.config_img_size) scale = (float(config_img_size) / np.max(img.shape[:2])) else: scale = 1.0#scaling_factor center = np.round(np.array(img.shape[:2]) / 2).astype(int) # image center in (x,y) center = center[::-1] crop, proc_param = img_util.scale_and_crop( img, scale, center, config_img_size) print(proc_param) #exit(0) crop = torch.tensor(crop) crop = crop.permute(2, 0, 1) crop = crop[None, :, :, :].float().cuda() # print(crop) # build model resnet50 = torch.load("./good_resnet50.pkl") resnet50.cuda() resnet50.fc = Identity() # print(resnet50) regression = torch.load("./good_model.pkl") regression.cuda() config = get_config() config.batch_size = 1 flamelayer = FLAME(config) flamelayer.requires_grad_ = False flamelayer.cuda() # run the model res_output = resnet50(crop) # Empty estimates as the initial value for concatenation regress_estimates = torch.zeros([ res_output.shape[0], MyRingnet.regress_out_size ]).cuda() # Regression model for _ in range(MyRingnet.regress_iteration_cnt): # Preprocess regression input - concatenation regress_input = torch.cat([res_output, regress_estimates], 1) regress_estimates = regression(regress_input) regress_output = regress_estimates # FLAME model cam_params, pose_params = regress_output[0:, 0:3], regress_output[0:, 3:9] shape_params, exp_params = regress_output[0:, 9:109], regress_output[0:, 109:159] # pose_params[0,2] = 3.14/5 flame_vert, flame_lmk = flamelayer(shape_params, exp_params, pose_params) # Render and display the mesh print(flame_lmk, cam_params) # flame_lmk[0]=cam_params[0]*-1 # a_params = cam_params[:,:]*-1 mesh_vertices, mesh_faces = flame_vert.detach().cpu().numpy().squeeze(), flamelayer.faces mesh_vertices_colors = np.ones([mesh_vertices.shape[0], 4]) * [0.3, 0.3, 0.3, 0.8] renderMesh(mesh_vertices, mesh_faces, mesh_vertices_colors, flame_lmk.detach().cpu().numpy().squeeze()) #renderMesh(mesh_vertices, mesh_faces, mesh_vertices_colors, cam_params[0]) # flame_lmk[:, :, 1] *= -1 # cam_params[:,1]*=-1 # cam_params[:, 0] = 2 # cam_params[:, 1] = 0.2 # print(flame_lmk) center = torch.tensor(center.copy()).cuda() print(cam_params) new_cam = MyRingnet.transform_cam(cam_params, 1. / scale, config_img_size, center[None, :]) projected_lmks = MyRingnet.project_points(flame_lmk, new_cam) #op_pts = openpose[0,:68,:] #ground_truth_weights = ((op_pts[:,2] > 0.41).astype(float)) #print(ground_truth_weights) #print(op_pts) # print(projected_lmks) # print(openpose) plt.figure plt.imshow(img) count = 0 cpu_lmks = projected_lmks.cpu() #print(img.shape) for i in cpu_lmks[0]: x = i[0].int() y = i[1].int() plt.annotate(str(count), xy=(x, y)) plt.scatter(x, y, s=50, c='red', marker='o') count = count + 1 count = 0 #openpose[0] *= scale for i in openpose[0]: x = i[0] y = i[1] plt.annotate(str(count), xy=(x, y)) plt.scatter(x, y, s=50, c='blue', marker='o') count = count + 1 plt.show() renderer = vis_util.SMPLRenderer(faces=mesh_faces) print(img.shape[:2]) cam_for_render, vert_shifted = vis_util.get_original( #proc_param, mesh_vertices, new_cam.detach().cpu().numpy().squeeze(), img_size=img.shape[:2] proc_param, mesh_vertices, cam_params.detach().cpu().numpy().squeeze(), img_size=img.shape[:2] ) print(cam_params, new_cam, cam_for_render) #exit(0) # rend_img_overlay = renderer( # #vert_shifted * 1.0, cam=new_cam.squeeze().detach().cpu().numpy(), img=img, do_alpha=True # #vert_shifted * 1.0, cam=cam_for_render, img=img, do_alpha=True # vert_shifted * 1.0, cam=cam_for_render, img=img, do_alpha=True # ) rend_img_vp1 = renderer.rotated( mesh_vertices, 30, cam=new_cam.squeeze().detach().cpu().numpy(), img_size=img.shape[:2] #vert_shifted * 1.0, 30, cam=cam_for_render, img_size=img.shape[:2] ) plt.imshow(rend_img_vp1) plt.show()
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 25064, 198, 11748, 28686, 198, 6738, 2352, 75, 1330, 9701, 198, 11748, 299, 3...
2.320094
2,543
#!/usr/bin/python import os os.system("sudo ./scan.py") os.system("sudo ./enable-wifi.py")
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 11748, 28686, 198, 198, 418, 13, 10057, 7203, 24032, 24457, 35836, 13, 9078, 4943, 198, 418, 13, 10057, 7203, 24032, 24457, 21633, 12, 86, 22238, 13, 9078, 4943, 198 ]
2.486486
37
from sklearn.ensemble import RandomForestClassifier import xgboost
[ 6738, 1341, 35720, 13, 1072, 11306, 1330, 14534, 34605, 9487, 7483, 198, 11748, 2124, 70, 39521, 628, 198 ]
3.833333
18
from keras.optimizers import RMSprop from keras.layers import Input, Embedding, Dense, LSTM, Bidirectional, GRU from keras.layers import concatenate, Reshape, SpatialDropout1D from keras.models import Model from keras import backend as K from .AttentionWeightedAverage import AttentionWeightedAverage def textgenrnn_model(num_classes, cfg, context_size=None, weights_path=None, dropout=0.0, optimizer=RMSprop(lr=4e-3, rho=0.99)): ''' Builds the model architecture for textgenrnn and loads the specified weights for the model. ''' input = Input(shape=(cfg['max_length'],), name='input') embedded = Embedding(num_classes, cfg['dim_embeddings'], input_length=cfg['max_length'], name='embedding')(input) if dropout > 0.0: embedded = SpatialDropout1D(dropout, name='dropout')(embedded) rnn_layer_list = [] for i in range(cfg['rnn_layers']): prev_layer = embedded if i == 0 else rnn_layer_list[-1] if cfg.get('rnn_type') == 'gru': rnn_layer_list.append(new_rnn_gru(cfg, i + 1)(prev_layer)) else: rnn_layer_list.append(new_rnn(cfg, i + 1)(prev_layer)) seq_concat = concatenate([embedded] + rnn_layer_list, name='rnn_concat') attention = AttentionWeightedAverage(name='attention')(seq_concat) output = Dense(num_classes, name='output', activation='softmax')(attention) if context_size is None: model = Model(inputs=[input], outputs=[output]) if weights_path is not None: model.load_weights(weights_path, by_name=True) model.compile(loss='categorical_crossentropy', optimizer=optimizer) else: context_input = Input( shape=(context_size,), name='context_input') context_reshape = Reshape((context_size,), name='context_reshape')(context_input) merged = concatenate([attention, context_reshape], name='concat') main_output = Dense(num_classes, name='context_output', activation='softmax')(merged) model = Model(inputs=[input, context_input], outputs=[main_output, output]) if weights_path is not None: model.load_weights(weights_path, by_name=True) model.compile(loss='categorical_crossentropy', optimizer=optimizer, loss_weights=[0.8, 0.2]) return model ''' Create a new LSTM layer per parameters. Unfortunately, each combination of parameters must be hardcoded. The normal LSTMs use sigmoid recurrent activations for parity with CuDNNLSTM: https://github.com/keras-team/keras/issues/8860 '''
[ 6738, 41927, 292, 13, 40085, 11341, 1330, 371, 5653, 22930, 198, 6738, 41927, 292, 13, 75, 6962, 1330, 23412, 11, 13302, 6048, 278, 11, 360, 1072, 11, 406, 2257, 44, 11, 43484, 4154, 282, 11, 10863, 52, 198, 6738, 41927, 292, 13, 75...
2.298495
1,196
# Copyright 2015 Internap. # # 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 unittest import mock from flexmock import flexmock, flexmock_teardown from hamcrest import assert_that, has_length, equal_to, is_, none, empty from netaddr import IPNetwork from netaddr.ip import IPAddress from netman.adapters.switches import brocade_factory_ssh, brocade_factory_telnet from netman.adapters.switches.brocade import Brocade, parse_if_ranges from netman.adapters.switches.util import SubShell from netman.core.objects.access_groups import IN, OUT from netman.core.objects.exceptions import IPNotAvailable, UnknownVlan, UnknownIP, UnknownAccessGroup, BadVlanNumber, \ BadVlanName, UnknownInterface, TrunkVlanNotSet, UnknownVrf, VlanVrfNotSet, VrrpAlreadyExistsForVlan, BadVrrpPriorityNumber, BadVrrpGroupNumber, \ BadVrrpTimers, BadVrrpTracking, NoIpOnVlanForVrrp, VrrpDoesNotExistForVlan, UnknownDhcpRelayServer, DhcpRelayServerAlreadyExists, \ VlanAlreadyExist, InvalidAccessGroupName, IPAlreadySet from netman.core.objects.interface_states import OFF, ON from netman.core.objects.port_modes import ACCESS, TRUNK from netman.core.objects.switch_descriptor import SwitchDescriptor def vlan_with_vif_display(vlan_id, vif_id, name="[None]"): return vlan_display(vlan_id, name, vif_id=vif_id) def vlan_display(vlan_id=9, vlan_name="[None]", tagged_port_str=None, untagged_port_str=None, vif_id=None): ret = [ "PORT-VLAN {}, Name {}, Priority Level -, Priority Force 0, Creation Type STATIC".format(vlan_id, vlan_name), "Topo HW idx : 81 Topo SW idx: 257 Topo next vlan: 0", "L2 protocols : STP", ] if untagged_port_str: ret.append("Untagged Ports : {}".format(untagged_port_str)) if tagged_port_str: ret.append("Statically tagged Ports : {}".format(tagged_port_str)) ret.extend([ "Associated Virtual Interface Id: {}".format(vif_id or "NONE"), "----------------------------------------------------------", "No ports associated with VLAN", "Arp Inspection: 0", "DHCP Snooping: 0", "IPv4 Multicast Snooping: Disabled", "IPv6 Multicast Snooping: Disabled", ]) if vif_id: ret.extend([ "Ve{} is down, line protocol is down".format(vif_id), " Type is Vlan (Vlan Id: {})".format(vlan_id), " Hardware is Virtual Ethernet, address is 748e.f8a7.1b01 (bia 748e.f8a7.1b01)", " No port name", " Vlan id: {}".format(vlan_id), " Internet address is 0.0.0.0/0, IP MTU 1500 bytes, encapsulation ethernet", " Configured BW 0 kbps", ]) else: ret.append("No Virtual Interfaces configured for this vlan") return ret
[ 2, 15069, 1853, 2445, 499, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, ...
2.641876
1,237
import uuid from authtools import models as authtools_models from django.core.validators import URLValidator from django.db import models from django.utils import timezone from solo.models import SingletonModel
[ 11748, 334, 27112, 198, 198, 6738, 6284, 31391, 1330, 4981, 355, 6284, 31391, 62, 27530, 198, 6738, 42625, 14208, 13, 7295, 13, 12102, 2024, 1330, 10289, 47139, 1352, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208,...
3.839286
56
import numpy as np types = ["int", "float", "double"] rngs = {"int": randi, "float": np.random.randn, "double": np.random.randn} embodiments = { "function": "R.%s(A,B).AllClose(C)", "op": "(A %s B).AllClose(C)", "inline_op": "(R = A, R %s B).AllClose(C)", "inline_function": "( R = A, R.%s(B) ).AllClose(C)" } tests = { '+': ("Addition", "Add", [], []), '*': ("Multiplication", "Multiply", [], []), '-': ("Subtraction", "Subtract", [], []), '/': ("Division", "Divide", ["int"], []), 'dp': ("Dot product", "Dot", [], ["op", "inline_op"]) } for type in types: rng = rngs[type] for op, details in tests.iteritems(): test_title, function, exclude, ignore = details if type in exclude: break iop = op + "=" ifunction = "Inline" + function names = { "function": function, "op": op, "inline_op": iop, "inline_function": ifunction } n = 7 m = 7 A = rng(n, m) B = rng(n, m) if op == "+": C = A + B elif op == "/": C = A / B elif op == "-": C = A - B elif op == "*": C = A * B elif op == "dp": C = np.dot(A, B) m1 = " ;\n".join([" ".join([str(y) for y in x]) for x in A]) m2 = " ;\n".join([" ".join([str(y) for y in x]) for x in B]) m3 = " ;\n".join([" ".join([str(y) for y in x]) for x in C]) print """ SCENARIO("%s") { _M<%s> A,B,C,R; R.Resize( %d, %d ); A = _M<%s>(R\"(\n%s\n)\"); B = _M<%s>(R\"(\n%s\n)\"); C = _M<%s>(R\"(\n%s\n)\"); """ % (test_title + " for " + type, type, n, m, type, m1, type, m2, type, m3) for method, emb in embodiments.iteritems(): if method in ignore: continue name = names[method] tt = emb % name print "EXPECT( %s );" % tt print "};" print
[ 11748, 299, 32152, 355, 45941, 198, 19199, 796, 14631, 600, 1600, 366, 22468, 1600, 366, 23352, 8973, 628, 198, 198, 81, 782, 82, 796, 19779, 600, 1298, 374, 26800, 11, 366, 22468, 1298, 45941, 13, 25120, 13, 25192, 77, 11, 366, 23352...
1.82453
1,117
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. # 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 tensorflow as tf import numpy as np from utils import path_utils, midi_utils, display_utils # --- local samples------------------------------------------------------------------ def load_melody_samples(n_sample=10): """Load the samples used for evaluation.""" sample_source_path = './dataset/eval.npy' data = np.load(sample_source_path) data = np.asarray(data, dtype=np.float32) # {-1, 1} random_idx = np.random.choice(len(data), n_sample, replace=False) sample_x = data[random_idx] sample_z = tf.random.truncated_normal((n_sample, 2, 8, 512)) print("Loaded {} melody samples".format(len(sample_x))) return sample_x, sample_z # --- Training ------------------------------------------------------------------
[ 2, 15069, 13130, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 198, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 198, 2, 428, 3788, 290, 3917, 103...
3.348748
519
from enum import Enum from sys import stderr
[ 6738, 33829, 1330, 2039, 388, 198, 6738, 25064, 1330, 336, 1082, 81 ]
3.666667
12
from django.contrib import admin from .models import Image
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 7412, 198 ]
3.933333
15