content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
#!/usr/bin/env python # Extracts examples of given strings with context in a TAB-separated # field format from given text documents. from __future__ import with_statement import sys import re from os import path options = None if __name__ == "__main__": sys.exit(main(sys.argv))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2, 29677, 82, 6096, 286, 1813, 13042, 351, 4732, 287, 257, 309, 6242, 12, 25512, 515, 198, 2, 2214, 5794, 422, 1813, 2420, 4963, 13, 198, 198, 6738, 11593, 37443, 834, 1330, 351...
3.2
90
#======================================================================= # verilog_bug_test.py #======================================================================= import pytest from pymtl import * from exceptions import VerilatorCompileError pytestmark = requires_verilator #----------------------------------------------------------------------- # Point BitStruct #----------------------------------------------------------------------- #----------------------------------------------------------------------- # setup_sim #----------------------------------------------------------------------- def setup_sim( model ): model = TranslationTool( model ) model.elaborate() sim = SimulationTool( model ) return model, sim #----------------------------------------------------------------------- # test_bitstruct_tick_reg #----------------------------------------------------------------------- #----------------------------------------------------------------------- # test_verilator_compile_error #----------------------------------------------------------------------- def test_verilator_compile_error( ): with pytest.raises( VerilatorCompileError ): model = TestVerilatorCompileError() model, sim = setup_sim( model )
[ 2, 23926, 1421, 18604, 198, 2, 3326, 346, 519, 62, 25456, 62, 9288, 13, 9078, 198, 2, 23926, 1421, 18604, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 279, 4948, 28781, 220, 220, 220, 220, 220, 1330, 1635, 198, 6738, 13269, 1330, 4...
5.553097
226
import os # Get the list of all files with a specific extension # In this example, we will take a path of a directory and try to # list all the files, with a specific extension .py here, # in the directory and its sub-directories recursively. path = r'C:\Users\10900225\Documents\Witch\BTX\Workspaces\Library' for root, dirs, files in os.walk(path): for file in files: if(file.endswith(".py")): print(os.path.join(root,file))
[ 11748, 28686, 198, 198, 2, 3497, 262, 1351, 286, 477, 3696, 351, 257, 2176, 7552, 198, 2, 554, 428, 1672, 11, 356, 481, 1011, 257, 3108, 286, 257, 8619, 290, 1949, 284, 220, 198, 2, 1351, 477, 262, 3696, 11, 351, 257, 2176, 7552, ...
3.006897
145
#-*- coding: utf-8-*- from odoo import api, fields, models, _ # Wizard class
[ 2, 12, 9, 12, 19617, 25, 3384, 69, 12, 23, 12, 9, 12, 198, 198, 6738, 16298, 2238, 1330, 40391, 11, 7032, 11, 4981, 11, 4808, 198, 198, 2, 16884, 1398 ]
2.516129
31
#!/bin/env python3 import re from typing import List import numpy as np import matplotlib.pyplot as plt filtered_users = ["join-backup", "join-slave", "ucs-sso"] filtered_groups = ["computers", "dc backup hosts", "dc slave hosts"] def read_groupdump(): _group_list = LDAPGroupList() with open("groupdump.txt", "r") as file: current_group = None for line in file: if line == "\n": continue if line.startswith("DN"): current_group = LDAPGroup(re.findall(r"cn=(.*?),", line)[0]) _group_list.add(current_group) # print(current_user) if current_group.name.startswith("dns-") or current_group.name.startswith( "ucs-") or current_group.name.startswith("join-"): continue if line.startswith(" users"): user = LDAPUser(re.findall(r"uid=(.*?),", line)[0]) # print(" ", group) current_group.add_member(user) if line.startswith(" nestedGroup"): subgroup = re.findall(r"cn=(.*?),", line)[0] # print(" ", group) current_group.add_subgroup(subgroup) if line.startswith(" sambaRID:"): rid = re.findall(r"([0-9]{1,4})", line)[0] current_group.samba_rid = int(rid) return _group_list def paint_matrix(groups: LDAPGroupList): user_list = sorted(groups.get_user_list(), reverse=True) x_count = len(groups.content) y_count = len(user_list) matrix = np.zeros((x_count, y_count)) for g_index, group in enumerate(groups.content): for user in group.members: matrix[g_index][user_list.index(user)] = 1 plt.pcolor(matrix.T, edgecolors='k', cmap="Greys", vmin=0, vmax=1) x_locations = [x + 0.5 for x in range(x_count)] y_locations = [x + 0.5 for x in range(y_count)] plt.xticks(x_locations, [group.name for group in groups.content], rotation=45, fontsize=4, ha="right") plt.yticks(y_locations, [user.name for user in user_list], fontsize=2) plt.tight_layout() plt.savefig("groups.png", dpi=600) if __name__ == '__main__': groups = read_groupdump() for group in groups.content: group.parse_subgroups(groups) groups.tidy() paint_matrix(groups)
[ 2, 48443, 8800, 14, 24330, 21015, 18, 198, 11748, 302, 198, 6738, 19720, 1330, 7343, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 198, 10379, 4400, 62, 18417, 796, 14631, 22179, ...
2.107623
1,115
from sqlalchemy import create_engine, Column, Integer, BigInteger, String, Boolean, MetaData, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy.types import DateTime, Date, Interval from sqlalchemy.pool import NullPool from .conf import settings from logging import Logger print("loaded dbobjects module") #class DeduplicationLink(DB.Base, MapBase): def test(): from . import postgresutils utils = postgresutils.Utils() utils.blank_database() print("instantiating db") db = DB() session = db.Session() db.Base.metadata.create_all(db.pg_db_engine) new = Source(source_id_id_num = 1, source_name='Orange County Corrections') session.add(new) session.commit() print("done") if __name__ == "__main__": import sys sys.exit(test()) #The MIT License # #Copyright (c) 2011, Alexandria Consulting LLC # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: # #The above copyright notice and this permission notice shall be included in #all copies or substantial portions of the Software. # #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #THE SOFTWARE
[ 6738, 44161, 282, 26599, 1330, 2251, 62, 18392, 11, 29201, 11, 34142, 11, 4403, 46541, 11, 10903, 11, 41146, 11, 30277, 6601, 11, 8708, 9218, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 32446, 283, 876, 1330, 2377, 283, 876, 62, 8692,...
2.322581
1,054
import Image from ImageColor import getrgb from reportlab.pdfgen import canvas from reportlab.lib.units import mm from reportlab.lib.pagesizes import A4 import uuid BEAD_RADIUS = 1.75*mm BEAD_THICKNESS = 1*mm BOARD_SPACING = 4.85*mm BOARD_BORDER = 4*mm #A4 60x43 = 2580 #A3 86x60 = 5160 #A2 86x120 = 10,320 #MARQUEE A4+A4 = 120x43 colours = beadColours() #read image file header try: im = Image.open("images\\pikachu.gif") image_width = im.size[0] image_height = im.size[1] image_format = im.format except IOError: print "Error opening file" out_file = 'result%s.pdf' % uuid.uuid1() pdf = canvas.Canvas(out_file, pagesize=A4) ##work out the best orientation a4_width, a4_height = A4 #if (width - (BOARD_BORDER * 2)) < (image_width * BOARD_SPACING): #width_temp = width #width = height #height = width_temp #for now, just use generated page size width = (image_width * BOARD_SPACING) + (BOARD_BORDER * 2) height = (image_height * BOARD_SPACING) + (BOARD_BORDER * 2) if width < a4_width and width < a4_height: height = a4_height pdf.setPageSize((width, height)) im = im.convert('RGB') data = list(im.getdata()) list_pos = 0 for y in range(0, im.size[1]): pos_y = height - BOARD_BORDER - (y * BOARD_SPACING) for x in range(0, im.size[0]): r = data[list_pos][0] g = data[list_pos][1] b = data[list_pos][2] r, g, b = colours.bestMatch(r,g,b) pos_x = BOARD_BORDER + (x * BOARD_SPACING) pdf.setLineWidth(BEAD_THICKNESS) pdf.setStrokeColorRGB(float(r)/255,float(g)/255,float(b)/255) pdf.circle(pos_x, pos_y, BEAD_RADIUS, stroke=1, fill=0) #for light colour we need a thin black border if r + g + b >= 750: pdf.setLineWidth(0.25*mm) pdf.setStrokeColorRGB(0,0,0) pdf.circle(pos_x, pos_y, BEAD_RADIUS + (BEAD_THICKNESS / 2), stroke=1, fill=0) pdf.circle(pos_x, pos_y, BEAD_RADIUS - (BEAD_THICKNESS / 2), stroke=1, fill=0) list_pos += 1 pdf.showPage() pdf.save()
[ 11748, 7412, 198, 6738, 7412, 10258, 1330, 651, 81, 22296, 198, 6738, 989, 23912, 13, 12315, 5235, 1330, 21978, 198, 6738, 989, 23912, 13, 8019, 13, 41667, 1330, 8085, 198, 6738, 989, 23912, 13, 8019, 13, 31126, 4340, 1330, 317, 19, 1...
2.207965
904
""" ----------------------------------------------------------------------------------------------------------- Package: AequilibraE Name: Report dialog Purpose: Dialog for showing the report from algorithm runs Original Author: Pedro Camargo (c@margo.co) Contributors: Last edited by: Pedro Camargo Website: www.AequilibraE.com Repository: https://github.com/AequilibraE/AequilibraE Created: 2014-03-19 Updated: 30/09/2016 Copyright: (c) AequilibraE authors Licence: See LICENSE.TXT ----------------------------------------------------------------------------------------------------------- """ from qgis.core import * from PyQt4 import QtGui, uic from PyQt4.QtGui import * import sys import os from auxiliary_functions import standard_path FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'forms/ui_report.ui'))
[ 37811, 198, 16529, 3880, 32284, 198, 15717, 25, 220, 220, 220, 317, 4853, 22282, 430, 36, 628, 6530, 25, 220, 220, 220, 220, 220, 220, 6358, 17310, 198, 32039, 25, 220, 220, 220, 21269, 519, 329, 4478, 262, 989, 422, 11862, 4539, 62...
3.402299
261
import os import sys sys.path.append('.') sys.path.append('..') import warnings warnings.filterwarnings("ignore") from datetime import datetime import matplotlib matplotlib.use("TkAgg") import matplotlib.lines as lines import matplotlib.image as mpimg from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import tkinter as tk from tools.get_dates_umich import get_dates_umich from tools.staticmap_for_gps import map_for_gps from tools.data_manager import DataManager from tools.view_lidar import hokuyo_plot from tools.view_lidar import threshold_lidar_pts if __name__ == '__main__': app = MainWindow(None) app.mainloop()
[ 11748, 28686, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 10786, 2637, 8, 198, 17597, 13, 6978, 13, 33295, 10786, 492, 11537, 198, 198, 11748, 14601, 198, 40539, 654, 13, 24455, 40539, 654, 7203, 46430, 4943, 198, 198, 6738, 481...
2.935897
234
#!/usr/bin/env python # -*- coding: utf-8 -*- lengths = "187,254,0,81,169,219,1,190,19,102,255,56,46,32,2,216" suffix = [17, 31, 73, 47, 23] num_rounds = 64 if __name__ == "__main__": print("1: {}".format(puzzle1())) print("2: {}".format(puzzle2()))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 13664, 82, 796, 366, 23451, 11, 24970, 11, 15, 11, 6659, 11, 22172, 11, 28896, 11, 16, 11, 19782, 11, 1129, 11, 153...
2.03125
128
# -*- coding: utf-8 -*- """ @author:XuMingxuming624@qq.com) @description: """ import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers as layers # num_words = 2000 num_tags = 12 num_departments = 4 # body_input = keras.Input(shape=(None,), name='body') title_input = keras.Input(shape=(None,), name='title') tag_input = keras.Input(shape=(num_tags,), name='tag') # body_feat = layers.Embedding(num_words, 64)(body_input) title_feat = layers.Embedding(num_words, 64)(title_input) # body_feat = layers.LSTM(32)(body_feat) title_feat = layers.LSTM(128)(title_feat) features = layers.concatenate([title_feat,body_feat, tag_input]) # priority_pred = layers.Dense(1, activation='sigmoid', name='priority')(features) department_pred = layers.Dense(num_departments, activation='softmax', name='department')(features) # model = keras.Model(inputs=[body_input, title_input, tag_input], outputs=[priority_pred, department_pred]) model.summary() keras.utils.plot_model(model, 'multi_model.png', show_shapes=True) model.compile(optimizer=keras.optimizers.RMSprop(1e-3), loss={'priority': 'binary_crossentropy', 'department': 'categorical_crossentropy'}, loss_weights=[1., 0.2]) import numpy as np # title_data = np.random.randint(num_words, size=(1280, 10)) body_data = np.random.randint(num_words, size=(1280, 100)) tag_data = np.random.randint(2, size=(1280, num_tags)).astype('float32') # priority_label = np.random.random(size=(1280, 1)) department_label = np.random.randint(2, size=(1280, num_departments)) # history = model.fit( {'title': title_data, 'body':body_data, 'tag':tag_data}, {'priority':priority_label, 'department':department_label}, batch_size=32, epochs=5 ) model.save('model_save.h5') del model model = keras.models.load_model('model_save.h5')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 31, 9800, 25, 55, 84, 44, 278, 87, 12595, 21, 1731, 31, 38227, 13, 785, 8, 198, 31, 11213, 25, 220, 198, 37811, 198, 198, 11748, 11192, 273, 11125, 355, ...
2.488771
757
expected_output = { 'vrf': {'default': {'address_family': {'ipv4': {'instance': {'1': {'areas': {'0.0.0.0': {'area_id': '0.0.0.0', 'area_type': 'normal', 'authentication': 'none', 'existed': '1w5d', 'numbers': {'active_interfaces': 4, 'interfaces': 6, 'loopback_interfaces': 4, 'passive_interfaces': 0}, 'statistics': {'area_scope_lsa_cksum_sum': '1', 'area_scope_lsa_count': 1, 'spf_last_run_time': 0.000447, 'spf_runs_count': 2}}}, 'auto_cost': {'bandwidth_unit': 'mbps', 'enable': False, 'reference_bandwidth': 40000}, 'enable': False, 'discard_route_external': True, 'discard_route_internal': True, 'graceful_restart': {'ietf': {'enable': True, 'exist_status': 'none', 'restart_interval': 60, 'state': 'Inactive', 'type': 'ietf'}}, 'instance': 1, 'nsr': {'enable': True}, 'numbers': {'active_areas': {'normal': 1, 'nssa': 0, 'stub': 0, 'total': 1}, 'areas': {'normal': 1, 'nssa': 0, 'stub': 0, 'total': 1}}, 'opaque_lsa_enable': True, 'preference': {'single_value': {'all': 110}}, 'router_id': '10.100.2.2', 'single_tos_routes_enable': True, 'spf_control': {'paths': 8, 'throttle': {'lsa': {'group_pacing': 10, 'hold': 5000, 'maximum': 5000, 'minimum': 1000, 'numbers': {'external_lsas': {'checksum': '0', 'total': 0}, 'opaque_as_lsas': {'checksum': '0', 'total': 0}}, 'start': 0.0}, 'spf': {'hold': 1000, 'maximum': 5000, 'start': 200}}}}}}}}}}
[ 198, 198, 40319, 62, 22915, 796, 1391, 198, 220, 220, 220, 705, 37020, 69, 10354, 198, 220, 220, 220, 220, 220, 220, 220, 1391, 6, 12286, 10354, 198, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1391, 6, 21975, 62, 17989...
1.254221
3,139
#!/usr/bin/env python # -*- coding:utf-8 -*- import json import platform import time from getdevinfo import getdevinfo import psutil from rain.common import rain_log from rain.common import utils from rain.common.utils import async_call logger = rain_log.logg(__name__) def get_memcache_info(self): """Collect memory and swap information and return dictionary type. """ memcache_info = psutil.virtual_memory() memcache_total = memcache_info.total / 1024 ** 2 memcache_used = memcache_info.used / 1024 ** 2 memcache_available = memcache_info.available / 1024 ** 2 memcache_buff = memcache_info.cached / 1024 ** 2 memcache_cached = memcache_info.cached / 1024 ** 2 memcache_percent = memcache_info.percent memcache_info_dict = { 'memcache_total_MB': memcache_total, 'memcache_used_MB': memcache_used, 'memcache_available_MB': memcache_available, 'memcache_buff_MB': memcache_buff, 'memcache_cached_MB': memcache_cached, 'memcache_percent': memcache_percent } logger.info('Collect memory related information.') return memcache_info_dict def _get_user(self): """Collect login user information. """ user_info_list = [] user_list = psutil.users() for user in user_list: user_dict = {} user_dict['name'] = user.name user_dict['host'] = user.host user_dict['conn_time'] = utils.str_time(user.started) user_info_list.append(user_dict) return user_info_list def get_system_info(self): """Collect system information. """ system_info = {} system_info['python_version'] = platform.python_version() system_info['hostname'] = platform.node() system_info['system_info'] = platform.platform() system_info['boot_time'] = utils.str_time(psutil.boot_time()) system_info['time'] = time.asctime(time.localtime(time.time())) system_info['user'] = self._get_user() logger.info('Collect user login information.') return system_info
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 198, 11748, 33918, 198, 11748, 3859, 198, 11748, 640, 198, 198, 6738, 651, 67, 6830, 6513, 1330, 651, 67, 6830, 6513, 198,...
2.34435
938
"""Model Definations for trpo.""" import gym import numpy as np import torch import time import scipy.optimize import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from distributions import DiagonalGaussian from helpers import get_flat_params, set_flat_params, get_flat_grads #from helpers import sample_trajectories, compute_advantage_returns, get_flat_params def test_policy_value(): env = gym.make("MountainCarContinuous-v0") policy = GaussianMLPPolicy(env.observation_space, env.action_space, use_std_net=True) paths = sample_trajectories(env, policy, 1000) print(len(paths["rewards"])) baseline = MLPBaseline(env.observation_space, env.action_space) compute_advantage_returns(paths, baseline, 0.9, 0.1) print(paths.keys()) baseline.update(paths) print(paths['dist'].keys()) flat_params_mean = get_flat_params(policy.mean_network.parameters()) flat_params_std = get_flat_params(policy.std_network.parameters()) print(flat_params) #test_policy_value()
[ 37811, 17633, 2896, 7352, 329, 491, 7501, 526, 15931, 198, 198, 11748, 11550, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 11748, 640, 198, 11748, 629, 541, 88, 13, 40085, 1096, 198, 11748, 28034, 13, 20471, 355, 299, 77,...
2.762887
388
from django.contrib import admin from sample_1.models import * # Register your models here. admin.site.register(Author) admin.site.register(Book)
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 6291, 62, 16, 13, 27530, 1330, 1635, 198, 2, 17296, 534, 4981, 994, 13, 628, 198, 28482, 13, 15654, 13, 30238, 7, 13838, 8, 198, 28482, 13, 15654, 13, 30238, 7, 10482, 8, ...
3.363636
44
from django.db import models import uuid # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 11748, 334, 27112, 198, 198, 2, 13610, 534, 4981, 994, 13, 628 ]
3.5
20
import os from shutil import move, rmtree from itertools import chain from genres import genre_of, DOWNLOAD_DIR, DST_DIRS, VIDEO_EXTENSIONS print(genre_of) print(f'moving files from {DOWNLOAD_DIR}: \n' # f'with keywords: {COMEDY_TAGS} \n' # f'with extensions: {VIDEO_EXTENSIONS} \n' ) files_moved = 0 for file_name in os.listdir(DOWNLOAD_DIR): name_parts = file_name.split('.') # check single & double word combos todo: generalize to more than 2 two_words = ('.'.join(name_parts[i:i + 2]) for i in range(len(name_parts) - 1)) file_path = os.path.join(DOWNLOAD_DIR, file_name) if os.path.isfile(file_path): # skip files continue # print(file_name, os.access(file_path, os.W_OK)) # todo: doesn't check if it's locked! # move files to corresponding dir try: # print(f'Try {file_name}') # with open(os.path.join(DOWNLOAD_DIR, file_name), 'r') as f: if any((keyword := part) in genre_of for part in chain(name_parts, two_words)): dst_dir = DST_DIRS[genre_of[keyword]] # move video file for maybe_vid in (name for name in os.listdir(file_path)): if any(maybe_vid.endswith(ext) for ext in VIDEO_EXTENSIONS): move(os.path.join(file_path, maybe_vid), dst_dir) print(f'moved {maybe_vid} to {dst_dir}') # delete empty file rmtree(file_path) files_moved += 1 # now extract the vid & delete dir except PermissionError: print('permission denied') continue # skip this file if locked (eg by qTorrent) print(f'{files_moved = }')
[ 11748, 28686, 198, 6738, 4423, 346, 1330, 1445, 11, 374, 16762, 631, 198, 6738, 340, 861, 10141, 1330, 6333, 198, 198, 6738, 27962, 1330, 12121, 62, 1659, 11, 30320, 35613, 62, 34720, 11, 360, 2257, 62, 34720, 50, 11, 35507, 62, 13918...
2.258503
735
"""Handlers for project-related APIs.""" from __future__ import annotations from typing import Dict, Tuple from flask import request from flask_accept import accept_fallback from keeper.auth import token_auth from keeper.logutils import log_route from keeper.models import Organization, Product, db from keeper.services.createproduct import create_product from keeper.services.updateproduct import update_product from keeper.taskrunner import launch_tasks from keeper.v2api import v2api from ._models import ( ProjectPatchRequest, ProjectPostRequest, ProjectResponse, ProjectsResponse, ) from ._urls import url_for_project __all__ = ["get_projects", "get_project", "create_project", "update_project"]
[ 37811, 12885, 8116, 329, 1628, 12, 5363, 23113, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 360, 713, 11, 309, 29291, 198, 198, 6738, 42903, 1330, 2581, 198, 6738, 42903, 62, 13635, 1330, 245...
3.635
200
# -*- coding: utf-8 -*- """ Allow server-side KaTeX rendering for Markdown through node.js The markdown extension adds regex patterns for `$` and `$$` in the source `.md` file, and applies KaTeX to the intermediate text with a `python-bond` call to node.js requires * node * npm * katex (npm install katex) * python-bond (pip3 install --user python-bond) KaTeX: https://github.com/Khan/KaTeX """ import markdown from markdown.util import etree import bond JS = bond.make_bond('JavaScript') JS.eval_block( r''' katex = require('katex'); function render(s, is_block) { return katex.renderToString(s, { displayMode: is_block, throwOnError: false }); } ''' ) katex = JS.callable('render') memoise = {} ###############################################################################
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 198, 35265, 4382, 12, 1589, 11611, 49568, 14837, 329, 2940, 2902, 832, 10139, 13, 8457, 198, 198, 464, 1317, 2902, 7552, 6673, 40364, 7572, 329, 4600, 3, 63,...
2.744262
305
# N 1 # , n 1 ( -1). # , n = 100, : 100, 99, 98, , 3, 2, 1. n = int(input()) for i in range(n, 0, -1): print(i)
[ 2, 220, 220, 399, 220, 352, 220, 220, 220, 198, 2, 220, 220, 220, 837, 220, 220, 220, 220, 299, 220, 352, 220, 220, 220, 357, 532, 16, 737, 198, 2, 837, 220, 299, 796, 1802, 11, 220, 220, 220, 1058, 1802, 11, 7388, 11, 9661, ...
1.642857
84
"""simpleclassroom URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from views import views from views import io urlpatterns = [ url(r'^$', views.display_classrooms, name='index'), url(r'^classrooms/', views.display_classrooms, name='classrooms'), url(r'^student_list/', views.display_students, name='student list'), url(r'^student_details/', views.display_student_details, name='student view'), url(r'^io/add_class/', io.add_classroom, name='add class'), url(r'^io/del_class/', io.delete_classroom, name='delete class'), url(r'^io/add_student/', io.add_student, name='add student'), url(r'^io/del_student/', io.delete_student, name='delete student'), url(r'^io/enroll/', io.enroll_student, name='enroll student'), url(r'^io/unenroll/', io.unenroll_student, name='unenroll student'), url(r'^admin/', admin.site.urls), ]
[ 37811, 36439, 4871, 3823, 10289, 28373, 198, 198, 464, 4600, 6371, 33279, 82, 63, 1351, 11926, 32336, 284, 5009, 13, 1114, 517, 1321, 3387, 766, 25, 198, 220, 220, 220, 3740, 1378, 31628, 13, 28241, 648, 404, 305, 752, 13, 785, 14, ...
2.785047
535
#!usr/bin/env python import sys, logging import re import mechanize logger = logging.getLogger('mechanize') logger.addHandler(logging.StreamHandler(sys.stdout)) logger.setLevel(logging.DEBUG) br = mechanize.Browser() br.set_debug_http(True) br.set_debug_responses(True) br.set_debug_redirects(True) br.open("https://750words.com/auth") email = open('email.txt', 'r').read() password = open('password.txt', 'r').read() print email, password br.select_form(nr=0) br['person[email_address]'] = 'rpvnwnkl@gmail.com' br['person[password]'] = 'password' response2 = br.submit() print br.title print response2.geturl() print response2.info() print response2.read() print br.select_form(nr=0) print br['entry[body]']
[ 2, 0, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 25064, 11, 18931, 198, 198, 11748, 302, 198, 11748, 3962, 1096, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 10786, 1326, 3147, 1096, 11537, 198, 6404, 1362, 13, 2860, 2...
2.725191
262
# \file DataWriter.py # \brief Class to read data # # \author Michael Ebner (michael.ebner.14@ucl.ac.uk) # \date June 2018 import os import sys import numpy as np import nibabel as nib import SimpleITK as sitk import pysitk.python_helper as ph import pysitk.simple_itk_helper as sitkh from simplereg.definitions import ALLOWED_IMAGES from simplereg.definitions import ALLOWED_LANDMARKS from simplereg.definitions import ALLOWED_TRANSFORMS from simplereg.definitions import ALLOWED_TRANSFORMS_DISPLACEMENTS
[ 2, 3467, 7753, 6060, 34379, 13, 9078, 198, 2, 220, 3467, 65, 3796, 5016, 284, 1100, 1366, 198, 2, 198, 2, 220, 3467, 9800, 3899, 12119, 1008, 357, 76, 40302, 13, 1765, 1008, 13, 1415, 31, 36616, 13, 330, 13, 2724, 8, 198, 2, 220...
2.903955
177
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # http://www.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is configman # # The Initial Developer of the Original Code is # Mozilla Foundation # Portions created by the Initial Developer are Copyright (C) 2011 # the Initial Developer. All Rights Reserved. # # Contributor(s): # K Lars Lohn, lars@mozilla.com # Peter Bengtsson, peterbe@mozilla.com # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the "GPL"), or # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** import datetime def datetime_from_ISO_string(s): """ Take an ISO date string of the form YYYY-MM-DDTHH:MM:SS.S and convert it into an instance of datetime.datetime """ try: return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S') except ValueError: try: return datetime.datetime.strptime(s, '%Y-%m-%d') except ValueError: return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f') def date_from_ISO_string(s): """ Take an ISO date string of the form YYYY-MM-DD and convert it into an instance of datetime.date """ return datetime.datetime.strptime(s, '%Y-%m-%d').date() def datetime_to_ISO_string(aDate): """ Take a datetime and convert to string of the form YYYY-MM-DDTHH:MM:SS.S """ return aDate.isoformat() def date_to_ISO_string(aDate): """ Take a datetime and convert to string of the form YYYY-MM-DD """ return aDate.strftime('%Y-%m-%d') def str_to_timedelta(input_str): """ a string conversion function for timedelta for strings in the format DD:HH:MM:SS """ days, hours, minutes, seconds = 0, 0, 0, 0 details = input_str.split(':') if len(details) >= 4: days = int(details[-4]) if len(details) >= 3: hours = int(details[-3]) if len(details) >= 2: minutes = int(details[-2]) if len(details) >= 1: seconds = int(details[-1]) return datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds) def timedelta_to_str(aTimedelta): """ a conversion function for time deltas to string in the form DD:HH:MM:SS """ days = aTimedelta.days temp_seconds = aTimedelta.seconds hours = temp_seconds / 3600 minutes = (temp_seconds - hours * 3600) / 60 seconds = temp_seconds - hours * 3600 - minutes * 60 return '%d:%d:%d:%d' % (days, hours, minutes, seconds)
[ 2, 25998, 9, 347, 43312, 38559, 24290, 9878, 11290, 25998, 9, 198, 2, 10628, 25, 4904, 43, 352, 13, 16, 14, 38, 6489, 362, 13, 15, 14, 41257, 6489, 362, 13, 16, 198, 2, 198, 2, 383, 10154, 286, 428, 2393, 389, 2426, 284, 262, ...
2.724798
1,359
from django.contrib.auth import get_user_model from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from rest_framework.test import APITestCase, APIClient from rest_framework.views import status from voluntario.models import Voluntario
[ 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 1330, 651, 62, 7220, 62, 19849, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 6738, 1334, 62, 30604, 13, 18439, 30001, 13, 27530, 1330, 29130, 198, 6738, ...
3.623377
77
# -*- coding:utf-8 -*- """ @Time2022/05/05 12:57 @AuthorKI @Filemain.py @MottoHungry And Humble """ from data_process import clients_wind from server import Scaffold if __name__ == '__main__': main()
[ 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 37811, 198, 31, 7575, 1238, 1828, 14, 2713, 14, 2713, 1105, 25, 3553, 198, 31, 13838, 37845, 198, 31, 8979, 12417, 13, 9078, 198, 31, 44, 17631, 39505, 563, 843, 367, 103...
2.493976
83
#!/usr/bin/env python import pycassa sys = pycassa.SystemManager("cassandra.service.consul:9160") if "reddit" not in sys.list_keyspaces(): print "creating keyspace 'reddit'" sys.create_keyspace("reddit", "SimpleStrategy", {"replication_factor": "3"}) print "done" if "permacache" not in sys.get_keyspace_column_families("reddit"): print "creating column family 'permacache'" sys.create_column_family("reddit", "permacache") print "done"
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 12972, 66, 562, 64, 198, 17597, 796, 12972, 66, 562, 64, 13, 11964, 13511, 7203, 66, 562, 15918, 13, 15271, 13, 5936, 377, 25, 24, 14198, 4943, 198, 198, 361, 366, 10748,...
2.729412
170
## 1. Data Structures ## import pandas as pd fandango = pd.read_csv('fandango_score_comparison.csv') print(fandango.head(2)) ## 2. Integer Indexes ## fandango = pd.read_csv('fandango_score_comparison.csv') series_film = fandango['FILM'] series_rt = fandango['RottenTomatoes'] print(series_film[:5]) print(series_rt[:5]) ## 3. Custom Indexes ## # Import the Series object from pandas from pandas import Series film_names = series_film.values rt_scores = series_rt.values series_custom=pd.Series(index = film_names, data = rt_scores) ## 4. Integer Index Preservation ## series_custom = Series(rt_scores , index=film_names) series_custom[['Minions (2015)', 'Leviathan (2014)']] fiveten = series_custom[5:10] print(fiveten) ## 5. Reindexing ## original_index = series_custom.index.tolist() sorted_by_index = series_custom.reindex(index = sorted(original_index)) ## 6. Sorting ## sc2 = series_custom.sort_index() sc3 = series_custom.sort_values() print(sc2.head(10)) print(sc3.head(10)) ## 7. Transforming Columns With Vectorized Operations ## series_normalized = series_custom/20 ## 8. Comparing and Filtering ## criteria_one = series_custom > 50 criteria_two = series_custom < 75 both_criteria = series_custom[criteria_one & criteria_two] ## 9. Alignment ## rt_critics = Series(fandango['RottenTomatoes'].values, index=fandango['FILM']) rt_users = Series(fandango['RottenTomatoes_User'].values, index=fandango['FILM']) rt_mean =(rt_users + rt_critics) / 2
[ 2235, 352, 13, 6060, 32112, 942, 22492, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 69, 392, 14208, 796, 279, 67, 13, 961, 62, 40664, 10786, 69, 392, 14208, 62, 26675, 62, 785, 1845, 1653, 13, 40664, 11537, 198, 4798, 7, 69, 3...
2.751402
535
n=int(input()) link=[[100]*n for i in range(n)] for i in range(n): x=input() for j in range(n): if x[j]=='Y': link[i][j]=1 for i in range(n): for j in range(n): for k in range(n): if link[j][i]+link[i][k]<link[j][k]: link[j][k]=link[j][i]+link[i][k] link[k][j]=link[j][k] ans=0 for i in range(n): t=0 for j in range(n): if link[i][j]<=2 and i!=j: t+=1 ans=max(t,ans) print(ans)
[ 77, 28, 600, 7, 15414, 28955, 198, 8726, 28, 30109, 3064, 60, 9, 77, 329, 1312, 287, 2837, 7, 77, 15437, 198, 1640, 1312, 287, 2837, 7, 77, 2599, 198, 220, 2124, 28, 15414, 3419, 198, 220, 329, 474, 287, 2837, 7, 77, 2599, 198, ...
1.847826
230
import pytest import os,sys import warnings try: from exceptions import Exception, TypeError, ImportError except: pass from runipy.notebook_runner import NotebookRunner wrapped_stdin = sys.stdin sys.stdin = sys.__stdin__ sys.stdin = wrapped_stdin try: from Queue import Empty except: from queue import Empty # code copied from runipy main.py with warnings.catch_warnings(): try: from IPython.utils.shimmodule import ShimWarning warnings.filterwarnings('error', '', ShimWarning) except ImportError: try: # IPython 3 from IPython.nbformat import reads, NBFormatError except ShimWarning: # IPython 4 from nbformat import reads, NBFormatError except ImportError: # IPython 2 from IPython.nbformat.current import reads, NBFormatError finally: warnings.resetwarnings() def get_cell_description(cell_input): """Gets cell description Cell description is the first line of a cell, in one of this formats: * single line docstring * single line comment * function definition """ try: first_line = cell_input.split("\n")[0] if first_line.startswith(('"', '#', 'def')): return first_line.replace('"','').replace("#",'').replace('def ', '').replace("_", " ").strip() except: pass return "no description"
[ 11748, 12972, 9288, 198, 11748, 28686, 11, 17597, 198, 11748, 14601, 198, 28311, 25, 198, 220, 220, 220, 422, 13269, 1330, 35528, 11, 5994, 12331, 11, 17267, 12331, 198, 16341, 25, 198, 220, 220, 220, 1208, 198, 198, 6738, 1057, 541, ...
2.648184
523
items = {"a": True, "b": False} b = [v for k, v in items.items() if v == True] print(b)
[ 23814, 796, 19779, 64, 1298, 6407, 11, 366, 65, 1298, 10352, 92, 198, 198, 65, 796, 685, 85, 329, 479, 11, 410, 287, 3709, 13, 23814, 3419, 611, 410, 6624, 6407, 60, 198, 198, 4798, 7, 65, 8, 198 ]
2.307692
39
#! /usr/bin/env python # DESCRIPTION = "ztflc: Force photometry lc fitter" LONG_DESCRIPTION = """ Force photometry lc fitter""" DISTNAME = "ztflc" AUTHOR = "Mickael Rigault" MAINTAINER = "Mickael Rigault" MAINTAINER_EMAIL = "m.rigault@ipnl.in2p3.fr" URL = "https://github.com/MickaelRigault/ztflc/" LICENSE = "BSD (3-clause)" DOWNLOAD_URL = "https://github.com/MickaelRigault/ztflc/tarball/0.2" VERSION = "0.2.3" try: from setuptools import setup, find_packages _has_setuptools = True except ImportError: from distutils.core import setup _has_setuptools = False if __name__ == "__main__": install_requires = check_dependencies() if _has_setuptools: packages = find_packages() print(packages) else: # This should be updated if new submodules are added packages = ["ztflc"] setup( name=DISTNAME, author=AUTHOR, author_email=MAINTAINER_EMAIL, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, license=LICENSE, url=URL, version=VERSION, download_url=DOWNLOAD_URL, install_requires=install_requires, scripts=["bin/forcephoto.py"], packages=packages, include_package_data=True, # package_data={'pysedm': ['data/*.*']}, classifiers=[ "Intended Audience :: Science/Research", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.5", "License :: OSI Approved :: BSD License", "Topic :: Scientific/Engineering :: Astronomy", "Operating System :: POSIX", "Operating System :: Unix", "Operating System :: MacOS", ], )
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 198, 30910, 40165, 796, 366, 89, 83, 2704, 66, 25, 5221, 2825, 15748, 300, 66, 277, 1967, 1, 198, 43, 18494, 62, 30910, 40165, 796, 37227, 5221, 2825, 15748, 300, 66, 277...
2.238916
812
#!/usr/bin/python __author__ = 'thovo' import sys ibm1()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 834, 9800, 834, 796, 705, 400, 18768, 6, 198, 198, 11748, 25064, 628, 198, 571, 76, 16, 3419 ]
2.269231
26
import random from .utils import filler from .array import RawWordFindArray, WordArray
[ 11748, 4738, 198, 6738, 764, 26791, 1330, 41134, 198, 6738, 764, 18747, 1330, 16089, 26449, 16742, 19182, 11, 9678, 19182, 628, 628 ]
4.090909
22
# ****************************************************************************** # Copyright 2017-2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ****************************************************************************** from __future__ import print_function, absolute_import import logging from builtins import object import neon as ng logger = logging.getLogger(__name__) try: from aeon import DataLoader except ImportError: msg = "\n".join(["", "Unable to import Aeon module.", "Please see installation instructions at:", "*****************", "https://github.com/NervanaSystems/aeon/blob/rc1-master/README.md", "*****************", ""]) logger.error(msg) raise ImportError(msg) NAME_MAP = {"channels": "C", "height": "H", "width": "W", "frames": "D"} """Converts aeon axis names to canonical ngraph axis types."""
[ 2, 41906, 17174, 46068, 1174, 198, 2, 15069, 2177, 12, 7908, 8180, 10501, 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, ...
2.919694
523
wordCounter = dict() while True : inputFile = input('Enter a file: ') try : fileName = open(inputFile) except : fileName = 'invalid' if fileName == 'invalid' : if inputFile == 'done' : break else : print('Invalid Input') continue for lines in fileName : lines = lines.rstrip() words = lines.split() for wordItems in words : wordCounter[wordItems] = wordCounter.get(wordItems, 0) + 1 largestWordCount = None largestWord = None for word,count in wordCounter.items() : if largestWordCount is None or count > largestWordCount : largestWord = word largestWordCount = count print('Largest Word:', largestWord, 'Count:', largestWordCount) print(wordCounter) continue
[ 4775, 31694, 796, 8633, 3419, 198, 198, 4514, 6407, 1058, 198, 220, 220, 220, 5128, 8979, 796, 5128, 10786, 17469, 257, 2393, 25, 705, 8, 198, 220, 220, 220, 1949, 1058, 198, 220, 220, 220, 220, 220, 220, 220, 2393, 5376, 796, 1280,...
2.297587
373
from iris.cli.base import Command, format_docstring, get_command_class HELP = format_docstring(""" Usage: iris [options] <command> [<args>...] Iris is the personification of the rainbow and messenger of the gods. {COMMON_OPTIONS} Commands: instance Run a single service instance (one process). node Run a node service that manages a group of processes on the same machine. request Send a request message to some service and output the reply. inspect Describe the available rpc methods of a service. tail Stream the logs of one or more services. discover Show available services. help Display help information about iris. """)
[ 6738, 4173, 271, 13, 44506, 13, 8692, 1330, 9455, 11, 5794, 62, 15390, 8841, 11, 651, 62, 21812, 62, 4871, 628, 198, 39, 3698, 47, 796, 5794, 62, 15390, 8841, 7203, 15931, 198, 28350, 25, 4173, 271, 685, 25811, 60, 1279, 21812, 29, ...
3.214953
214
# ---------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License # ---------------------------------------------------------------------- """Generates JSON files based on data previously pickled""" import lzma import os import pickle import sys import json # Note that this isn't used directly, but is required by the picked python content import pandas as pd import CommonEnvironment from CommonEnvironment import CommandLine from CommonEnvironment import FileSystem from CommonEnvironment.StreamDecorator import StreamDecorator # ---------------------------------------------------------------------- _script_fullpath = CommonEnvironment.ThisFullpath() _script_dir, _script_name = os.path.split(_script_fullpath) # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- def _holiday_data_loader(_path): """Load holiday data as a static initializer.""" with lzma.open(_path, "rb") as fr: df = pickle.loads(fr.read()) df['countryRegionCode'] = df['countryRegionCode'] \ .apply(lambda x: x if type(x) == str else None) df['isPaidTimeOff'] = df['isPaidTimeOff'] \ .apply(lambda x: x if type(x) == bool else None) return df # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- if __name__ == "__main__": try: sys.exit(CommandLine.Main()) except KeyboardInterrupt: pass
[ 2, 16529, 23031, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 198, 2, 16529, 23031, 198, 37811, 8645, 689, 19449, 3696, 1912, 319, 1366, 4271, 2298, 992, 37811, 198, 198, ...
4.083512
467
# Two lines that remove tensorflow GPU logs # import os # os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras.optimizers import Adam from keras.models import Sequential, model_from_json from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout, BatchNormalization, Activation from keras.preprocessing.image import ImageDataGenerator from sklearn import model_selection from math import ceil # Loads csv files and appends pixels to X and labels to y run_model()
[ 2, 4930, 3951, 326, 4781, 11192, 273, 11125, 11362, 17259, 198, 2, 1330, 28686, 198, 2, 28686, 13, 268, 2268, 17816, 10234, 62, 8697, 47, 62, 23678, 62, 25294, 62, 2538, 18697, 20520, 796, 705, 18, 6, 198, 198, 11748, 299, 32152, 35...
3.140449
178
from pprint import pprint import requests from lxml import etree if __name__ == "__main__": main()
[ 6738, 279, 4798, 1330, 279, 4798, 198, 11748, 7007, 198, 6738, 300, 19875, 1330, 2123, 631, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419, 198 ]
3
35
import urllib.request,json from .models import Source,Article from . import main # Getting Api Key api_Key = None #Getting the base urls sources_base_url = None articles_base_url = None def configure_request(app): ''' Function to acquire the api key and base urls ''' global api_Key,sources_base_url,articles_base_url api_Key = app.config['NEWS_API_KEY'] sources_base_url = app.config['NEWS_SOURCES_BASE_URL'] articles_base_url = app.config['NEWS_ARTICLES_BASE_URL'] def get_sources(category): ''' Function that gets the json response to our url request ''' get_sources_url = sources_base_url.format(category) with urllib.request.urlopen(get_sources_url,data=None) as url: get_sources_data = url.read() get_sources_response = json.loads(get_sources_data) sources_results = None if get_sources_response['sources']: sources_results_list = get_sources_response['sources'] sources_results = process_sources(sources_results_list) # print(sources_results) return sources_results def process_sources(sources_results): ''' Function that processes the sources result and transform them to a list of Objects Args: sources_results: A list of dictionaries that contain sources details Returns : sources_list: A list of sources objects ''' sources_list = [] for source_item in sources_results: id = source_item.get('id') name = source_item.get('name') description = source_item.get('description') url = source_item.get('url') category = source_item.get('category') source_object = Source(id,name,description,url,category) sources_list.append(source_object) return sources_list def get_articles(source): ''' Function that gets the json response to our url request ''' get_articles_url = articles_base_url.format(source,api_Key) with urllib.request.urlopen(get_articles_url,data=None) as url: get_articles_data = url.read() get_articles_response = json.loads(get_articles_data) articles_results = None if get_articles_response['articles']: articles_results_list = get_articles_response['articles'] articles_results = process_articles(articles_results_list) return articles_results def process_articles(articles_results): ''' Function that processes the articles result and transform them to a list of Objects Args: articles_results: A list of dictionaries that contain articles details Returns : articles_list: A list of articles objects ''' articles_list = [] for article_item in articles_results: name = article_item.get('name') author = article_item.get('author') title = article_item.get('title') description = article_item.get('description') url = article_item.get('url') urlToImage = article_item.get('urlToImage') publishedAt = article_item.get('publishedAt') if publishedAt and author and urlToImage: article_object = Article(name,author,title,description,url,urlToImage,publishedAt) articles_list.append(article_object) return articles_list
[ 11748, 2956, 297, 571, 13, 25927, 11, 17752, 198, 6738, 764, 27530, 1330, 8090, 11, 14906, 198, 6738, 764, 1330, 1388, 198, 198, 2, 18067, 5949, 72, 7383, 198, 15042, 62, 9218, 796, 6045, 198, 2, 20570, 262, 2779, 2956, 7278, 198, 8...
3.019368
981
if __name__ == '__main__': players = get_names() print(players) scores = get_player_scores(players) print(scores)
[ 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1938, 796, 651, 62, 14933, 3419, 198, 220, 220, 220, 3601, 7, 32399, 8, 198, 220, 220, 220, 8198, 796, 651, 62, 7829, 62, 1416, 2850, 7, 32399...
2.418182
55
import os os.environ['SLACK_WEBHOOK_URL'] = 'https://example.com/slack'
[ 11748, 28686, 198, 198, 418, 13, 268, 2268, 17816, 8634, 8120, 62, 8845, 33, 39, 15308, 62, 21886, 20520, 796, 705, 5450, 1378, 20688, 13, 785, 14, 6649, 441, 6, 628 ]
2.387097
31
from twisted.protocols import basic from twisted.internet import protocol, reactor reactor.listenTCP(8000, HTTPEchoFactory()) reactor.run()
[ 6738, 19074, 13, 11235, 4668, 82, 1330, 4096, 198, 6738, 19074, 13, 37675, 1330, 8435, 11, 21905, 198, 198, 260, 11218, 13, 4868, 268, 4825, 47, 7, 33942, 11, 14626, 36, 6679, 22810, 28955, 198, 260, 11218, 13, 5143, 3419, 628 ]
3.463415
41
import requests import json import os import time from app01.models import UserTitle # idnaame URL = "https://video.kuaishou.com/graphql" headers = { "accept":"*/*", "Content-Length":"<calculated when request is sent>", "Accept-Encoding": "gzip, deflate", "Connection": "keep-alive", "content-type": "application/json", "Cookie": r'kpf=PC_WEB; kpn=KUAISHOU_VISION; clientid=3; did=web_ec874916e390b9741609686125a0452e; didv=1613879531823; client_key=65890b29; ktrace-context=1|MS43NjQ1ODM2OTgyODY2OTgyLjc1MjgyMjUyLjE2MTU0NDI5NDQ0MzYuMTU2OTE=|MS43NjQ1ODM2OTgyODY2OTgyLjIxMjcxODY4LjE2MTU0NDI5NDQ0MzYuMTU2OTI=|0|graphql-server|webservice|false|NA; userId=427400950; kuaishou.server.web_st=ChZrdWFpc2hvdS5zZXJ2ZXIud2ViLnN0EqABUkHhV7V4kZgEsKH5ujlHNWEHV_KRDoBGhvSztjMMB54VfcpY6EJgzK_b3ZYFhM0obMSTVBDc7Csb-KuDKQpR8sobH5ozd82kEMIV5eb3S0QSJBxAemnSYimqR5IskD_IGA06cph50uA_oH2OftW2tSpaBuXl3vyYhFv6aS_24d8z0n9WILEo5JcTI0QpDdmDoRnXxHc_x7JHIR3s1pBlBhoSzFZBnBL4suA5hQVn0dPKLsMxIiDp66EsPPenAZG6MBgmJkQL2mrCKEDn1OPcTisxS6wffSgFMAE; kuaishou.server.web_ph=cb43dea88ab3a4c31dd231f2dc9cc29b8680', "Host": "video.kuaishou.com", "Origin": "https://video.kuaishou.com", "Referer": "https://video.kuaishou.com/profile/3xsms2z7ft9fmhg", "User-Agent": "PostmanRuntime/7.26.8" } payload = {"operationName":"visionProfileUserList","variables":{"ftype":1},"query":"query visionProfileUserList($pcursor: String, $ftype: Int) {\n visionProfileUserList(pcursor: $pcursor, ftype: $ftype) {\n result\n fols {\n user_name\n headurl\n user_text\n isFollowing\n user_id\n __typename\n }\n hostName\n pcursor\n __typename\n }\n}\n"} if __name__ == "__main__": start_data()
[ 11748, 7007, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 640, 198, 6738, 598, 486, 13, 27530, 1330, 11787, 19160, 198, 2, 4686, 2616, 480, 198, 21886, 796, 366, 5450, 1378, 15588, 13, 74, 6413, 680, 280, 13, 785, 14, 34960, 1397...
1.9129
907
import os import sys this_dir = os.path.dirname(__file__) import numpy as np openpose_path = os.path.join(this_dir, 'openpose') op_release_path = os.path.join(openpose_path, 'Release') model_path = os.path.join(openpose_path, 'models') print(op_release_path) sys.path.append(op_release_path); os.environ['PATH'] = os.environ['PATH'] + ';' + openpose_path + '/x64/Release;' + openpose_path + '/bin;' import pyopenpose as op opWrapper = op.WrapperPython() params = dict() params["model_folder"] = model_path params["number_people_max"] = 1 params["net_resolution"]="-1x160" params["body"] = 1 params["output_resolution"] = "-1x-1" params["disable_multi_thread"] = True opWrapper.configure(params) opWrapper.start()
[ 11748, 28686, 198, 11748, 25064, 198, 5661, 62, 15908, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 8, 198, 198, 11748, 299, 32152, 355, 45941, 198, 9654, 3455, 62, 6978, 796, 28686, 13, 6978, 13, 22179, 7, 5661, 62, 15...
2.729008
262
import pytest import importlib import numba, numba.cuda import numpy as np from pybench import run_benchmark _shapes = { "small": [(int(2 ** 14), 512), (int(2 ** 15), 512), (int(2 ** 16), 512)], "large": [(int(2 ** 20), 512), (int(2 ** 21), 512), (int(2 ** 22), 512)], }
[ 11748, 12972, 9288, 198, 198, 11748, 1330, 8019, 198, 11748, 997, 7012, 11, 997, 7012, 13, 66, 15339, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 12972, 26968, 1330, 1057, 62, 26968, 4102, 198, 198, 62, 1477, 7916, 796, 1391, ...
2.462185
119
def resolve(): ''' code here ''' N , M = [int(item) for item in input().split()] LRs = [[int(item) for item in input().split()] for _ in range(M)] L_max = 0 R_min = N for L, R in LRs: L_max = max(L_max, L) R_min = min(R_min, R) delta = R_min - L_max if delta >= 0: print(delta + 1) else: print(0) if __name__ == "__main__": resolve()
[ 4299, 10568, 33529, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 2438, 994, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 399, 837, 337, 796, 685, 600, 7, 9186, 8, 329, 2378, 287, 5128, 22446, 35312, 3419, 60, 198, 220,...
1.962617
214
# ====================================================================== # Globally useful modules, imported here and then accessible by all # functions in this file: from __future__ import print_function # Fonts, latex: import matplotlib matplotlib.rc('font',**{'family':'serif', 'serif':['TimesNewRoman']}) matplotlib.rc('text', usetex=True) import corner import pylab, sys, numpy as np # ====================================================================== def plot_sample(sample, saveImg=False, fig=None, color='black', parameters=('MAGI','IMSEP','VELDISP','ZLENS','ZSRC')): """ Given an OM10 sample, make a corner plot of the required quantities. Parameters ---------- parameters : str, tuple Names of the lens parameters to plot saveImg : bool If true, save image with standardized name. IQ : float Image quality, for reference. fig : matplotlib figure object Overlay plot on an existing figure Returns ------- fig : matplotlib figure object New or updated figure """ features, labels = extract_features(sample, parameters) if fig is None: fig = corner.corner(features, labels=labels, color=color, smooth=1.0) else: _ = corner.corner(features, labels=labels, color=color, smooth=1.0, fig=fig) for ax in fig.axes: for item in ([ax.xaxis.label, ax.yaxis.label]): item.set_fontsize(20) for item in (ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(16) if saveImg: pngfile = "om10_sample.png" pylab.savefig(pngfile) print("OM10: Sample plot saved to file:", pngfile) return fig # ====================================================================== def extract_features(x, names): """ Given an OM10 table of lenses, extract the required parameters and provide labels for them. Parameters ---------- x : Table OM10 lens sample. names : str, tuple Names of features required. Returns ------- features : float, ndarray Values of requested features, for each lens in the Table labels : str, list Corresponding axis labels """ features = np.array([]) labels = [] p = len(names) n = len(x) for name in names: features = np.append(features, x[name]) labels.append(axis_labels[name]) return features.reshape(p,n).transpose(), labels # ====================================================================== def plot_lens(lens, saveImg=False, IQ=0.7): """ Given an OM10 lens, compute some basic quantities and use them to plot a cartoon visualization of the lens. Parameters ---------- saveImg : bool If true, save image with standardized name. IQ : float Image quality, for reference. """ # # Force matplotlib to not use any Xwindows backend: # if saveImg: # try: matplotlib.use('Agg') # except: pass # else: # try: matplotlib.use('TkAgg') # except: pass # Pull out data for ease of use: id = lens['LENSID'][0] xi = lens['XIMG'][0] yi = lens['YIMG'][0] nim = lens['NIMG'][0] mui = lens['MAG'][0] md = lens['APMAG_I'][0] ms = lens['MAGI_IN'][0] xs = lens['XSRC'][0] ys = lens['YSRC'][0] xd = 0.0 yd = 0.0 zd = lens['ZLENS'][0] zs = lens['ZSRC'][0] q = 1.0 - lens['ELLIP'][0] phi = lens['PHIE'][0] print("OM10: Plotting image configuration of lens ID ",id) # Compute image magnitudes: mi = np.zeros(nim) lfi = np.zeros(nim) for i in range(nim): mi[i] = ms - 2.5*np.log10(np.abs(mui[i])) lfi[i] = 0.4*(24-mi[i]) print("OM10: lens, image magnitudes:",md,mi) lfd = 0.4*(24-md) # print("om10.plot_lens: lens, image log fluxes:",lfd,lfi) # ------------------------------------------------------------------ # Compute caustics and critical curves: # ------------------------------------------------------------------ # Start figure: fig = pylab.figure(figsize=(8,8)) # ,aspect='equal') # Axes limits, useful sizes: xmax = 1.99 dm = 1.0/10 # Plot command sets its own axes. 'bp' = blue pentagons # pylab.plot(xi, yi, 'bp') pylab.plot(xi, yi, color='blue', \ marker='+', markersize=10, markeredgewidth=2, \ linestyle='') pylab.plot(xs, ys, color='lightblue', \ marker='+', markersize=10, markeredgewidth=2, \ linestyle='') pylab.plot(xd, yd, color='orange', \ marker='+', markersize=10, markeredgewidth=2, \ linestyle='') # Ellipse to represent lens brightness: ell = matplotlib.patches.Ellipse((xd,yd), width=2*dm*lfd, height=2*q*dm*lfd, angle=phi, alpha=0.2, fc='orange') pylab.gca().add_patch(ell) # Circles to represent image brightness: for i in range(nim): cir = pylab.Circle((xi[i],yi[i]), radius=dm*lfi[i], alpha=0.2, fc='blue') pylab.gca().add_patch(cir) # Circle to represent seeing: cir = pylab.Circle((1.5,-1.5), radius=IQ/2.0, alpha=0.1, fc='grey') pylab.gca().add_patch(cir) text = '{:3.1f}" seeing'.format(IQ) pylab.annotate(text, (370,5), xytext=None, fontsize=14, \ xycoords='axes points',textcoords='axes points') # Legend giving lens, source redshift: text1 = "$z_d$ = %5.2f" % zd text2 = "$z_s$ = %5.2f" % zs pylab.annotate(text1, (10,430), xytext=None, fontsize=14, \ xycoords='axes points',textcoords='axes points') pylab.annotate(text2, (10,410), xytext=None, fontsize=14, \ xycoords='axes points',textcoords='axes points') # Plot title: title = "OM10 lensed QSO, ID="+str(id) pylab.title(title,fontsize=20) # Set axes labels: pylab.xlabel("x / arcsec",fontsize=20) pylab.ylabel("y / arcsec",fontsize=20) # Set axis limits: pylab.axis([-xmax,xmax,-xmax,xmax]) # Add a grid: pylab.grid(color='grey', linestyle='--', linewidth=0.5) # Plot graph to file: if saveImg: pngfile = "om10_qso_ID="+str(id)+".png" pylab.savefig(pngfile) print("OM10: Lens plot saved to file:",pngfile) # ====================================================================== axis_labels = {} axis_labels['ZLENS'] = '$z_{\\rm d}$' axis_labels['VELDISP'] = '$\sigma_{\\rm d}$ / km/s' axis_labels['ELLIP'] = '$\epsilon_{\\rm d}$' axis_labels['PHIE'] = '$\phi_{\\rm d}$ / km/s' axis_labels['GAMMA'] = '$\gamma$' axis_labels['PHIG'] = '$\phi_{\gamma}$' axis_labels['ZSRC'] = '$z_{\\rm s}$' axis_labels['MAGI'] = '$i_3$' axis_labels['MAGI_IN'] = '$i_{\\rm s}$' axis_labels['IMSEP'] = '$\Delta \\theta$ / arcsec' axis_labels['i_SDSS_lens'] = '$i_{\\rm d}$ (AB mag)' axis_labels['i_SDSS_quasar'] = '$i_{\\rm s}$ (AB mag)' axis_labels['ug'] = '$u-g$ color' axis_labels['gr'] = '$g-r$ color' axis_labels['ri'] = '$r-i$ color' axis_labels['iz'] = '$i-z$ color' axis_labels['ug'] = '$u-g$ color'
[ 2, 38093, 1421, 28, 198, 198, 2, 40713, 453, 4465, 13103, 11, 17392, 994, 290, 788, 9857, 416, 477, 198, 2, 5499, 287, 428, 2393, 25, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 2, 24060, 82, 11, 47038, 25, 198, ...
2.313375
3,073
# -*- coding: utf-8 -*-
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198 ]
1.714286
14
""" Modified version of ../muvm/registers.py. Will update as needed. """ #from rpython.jit.backend.arm.locations import VFPRegisterLocation #from rpython.jit.backend.arm.locations import SVFPRegisterLocation #from rpython.jit.backend.arm.locations import RegisterLocation from rpython.jit.metainterp.history import (Const, ConstInt, ConstFloat, ConstPtr, INT, REF, FLOAT) registers = [] vfpregisters = [] svfpregisters = [] all_regs = [] all_vfp_regs = vfpregisters[] argument_regs = caller_resp = [] callee_resp = [] callee_saved_registers = callee_resp callee_restored_registers = callee_resp vfp_argument_regs = caller_vfp_resp = [] svfp_argument_regs = [] callee_vfp_resp = [] callee_saved_vfp_registers = callee_vfp_resp
[ 37811, 40499, 2196, 286, 11485, 14, 30300, 14761, 14, 2301, 6223, 13, 9078, 13, 2561, 4296, 355, 2622, 13, 198, 37811, 198, 2, 6738, 374, 29412, 13, 45051, 13, 1891, 437, 13, 1670, 13, 17946, 602, 1330, 569, 37, 4805, 1533, 1694, 14...
2.277008
361
""" This file contains code to post data from the database. This is meant to centralize the insertion of data into the database so that multiple apps can call on the methods in this file without having to define their own and to prevent code redundancy. """ from ..models import * from ..utils.common import ensure_required_fields from ..utils.create_factory import CreateFactory
[ 37811, 198, 1212, 2393, 4909, 2438, 284, 1281, 1366, 422, 262, 6831, 13, 220, 770, 318, 4001, 284, 220, 198, 31463, 1096, 262, 36075, 286, 1366, 656, 262, 6831, 523, 326, 3294, 6725, 460, 198, 13345, 319, 262, 5050, 287, 428, 2393, ...
4.23913
92
# this actually won't work with keras... not exactly a keras utility import tensorflow as tf # function is untested
[ 2, 428, 1682, 1839, 470, 670, 351, 41927, 292, 986, 407, 3446, 257, 41927, 292, 10361, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 2, 2163, 318, 1418, 7287 ]
3.866667
30
# coding:utf-8 from __future__ import unicode_literals from __future__ import division from __future__ import print_function import os from src.utils import utils from src.data_generator import vocabulary
[ 2, 19617, 25, 40477, 12, 23, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 28686, 198, 6738, 12351, 13, ...
3.696429
56
from elasticsearch import Elasticsearch # TODO: Not implemented yet es = Elasticsearch(["localhost"], sniff_on_connection_fail=True, sniffer_timeout=60)
[ 6738, 27468, 12947, 1330, 48567, 12947, 198, 198, 2, 16926, 46, 25, 1892, 9177, 1865, 198, 274, 796, 48567, 12947, 7, 14692, 36750, 33116, 26300, 62, 261, 62, 38659, 62, 32165, 28, 17821, 11, 26300, 263, 62, 48678, 28, 1899, 8 ]
3.731707
41
from init import * VOC_CLASSES = [ "background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "potted plant", "sheep", "sofa", "train", "tv/monitor", ] VOC_COLORMAP = [ [0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64, 128], ] palette = np.array(VOC_COLORMAP) custom_transforms = [transforms.Normalize(mean=[-0.485, -0.456,-0.406], std=[1/0.229, 1/0.224,1/0.225])] inv_trans = torchvision.transforms.Compose(custom_transforms) transform = A.Compose([A.Resize(512,512), A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),ToTensorV2() ])
[ 6738, 2315, 1330, 1635, 201, 198, 201, 198, 53, 4503, 62, 31631, 1546, 796, 685, 201, 198, 220, 220, 220, 366, 25249, 1600, 201, 198, 220, 220, 220, 366, 25534, 20106, 1531, 1600, 201, 198, 220, 220, 220, 366, 65, 35298, 1600, 201, ...
1.794258
627
""" A utility function to generate yaml config for SkyQ media players. To support easy usage with other home assistant integrations, e.g. google home """ import os.path as _path import yaml from ..const import CONST_ALIAS_FILENAME
[ 37811, 198, 32, 10361, 2163, 284, 7716, 331, 43695, 4566, 329, 5274, 48, 2056, 1938, 13, 198, 198, 2514, 1104, 2562, 8748, 351, 584, 1363, 8796, 4132, 9143, 11, 304, 13, 70, 13, 23645, 1363, 198, 37811, 198, 11748, 28686, 13, 6978, ...
3.560606
66
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 import datetime import logging from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm from django.core.exceptions import ValidationError from django.forms import CharField from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from django.contrib.auth.models import User, Group from django_digest.models import PartialDigest from django.contrib import messages from django.utils.safestring import mark_safe from django.contrib.admin.views.main import ChangeList from datawinners.common.admin.utils import get_text_search_filter, get_admin_panel_filter from datawinners.project.submission.export import create_excel_response from datawinners.search.index_utils import get_elasticsearch_handle from forms import forms from datawinners.accountmanagement.models import OrganizationSetting, SMSC, PaymentDetails, MessageTracker, Organization, NGOUserProfile, OutgoingNumberSetting from mangrove.form_model.field import ExcelDate from mangrove.utils.types import is_empty, is_not_empty from datawinners.countrytotrialnumbermapping.models import Country, Network from datawinners.utils import get_database_manager_for_org from datawinners.feeds.database import feeds_db_for from django.db.models import Q admin.site.disable_action('delete_selected') def _remove_default_name_fields(): user_display_fields = list(UserAdmin.list_display) user_display_fields.remove('first_name') user_display_fields.remove('last_name') return tuple(user_display_fields) def export_user_list_to_excel(a,b,c): #Custom Method to export user details. list = [] for ngo_user in NGOUserProfile.objects.all(): try: user = User.objects.get(id=ngo_user.user_id) if is_required(user) and not user.is_superuser: details = [] details.append(user.first_name + ' ' + user.last_name) details.append(user.username) org_id = ngo_user.org_id organization = Organization.objects.get(org_id = org_id) details.append(organization.name) details.append(organization.status) details.append(organization.language) details.append(user_role(user)) list.append(details) except Exception: continue headers = ['Name', 'email', 'Organization Name', 'Status', 'Account language','User Role'] response = create_excel_response(headers,list,'user_list') return response admin.site.unregister(Group) admin.site.unregister(User) admin.site.register(OrganizationSetting, OrganizationSettingAdmin) admin.site.register(OutgoingNumberSetting, admin.ModelAdmin) admin.site.register(SMSC, admin.ModelAdmin) admin.site.register(MessageTracker, MessageTrackerAdmin) admin.site.register(Organization, OrganizationAdmin) admin.site.register(Country, CountryAdmin) admin.site.register(Network, NetworkAdmin) admin.site.register(User, DWUserAdmin)
[ 2, 43907, 25, 257, 72, 40379, 28, 19, 39747, 28, 19, 2123, 1509, 28, 19, 21004, 28, 40477, 12, 23, 198, 11748, 4818, 8079, 198, 11748, 18931, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 28482, 1330, 11787, 46787, 198...
2.853296
1,077
import pytest from unittest import mock import os import pathlib
[ 11748, 12972, 9288, 198, 6738, 555, 715, 395, 1330, 15290, 198, 11748, 28686, 198, 11748, 3108, 8019, 628 ]
3.666667
18
# This is mostly a repeat of model.setup from the pygemini repository except for that it setups up a periodic # grid for us in full-globe simulations. from __future__ import annotations import argparse from pathlib import Path import typing as T import shutil import os from gemini3d.config import read_nml import gemini3d.model def model_setup(path: Path | dict[str, T.Any], out_dir: Path, gemini_root: Path = None): """ top-level function to create a new simulation FROM A FILE config.nml Parameters ---------- path: pathlib.Path path (directory or full path) to config.nml out_dir: pathlib.Path directory to write simulation artifacts to """ # %% read config.nml if isinstance(path, dict): cfg = path elif isinstance(path, (str, Path)): cfg = read_nml(path) else: raise TypeError("expected Path to config.nml or dict with parameters") if not cfg: raise FileNotFoundError(f"no configuration found for {out_dir}") cfg["dphi"]=90.0 cfg["out_dir"] = Path(out_dir).expanduser().resolve() if gemini_root: cfg["gemini_root"] = Path(gemini_root).expanduser().resolve(strict=True) for k in {"indat_size", "indat_grid", "indat_file"}: cfg[k] = cfg["out_dir"] / cfg[k] # FIXME: should use is_absolute() ? for k in {"eq_dir", "eq_archive", "E0dir", "precdir"}: if cfg.get(k): cfg[k] = (cfg["out_dir"] / cfg[k]).resolve() # %% copy input config.nml to output dir input_dir = cfg["out_dir"] / "inputs" input_dir.mkdir(parents=True, exist_ok=True) shutil.copy2(cfg["nml"], input_dir) os.environ["GEMINI_ROOT"]="~/libs/bin/" # %% is this equilibrium or interpolated simulation if "eq_dir" in cfg: gemini3d.model.interp(cfg) else: gemini3d.model.equilibrium(cfg)
[ 2, 770, 318, 4632, 257, 9585, 286, 2746, 13, 40406, 422, 262, 12972, 24090, 5362, 16099, 2845, 329, 326, 340, 44266, 510, 257, 27458, 198, 2, 220, 220, 10706, 329, 514, 287, 1336, 12, 4743, 5910, 27785, 13, 220, 220, 198, 6738, 1159...
2.454068
762
import board
[ 11748, 3096, 198 ]
4.333333
3
import wpilib import ctre from wpilib.drive import DifferentialDrive from wpilib.interfaces import GenericHID #MOTOR PORTS LEFT = 1 RIGHT = 3 CENTER1 = 2 CENTER2 = 4 #BALL MANIPULATOR BALL_MANIP_ID = 5 GATHER_SPEED = 1.0 SPIT_SPEED = -1.0 STOP_SPEED = 0.0 LEFT_HAND = GenericHID.Hand.kLeft RIGHT_HAND = GenericHID.Hand.kRight def deadzone(val, deadzone): if abs(val) < deadzone: return 0 elif val < (0): x = ((abs(val) - deadzone)/(1-deadzone)) return (-x) else: x = ((val - deadzone)/(1-deadzone)) return (x) if __name__ == "__main__": wpilib.run(MyRobot)
[ 11748, 266, 79, 22282, 198, 11748, 269, 33945, 198, 6738, 266, 79, 22282, 13, 19472, 1330, 20615, 498, 24825, 198, 6738, 266, 79, 22282, 13, 3849, 32186, 1330, 42044, 39, 2389, 198, 198, 2, 44, 2394, 1581, 350, 33002, 198, 2538, 9792,...
2.142361
288
from . import base from mock import patch import decorators
[ 6738, 764, 1330, 2779, 198, 6738, 15290, 1330, 8529, 198, 11748, 11705, 2024, 198 ]
4.285714
14
import re, operator, array from collections import namedtuple
[ 11748, 302, 11, 10088, 11, 7177, 198, 6738, 17268, 1330, 3706, 83, 29291, 198 ]
4.428571
14
""" Ramsay RSG1000B RF Signal Generator, controlled via RS-323 interface See: Ramsay RSG1000B RF Signal Generator User Guide, p.10-11 Settings: 9600 baud, 8 bits, parity none, stop bits 1, flow control none DB09 connector pin 2 = TxD, 3 = RxD, 5 = Ground The controller accepts unterminate ASCII text commands and generates newline- terminated ASCII text replies. Commands: {255 - Initiate communication by addressing device number 255 (default device number). Reply "\r\n". (Before that command all command with be ignored.) GO - Get " RF ON\r\n" or " RF OFF\r\n" O - Toggle RF on/off, reply: " " Cabling: "Pico8" iMac -> Prolific USB-SErial 2303 cable -> DB--9 female gender changer -> Ramsay RSG1000B RF Signal Generator, DB-9 male serial port Authors: Friedrich Schotte Date created: 2018-01-22 Date last modified: 2018-01-23 """ from logging import error,warn,info,debug __version__ = "1.0" def __query__(self,command,count=None): """Send a command to the controller and return the reply""" from time import time from sleep import sleep sleep(self.last_reply_time + self.wait_time - time()) self.write(command) reply = self.read(count=count) self.last_reply_time = time() return reply def write(self,command): """Send a command to the controller""" if self.port is not None: self.port.write(command) debug("%s: Sent %r" % (self.port.name,command)) def read(self,count=None,port=None): """Read a reply from the controller, count: from non-terminated replies: number of bytes expected If count is None, a newline or carriage return is expected to terminate the reply""" ##debug("read count=%r,port=%r" % (count,port)) if port is None: port = self.port if port is not None: port.timeout = self.timeout if count: #print("in wait:" + str(self.port.inWaiting())) debug("Trying to read %r bytes from %s..." % (count,port.name)) reply = port.read(count) else: debug("Expecting newline terminated reply from %s..." % (port.name)) reply = port.readline() debug("%s: Read %r" % (port.name,reply)) else: reply = "" return reply def init_communications(self): """To do before communncating with the controller""" from os.path import exists from serial import Serial if self.port is not None: try: info("Checking whether device is still responsive...") self.port.write(self.id_query) debug("%s: Sent %r" % (self.port.name,self.id_query)) reply = self.read(count=self.id_reply_length) if not self.id_reply_valid(reply): debug("%s: %r: invalid reply %r" % (self.port.name,self.id_query,reply)) info("%s: lost connection" % self.port.name) self.port = None else: info("Device is still responsive.") except Exception,msg: debug("%s: %s" % (Exception,msg)) self.port = None if self.port is None: port_basenames = ["COM"] if not exists("/dev") \ else ["/dev/tty.usbserial","/dev/ttyUSB"] for i in range(-1,50): for port_basename in port_basenames: port_name = port_basename+("%d" % i if i>=0 else "") ##debug("Trying port %s..." % port_name) try: port = Serial(port_name,baudrate=self.baudrate) port.write(self.id_query) debug("%s: Sent %r" % (port.name,self.id_query)) reply = self.read(count=self.id_reply_length,port=port) if self.id_reply_valid(reply): self.port = port info("Discovered device at %s based on reply %r" % (self.port.name,reply)) break except Exception,msg: debug("%s: %s" % (Exception,msg)) if self.port is not None: break def get_RF_on(self): """Is radiofrequency output enabled?""" debug("Reading radiofrequency output state") reply = self.query("GO") # ' RF OFF\r\n' value = "RF ON" in reply if not "RF " in reply: warn("Reading radiofrequency output state unreadable") from numpy import nan value = nan return value RF_on = property(get_RF_on,set_RF_on) VAL = RF_on Ramsey_RF_driver = RamseyRFDriver() Ramsey_RF_IOC = RamseyRF_IOC() def run_IOC(): """Serve the Ensemble IPAQ up on the network as EPICS IOC""" import logging from tempfile import gettempdir logfile = gettempdir()+"/Ramsey_RF.log" logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s", filename=logfile, ) Ramsey_RF_IOC.run() def alias(name): """Make property given by name be known under a different name""" return property(get,set) from EPICS_motor import EPICS_motor Ramsey_RF_generator = RamseyRF(prefix="NIH:RF",name="Ramsey_RF") def binstr(n): """binary number representation of n""" s = "" for i in range(31,-1,-1): if (n >> i) & 1: s += "1" elif s != "": s += "0" return s if __name__ == "__main__": # for testing from sys import argv if "run_IOC" in argv: run_IOC() from pdb import pm import logging logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s") self = Ramsey_RF_driver # for debugging print('Ramsey_RF_driver.init_communications()') print("Ramsey_RF_driver.port_name") print("Ramsey_RF_driver.RF_on") print("Ramsey_RF_IOC.run()") print("run_IOC()")
[ 37811, 198, 49, 4105, 323, 19340, 38, 12825, 33, 20445, 26484, 35986, 11, 6856, 2884, 19340, 12, 32637, 7071, 198, 6214, 25, 47959, 19340, 38, 12825, 33, 20445, 26484, 35986, 11787, 10005, 11, 279, 13, 940, 12, 1157, 198, 198, 26232, ...
2.21547
2,715
import json def save_json(dict_, json_filepath): ''' [Example] Write JSON ''' ''' dict_ = {"0":{"title":"test-A", "is-available": False, "link":"https://www.AAA.XXX..."}, "1":{"title":"test-B", "is-available": True, "link":"https://www.BBB.XXX..."}} with open("dict_.txt", 'w') as output_file: json.dump(dict_, output_file) ''' with open(json_filepath, 'w') as output_file: json.dump(dict_, output_file) def load_json(json_filepath): ''' [Example] Read JSON ''' ''' with open("dict_.txt", 'r') as json_file: dict_ = json.load(json_file) print(dict_) print(type(dict_)) ''' with open(json_filepath, 'r') as json_file: dict_ = json.load(json_file) #print(dict_) #print(type(dict_)) return dict_
[ 11748, 33918, 198, 198, 4299, 3613, 62, 17752, 7, 11600, 62, 11, 33918, 62, 7753, 6978, 2599, 198, 220, 220, 220, 705, 7061, 685, 16281, 60, 19430, 19449, 705, 7061, 198, 220, 220, 220, 705, 7061, 198, 220, 220, 220, 8633, 62, 796, ...
2.184
375
# GUI Application automation and testing library # Copyright (C) 2006 Mark Mc Mahon # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation; either version 2.1 # of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place, # Suite 330, # Boston, MA 02111-1307 USA "Module to find the closest match of a string in a list" __revision__ = "$Revision: 679 $" import re import difflib from . import fuzzydict #import ctypes #import ldistance #levenshtein_distance = ctypes.cdll.levenshtein.levenshtein_distance #levenshtein_distance = ldistance.distance # need to use sets.Set for python 2.3 compatability # but 2.6 raises a deprecation warning about sets module try: set except NameError: import sets set = sets.Set find_best_control_match_cutoff = .6 #==================================================================== _cache = {} # given a list of texts return the match score for each # and the best score and text with best score #==================================================================== def _get_match_ratios(texts, match_against): "Get the match ratio of how each item in texts compared to match_against" # now time to figre out the matching ratio_calc = difflib.SequenceMatcher() ratio_calc.set_seq1(match_against) ratios = {} best_ratio = 0 best_text = '' global cache for text in texts: if 0: pass if (text, match_against) in _cache: ratios[text] = _cache[(text, match_against)] elif(match_against, text) in _cache: ratios[text] = _cache[(match_against, text)] else: # set up the SequenceMatcher with other text ratio_calc.set_seq2(text) # try using the levenshtein distance instead #lev_dist = levenshtein_distance(unicode(match_against), unicode(text)) #ratio = 1 - lev_dist / 10.0 #ratios[text] = ratio # calculate ratio and store it ratios[text] = ratio_calc.ratio() _cache[(match_against, text)] = ratios[text] # if this is the best so far then update best stats if ratios[text] > best_ratio: best_ratio = ratios[text] best_text = text return ratios, best_ratio, best_text #==================================================================== def find_best_match(search_text, item_texts, items, limit_ratio = .5): """Return the item that best matches the search_text * **search_text** The text to search for * **item_texts** The list of texts to search through * **items** The list of items corresponding (1 to 1) to the list of texts to search through. * **limit_ratio** How well the text has to match the best match. If the best match matches lower then this then it is not considered a match and a MatchError is raised, (default = .5) """ search_text = _cut_at_tab(search_text) text_item_map = UniqueDict() # Clean each item, make it unique and map to # to the item index for text, item in zip(item_texts, items): text_item_map[_cut_at_tab(text)] = item ratios, best_ratio, best_text = \ _get_match_ratios(list(text_item_map.keys()), search_text) if best_ratio < limit_ratio: raise MatchError(items = list(text_item_map.keys()), tofind = search_text) return text_item_map[best_text] #==================================================================== _after_tab = re.compile(r"\t.*", re.UNICODE) _non_word_chars = re.compile(r"\W", re.UNICODE) def _cut_at_tab(text): "Clean out non characters from the string and return it" # remove anything after the first tab return _after_tab.sub("", text) def _clean_non_chars(text): "Remove non word characters" # should this also remove everything after the first tab? # remove non alphanumeric characters return _non_word_chars.sub("", text) def IsAboveOrToLeft(ref_control, other_ctrl): "Return true if the other_ctrl is above or to the left of ref_control" text_r = other_ctrl.Rectangle() ctrl_r = ref_control.Rectangle() # skip controls where text win is to the right of ctrl if text_r.left >= ctrl_r.right: return False # skip controls where text win is below ctrl if text_r.top >= ctrl_r.bottom: return False # text control top left corner is below control # top left corner - so not to the above or left :) if text_r.top >= ctrl_r.top and text_r.left >= ctrl_r.left: return False return True #==================================================================== distance_cuttoff = 999 def GetNonTextControlName(ctrl, controls): """return the name for this control by finding the closest text control above and to its left""" names = [] ctrl_index = controls.index(ctrl) if ctrl_index != 0: prev_ctrl = controls[ctrl_index-1] if prev_ctrl.FriendlyClassName() == "Static" and \ prev_ctrl.IsVisible() and prev_ctrl.WindowText() and \ IsAboveOrToLeft(ctrl, prev_ctrl): names.append( prev_ctrl.WindowText() + ctrl.FriendlyClassName()) # get the visible text controls so that we can get # the closest text if the control has no text text_ctrls = [ctrl_ for ctrl_ in controls if ctrl_.IsVisible() and ctrl_.WindowText() and ctrl_.can_be_label] best_name = '' closest = distance_cuttoff # now for each of the visible text controls for text_ctrl in text_ctrls: # get aliases to the control rectangles text_r = text_ctrl.Rectangle() ctrl_r = ctrl.Rectangle() # skip controls where text win is to the right of ctrl if text_r.left >= ctrl_r.right: continue # skip controls where text win is below ctrl if text_r.top >= ctrl_r.bottom: continue # calculate the distance between the controls # at first I just calculated the distance from the top let # corner of one control to the top left corner of the other control # but this was not best, so as a text control should either be above # or to the left of the control I get the distance between # the top left of the non text control against the # Top-Right of the text control (text control to the left) # Bottom-Left of the text control (text control above) # then I get the min of these two # We do not actually need to calculate the difference here as we # only need a comparative number. As long as we find the closest one # the actual distance is not all that important to us. # this reduced the unit tests run on my by about 1 second # (from 61 ->60 s) # (x^2 + y^2)^.5 #distance = ( # (text_r.left - ctrl_r.left) ** 2 + # (x^2 + y^2) # (text_r.bottom - ctrl_r.top) ** 2) \ # ** .5 # ^.5 #distance2 = ( # (text_r.right - ctrl_r.left) ** 2 + # (x^2 + y^2) # (text_r.top - ctrl_r.top) ** 2) \ # ** .5 # ^.5 distance = abs(text_r.left - ctrl_r.left) + abs(text_r.bottom - ctrl_r.top) distance2 = abs(text_r.right - ctrl_r.left) + abs(text_r.top - ctrl_r.top) distance = min(distance, distance2) # if this distance was closer then the last one if distance < closest: closest = distance best_name = text_ctrl.WindowText() + ctrl.FriendlyClassName() names.append(best_name) return names #==================================================================== def get_control_names(control, allcontrols): "Returns a list of names for this control" names = [] # if it has a reference control - then use that #if hasattr(control, 'ref') and control.ref: # control = control.ref # Add the control based on it's friendly class name names.append(control.FriendlyClassName()) # if it has some character text then add it base on that # and based on that with friendly class name appended cleaned = control.WindowText() # Todo - I don't like the hardcoded classnames here! if cleaned and control.has_title: names.append(cleaned) names.append(cleaned + control.FriendlyClassName()) # it didn't have visible text else: # so find the text of the nearest text visible control non_text_names = GetNonTextControlName(control, allcontrols) # and if one was found - add it if non_text_names: names.extend(non_text_names) # return the names - and make sure there are no duplicates return set(names) #==================================================================== #==================================================================== def build_unique_dict(controls): """Build the disambiguated list of controls Separated out to a different function so that we can get the control identifiers for printing. """ name_control_map = UniqueDict() # collect all the possible names for all controls # and build a list of them for ctrl in controls: ctrl_names = get_control_names(ctrl, controls) # for each of the names for name in ctrl_names: name_control_map[name] = ctrl return name_control_map #==================================================================== def find_best_control_matches(search_text, controls): """Returns the control that is the the best match to search_text This is slightly differnt from find_best_match in that it builds up the list of text items to search through using information from each control. So for example for there is an OK, Button then the following are all added to the search list: "OK", "Button", "OKButton" But if there is a ListView (which do not have visible 'text') then it will just add "ListView". """ name_control_map = build_unique_dict(controls) # # collect all the possible names for all controls # # and build a list of them # for ctrl in controls: # ctrl_names = get_control_names(ctrl, controls) # # # for each of the names # for name in ctrl_names: # name_control_map[name] = ctrl search_text = str(search_text) best_ratio, best_texts = name_control_map.FindBestMatches(search_text) best_ratio_ci, best_texts_ci = \ name_control_map.FindBestMatches(search_text, ignore_case = True) best_ratio_clean, best_texts_clean = \ name_control_map.FindBestMatches(search_text, clean = True) best_ratio_clean_ci, best_texts_clean_ci = \ name_control_map.FindBestMatches( search_text, clean = True, ignore_case = True) if best_ratio_ci > best_ratio: best_ratio = best_ratio_ci best_texts = best_texts_ci if best_ratio_clean > best_ratio: best_ratio = best_ratio_clean best_texts = best_texts_clean if best_ratio_clean_ci > best_ratio: best_ratio = best_ratio_clean_ci best_texts = best_texts_clean_ci if best_ratio < find_best_control_match_cutoff: raise MatchError(items = list(name_control_map.keys()), tofind = search_text) return [name_control_map[best_text] for best_text in best_texts] # #def GetControlMatchRatio(text, ctrl): # # get the texts for the control # ctrl_names = get_control_names(ctrl) # # #get the best match for these # matcher = UniqueDict() # for name in ctrl_names: # matcher[name] = ctrl # # best_ratio, unused = matcher.FindBestMatches(text) # # return best_ratio # # # #def get_controls_ratios(search_text, controls): # name_control_map = UniqueDict() # # # collect all the possible names for all controls # # and build a list of them # for ctrl in controls: # ctrl_names = get_control_names(ctrl) # # # for each of the names # for name in ctrl_names: # name_control_map[name] = ctrl # # match_ratios, best_ratio, best_text = \ # _get_match_ratios(name_control_map.keys(), search_text) # # return match_ratios, best_ratio, best_text,
[ 2, 25757, 15678, 22771, 290, 4856, 5888, 201, 198, 2, 15069, 357, 34, 8, 4793, 2940, 1982, 8882, 261, 201, 198, 2, 201, 198, 2, 770, 5888, 318, 1479, 3788, 26, 345, 460, 17678, 4163, 340, 290, 14, 273, 201, 198, 2, 13096, 340, 7...
2.523203
5,258
from setuptools import setup, find_packages exclude_dirs = ['ez_setup', 'examples', 'tests', 'venv'] # Runtime requirements reqs = [ 'requests', 'six', 'future', 'aenum' ] # Requirements for testing test_reqs = ['pytest', 'hypothesis', 'requests_mock'] # Requirements for setup setup_reqs = ['flake8', 'pep8', 'pytest-runner'] setup( name='fabricate-it', version='1.1.0', author='Brett Levenson', author_email='blevenson@apple.com', description='A library that makes creating API clients simple and declarative', url='https://github.com/boichee/fabricator', packages=find_packages(exclude=exclude_dirs), install_requires=reqs, tests_require=test_reqs, setup_requires=setup_reqs, classifiers=[ 'Development Status :: 4 - Beta', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Topic :: Software Development', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.6', 'Intended Audience :: Developers' ] )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 1069, 9152, 62, 15908, 82, 796, 37250, 8471, 62, 40406, 3256, 705, 1069, 12629, 3256, 705, 41989, 3256, 705, 574, 85, 20520, 198, 198, 2, 43160, 5359, 198, 42180, 82,...
2.57554
417
s3_available_options = ['s3', 'aws_s3', 'aws'] gcs_available_options = ['gcs', 'google_storage', 'google storage']
[ 82, 18, 62, 15182, 62, 25811, 796, 37250, 82, 18, 3256, 705, 8356, 62, 82, 18, 3256, 705, 8356, 20520, 198, 70, 6359, 62, 15182, 62, 25811, 796, 37250, 70, 6359, 3256, 705, 13297, 62, 35350, 3256, 705, 13297, 6143, 20520, 198 ]
2.738095
42
from __future__ import print_function, division if __name__=='__main__': from cc_weights import Weight_model else: from . import Weight_model from keras.models import load_model import keras.backend as K import plotload import sys from selector import Selector #from masker import mask_from_template,mask_randomly_square,mask_green_corner,combine_imgs_with_mask import masker as ms import matplotlib.pyplot as plt import numpy as np from tqdm import tqdm import cutter import masker if __name__ == '__main__': cc = CCgan(256,256) #cc.build_model() #cc.train_model() cc.load_model() #cc.load_model_weights() w=cc.build_wrapper() root='/home/mathias/Documents/kvasir-dataset-v2/med/' cc.sort_folder(w,path=root) cc.sort_folder(w,path='/media/mathias/A_New_Hope/medico_test/')
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 11, 7297, 198, 361, 11593, 3672, 834, 855, 6, 834, 12417, 834, 10354, 198, 220, 220, 220, 422, 36624, 62, 43775, 1330, 14331, 62, 19849, 198, 17772, 25, 198, 220, 220, 220, 422, 764, 13...
2.520833
336
# -*- coding: utf-8 -*- # Copyright 2014 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This file provides some classes for setting up (partially-populated) # homeservers; either as a full homeserver as a real application, or a small # partial one for unit test mocking. # Imports required for the default HomeServer() implementation from synapse.federation import initialize_http_replication from synapse.api.events import serialize_event from synapse.api.events.factory import EventFactory from synapse.notifier import Notifier from synapse.api.auth import Auth from synapse.handlers import Handlers from synapse.rest import RestServletFactory from synapse.state import StateHandler from synapse.storage import DataStore from synapse.types import UserID, RoomAlias, RoomID from synapse.util import Clock from synapse.util.distributor import Distributor from synapse.util.lockutils import LockManager from synapse.streams.events import EventSources from synapse.api.ratelimiting import Ratelimiter def parse_roomalias(self, s): """Parse the string given by 's' as a Room Alias and return a RoomAlias object.""" return RoomAlias.from_string(s, hs=self) def parse_roomid(self, s): """Parse the string given by 's' as a Room ID and return a RoomID object.""" return RoomID.from_string(s, hs=self) # Build magic accessors for every dependency for depname in BaseHomeServer.DEPENDENCIES: BaseHomeServer._make_dependency_method(depname)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 1946, 4946, 27470, 12052, 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, ...
3.411168
591
from pythonforandroid.toolchain import CythonRecipe, shprint, current_directory, ArchAndroid from os.path import exists, join import sh import glob recipe = KivyRecipe()
[ 198, 6738, 21015, 1640, 19411, 13, 25981, 7983, 1330, 327, 7535, 37523, 11, 427, 4798, 11, 1459, 62, 34945, 11, 5579, 25934, 198, 6738, 28686, 13, 6978, 1330, 7160, 11, 4654, 198, 11748, 427, 198, 11748, 15095, 628, 198, 198, 29102, 4...
3.55102
49
import random import json import torch from model import NeuralNet from nltk_utils import * device = "cuda" with open('intents.json','r') as f: intents = json.load(f) FILE = 'data.pth' data = torch.load(FILE) input_size = data['input_size'] output_size = data['output_size'] hidden_size = data['hidden_size'] all_words = data['all_words'] tags = data['tags'] model_state = data['model_state'] model = NeuralNet(input_size, hidden_size, output_size).to(device) model.load_state_dict(model_state) model.eval() bot_name = 'Programmer-RD-AI' print('Lets chat ! type "quit" to exit') while True: sentence = input('You : ') if sentence == 'quit': break sentence = tokenize(sentence) X = bag_of_words(sentence,all_words) X = X.reshape(1,X.shape[0]) X = torch.from_numpy(X).to(device) pred = model(X) pred_ = pred.clone() _,pred = torch.max(pred,dim=1) tag = tags[pred.item()] probs = torch.softmax(pred_,dim=1) prob = probs[0][pred.item()] if prob.item() > 0.75: for intent in intents['intents']: if tag == intent['tag']: print(f'{bot_name}: {random.choice(intent["responses"])}') else: print(f'{bot_name}: IDK..')
[ 11748, 4738, 198, 11748, 33918, 198, 11748, 28034, 198, 6738, 2746, 1330, 47986, 7934, 198, 6738, 299, 2528, 74, 62, 26791, 1330, 1635, 198, 25202, 796, 366, 66, 15339, 1, 198, 4480, 1280, 10786, 600, 658, 13, 17752, 41707, 81, 11537, ...
2.382813
512
# -*- utf-8 -*- import random import redis import requests # GetIps()
[ 2, 532, 9, 12, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 4738, 198, 11748, 2266, 271, 198, 11748, 7007, 198, 198, 2, 3497, 40, 862, 3419, 198 ]
2.448276
29
# -*- coding: utf-8 -*- import setuptools setuptools.setup( name='ftpservercontext', version='2018.3.0', license='commercial', author='Thomas Guettler', author_email='guettliml.ftpservercontext@thomas-guettler.de', url='https://github.com/tbz-pariv/ftpservercontext', long_description=open('README.rst').read(), packages=setuptools.find_packages(), zip_safe = False, # https://www.tbz-pariv.lan/index.html/doku.php?id=python_packages#requirementstxt_vs_install_requires # All reusable libraries use install_requires. # Projects (containing only config) can use requirements.txt install_requires=[ 'pyftpdlib', ], include_package_data=True, entry_points={ 'console_scripts': [ 'serve_directory_via_ftp=ftpservercontext.console_scripts:serve_directory_via_ftp', ], } )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 900, 37623, 10141, 628, 198, 2617, 37623, 10141, 13, 40406, 7, 198, 220, 220, 220, 1438, 11639, 701, 862, 18497, 22866, 3256, 198, 220, 220, 220, 2196, 11639, 790...
2.474576
354
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ * Filename: cli.py * Description: cli program entry * Time: 2020.11.30 * Author: liuf5 */ """ import os import sys import argparse module_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.insert(1, module_path) from zoomeye import core def main(): """ parse user input args :return: """ parser = ZoomEyeParser() subparsers = parser.add_subparsers() # zoomeye account info parser_info = subparsers.add_parser("info", help="Show ZoomEye account info") parser_info.set_defaults(func=core.info) # query zoomeye data parser_search = subparsers.add_parser( "search", help="Search the ZoomEye database" ) parser_search.add_argument( "dork", help="The ZoomEye search keyword or ZoomEye exported file" ) parser_search.add_argument( "-num", default=20, help="The number of search results that should be returned", type=int, metavar='value' ) parser_search.add_argument( "-facet", default=None, nargs='?', const='app,device,service,os,port,country,city', type=str, help=(''' Perform statistics on ZoomEye database, field: [app,device,service,os,port,country,city] '''), metavar='field' ) parser_search.add_argument( "-filter", default=None, metavar='field=regexp', nargs='?', const='app', type=str, help=(''' Output more clearer search results by set filter field, field: [app,version,device,port,city,country,asn,banner,*] ''') ) parser_search.add_argument( '-stat', default=None, metavar='field', nargs='?', const='app,device,service,os,port,country,city', type=str, help=(''' Perform statistics on search results, field: [app,device,service,os,port,country,city] ''') ) parser_search.add_argument( "-save", default=None, metavar='field=regexp', help=(''' Save the search results with ZoomEye json format, if you specify the field, it will be saved with JSON Lines '''), nargs='?', type=str, const='all' ) parser_search.add_argument( "-count", help="The total number of results in ZoomEye database for a search", action="store_true" ) parser_search.set_defaults(func=core.search) # initial account configuration related commands parser_init = subparsers.add_parser("init", help="Initialize the token for ZoomEye-python") parser_init.add_argument("-apikey", help="ZoomEye API Key", default=None, metavar='[api key]') parser_init.add_argument("-username", help="ZoomEye account username", default=None, metavar='[username]') parser_init.add_argument("-password", help="ZoomEye account password", default=None, metavar='[password]') parser_init.set_defaults(func=core.init) args = parser.parse_args() try: args.func(args) except AttributeError: parser.print_help() if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 9, 7066, 12453, 25, 537, 72, 13, 9078, 198, 9, 12489, 25, 537, 72, 1430, 5726, 198, 9, 3862, ...
2.26525
1,459
import scipy.stats as stats def mannwhitneyu(sample_0, sample_1, one_sided=False): """ Performs the Mann-Whitney U test :param sample_0: array of values :param sample_1: array of values :param one_sided: True iff you want to use less than alternative hypothesis :return: statistic, pvalue """ res = stats.mannwhitneyu(sample_0, sample_1, alternative="two-sided" if not one_sided else "less") return res.statistic, res.pvalue
[ 11748, 629, 541, 88, 13, 34242, 355, 9756, 628, 198, 4299, 582, 77, 1929, 270, 1681, 84, 7, 39873, 62, 15, 11, 6291, 62, 16, 11, 530, 62, 22339, 28, 25101, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 2448, 23914, 262, 2...
2.817073
164
import cv2 as cv if __name__ == "__main__": # 0 => first (default) webcam connected, # 1 => second webcam and so on. cap = cv.VideoCapture(0, cv.CAP_DSHOW) # cv.namedWindow("Window") if not cap.isOpened(): raise IOError("Webcam could not be opened!") while True: res, frame = cap.read() # returns (bool, ndarray) # in case any error occurs if not res: break frame = cv.resize(frame, None, fx=.5, fy=.5) cv.imshow("Video Stream", frame) keyboardInput = cv.waitKey(1) if keyboardInput == 27: # ESC button ascii code break cap.release() cv.destroyAllWindows() # you can also replace a normal video with webcam # in video capture object, just give it the address of # the video instead of 0 or number of your webcam
[ 11748, 269, 85, 17, 355, 269, 85, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 220, 198, 220, 220, 220, 1303, 657, 5218, 717, 357, 12286, 8, 49823, 5884, 11, 198, 220, 220, 220, 1303, 352,...
2.348774
367
import datetime from current_user.models import CurrentUserField from django.conf import settings from django.db import models from django.urls import reverse from django.utils.timezone import now from django.utils.translation import gettext_lazy as _ from sso.accounts.models import Application from sso.models import AbstractBaseModel, AbstractBaseModelManager from sso.organisations.models import is_validation_period_active, Organisation
[ 11748, 4818, 8079, 198, 198, 6738, 1459, 62, 7220, 13, 27530, 1330, 9236, 12982, 15878, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 19...
3.878261
115
import os from time import time import numpy as np import soundfile from matplotlib import pyplot as plt from wavelet.fast_transform import FastWaveletTransform from wavelet.util.utility import threshold, mad, snr, amp_to_db INPUT_FILE = "/example/input/file.wav" OUTPUT_DIR = "/example/output/" info = soundfile.info(INPUT_FILE) # getting info of the audio rate = info.samplerate WAVELET_NAME = "coif1" t = FastWaveletTransform(WAVELET_NAME) outputFileName = os.path.join(OUTPUT_DIR, "_" + WAVELET_NAME + ".wav") noiseRatios = list() with soundfile.SoundFile(outputFileName, "w", samplerate=rate, channels=info.channels) as of: start = time() for block in soundfile.blocks(INPUT_FILE, int(rate * info.duration * 0.10)): # reading 10 % of duration coefficients = t.waveDec(block) # VISU Shrink sigma = mad(coefficients) thresh = sigma * np.sqrt(2 * np.log(len(block))) # thresholding using the noise threshold generated coefficients = threshold(coefficients, thresh) # getting the clean signal as in original form and writing to the file clean = t.waveRec(coefficients) clean = np.asarray(clean) of.write(clean) noiseRatios.append(snr(amp_to_db(clean))) end = time() x = [] for i in range(len(noiseRatios)): x.append(i) plt.plot(x, np.array(noiseRatios).astype(float)) plt.show() print(f"Finished processing with {WAVELET_NAME}") print(f"Time taken :: {end - start} s")
[ 11748, 28686, 198, 6738, 640, 1330, 640, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2128, 7753, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 198, 198, 6738, 6769, 1616, 13, 7217, 62, 35636, 1330, 12549, 3970...
2.581633
588
# -*- coding: utf-8 -*- from pynput import keyboard from PyQt5.QtCore import QThread, pyqtSignal
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 279, 2047, 1996, 1330, 10586, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 14055, 1330, 1195, 16818, 11, 12972, 39568, 11712, 282, 628 ]
2.512821
39
""" Commands and operators used by NAD. CMDS[domain][function] """ CMDS = { 'main': { 'dimmer': {'cmd': 'Main.Dimmer', 'supported_operators': ['+', '-', '=', '?'] }, 'mute': {'cmd': 'Main.Mute', 'supported_operators': ['+', '-', '=', '?'] }, 'power': {'cmd': 'Main.Power', 'supported_operators': ['+', '-', '=', '?'] }, 'volume': {'cmd': 'Main.Volume', 'supported_operators': ['+', '-', '=', '?'] }, 'ir': {'cmd': 'Main.IR', 'supported_operators': ['='] }, 'listeningmode': {'cmd': 'Main.ListeningMode', 'supported_operators': ['+', '-'] }, 'sleep': {'cmd': 'Main.Sleep', 'supported_operators': ['+', '-'] }, 'source': {'cmd': 'Main.Source', 'supported_operators': ['+', '-', '=', '?'] }, 'version': {'cmd': 'Main.Version', 'supported_operators': ['?'] } }, 'tuner': { 'am_frequency': {'cmd': 'Tuner.AM.Frequency', 'supported_operators': ['+', '-'] }, 'am_preset': {'cmd': 'Tuner.AM.Preset', 'supported_operators': ['+', '-', '=', '?'] }, 'band': {'cmd': 'Tuner.Band', 'supported_operators': ['+', '-', '=', '?'] }, 'fm_frequency': {'cmd': 'Tuner.FM.Frequency', 'supported_operators': ['+', '-'] }, 'fm_mute': {'cmd': 'Tuner.FM.Mute', 'supported_operators': ['+', '-', '=', '?'] }, 'fm_preset': {'cmd': 'Tuner.FM.Preset', 'supported_operators': ['+', '-', '=', '?'] } } }
[ 37811, 198, 6935, 1746, 290, 12879, 973, 416, 49204, 13, 198, 198, 24187, 5258, 58, 27830, 7131, 8818, 60, 198, 37811, 198, 24187, 5258, 796, 1391, 198, 220, 220, 220, 705, 12417, 10354, 198, 220, 220, 220, 220, 220, 220, 220, 1391, ...
1.520678
1,475
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'addsite.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 5178, 7822, 7560, 422, 3555, 334, 72, 2393, 705, 2860, 15654, 13, 9019, 6, 198, 2, 198, 2, 15622, 416, 25, 9485, 48, 83, 20, 12454, 2438, 17301, 642, 13, 2...
2.855422
83
from enum import Enum, auto
[ 6738, 33829, 1330, 2039, 388, 11, 8295, 198 ]
3.5
8
""" In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data. You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively. The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were. If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. Example 1: Input: nums = [[1, 2], [3, 4]] r = 1, c = 4 Output: [[1, 2, 3, 4]] Explanation: The row-traversing of nums is [1, 2, 3, 4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list. Example 2: Input: nums = [[1, 2], [3, 4]] r = 2, c = 4 Output: [[1, 2], [3, 4]] Explanation: There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix. Note: 1. The height and width of the given matrix is in range [1, 100]. 2. The given r and c are all positive. """
[ 37811, 198, 818, 36775, 48780, 11, 612, 318, 257, 845, 4465, 2163, 1444, 705, 3447, 1758, 3256, 543, 460, 27179, 1758, 257, 17593, 656, 220, 198, 64, 649, 530, 351, 1180, 2546, 475, 1394, 663, 2656, 1366, 13, 921, 821, 1813, 257, 17...
2.878995
438
#!/usr/bin/env python3 import socket import select from time import sleep import message_pb2 from google.protobuf.internal import encoder import tensorflow as tf from tensorflow.keras import preprocessing import pickle import numpy as np ## RNN part # Load the inference model # Load the tokenizer # Talking with our Chatbot ### END RNN PART ### PORT = 9987 if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 11748, 17802, 198, 11748, 2922, 198, 6738, 640, 1330, 3993, 198, 11748, 3275, 62, 40842, 17, 198, 6738, 23645, 13, 11235, 672, 3046, 13, 32538, 1330, 2207, 12342, 198, 11748, 11192, ...
3.2
125
"""JSON implementations of authorization sessions.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowed in package json package scope # pylint: disable=too-many-ancestors # Inheritance defined in specification from bson.objectid import ObjectId from . import objects from . import queries from .. import utilities from ..id.objects import IdList from ..osid import sessions as osid_sessions from ..osid.sessions import OsidSession from ..primitives import DateTime from ..primitives import Id from ..primitives import Type from ..utilities import JSONClientValidated from ..utilities import PHANTOM_ROOT_IDENTIFIER from ..utilities import overlap from dlkit.abstract_osid.authorization import sessions as abc_authorization_sessions from dlkit.abstract_osid.authorization.objects import AuthorizationForm as ABCAuthorizationForm from dlkit.abstract_osid.authorization.objects import VaultForm as ABCVaultForm from dlkit.abstract_osid.id.primitives import Id as ABCId from dlkit.abstract_osid.osid import errors from dlkit.abstract_osid.type.primitives import Type as ABCType DESCENDING = -1 ASCENDING = 1 CREATED = True UPDATED = True ENCLOSURE_RECORD_TYPE = Type( identifier='enclosure', namespace='osid-object', authority='ODL.MIT.EDU') COMPARATIVE = 0 PLENARY = 1 authorizations = property(fget=get_authorizations) class AuthorizationQuerySession(abc_authorization_sessions.AuthorizationQuerySession, osid_sessions.OsidSession): """This session provides methods for searching ``Authorization`` objects. The search query is constructed using the ``AuthorizationQuery``. This session defines views that offer differing behaviors for searching. * federated view: searches include authorizations in ``Vaults`` of which this vault is a ancestor in the vault hierarchy * isolated view: searches are restricted to authorizations in this ``Vault`` * implicit authorization view: authorizations include implicit authorizations * explicit authorization view: only explicit authorizations are returned """ def get_vault_id(self): """Gets the ``Vault`` ``Id`` associated with this session. return: (osid.id.Id) - the ``Vault Id`` associated with this session *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceLookupSession.get_bin_id return self._catalog_id vault_id = property(fget=get_vault_id) def get_vault(self): """Gets the ``Vault`` associated with this session. return: (osid.authorization.Vault) - the ``Vault`` associated with this session raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceLookupSession.get_bin return self._catalog vault = property(fget=get_vault) def can_search_authorizations(self): """Tests if this user can perform authorization searches. A return of true does not guarantee successful authorization. A return of false indicates that it is known all methods in this session will result in a ``PermissionDenied``. This is intended as a hint to an application that may opt not to offer search operations to unauthorized users. return: (boolean) - ``false`` if search methods are not authorized, ``true`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceQuerySession.can_search_resources # NOTE: It is expected that real authentication hints will be # handled in a service adapter above the pay grade of this impl. return True def use_federated_vault_view(self): """Federates the view for methods in this session. A federated view will include authorizations in vaults which are children of this vault in the vault hierarchy. *compliance: mandatory -- This method is must be implemented.* """ # Implemented from template for # osid.resource.ResourceLookupSession.use_federated_bin_view self._use_federated_catalog_view() def use_isolated_vault_view(self): """Isolates the view for methods in this session. An isolated view restricts searches to this vault only. *compliance: mandatory -- This method is must be implemented.* """ # Implemented from template for # osid.resource.ResourceLookupSession.use_isolated_bin_view self._use_isolated_catalog_view() def use_implicit_authorization_view(self): """Sets the view for methods in this session to implicit authorizations. An implicit view will include authorizations derived from other authorizations as a result of the ``Qualifier,`` ``Function`` or ``Resource`` hierarchies. This method is the opposite of ``explicit_aut`` *compliance: mandatory -- This method is must be implemented.* """ raise errors.Unimplemented() def use_explicit_authorization_view(self): """Sets the view for methods in this session to explicit authorizations. An explicit view includes only those authorizations that were explicitly defined and not implied. This method is the opposite of ``implicitAuthorizationView()``. *compliance: mandatory -- This method is must be implemented.* """ raise errors.Unimplemented() def get_authorization_query(self): """Gets an authorization query. return: (osid.authorization.AuthorizationQuery) - the authorization query *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceQuerySession.get_resource_query_template return queries.AuthorizationQuery(runtime=self._runtime) authorization_query = property(fget=get_authorization_query) def can_delete_authorizations(self): """Tests if this user can delete ``Authorizations``. A return of true does not guarantee successful authorization. A return of false indicates that it is known deleting an ``Authorization`` will result in a ``PermissionDenied``. This is intended as a hint to an application that may opt not to offer delete operations to an unauthorized user. return: (boolean) - ``false`` if ``Authorization`` deletion is not authorized, ``true`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceAdminSession.can_delete_resources # NOTE: It is expected that real authentication hints will be # handled in a service adapter above the pay grade of this impl. return True def can_manage_authorization_aliases(self): """Tests if this user can manage ``Id`` aliases for ``Authorizations``. A return of true does not guarantee successful authorization. A return of false indicates that it is known changing an alias will result in a ``PermissionDenied``. This is intended as a hint to an application that may opt not to offer alias operations to an unauthorized user. return: (boolean) - ``false`` if ``Authorization`` aliasing is not authorized, ``true`` otherwise *compliance: mandatory -- This method must be implemented.* """ # NOTE: It is expected that real authentication hints will be # handled in a service adapter above the pay grade of this impl. return True vaults = property(fget=get_vaults) class VaultQuerySession(abc_authorization_sessions.VaultQuerySession, osid_sessions.OsidSession): """This session provides methods for searching among ``Vault`` objects. The search query is constructed using the ``VaultQuery``. Vaults may have a query record indicated by their respective record types. The query record is accessed via the ``VaultQuery``. """ _session_namespace = 'authorization.VaultQuerySession' def can_search_vaults(self): """Tests if this user can perform ``Vault`` searches. A return of true does not guarantee successful authorization. A return of false indicates that it is known all methods in this session will result in a ``PermissionDenied``. This is intended as a hint to an application that may opt not to offer search operations to unauthorized users. return: (boolean) - ``false`` if search methods are not authorized, ``true`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.BinQuerySession.can_search_bins_template # NOTE: It is expected that real authentication hints will be # handled in a service adapter above the pay grade of this impl. return True def get_vault_query(self): """Gets a vault query. return: (osid.authorization.VaultQuery) - a vault query *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.BinQuerySession.get_bin_query_template return queries.VaultQuery(runtime=self._runtime) vault_query = property(fget=get_vault_query) def can_delete_vaults(self): """Tests if this user can delete vaults. A return of true does not guarantee successful authorization. A return of false indicates that it is known deleting a ``Vault`` will result in a ``PermissionDenied``. This is intended as a hint to an application that may not wish to offer delete operations to unauthorized users. return: (boolean) - ``false`` if ``Vault`` deletion is not authorized, ``true`` otherwise *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.BinAdminSession.can_delete_bins # NOTE: It is expected that real authentication hints will be # handled in a service adapter above the pay grade of this impl. if self._catalog_session is not None: return self._catalog_session.can_delete_catalogs() return True def can_manage_vault_aliases(self): """Tests if this user can manage ``Id`` aliases for ``Vaults``. A return of true does not guarantee successful authorization. A return of false indicates that it is known changing an alias will result in a ``PermissionDenied``. This is intended as a hint to an application that may opt not to offer alias operations to an unauthorized user. return: (boolean) - ``false`` if ``Vault`` aliasing is not authorized, ``true`` otherwise *compliance: mandatory -- This method must be implemented.* """ # NOTE: It is expected that real authentication hints will be # handled in a service adapter above the pay grade of this impl. return True
[ 37811, 40386, 25504, 286, 19601, 10991, 526, 15931, 198, 198, 2, 279, 2645, 600, 25, 15560, 28, 3919, 12, 15003, 198, 2, 220, 220, 220, 220, 45261, 6097, 836, 470, 2421, 11593, 15003, 834, 13, 198, 2, 279, 2645, 600, 25, 15560, 28, ...
2.990849
3,934
############################################################################################### # 5. # dp ########### # O(n^2) # O(n^2) ###############################################################################################
[ 29113, 29113, 14468, 7804, 4242, 21017, 201, 198, 2, 642, 13, 220, 201, 198, 2, 288, 79, 201, 198, 7804, 21017, 201, 198, 2, 440, 7, 77, 61, 17, 8, 201, 198, 2, 440, 7, 77, 61, 17, 8, 201, 198, 29113, 29113, 14468, 7804, 4242,...
4.979167
48
"""Variational auto-encoder for MNIST data. References ---------- http://edwardlib.org/tutorials/decoder http://edwardlib.org/tutorials/inference-networks """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import edward as ed import numpy as np import os import tensorflow as tf from edward.models import Bernoulli, Normal from edward.util import Progbar from observations import mnist from scipy.misc import imsave tf.flags.DEFINE_string("data_dir", default="/tmp/data", help="") tf.flags.DEFINE_string("out_dir", default="/tmp/out", help="") tf.flags.DEFINE_integer("M", default=100, help="Batch size during training.") tf.flags.DEFINE_integer("d", default=2, help="Latent dimension.") tf.flags.DEFINE_integer("n_epoch", default=100, help="") FLAGS = tf.flags.FLAGS if not os.path.exists(FLAGS.out_dir): os.makedirs(FLAGS.out_dir) if __name__ == "__main__": tf.app.run()
[ 37811, 23907, 864, 8295, 12, 12685, 12342, 329, 29060, 8808, 1366, 13, 198, 198, 19927, 198, 35937, 198, 4023, 1378, 276, 904, 8019, 13, 2398, 14, 83, 44917, 82, 14, 12501, 12342, 198, 4023, 1378, 276, 904, 8019, 13, 2398, 14, 83, 4...
2.959375
320
#!/usr/bin/env python """copy-couch makes copies of couches. no joke. License: Apache 2.0 - http://opensource.org/licenses/Apache-2.0 """ import argparse import base64 import ConfigParser import datetime import json import requests argparser = argparse.ArgumentParser() argparser.add_argument('config_file', type=file, help="Config INI file. See `config.sample.ini` for info.") args = argparser.parse_args() config = ConfigParser.RawConfigParser({ 'protocol': 143, 'host': 'localhost:5984' }) config.readfp(args.config_file) local_couch = config._sections['local'] local_couch['password'] = base64.b64decode(local_couch['password']) local_url = local_couch['protocol'] + '://' + local_couch['host'] + '/' remote_couch = config._sections['remote'] remote_couch['password'] = base64.b64decode(remote_couch['password']) remote_url = remote_couch['protocol'] + '://' + remote_couch['host'] + '/' # setup local db session local_db = requests.Session() local_db.auth = (local_couch['user'], local_couch['password']) # setup remote db session remote_db = requests.Session() remote_db.auth = (remote_couch['user'], remote_couch['password']) rv = local_db.get(local_url).json() uuid = rv['uuid'] rv = local_db.get(local_url + '_all_dbs').json() # TODO: make which DB's configurable dbs = [db for db in rv if db[0] != '_'] # create & store one rep_doc per database for db in dbs: # create _replicator docs for each DB on local; target remote rep_doc = { "_id": "backup~" + datetime.datetime.now().isoformat(), "source": local_url, "target": remote_couch['protocol'] + '://' \ + remote_couch['user'] + ':' + remote_couch['password'] \ + '@' + remote_couch['host'] + '/backup%2F' + uuid + '%2F', "create_target": True } rep_doc['source'] += db; rep_doc['target'] += db; # TODO: make the backup db name configurable / reusable print 'Copying ' + db print ' from: ' + local_url print ' to: ' + remote_url + 'backup%2F' + uuid + '%2F' + db rv = local_db.post(local_url + '_replicate', json=rep_doc, headers = { 'Content-Type': 'application/json'}) print rv.json()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 37811, 30073, 12, 66, 7673, 1838, 9088, 286, 2284, 2052, 13, 645, 9707, 13, 198, 198, 34156, 25, 24843, 362, 13, 15, 532, 2638, 1378, 44813, 1668, 13, 2398, 14, 677, 4541, 14, ...
2.580494
851
#Script para la importacion de datos netCDF de un mes del GPCC en PostGIS. #Autor: Jos I. lvarez Francoso import sys from osgeo import gdal, ogr, osr from osgeo.gdalconst import GA_ReadOnly, GA_Update # Funcion para sobreescribir el mensaje de porcentaje completado if __name__ == '__main__': # El usuario tiene que definir al menos un parametro: la cadena de conexion Postgis GDAL if len(sys.argv) < 4 or len(sys.argv) > 4: print "uso: <GDAL PostGIS connection string> <mes> <agno>" raise SystemExit pg_connection_string = sys.argv[1] mes = sys.argv[2] agno = sys.argv[3] gpcc2gcm_win(pg_connection_string, mes, agno) raise SystemExit
[ 2, 7391, 31215, 8591, 1330, 49443, 390, 4818, 418, 2010, 34, 8068, 390, 555, 18842, 1619, 14714, 4093, 551, 2947, 38, 1797, 13, 198, 2, 16541, 273, 25, 22568, 314, 13, 300, 85, 19655, 4682, 28213, 198, 11748, 25064, 198, 6738, 28686, ...
2.421986
282
import streamlit as st import pandas as pd import numpy as np import plotly.express as px from plotly.subplots import make_subplots import plotly.graph_objects as go import matplotlib.pyplot as plt df = load_data('hdi.csv') st.title('Human Development Index in Brazil') select = st.sidebar.selectbox('Choose', ['Home', 'Analysis by Year', 'Analysis by State']) if select == 'Home': st.write('That is a dashboard to see the HDI of all states in Brazil, you can see graphics and values!') st.write('In soon, more improvements. #Version 1') st.write('In the sidebar, choose your option for the better view for you!') st.write('Author: Raisler Voigt | suggestions? raisler.dev@gmail.com') st.markdown('''<p align="center"> <a href="https://www.instagram.com/raislervoigt/" target="_blank" rel="noopener noreferrer">Instagram</a> <a href="https://twitter.com/VoigtRaisler" target="_blank" rel="noopener noreferrer">Twitter</a> <a href="https://www.linkedin.com/in/raisler-voigt7/" target="_blank" rel="noopener noreferrer">Linkedin</a> <a href="https://github.com/Raisler" target="_blank" rel="noopener noreferrer">GitHub</a> </p>''', unsafe_allow_html=True) if select == 'Analysis by Year': select1 = st.sidebar.selectbox('Anlise por Ano', [2017, 2010, 2000, 1991]) fig1 = px.scatter(df, x="HDI Health {0}".format(select1), y="HDI Education {0}".format(select1), size="HDI {0}".format(select1), color="UF") fig2 = px.histogram(df, x="UF", y = "HDI {0}".format(select1)).update_xaxes(categoryorder='total descending') fig3 = px.histogram(df, x="UF", y = "HDI Education {0}".format(select1)).update_xaxes(categoryorder='total descending') fig4 = px.histogram(df, x="UF", y = "HDI Health {0}".format(select1)).update_xaxes(categoryorder='total descending') fig5 = px.histogram(df, x="UF", y = "HDI Wealth {0}".format(select1)).update_xaxes(categoryorder='total descending') fig6 = df[['UF', "HDI Education {0}".format(select1), "HDI Health {0}".format(select1), "HDI Wealth {0}".format(select1)]] st.write(fig1) st.write(fig2) st.subheader('HDI Education') st.write(fig3) st.subheader('HDI Health') st.write(fig4) st.subheader('HDI Wealth') st.write(fig5) st.write(fig6) if select == 'Analysis by State': select2 = st.sidebar.selectbox('Choose the State', df['UF']) cdf = df cdf.index = cdf['UF'] state = cdf.index == '{}'.format(select2) state = cdf[state] trans = state.transpose() trans = trans.sort_index(ascending = False) fig1 = px.histogram(x = trans.index, y = trans['{}'.format(select2)]).update_xaxes(categoryorder='total descending') fig2 = state.transpose() st.write(fig1) st.write(fig2)
[ 11748, 4269, 18250, 355, 336, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 7110, 306, 13, 42712, 355, 279, 87, 198, 6738, 7110, 306, 13, 7266, 489, 1747, 1330, 787, 62, 7266, 489, 1747, 198, ...
2.561111
1,080
# main.py import pycom import time pycom.heartbeat(False) red = 0x08 blue = 0x00 green = 0x00 sleepTime = 0.01 while True: ### #if red >= 0x08: # if green > 0: # green -= 1 # else: # blue += 1 #if blue >= 0x08: # if red > 0: # red -= 1 # else: # green += 1 #if green >= 0x08: # if blue > 0: # blue -= 1 # else: # red += 1 ### setRgb(red, green, blue) time.sleep(sleepTime)
[ 2, 1388, 13, 9078, 198, 11748, 12972, 785, 198, 11748, 640, 198, 198, 9078, 785, 13, 11499, 12945, 7, 25101, 8, 198, 198, 445, 796, 657, 87, 2919, 198, 17585, 796, 657, 87, 405, 198, 14809, 796, 657, 87, 405, 198, 42832, 7575, 796...
1.809859
284
from spacetime import get_s_address_for_t_address from s_address import node_for_s_address from dsn.s_expr.structure import TreeText from dsn.pp.structure import PPNone, PPSingleLine, PPLispy, PPAnnotatedSExpr from dsn.pp.clef import PPUnset, PPSetSingleLine, PPSetLispy def construct_pp_tree(tree, pp_annotations): """Because pp notes take a t_address, they can be applied on future trees (i.e. the current tree). The better (more general, more elegant and more performant) solution is to build the pp_tree in sync with the general tree, and have construct_pp_tree be a function over notes from those clefs rather than on trees. """ annotated_tree = build_annotated_tree(tree, PPNone()) for annotation in pp_annotations: pp_note = annotation.annotation s_address = get_s_address_for_t_address(tree, pp_note.t_address) if s_address is None: continue # the node no longer exists annotated_node = node_for_s_address(annotated_tree, s_address) if isinstance(pp_note, PPUnset): new_value = PPNone() elif isinstance(pp_note, PPSetSingleLine): new_value = PPSingleLine() elif isinstance(pp_note, PPSetLispy): new_value = PPLispy() else: raise Exception("Unknown PP Note") # let's just do this mutably first... this is the lazy approach (but that fits with the caveats mentioned at the # top of this method) annotated_node.annotation = new_value return annotated_tree
[ 6738, 34752, 8079, 1330, 651, 62, 82, 62, 21975, 62, 1640, 62, 83, 62, 21975, 198, 6738, 264, 62, 21975, 1330, 10139, 62, 1640, 62, 82, 62, 21975, 198, 198, 6738, 288, 16184, 13, 82, 62, 31937, 13, 301, 5620, 1330, 12200, 8206, 19...
2.612142
593
"""A module to parse genetics file formats.""" # This file is part of geneparse. # # The MIT License (MIT) # # Copyright (c) 2017 Pharmacogenomics Centre # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import re from .readers import plink, impute2, dataframe, bgen, dict_based, vcf from .core import (Genotypes, Variant, ImputedVariant, SplitChromosomeReader, Chromosome) from .extract.extractor import Extractor try: from .version import geneparse_version as __version__ except ImportError: __version__ = None __author__ = "Marc-Andre Legault" __copyright__ = "Copyright 2014, Beaulieu-Saucier Pharmacogenomics Centre" __credits__ = ["Louis-Philippe Lemieux Perreault", "Marc-Andre Legault"] __license__ = "MIT" __maintainer__ = "Louis-Philippe Lemieux Perreault" __email__ = "louis-philippe.lemieux.perreault@statgen.org" __status__ = "Development" # TODO: # 1. Warn and show last exception if no reader correctly initialized. # 2. Could also make it async to load faster. parsers = { "plink": plink.PlinkReader, "bgen": bgen.BGENReader, "vcf": vcf.VCFReader, "chrom-split-plink": _SplitChromosomeReaderFactory(plink.PlinkReader), "impute2": impute2.Impute2Reader, "chrom-split-impute2": _SplitChromosomeReaderFactory( impute2.Impute2Reader ), "chrom-split-bgen": _SplitChromosomeReaderFactory(bgen.BGENReader), "dataframe": dataframe.DataFrameReader, "dict-based": dict_based.DictBasedReader, "pickle": dict_based.PickleBasedReader, }
[ 37811, 32, 8265, 284, 21136, 25862, 2393, 17519, 526, 15931, 198, 198, 2, 770, 2393, 318, 636, 286, 2429, 538, 17208, 13, 198, 2, 198, 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 198, 2, 15069, 357, 66, 8, 2177, 37908, 6644, 3199...
3.105263
817
from cadquery import * from math import sin,cos,acos,asin,pi,atan2 if __name__== "__main__": p = Pallet() ks = list(p.torx6.keys()) ks.reverse() a = cq.Workplane().circle(12).extrude(-3) for k in ks: a = a.union(p.torx(a.faces(">Z").workplane(),k).extrude(1))
[ 6738, 20603, 22766, 1330, 1635, 198, 6738, 10688, 1330, 7813, 11, 6966, 11, 330, 418, 11, 47337, 11, 14415, 11, 39036, 17, 198, 198, 361, 11593, 3672, 834, 855, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 279, 796, 3175, 1616, 3...
2.020408
147
# Copyright (c) 2015 Microsoft Corporation from z3 import * print(simplify(Sqrt(2)).sexpr()) set_option(":pp-decimal-precision", 50, pp_decimal=True) print(simplify(Sqrt(2)).sexpr()) set_option(precision=20) print(simplify(Sqrt(2)))
[ 198, 2, 15069, 357, 66, 8, 1853, 5413, 10501, 198, 6738, 1976, 18, 1330, 1635, 198, 198, 4798, 7, 14323, 489, 1958, 7, 50, 80, 17034, 7, 17, 29720, 8044, 1050, 28955, 198, 2617, 62, 18076, 7, 1298, 381, 12, 12501, 4402, 12, 3866, ...
2.473684
95
import pytest import allure from data_detective_airflow.constants import PG_CONN_ID, S3_CONN_ID from data_detective_airflow.dag_generator.results import PgResult, PickleResult from data_detective_airflow.dag_generator import ResultType, WorkType
[ 11748, 12972, 9288, 198, 198, 11748, 477, 495, 198, 6738, 1366, 62, 15255, 13967, 62, 958, 11125, 13, 9979, 1187, 1330, 23842, 62, 10943, 45, 62, 2389, 11, 311, 18, 62, 10943, 45, 62, 2389, 198, 6738, 1366, 62, 15255, 13967, 62, 958...
3.012048
83
from typing import List if __name__ == "__main__": s = Solution() result = s.largeGroupPositions("abc") print(result)
[ 6738, 19720, 1330, 7343, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 264, 796, 28186, 3419, 198, 220, 220, 220, 1255, 796, 264, 13, 11664, 13247, 21604, 1756, 7203, 39305, 4943, 198, 220...
2.714286
49
import time import math import py_qmc5883l import pigpio import adafruit_bmp280 from i2c_ADXL345 import ADXL345 import numpy as np from i2c_ITG3205 import Gyro if __name__ == "__main__": pi = pigpio.pi('192.168.178.229') imu = IMU(pi) while True: print(imu.get_roll_pitch_yaw())
[ 11748, 640, 198, 11748, 10688, 198, 11748, 12972, 62, 80, 23209, 3365, 5999, 75, 198, 11748, 12967, 79, 952, 198, 11748, 512, 1878, 4872, 62, 65, 3149, 21033, 198, 6738, 1312, 17, 66, 62, 2885, 32457, 27712, 1330, 5984, 32457, 27712, ...
2.220588
136