text
string
size
int64
token_count
int64
def make_attachment_uri(discriminator, filename): return 'disco://%s/%s' % (discriminator, filename)
105
38
import os import re from pyramid.config import Configurator from pyramid.events import NewRequest from oaipmh import ( repository, datastores, sets, utils, articlemeta, entities, ) from oaipmh.formatters import ( oai_dc, oai_dc_openaire, ...
5,266
1,792
import flightdata import weatherparser import airportdata import pandas as pd from datetime import datetime from pathlib import Path flights = flightdata.read_csv('data/unpacked/flights/On_Time_On_Time_Performance_2016_1.csv') fname = 'data/processed/training/training{:04}_v1.csv' prev_time = datetime.now() df = pd...
1,613
564
from PyQt5 import QtCore, QtGui, QtWidgets from db import Db class Ui_Signup(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.setFixedSize(638, 441) # self.label = QtWidgets.QLabel(Dialog) # self.label.setGeometry(QtCore.QRect(110, 190, 151, 31)) #...
5,618
1,840
from gym_android_wechat_jump.env.wechat_jump_env import WechatJumpEnv
70
29
import requests from bot.constants import BASE_ENDPOINT import cli.app @cli.app.CommandLineApp def bot(app): ping_response = requests.get(BASE_ENDPOINT+'api/v3/ping') print(f'{ping_response}:{ping_response.json()}') # bot.add_param("-h", "--help", help="HELP me") if __name__ == '__main__': bot.run()
318
125
import os import imp from pathlib import Path import configparser import requests import gpgrecord config = configparser.ConfigParser() INSTALLED = imp.find_module('metadrive')[1] HOME = str(Path.home()) DEFAULT_LOCATION = os.path.join(HOME,'.metadrive') CONFIG_LOCATION = os.path.join(DEFAULT_LOCATION, 'config') CRED...
4,374
1,619
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('reporting', '0002_remove_petreport_revision_number'), ('socializing', '__first__'), ] operations = [ migrations.Crea...
1,272
371
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from . import utilities, tables class GetIpRangesResult: """ A...
3,273
986
import os import sys import json import pkgutil import logging import uuid import time import multiprocessing from pathlib import Path from threading import Thread from types import SimpleNamespace from multiprocessing import Process, Queue from lithops.utils import version_str, is_unix_system from lithops.worker impor...
5,123
1,580
#if 0 # $Id: riffinfo.py,v 1.33 2005/03/15 17:50:45 dischi Exp $ # $Log: riffinfo.py,v $ # Revision 1.33 2005/03/15 17:50:45 dischi # check for corrupt avi # # Revision 1.32 2005/03/04 17:41:29 dischi # handle broken avi files # # Revision 1.31 2004/12/13 10:19:07 dischi # more debug, support LIST > 20000 (new ma...
17,878
6,225
"""H1st CLI.""" import click from .pred_maint import h1st_pmfp_cli @click.group(name='h1st', cls=click.Group, commands={ 'pmfp': h1st_pmfp_cli, }, # Command kwargs context_settings=None, # callback=None, # ...
843
255
""" File: dice_rolls_sum.py Name: Sharon ----------------------------- This program finds all the dice rolls permutations that sum up to a constant TOTAL. Students will find early stopping a good strategy of decreasing the number of recursive calls """ # This constant controls the sum of dice of our interest TOTAL = 8...
1,008
316
#!/usr/bin/env python # encoding: utf-8 """ valid_parentheses.py Created by Shengwei on 2014-07-24. """ # https://oj.leetcode.com/problems/valid-parentheses/ # tags: easy, array, parentheses, stack """ Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is val...
909
280
"""Terms used in the bot.""" from collections import OrderedDict from dataclasses import dataclass from typing import List from django.utils.translation import gettext_lazy as _ from JellyBot.systemconfig import Database @dataclass class TermExplanation: """An entry for a term and its explanation.""" term:...
3,104
772
import numpy as np import operator from itertools import cycle from torch import nn import torch.nn.functional as F import torch from torch.nn.modules.loss import * from kornia.losses import * class Loss: def compute(self, output, target): raise NotImplementedError() def __call__(self, *args, **kwargs...
2,619
814
# -*- coding: utf-8 -*- import uuid import pytest from dbtrigger.cli import DatabaseCli, QueryCli, ServerCli from dbtrigger.config import settings from dbtrigger.models import Database @pytest.fixture(autouse=True) def add_server(server): ServerCli.add(server.identifier, server.hostname, server.dialect) def ...
5,111
1,486
import zmq, time, json context = zmq.Context() pub = context.socket(zmq.REQ) # These are random useless keys for testing Curve auth pubkey = u"7d0:tz+tGVT&*ViD/SzU)dz(3=yIE]aT2TRNrG2$" privkey = u"FCFo%:3pZTbiQq?MARHYk(<Kp*B-<RpRG7QMUlXr" serverkey = u"mN>y$-+17hxa6F>r@}sxmL-uX}IM=:wIq}G4y*f[" pub.setsockopt_string(...
1,557
687
from abc import ABC, abstractmethod from typing import List class EmailFilterInterface(ABC): """ Interface for email filters """ @abstractmethod def filter(self, emails: List[str]) -> List[str]: """ Filter emails by params :param: list(str) emails: list of emails for filt...
392
102
"""tooling integration""" # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ------------------------------------------...
6,144
1,779
import os os.system("cp -r ../../../topic_scripts/* ./")
57
20
# -*- coding: utf-8 -*- """ Minimal worker implementation. """ # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement # First Party from metaopt.concurrent.worker.base import BaseWorker class Worker(BaseWorker): """Minimal worker implementation.""" ...
537
163
# para importar todo from constantes import * from constantes import MI_CONSTANTE from constantes import Matematicas as Mate print(MI_CONSTANTE) print(Mate.PI) MI_CONSTANTE = "nuevo valor" Mate.PI = "3.14" print(">>>",MI_CONSTANTE) print(">>>",Mate.PI)
261
106
# shallowbundle.py - bundle10 implementation for use with shallow repositories # # Copyright 2013 Facebook, Inc. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from __future__ import absolute_import from mercurial.i18n import _ f...
10,131
2,931
#!/usr/bin/python # Functional tests for the main password manager page # Currently targeting Firefox # Depends on the vault configuration provided by the startdev.sh script. # Depends on pytest-sourceorder to force test case execution order. # TODO: configure vault data from pretest fixture. import datetime import ...
10,507
3,091
n, t = map(int, input().split()) f = [] results = [-1, -1, -1, -1] for i in range(0, n): f.append(list(map(int, input().split()))) # print(f) for j in range(0, n): if t in range(f[j][4], f[j][5]): for k in range(0, 4): if f[j][k] > results[k]: results[k] = f[j][k] for m in range(0, 4): print(results[m])
319
162
from typing import Optional from reacticket.extensions.abc import MixinMeta from reacticket.extensions.mixin import settings class ReacTicketUserSettingsMixin(MixinMeta): @settings.group() async def userpermissions(self, ctx): """Control the permissions that users have with their own tickets""" ...
2,031
591
from breakzip import command_line import pytest import os @pytest.fixture def enc_zip(rootdir): """Returns an EncryptedZipFile instance with a test zip""" test_zip = os.path.join(rootdir, "cats.zip") return test_zip def test_reading_file(enc_zip, mocker): mocker.patch.object(command_line.sys, "argv"...
1,276
449
from .command import Command from datetime import datetime import calendar from tourney.util import this_season_filter from tourney.stats import Stats class StatsCommand(Command): def __init__(self): super(StatsCommand, self).__init__("stats") self.set_ephemeral(False) def execute(self, lookup=None): ...
643
187
""" Agnostic Autocomplete URLS """ from django.conf.urls import url from .views import AgnocompleteView, CatalogView urlpatterns = [ url( r'^(?P<klass>[-_\w]+)/$', AgnocompleteView.as_view(), name='agnocomplete'), url(r'^$', CatalogView.as_view(), name='catalog'), ]
300
106
"""Repository operations""" import os from tem import config, util class Repo: """A python representation of a repository.""" def __init__(self, *args): if not args: self.path = "" if isinstance(args[0], str): self.path = args[0] elif isinstance(args[0], Repo)...
10,037
2,871
import json import sys #filename='/home/anon/js-acg-examples-master/Knockout_test_results/StatWala.json' cnt=0 cnt2=0 #item_dict = json.loads(filename) #import json filename1 = sys.argv[1] #filename2 = sys.argv[2] #out_key = filename2.read().split('\n') '''out_key = [line.rstrip('\n') for line in open(filename2)]''' ...
2,064
749
''' settings for Django ''' import os import django.conf.global_settings as DEFAULT_SETTINGS LOCALHOST = False DEBUG = False TEMPLATE_DEBUG = DEBUG DEBUG_PAYMENTS = DEBUG # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), os....
13,172
5,240
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os import shutil import subprocess import sys from pex.pex_info import PexInfo from pex.testing import run_pex_command from pex.typing import TYPE_CHECKING from pex.variables import...
1,151
452
#!/usr/bin/python3 # # Copyright (c) 2017-2020, SUSE LLC # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list ...
13,900
4,486
from dataclasses import dataclass import random from typing import List import numpy as np import torch from config import Config from domain import DispatchMode from models import DQN from modules.state import FeatureManager from objects import Area, Vehicle from objects.area import AreaManager from objects.vehicle ...
5,455
1,686
# Standard Python modules # ======================= import weakref from abc import ABCMeta, abstractmethod, abstractproperty # External modules # ================ from vtk import vtkActor from vtk import vtkMapper from vtk import vtkPolyDataAlgorithm from vtk import vtkBoundingBox # DICE modules # ============ from d...
4,716
1,384
#!/usr/bin/env python # # Copyright 2011-2013 Colin Scott # # 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...
2,272
818
import os a=input("enter username:") if a.isalpha(): os.system("useradd "+a) os.system("passwd a")
101
41
"""Views.""" from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import HttpResponse, Http404 from django.shortcuts import render, redirect from responsive_dashboard.dashboard import dashboards from responsive_dashboard.models import UserDashboard, UserDashlet ...
3,733
1,155
import os from dataclasses import dataclass @dataclass(frozen=True) class Config: listen_host: str listen_port: int yc_oauth_token: str yc_folder_id: str data_path: str debug_enabled: bool @staticmethod def create_from_env() -> 'Config': return Config( listen_host=...
769
269
import click import logging import multiprocessing import os import sys from atlas import __version__ from atlas.conf import make_config from atlas.parsers import refseq_parser from atlas.tables import merge_tables from atlas.workflows import download, run_workflow logging.basicConfig(level=logging.INFO, datefmt="%Y-...
15,486
5,038
"""Test cases for the python_jsonapi.core.types.relationships module.""" from python_jsonapi.core.types.relationships import Relationship from python_jsonapi.core.types.relationships import RelationshipsMixin def test_relationship_init() -> None: """Can init a new relationships.""" sut = Relationship() as...
1,101
348
from needlestack.indices.index import BaseIndex
48
15
from django.conf import settings from django.contrib.auth.models import User from django.core.mail import send_mail def username_or_email_resolver(username): if User.objects.filter(email=username).exists(): return User.objects.get(email=username).username else: return username de...
698
218
#! /usr/bin/python # -*- coding: utf-8 -*- __author__ = "Osman Baskaya" from nltk.stem.wordnet import WordNetLemmatizer import sys lmtzr = WordNetLemmatizer() for line in sys.stdin: print ' '.join(map(lmtzr.lemmatize, line.split()))
245
108
# https://realpython.com/blog/python/lyricize-a-flask-app-to-create-lyrics-using-markov-chains/ from random import choice import sys def generateModel(text, order): model = {} for i in range(0, len(text) - order): fragment = text[i:i+order] next_letter = text[i+order] if fragment not i...
4,066
1,176
""" Copyright © 2021 The Johns Hopkins University Applied Physics Laboratory 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...
1,545
505
# Adapted from Graham Neubig's Paired Bootstrap script # https://github.com/neubig/util-scripts/blob/master/paired-bootstrap.py import numpy as np from sklearn.metrics import f1_score, precision_score, recall_score from tqdm import tqdm EVAL_TYPE_ACC = "acc" EVAL_TYPE_BLEU = "bleu" EVAL_TYPE_BLEU_DETOK = "bleu_detok"...
9,265
3,596
from paginate_sqlalchemy import SqlalchemyOrmPage class Paginator(SqlalchemyOrmPage): def __init__(self, *args, radius=3, **kwargs): super().__init__(*args, **kwargs) self.radius = radius self.page_range = self._make_page_range() def _make_page_range(self): if self.page_count...
970
320
import tensorflow as tf # import slim # conv layers layers = tf.contrib.layers arg_scope = tf.contrib.framework.arg_scope def vgg_conv_dilation(inputs, weight_decay=0.0005): with arg_scope([layers.convolution2d, layers.max_pool2d], padding='SAME'): with arg_scope([layers.convolution2d], rate=1, ...
4,915
1,922
import datetime # Log parm(File_name) class logging_class: def __init__(self, log_file_name, verbose): self.log_file_name = log_file_name self.stream = open(log_file_name, "a") self.verbose = verbose # Write a line in the log file def create_log(self, to_add): if (to_add !=...
968
312
#!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ Utility classes to wrap command line tools. The module provides a class :class:`.CLITool` that provides boilerp...
10,541
2,847
# -*- coding: utf-8 -*- import facebook from allauth.socialaccount.models import SocialToken from django.core.exceptions import ObjectDoesNotExist class FacebookAuth(object): """ Interface bettween Django AllAuth and Facebook SDK """ def __init__(self, user_id): super(FacebookAuth, self).__ini...
1,128
307
import pprint import time import keras import numpy as np import joblib import dataset_loaders import selection_policy import augmentations import experiments import experiments_util import featurized_classifiers import visualization_util import matplotlib.pyplot as plt mem = joblib.Memory(cachedir="./cache", verbo...
11,386
3,628
from rest_framework import serializers from .models import * class MessageSerializer(serializers.ModelSerializer): created_at = serializers.DateTimeField(format="%d.%m.%Y %H:%M") class Meta: depth = 2 model = Message fields = ('id', 'description', 'created_at', 'answer', 'correct', 'i...
370
112
def to_iter(obj): try: return iter(obj) except TypeError: return obj,
96
33
# -*- coding: utf-8 -*- """ Created on 2014-5-13 @author: skycrab """ import json import time import random import string import urllib import hashlib import threading import traceback import xml.etree.ElementTree as ET import logging from urllib import request as urllib2 from functools import wraps from .config imp...
17,875
6,672
from __future__ import annotations from contextlib import contextmanager from typing import TYPE_CHECKING from typing import Any from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Union from argo_dsl.api.io.argoproj.workflow import v1alpha1 if ...
4,723
1,485
import unittest from app.models import Article class ArticleTest(unittest.TestCase): ''' Test Class to test the behaviour of the Article class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_article = Article('Jack Healy, Jack Nicas ...
1,007
332
# coding: utf-8 ''' Created on 18.04.2013 @author: кей ''' import dals.os_io.io_wrapper as dal def convert_one_line(msg): copy_line = msg.split(';')[0] if copy_line: name = copy_line.split('.')[-1] print copy_line+' as '+name if __name__=='__main__': sets = dal.get_utf8_t...
474
205
__version__ = '1.3.0.a3'
25
16
import logging import math from emoji import emojize from peewee import DoesNotExist from telegram import ParseMode from telegram.ext import CommandHandler from telegram.ext import ConversationHandler from telegram.ext import Filters from telegram.ext import MessageHandler from telegram.ext import RegexHandler from...
4,596
1,425
""" 파이션 - 무료이지만 강력하다 ` 만들고자 하는 대부분의 프로그램 가능 ` 물론, 하드웨어 제어같은 복잡하고 반복 연산이 많은 프로그램은 부적절 ` 그러나, 다른언어 프로그램을 파이썬에 포함 가능 [주의] 줄을 맞추지 않으면 실행 안됨 [실행] Run 메뉴를 클릭하거나 단축키로 shift + alt + F10 [도움말] ctrl + q """ """ 여러줄 주석 """ # 한줄 주석 # print("헬로우") # print('hello') # print("""안...
1,137
1,089
#!/usr/bin/env python3 import argparse import sys import io import os.path import shutil import requests from convert_file import convert_file from gooey import Gooey, GooeyParser if len(sys.argv) >= 2: if '--ignore-gooey' not in sys.argv: sys.argv.append('--ignore-gooey') @Gooey(program_name='SP to SR2 ...
2,502
819
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
5,289
1,509
#!/usr/bin/env python import argparse import os import sys import matplotlib import numpy as np matplotlib.use('Agg') import matplotlib.pyplot as plt import os, sys, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(...
4,563
1,694
from django.urls import reverse from rest_framework.test import APITestCase from testapp.models import ( A, B, C, Child, ChildProps, Container, Entry, MainObject, Parent, Tag, ) from .mixins import InclusionsMixin class ReferenceTests(InclusionsMixin, APITestCase): maxD...
16,548
4,921
# ---------------------------------------------------------------------------- # Copyright (c) 2022, Bokulich Laboratories. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # --------------------------------------------------------...
1,508
481
# vim: ts=8:sts=8:sw=8:noexpandtab # This file is part of python-markups module # License: 3-clause BSD, see LICENSE file # Copyright: (C) Dmitry Shachnev, 2012-2018 import markups.common as common from markups.abstract import AbstractMarkup, ConvertedMarkup class ReStructuredTextMarkup(AbstractMarkup): """Markup ...
2,652
964
import pandas as pd from pm4py.objects.log.importer.xes import importer as xes_import from pm4py.objects.log.util import log as utils from pm4py.statistics.start_activities.log.get import get_start_activities from pm4py.statistics.end_activities.log.get import get_end_activities from pm4py.algo.filtering.log.end_a...
8,025
3,760
#!/usr/bin/env python ############################################################################## # Copyright (c) 2014, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # Written by: # Nikhil Jain <nikhil.jain@acm.org> # Abhinav Bhatele <bhatele@llnl.gov...
9,480
3,224
#!/usr/bin/env python import shutil import itertools import random import sys import traceback from pathlib import Path import altair as alt import pandas as pd import plotly as plotly import plotly.express as px import plotly.graph_objects as go import streamlit as st from pandas.api.types import is_numeric_dtype fro...
46,894
14,575
def zipcode_to_feature(zipcode, lookup, feature): results = lookup.get(zipcode) if results is None: return None else: return results[feature] def zipcode_to_state(zipcode, lookup): return zipcode_to_feature(zipcode, lookup, 'state') def avg_price_by_zipcode(zipcode, lookup): retu...
691
246
import numpy as np from typing import List from math import sqrt from QFA.Automaton import Automaton from math import cos, sin, pi class MO_1QFA(Automaton): def __init__(self, alphabet: str, initial_state: np.ndarray, transition_matrices: List[np.ndarray], proj...
4,431
1,622
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.views.generic import TemplateView, ListView from django.shortcuts import render from rest_framework.authentication import TokenAuthentication from rest_framework import viewsets, mixins from rest_framework.response import Response from rest_fra...
2,292
681
#!/usr/bin/env python import rospy from geometry_msgs.msg import Vector3 from sensor_msgs.msg import Imu import numpy as np c_imu, c_angle = 0, 0 def cb_imu(msg): global c_imu c_imu += 1 def cb_angle(msg): global c_angle c_angle += 1 if c_angle == 400: print("count of received data of angle = {}".format(c_a...
591
265
# [START woosmap_http_zones_collection_request] import requests import json url = "https://api.woosmap.com/zones?private_key=YOUR_PRIVATE_API_KEY" payload = json.dumps({ "zones": [ { "zone_id": "ZoneA", "description": "Delivery Zone for Store A", "store_id": "STORE_ID_1...
2,431
1,610
import win32com.client # Disable early binding: full of race conditions writing the cache files, # and changes the semantics since inheritance isn't handled correctly import win32com.client.gencache _savedGetClassForCLSID = win32com.client.gencache.GetClassForCLSID win32com.client.gencache.GetClassForCLSID = lam...
1,692
606
import numpy as np import matplotlib.pyplot as plt from PIL import Image from PIL import ImageOps def view_image(img, filename = 'image'): fig, ax = plt.subplots(figsize=(6, 9)) ax.imshow(img.reshape(96, 96).squeeze()) ax.axis('off') plt.savefig(filename + '.png') def convert_to_PIL(img): img_r...
4,051
1,537
import os def ui_tools_js(): js_string = "" with open(os.path.join(os.path.dirname(__file__), 'template.js'), 'r') as f: js_string = f.read() return js_string def ui_tools_html(): html_string = "" with open(os.path.join(os.path.dirname(__file__), 'template.html'), 'r') as f: html_...
360
130
from django.shortcuts import render from django.http import Http404 from .models import CarOwner def detail(request, owner_id): try: #метод try-except - обработчик исключений p = CarOwner.objects.get(pk=owner_id) #pk - автоматически создается в джанго для любой таблицы в моделе (оно есть у любого объекта...
886
302
from .WtBtAnalyst import WtBtAnalyst from .WtCtaOptimizer import WtCtaOptimizer __all__ = ["WtBtAnalyst","WtCtaOptimizer"]
126
59
import math import sys import time from grove.adc import ADC class GroveRotaryAngleSensor(ADC): def __init__(self, channel): self.channel = channel self.adc = ADC() @property def value(self): return self.adc.read(self.channel) Grove = GroveRotaryAngleSensor def main(): if ...
608
218
# -*- coding: utf-8 -*- import string from flask_wtf import FlaskForm as Form from wtforms.fields.html5 import URLField, EmailField, TelField from wtforms import (ValidationError, HiddenField, TextField, HiddenField, PasswordField, SubmitField, TextAreaField, IntegerField, RadioField, FileField, Decima...
627
182
"""TLA+ parser and syntax tree.""" from .parser import parse, parse_expr
73
22
import keras.backend as K import keras.layers import runai.mp from .keep import Keep from .parallelised import Parallelised Activation = Keep.create('Activation') class Dense(Parallelised, keras.layers.Dense): def build(self, input_shape): assert len(input_shape) == 2 # TODO(levosos): support more than ...
2,084
608
from matplotlib import pyplot as plt import numpy as np def plot_bacteria(bacteria_ndarray: np.ndarray, dimensions: tuple, save_path: str = None, cmap: str='prism'): im = bacteria_ndarray.reshape(dimensions) fig = plt.imshow(im, cmap=cmap, vmin=0, vmax=1) plt.title('Red/Green graphic distribution') if ...
461
166
# utility functions import ast import urllib import datetime import pytz import pylibmc # Import settings from django.conf import settings # API Models from apps.api.models import APIKey, Character, APITimer # Eve_DB Models from eve_db.models import MapSolarSystem # API Access Masks CHARACTER_API_ACCESS_MASKS = {'A...
5,394
1,554
from django.shortcuts import render from ..models import Field def fields(request): fields = Field.objects.all() return render(request, 'fields.html', {'fields': fields}) def field(request, key=None, template='field.html'): field = Field.objects.get(field=key) return render(request, template, { ...
349
105
"""mcpython - a minecraft clone written in python licenced under MIT-licence authors: uuk, xkcdjerry original game by forgleman licenced under MIT-licence minecraft by Mojang blocks based on 1.14.4.jar of minecraft, downloaded on 20th of July, 2019""" import globals as G import crafting.IRecipeType import json import...
2,608
785
# Checks number of concurrent connections from XCaches to MWT2 dCache. # Creates alarm if more than 200 from any server. # ==== # It is run every 30 min from a cron job. import json from datetime import datetime import requests from alerts import alarms config_path = '/config/config.json' with open(con...
1,625
522
import csv def area(x1, y1, x2, y2, x3, y3): return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0) def isInside(lis): x, y = 0, 0 x1, y1, x2, y2, x3, y3 = lis[1:] x1 = int(x1) x2 = int(x2) x3 = int(x3) y1 = int(y1) y2 = int(y2) y3 = int(y3) ...
769
385
t = np.arange(0, 10, 0.1) # Time from 0 to 10 years in 0.1 steps with plt.xkcd(): p = np.exp(0.3 * t) fig = plt.figure(figsize=(6, 4)) plt.plot(t, p) plt.ylabel('Population (millions)') plt.xlabel('time (years)') plt.show()
238
119
# Tests for code in squarepants/src/main/python/squarepants/plugins/copy_resources/tasks/copy_resource_jars # # Run with: # ./pants test squarepants/src/test/python/squarepants_test/plugins:copy_resources from pants.backend.jvm.targets.jar_dependency import JarDependency from pants.backend.jvm.targets.jar_library impo...
1,063
344
import os import sys # If installed to a custom prefix directory, binwalk may not be in # the default module search path(s). Try to resolve the prefix module # path and make it the first entry in sys.path. # Ensure that 'src/binwalk' becomes '.' instead of an empty string _parent_dir = os.path.dirname(os.path.dirname(...
2,339
661
#!/usr/bin/python3 # file: mini_frame.py # Created by Guang at 19-7-19 # description: # *-* coding:utf8 *-* import time def login(): return "Welcome xxx login website! %s" % time.ctime() def register(): return "Welcome xxx register on our website! %s" % time.ctime() def profile(): return "你来到了一片荒原之...
642
234
import time import pymongo import schedule from order import * from utils import * # MONGODB db = pymongo.MongoClient("mongodb://localhost:27017/")["ShaurmaBinanceTerminal"] order_db = db["orders"] JOB_INTERVAL = 10.0 # interval of updating jobs_pool = {} def worker(symbol): try: time_start = time.ti...
3,174
1,105
""" Moduł spiający wszystkie wyszukiwania w jedną klasę - wszystkei dane dla adresu ip/domeny. Klasa bezpośrednio używana w widoku Django. """ from rest_framework.reverse import reverse from typing import List, Dict import whois import socket from connectors.credential import CredentialsNotFoundError from api_searcher...
4,979
1,421
# Python - 3.6.0 get_average = lambda marks: int(sum(marks) / len(marks))
75
32