text
string
size
int64
token_count
int64
import requests import yaml import json import os import sys import logging from kankaclient.client import KankaClient logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s') LOGGER = logging.getLogger('KankaManagement') class SpaceDumper(yaml.SafeDumper): # HACK: insert blank lines between top-level...
4,947
2,103
#!/usr/bin/env python import os import re import codecs from setuptools import setup, find_packages ground = os.path.abspath(os.path.dirname(__file__)) def read(filename): with codecs.open(os.path.join(ground, filename), 'rb', 'utf-8') as file: return file.read() metadata = read(os.path.join(ground, '...
1,788
568
''' This script makes an image very similar to Figure 2 of Hutchison et al. 2019 (https://arxiv.org/pdf/1905.08812.pdf). Undoubtedly, there are likely simpler ways to make this figure -- this is how I chose to code it up. Because the figure in the paper uses some proprietary data, the code below will generate fake dat...
7,850
3,406
# Licensed under an MIT style license -- see LICENSE.md import numpy as np from scipy.stats import gaussian_kde from matplotlib.colors import LinearSegmentedColormap, colorConverter import corner __author__ = ["Charlie Hoy <charlie.hoy@ligo.org>"] def _set_xlim(new_fig, ax, new_xlim): if new_fig: return...
8,517
2,705
from typing import List import pytest import dango def test_empty_phrase(): assert dango.tokenize('') == [], 'an empty phrase contains no tokens' @pytest.mark.parametrize('expected', [ # inflected verbs should be kept as one word ['昨日', '映画', 'を', '見ました'], ['私', 'は', '本', 'を', '読む'], ['私', 'は'...
2,240
1,114
# 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 # d...
2,829
788
# https://leetcode.com/problems/contains-duplicate/ # We are forming whole set always which isn't optimal though time complexity is O(n). class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return len(nums) != len(set(nums))
256
81
import sys import os if __name__ == '__main__': if len(sys.argv) < 3: print("Usage: {} <conf-list> <conf-dir> [white-list-files]".format(sys.argv[0])) sys.exit(-1) conf_list_file = sys.argv[1] conf_dir = sys.argv[2] conf_list = {} white_list_files = sys.argv[3:] ele_white_list ...
1,488
508
import torch from torch.autograd import Variable from util.util import * from util.data_util import * import numpy as np from PIL import Image from data.base_dataset import get_transform_params, get_raw_transform_fn, \ get_transform_fn, get_soft_bbox, get_masked_image from util.data_util i...
4,383
1,345
class Solution: # @return a list of lists of string def solveNQueens(self, n): board = [[1 for i in xrange(n)] for i in xrange(n)] rs = range(n) self.queens = [] self.directions = [[(-i, i), (i, i)] for i in xrange(1, n)] self.recursive(board, n, 0, rs) return sel...
2,102
808
import unittest import json from app import createApp from app.api.database.migrations.migrations import migrate class TestParties(unittest.TestCase): def setUp(self): self.app = createApp("testing") self.client = self.app.test_client() self.endpoint = "/api/v2/parties" self.partyI...
3,812
1,207
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if not PY2: json_text = lambda rv: rv.data.decode(rv.charset) else: json_text = lambda rv: rv.data
179
84
import os import oriskami import warnings from oriskami.test.helper import (OriskamiTestCase) class OriskamiAPIResourcesTests(OriskamiTestCase): def test_router_data_update(self): response = oriskami.RouterData.update("0", is_active="true") self.assertTrue(hasattr(response.data, "__iter__")) ...
763
243
from osbot_aws.apis.IAM import IAM class IAM_Policy: def __init__(self, policy_name=None, policy_path=None): self.iam = IAM() self.policy_name = policy_name self.version = "2012-10-17" self.statements = [] self.policy_path = policy_path self.account_id ...
1,625
483
# Visualization function import numpy as np import matplotlib.pyplot as plt from math import ceil from PIL import Image from scipy.ndimage.filters import gaussian_filter def img_combine(img, ncols=5, size=1, path=False): """ Draw the images with array img: image array to plot - size = n x im_w x im_h x 3 ...
3,959
1,404
# copyright (c) 2018 Larz60+ from lxml import html import ScraperPaths import CIA_ScanTools import GetPage import os import json import sys from bs4 import BeautifulSoup class CIA_History: def __init__(self): self.spath = ScraperPaths.ScraperPaths() self.gp = GetPage.GetPage() self.getpag...
2,037
654
from django.conf.urls import patterns from django.conf import settings urlpatterns = patterns( '', (r'^media/(?P<path>.+)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), (r'^(.*\.html)$', 'thumbnail_tests.views.direct_to_template'), )
301
104
import matplotlib.pyplot as plt hfont = {'fontname':'Lato'} #draw a simple line chart showing population grown over the last 115 years years = [1900, 1950, 1955, 1960, 1965, 1970, 1975, 1980, 1985, 1990, 1995, 2000, 2005, 2010, 2015] pops = [1.6, 2.5, 2.6, 3.0, 3.3, 3.6, 4.2, 4.4, 4.8, 5.3, 5.7, 6.1, 6.5, 6.9, 7.3]...
822
388
r"""Train an EfficientNet classifier. Currently implementation of multi-label multi-class classification is non-functional. During training, start tensorboard from within the classification/ directory: tensorboard --logdir run --bind_all --samples_per_plugin scalars=0,images=0 Example usage: python train_cla...
28,057
9,181
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
4,704
1,758
#!/usr/bin/env python3 import itertools class Node: def __init__(self, node_type, width, rows, times): self.node_type = node_type self.width = width self.rows = rows self.times = times self.inputs = [] self.parent = None def as_dict(self): return { ...
3,400
1,033
from sys import stdin from collections import defaultdict, deque MAX_COLORS = 51 def load_num(): return int(stdin.readline()) def load_pair(): return tuple(map(int, stdin.readline().split())) def load_case(): nbeads = load_num() return [load_pair() for b in range(nbeads)] def build_necklace(beads...
2,397
797
import pytest import doctest import os import numpy as np import pandas as pd import neurokit as nk run_tests_in_local = False #============================================================================== # data #============================================================================== #def test_read_acqknow...
458
135
""" Autogenerated Models for the vocabulary described by the ontologies: http://www.semanticweb.org/redin/ontologies/2020/11/untitled-ontology-25 (ParsingTesterOntology) https://w3id.org/saref (saref.ttl) """ from enum import Enum from typing import Dict, Union, List from filip.semantics.semantics_models import\ Se...
231,371
85,304
from utils import prepareLegend from colours import colours from ROOT import * gROOT.SetBatch(1) gStyle.SetPadLeftMargin(0.15) # increase space for left margin gStyle.SetPadBottomMargin(0.15) # increase space for left margin gStyle.SetGridStyle(3) gStyle.SetGridColor(kGray) gStyle.SetPadTickX(1) # add tics on top ...
2,744
1,108
""" Initialization methods. """ # pylint: disable=wildcard-import from .methods import * from . import methods __all__ = [] __all__ += methods.__all__
154
53
import spacy from nltk.tokenize import word_tokenize from nltk.tokenize import sent_tokenize from nltk.corpus import stopwords from nltk.probability import FreqDist from string import punctuation from tqdm import tqdm from rank_bm25 import BM25Okapi import time from collections import defaultdict from heapq import nlar...
2,362
648
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class JobsConfig(AppConfig): name = 'project_e.jobs' verbose_name = _("Jobs")
176
58
import csv from pylab import * import matplotlib.pyplot as plt count1=[] req_data=[] def get_request (str): f=open('weblog.txt','r') pdata=[] req_data1=[] data=csv.reader(f,delimiter=' ') for row in data: row[3]=row[3][1:] row[3]=...
3,080
1,212
## 2018/08/17 Initial ## 2018/08/18 Add CSV format ## 2018/08/23 Add def get_stockidxname_SeymourExcel(),def get_stockidx_SeymourExcel() ## def get_all_stockidx_SeymourExcel() from test_crawl.py ## 2018/09/06 Add value of column 'PBR' in def readExcel() ## 2018/10/27 Add exception handling in def readEx...
5,979
2,226
#!/usr/bin/env python import os import sys import time from getpass import getpass from optparse import OptionParser from termcolor import colored from launchpadlib.launchpad import Launchpad from github3 import login as github_login from github3 import GitHubError ACTIVE_STATUSES = [ "New", "Confirmed", "Tria...
3,950
1,364
entrada = str(input('Em que cidade você nasceu? ')) cidade = entrada.strip().lower() partido = cidade.split() pnome = partido[0] santo = (pnome == 'santo') print(santo)
168
63
# # Test for the standard lead acid parameters # import pybamm from tests import get_discretisation_for_testing import unittest class TestStandardParametersLeadAcid(unittest.TestCase): def test_scipy_constants(self): param = pybamm.LeadAcidParameters() self.assertAlmostEqual(param.R.evaluate(), 8...
8,754
2,863
#!/usr/bin/env python from datetime import datetime import serial import sys import time SERIAL_BAUD = 9600 SERIAL_PORT = '/dev/ttyUSB0' TIME_FORMAT = "T%s" # Reset device to activate time setting routine DO_RST = True # Open serial dong print 'opening serial port %s...' % SERIAL_PORT uart = serial.Serial( port...
890
359
#!/usr/bin/env python # ====================================================================== # This software is distributed under the MIT license reproduced below: # # Copyright (C) 2009-2014 Giampaolo Rodola' <g.rodola@gmail.com> # # Permission to use, copy, modify, and distribute this software and # its docum...
3,789
1,074
#!/usr/bin/python2.7 import sys import time import pprint import libiopc_rest as rst def gen_ssh_key(hostname, out_format): payload = '{' payload += '"ops":"gen_ssh_key"' payload += '}' return rst.http_post_ops_by_pyaload(hostname, payload) def get_status_until_key_generated(hostname, out_format): ...
3,248
1,220
from Stroke import Stroke from TactileBrush import TactileBrush import json from sortedcontainers import SortedList EPSILON = 0.001 class Point: def __init__(self, x : int, y : int): self.x = int(x) self.y = int(y) def __repr__(self): return "(" + str(self.x) + ", " + str(self.y) ...
4,746
1,485
import select import socket import json import threading import time import clipboard import math from datetime import datetime ip = "" localpart = "" name = "" tcp = 5555 udp = 5556 buffer_size = 1024 broadcast_try_count = 3 ping_try_count = 3 members = [] # item - (str) ipaddress current_room_ip = "" my_room_name =...
14,921
4,997
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
9,728
2,947
import sys import json from h5model import h5model if len(sys.argv) < 2: print('Usage: ' + sys.argv[0] + ' ' + '<model name>') exit(1) modelName = sys.argv[1] model = h5model(modelName) model.createModel() if model.responseStatus >= 400: print("Unable to create model '" + modelName + "': " + model.errorMessage...
387
144
a='' n=int(input()) while n != 0: a=str(n%2)+a n//=2 print(a)
70
41
from anthill.framework.utils.translation import translate_lazy as _ from anthill.platform.conf.settings import * import os # Build paths inside the application like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in ...
4,887
1,735
# -*- coding: utf-8 -*- import os, sys from PyQt5.QtWidgets import (QWizard, QMessageBox) from PyQt5.QtGui import QPixmap from PyQt5.QtCore import pyqtSlot, Qt try: import odmltables have_odmltables = True except: have_odmltables = False from .settings import Settings class OdmltablesWizard(QWizard): ...
2,787
868
import math #constants and globals background = '0' NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 dirs = {0 : "NORTH", 1 : "EAST", 2 : "SOUTH", 3 : "WEST"} class CellElement(): #CellELement Interface for the subclasses #Subclasses: RegularRoad, Switch, LevelCrossing, Bridge, Station def setPosition(self, x, y): ...
25,440
7,485
import argparse import glob import json import os import os.path import re import sys from collections import Counter, defaultdict from datetime import datetime from os import path import numpy as np import pandas as pd import tensorflow as tf from acr_module.acr.acr_module_service import get_all_file, load_json_conf...
25,083
8,089
import pytest @pytest.mark.usefixtures("dataset", "helpers") def test_add_get_label(dataset, helpers): file_1 = dataset.create_file( path="/test_file_" + helpers.generate_random_string(16) + ".csv" ) label_result = file_1.add_label("label1", "value1") assert label_result is True assert fil...
2,979
1,036
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== import sys import numbers import collections import copy import numpy as np from nu...
15,384
4,407
import math def oversample(all_paths, per_class_split, oversample_ids, class_names): union = set() all_sum = 0 print('Oversample stats:') print('Total images before =', len(all_paths[0])) for i in oversample_ids: duplicates = 1 print(f'id = {i} -> {class_names[i]} : num of oversampled =', len(per_cla...
1,457
532
# @l2g 932 python3 # [932] Beautiful Array # Difficulty: Medium # https://leetcode.com/problems/beautiful-array # # An array nums of length n is beautiful if: # # nums is a permutation of the integers in the range [1, n]. # For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums...
1,181
433
from cdm.objectmodel import CdmCorpusDefinition, CdmManifestDefinition from cdm.storage import LocalAdapter from cdm.enums import CdmObjectType def generate_manifest(local_root_path: str) -> 'CdmManifestDefinition': """ Creates a manifest used for the tests. """ cdmCorpus = CdmCorpusDefinition() ...
1,209
385
import eventlet from eventlet.green import urllib2 import logging logging.basicConfig() logger = logging.getLogger(__file__) logger.setLevel(logging.DEBUG) def consumer(task_queue): while True: next_task = task_queue.get() next_task() task_queue.task_done() class Task(object): def _...
894
311
from flask.ext.login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from app import db class User(UserMixin, db.Model): """ User who can use this application. """ __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db....
1,155
356
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 UnitedStack Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licen...
32,426
9,835
import unittest import torch from easy_bert.losses.label_smoothing_loss import LabelSmoothingCrossEntropy class MyTestCase(unittest.TestCase): def test(self): print('test~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') lsce = LabelSmoothingCrossEntropy() ...
1,298
472
""" ALGORITHM : Merge Sort WORST CASE => { PERFORMANCE: O(n log(n)) SPACE: O(n) } """ def merge_sort(arr): size = len(arr) if size == 1: return arr elif size == 2: if arr[1] > arr[0]: return [arr[0], arr[1]] mid = len(arr) // 2 lef...
747
315
import scrapy from locations.items import GeojsonPointItem from urllib.parse import urlencode from scrapy.selector import Selector from locations.hours import OpeningHours Days = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] class DollaramaSpider(scrapy.Spider): name = "dollarama" item_attributes = {"brand": "D...
2,295
672
# import the necessary packages from imutils.video import VideoStream import face_recognition import imutils import pickle import time import cv2 import os # https://www.pyimagesearch.com/2018/06/18/face-recognition-with-opencv-python-and-deep-learning/ # https://www.pyimagesearch.com/2018/06/11/how-to-build-a-custom-f...
4,614
1,359
from pytint.interpreters import FiniteAutomaton from typing import List, Union, Dict, Iterable import collections import yaml class IncompleteMachine(Exception): def __init__(self, missing: str, machine_type: str): self.missing = missing self.machine_type = machine_type def __str__(self): ...
3,298
938
import dash from dash.dependencies import Input, Output # type: ignore import datetime from treemap import generate_treemap, get_plot_data from app import app from store import store @app.callback(Output('treemap', 'figure'), Output('timeclock', "children"), Input('interval-component', '...
1,021
338
from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from useraccount.serializer import UserSerializer,AgentUserSerializer from rest_framework.views import APIView from useraccount.models import User from django.http.response import JsonResponse from django.template.loader import render_...
4,095
1,312
# -*- coding: utf-8 -* # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # U...
2,203
834
#!/usr/bin/env python from __future__ import absolute_import, print_function, unicode_literals from setuptools import setup, find_packages from unique_uploadto import __version__ with open('README.rst', 'r') as f: readme = f.read() setup( name='django-unique-uploadto', version=__version__, descript...
1,160
346
import random normal="\033[0m" bold="\033[1m" faint="\033[2m" italic="\033[3m" underline="\033[4m" blinkSlow="\033[5m" blinkRapid="\033[6m" inverse="\033[7m" conceal="\033[8m" crossedOut="\033[9m" black="\033[30m" red="\033[31m" green="\033[32m" yellow="\033[33m" blue="\033[34m" magenta="\033[35m" cyan="\033[36m" whit...
793
556
#!/usr/bin/env python # -*- coding: utf-8 -*- from tree_node import AVLTreeNode from binary_search_tree import BinarySearchTree class AVLTree(BinarySearchTree): def __init__(self): super(AVLTree, self).__init__() def insert(self, k, payload=None): # tree is empty construct the tree if...
2,918
983
from django.apps import AppConfig class TempArduinoConfig(AppConfig): name = 'ardget_app'
96
31
"""This module contains custom data-structures.""" import six class TreeMap(dict): """Tree structure implemented with nested dictionaries.""" def get_paths(self): """Get all paths from the root to the leaves. For example, given a chain like `{'a':{'b':{'c':None}}}`, this method would...
1,944
500
# functions for actions import random import string import GUI def generate_password(): password = '' GUI.lblError.config(text='') passLength = GUI.var.get() if (GUI.varDigi.get() == 1) & (GUI.varChLower.get() == 1) & (GUI.varChUpper.get() == 1): strin = string.ascii_letters for i in r...
2,605
909
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import datasets.registry from foundations import hparams from foundations.step import Step from lottery.branch import base import models.regist...
1,330
400
""" Created on Thu Mar 22 15:07:43 2018 @author: Tanvee First attempt at an program for the EV3 bot. The main aim of this is to develop an algorithm to search clockwise for and identify close objects, before rushing to meet them. """ print(0) from time import sleep import sys, os # Import the ev3dev specific library f...
1,860
655
from unittest import TestCase, mock from modelgen import ModelGenerator, Base from os import getcwd, path class TestModelgen(TestCase): @classmethod def setUpClass(self): self.yaml = {'tables': {'userinfo':{'columns': [{'name': 'firstname', 'type': 'varchar'}, ...
13,984
4,153
from django.apps import AppConfig class EInvoiceConfig(AppConfig): name = 'papermerge.apps.e_invoice' label = 'e_invoice' # def ready(self): # from papermerge.apps.data_retention import signals # noqa
223
79
from logging import getLogger from random import randrange import re from simone.handlers import Registry, exclude_private from .models import Shout # Based loosely on https://github.com/desert-planet/hayt/blob/master/scripts/loud.coffee class Loud(object): ''' Learns and repeats LOUD MESSAGES! To add n...
2,075
643
# Time: O(|V| + |E|) # Space: O(|V|) # """ # This is HtmlParser's API interface. # You should not implement it, or speculate about its implementation # """ class HtmlParser(object): def getUrls(self, url): """ :type url: str :rtype List[str] """ pass class Solution(object): ...
1,013
308
#!/usr/bin python3 """ The script to collect training data """ import logging import os import cv2 as cv import numpy as np from google_images_download import google_images_download as gid from lib.utils import get_folder from os.path import exists, isfile, join logger = logging.getLogger(__name__) # pylint: disable...
3,614
1,171
import os import random from shutil import copyfile import json random.seed(123) ROOT_PATH = './data/' k = 5 target_path = './data/wiki_5_splits/' ''' Splits the training set to 5 folds. In each split, the held out set is used for test. ''' path = os.path.join(ROOT_PATH, 'train_wiki' + '.json') data = json.load(op...
1,132
427
from heisen.config import settings from jsonrpclib.request import ConnectionPool def get_rpc_connection(): if settings.CREDENTIALS: username, passowrd = settings.CREDENTIALS[0] else: username = passowrd = None servers = {'self': []} for instance_number in range(settings.INSTANCE_COUNT...
604
186
# =============================================================================== # Copyright 2013 Jake Ross # # 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/licens...
3,182
941
#!/usr/bin/env python """ NGINX Status Stub Returns sample resources usage """ import logging import logging.handlers import random from optparse import OptionParser from flask import Flask app = Flask(__name__) app.debug = True # Initialisation logging.basicConfig(format='[%(asctime)-15s] [%(threadName)s] %(...
3,023
1,040
""" Question 4 Level 1 Question: Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,67,55,33,12,98 Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34'...
1,616
667
from scipy.integrate import quad __all__ = ["quad"]
53
19
import logging import discord import discord.ext.commands as commands _LOG = logging.getLogger('discord-util').getChild("uwu") class Uwu(commands.Cog): @commands.Cog.listener() async def on_message(self, message: discord.Message): if message.content.lower().startswith('hello bot') or message.content....
543
162
import math import os from curses_tools import draw_frame, get_frame_size def _limit(value, min_value, max_value): """Limit value by min_value and max_value.""" if value < min_value: return min_value if value > max_value: return max_value return value def _apply_acceleration(speed,...
4,011
1,273
import secrets import asyncio from datetime import datetime, timedelta import discord from discord.ext import commands from database import DatabasePersonality, DatabaseDeck class Roll(commands.Cog): def __init__(self, bot): """Initial the cog with the bot.""" self.bot = bot #### Commands #...
7,963
2,525
from __future__ import print_function import time from sr.robot import * SEARCHING = "SEARCHING" DRIVING = "DRIVING" R = Robot() def drive(speed, seconds): R.motors[0].m0.power = speed R.motors[0].m1.power = speed time.sleep(seconds) R.motors[0].m0.power = 0 R.motors[0].m1.power = 0 def turn(s...
2,195
779
from math import log def ef_cache(): acerto = eval(input("Digite a quantidade de acertos: ")) acessos = eval(input("Digite a quantidade de acessos: ")) e = acerto / acessos return e def bit_dados(): cap = eval(input("Digite a capacidade da cache: ")) byte = eval(input("Digite a quantidade de...
9,218
3,481
#!/usr/bin/python # -*- coding: utf-8 -*- # ====================================================================== # Copyright 2017 Julien LE CLEACH # # 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 Lice...
15,786
5,535
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist, TransformStamped from std_msgs.msg import String from enum import Enum import tf2_ros import math class mission_states(Enum): STOP = -1 SUBMERGE = 0 MOVE_TO_GATE = 1 MOVE_THROUGH_GATE = 2 def checkTolerance(current, wanted): t...
2,815
875
#!/usr/bin/python # Copyright 2021 Northern.tech AS # # 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 ap...
19,202
6,859
import os chrom_bins = {} with open("GSE88952_Sc_Su.32000.bed") as in_file: for line in in_file: line = line.strip().split() chrom_bins[line[3]] = "{}\t{}\t{}".format(line[0], line[1], line[2]) in_file.close() if not os.path.isfile("ctrl_32kb.bed"): with open("ctrl_32kb.bed", "w") as out_file: with open("ct...
1,167
563
# Author: Xinshuo Weng # email: xinshuo.weng@gmail.com import matplotlib.pyplot as plt, numpy as np # import seaborn as sns # from pandas import DataFrame # from sklearn.neighbors import NearestNeighbors from terminaltables import AsciiTable from collections import Counter from .private import save_vis_close_helper, ...
21,956
6,961
from django.apps import AppConfig class PizzaStoreConfig(AppConfig): name = 'pizza_store'
96
31
"""Vary the rhoref parameter to find a sane value. Copyright 2019 Simulation Lab University of Freiburg Author: Lukas Elflein <elfleinl@cs.uni-freiburg.de> """ from __future__ import print_function import os import shutil #import multiprocessing #import sys import random from loop_cost_functions import calc_cost_fun...
2,530
894
from __future__ import absolute_import, unicode_literals import pytest from libweasyl import staff from libweasyl.legacy import UNIXTIME_OFFSET from weasyl import errorcode from weasyl import siteupdate from weasyl.define import sessionmaker from weasyl.test import db_utils _FORM = { u'title': u'Title', u'c...
12,388
4,312
import sys N = int(sys.stdin.readline()) dis = list(map(int, sys.stdin.readline().split())) coin = list(map(int, sys.stdin.readline().split())) use_coin = coin[0] tot = dis[0] * use_coin for i in range(1, N - 1): if coin[i] < use_coin: use_coin = coin[i] tot += dis[i] * use_coin print(tot)
298
137
from twisted.internet import defer, reactor @defer.inlineCallbacks def main(): try: from txmsgpackrpc.client import connect c = yield connect('localhost', 8000, ssl=True, connectTimeout=5, waitTimeout=5) data = { 'firstName': 'John', 'lastName': 'S...
1,395
394
# Converts user-defined currencies using Google import webbrowser, os, selenium from selenium import webdriver driver = webdriver.Firefox() headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} currencyX = input("O...
714
267
class UniErrors(Exception): pass class SetupErrors(UniErrors): pass class SettingErrors(UniErrors): pass class ConfigureSyntaxErrors(UniErrors): pass class NoLocationErrors(UniErrors): pass class ImportedErrors(UniErrors): pass class KernelWaresSettingsErrors(UniErrors): pass c...
890
269
from stilio.crawler.dht.node import Node class TestNode: def setup_method(self): self.node = Node.create_random("192.168.1.1", 8000) def test_create_random(self) -> None: assert self.node.address == "192.168.1.1" assert self.node.port == 8000 def test_generate_random_id(self) -> ...
1,107
478
import napari import time from napari._qt.qthreading import thread_worker import numpy as np # create a viewer window viewer = napari.Viewer() # https://napari.org/guides/stable/threading.html @thread_worker def loop_run(): while True: # endless loop print("Hello world", time.time()) time.sleep(0....
714
234
from enum import Enum from requests import Response from urllib.parse import unquote import json class ApiErrorCode(Enum): PHP_INVALID = 0 PHP_MISSING_PARAMS = 1 PHP_AUTH_FAILED = 2 PHP_NAME_INVALID = 4 PHP_USERNAME_INVALID = 5 PHP_USER_ALREADY_EXISTS = 6 PHP_PASSWORD_INVALID = 7 PHP_U...
1,937
810