id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1785508
#!/usr/bin/env python import os from textwrap import dedent from blessings import Terminal import click from cookiecutter.main import cookiecutter import adama from adama import __version__ from adama.tools import location_of t = Terminal() HERE = os.path.join(location_of(adama.__file__), 'generator') @click.gro...
StarcoderdataPython
22413
<filename>generate_hamming_command.py import numpy as np import os path = 'preds' files = os.listdir(path) lst = [] for f in files: if f.find('_0_HASH') == -1: continue if f.find('CW') == -1: continue if f.find('low')==-1 and f.find('high')==-1 and f.find('mix')==-1: continue if...
StarcoderdataPython
1772696
from collections import abc, OrderedDict from .line import Unknown, Dialogue, Movie, Command, Sound, Picture, Comment, Style from .data import _Field __all__ = ( 'LineSection', 'FieldSection', 'EventsSection', 'StylesSection', 'ScriptInfoSection', ) class LineSection(abc.MutableSequence): FO...
StarcoderdataPython
1728196
<reponame>adilshiekh00/clash-wars import asyncio from pytgcalls import idle from driver.veez import call_py, bot async def mulai_bot(): print("[VEEZ]: STARTING BOT CLIENT") await bot.start() print("[VEEZ]: STARTING PYTGCALLS CLIENT") await call_py.start() await idle() await pidle() print("[...
StarcoderdataPython
41142
#!/usr/bin/env pythonw import numpy as np import matplotlib.pyplot as plt def flip_coins(flips = 1000000, bins=100): # Uninformative prior prior = np.ones(bins, dtype='float')/bins likelihood_heads = np.arange(bins)/float(bins) likelihood_tails = 1-likelihood_heads flips = np.random.choice(a=[True...
StarcoderdataPython
3390671
<filename>todo/signals.py from django import dispatch task_completion_toggled = dispatch.Signal(providing_args=["task"])
StarcoderdataPython
1622154
<filename>tests/playbook/test_playbook_tc_entity_types.py<gh_stars>0 """Test the TcEx Batch Module.""" # standard library from typing import TYPE_CHECKING, Any, Dict, List, Union # third-party import pytest # first-party from tcex.input.field_types import KeyValue if TYPE_CHECKING: # first-party from tcex.pl...
StarcoderdataPython
1692
<filename>CTFd/api/v1/users.py from flask import session, request, abort from flask_restplus import Namespace, Resource from CTFd.models import ( db, Users, Solves, Awards, Tracking, Unlocks, Submissions, Notifications, ) from CTFd.utils.decorators import authed_only, admins_only, rateli...
StarcoderdataPython
117439
<filename>muas_sid/muas_sid/cli.py #!/usr/bin/env python3 import argparse import logging import os import sys from pathlib import Path from muas_sid import __version__ module = sys.modules["__main__"].__file__ logger = logging.getLogger(module) def existing_file(value: str, extensions: tuple = None) -> Path: "...
StarcoderdataPython
3237407
<reponame>ID56/Multimodal-Fusion-CRNN<gh_stars>0 import albumentations as A import numpy as np import cv2 def joint_shift_scale_rotate(joint_points: np.ndarray, shift_limit: float, scale_limit: float, rotate_limit: int, p: float = 0.5) -> np.ndarray: """Shift, scale, and rotate joint points within a specified ran...
StarcoderdataPython
184369
class Solution: def trap(self, height: List[int]) -> int: res = 0 # build memos max_height_left = [0] * len(height) max_height_left[0] = height[0] for i in range(1, len(height)): max_height_left[i] = max(max_height_left[i-1], height[i]) max_height_right = ...
StarcoderdataPython
13154
import tensorflow as tf import pandas as pd import numpy as np import sys import time from cflow import ConditionalFlow from MoINN.modules.subnetworks import DenseSubNet from utils import train_density_estimation, plot_loss, plot_tau_ratio # import data tau1_gen = np.reshape(np.load("../data/tau1s_Pythia_gen.npy"), ...
StarcoderdataPython
132306
# imports shared throughout the project import sys import importlib import time import numpy as np import pandas as pd import matplotlib.pyplot as plt # CONSTANTS PJ_TO_GWH = 277.7778 # [GWh / PJ] GWH_TO_PJ = 1/PJ_TO_GWH #[PJ/GWH] # HELPER import FLUCCOplus.config as config EM_TO_EXCEL_colnames = { "pow...
StarcoderdataPython
1722762
# 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...
StarcoderdataPython
179533
import torch import torch.nn as nn #from torch.autograd import Function def lovasz_grad(gt_sorted): """ Computes gradient of the Lovasz extension w.r.t sorted errors See Alg. 1 in paper """ p = len(gt_sorted) gts = gt_sorted.sum() intersection = gts - gt_sorted.float().cumsum(0) union...
StarcoderdataPython
1678342
<reponame>AnneGilles/bok-choy """ Test basic HTML form input interactions. """ from __future__ import absolute_import from bok_choy.web_app_test import WebAppTest from .pages import ButtonPage, TextFieldPage, SelectPage, CheckboxPage class InputTest(WebAppTest): """ Test basic HTML form input interactions. ...
StarcoderdataPython
3208398
<gh_stars>0 from django.db import models from django.db.models import Sum from django.utils.translation import gettext_lazy as _ from mptt.models import MPTTModel, TreeForeignKey from sorl.thumbnail import ImageField class Department(MPTTModel): name = models.CharField(max_length=250, unique=True, verbose_name=_(...
StarcoderdataPython
55899
#!/usr/bin/env python from __future__ import print_function import numpy as np import cv2 as cv from tests_common import NewOpenCVTests class Bindings(NewOpenCVTests): def test_inheritance(self): bm = cv.StereoBM_create() bm.getPreFilterCap() # from StereoBM bm.getBlockSize() # from Ster...
StarcoderdataPython
3214665
<gh_stars>0 import os import sys import shutil import errno import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import glob import scipy as sp import scipy.stats import csv import logging sns.set(style="darkgrid") def delete_dirs(path_to_dir): _logger = logging.getLogger(_...
StarcoderdataPython
1673624
<reponame>josephwkim/schedulize import numpy as np import pandas as pd from calParser import obtainSchedule from audit_parser import audit_info from lsa_recommender import export_to_master,filter_available_classes from decision_tree import preference_score,top_preferred_courses from collaborative_filtering import loadA...
StarcoderdataPython
3301394
<reponame>cnheider/vulkan-kompute """ Script to handle conversion of compute shaders to spirv and to headers """ import os import sys import logging import click import subprocess logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler()) is_windows = sys.platform.startswith('win') CWD=os.pa...
StarcoderdataPython
1611451
<filename>test/sounds.py<gh_stars>1-10 # -*- coding: utf-8 -*- """ test.sounds ~~~~~~~~~~~ Tests various functions for Sanskrit sounds. :license: MIT and BSD """ from builtins import zip from sanskrit_util import sounds from . import TestCase class CleanTestCase(TestCase): def test(self): ...
StarcoderdataPython
3342008
__all__ = ['BioCDocument'] from .compat import _Py2Next from .meta import _MetaId, _MetaInfons, _MetaRelations, _MetaIter class BioCDocument(_MetaId, _MetaInfons, _MetaRelations, _MetaIter, _Py2Next): def __init__(self, document=None): self.id = '' self.infons = dict() self.relations = ...
StarcoderdataPython
139582
# Copyright (c) 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. import json from qiskit import __version__ from IBMQuantumExperience import IBMQuantumExperience from packaging import version import argparse imp...
StarcoderdataPython
3380435
from pathlib import Path import os.path import yaml from .models import RepositoryModel from everett.manager import ( ConfigEnvFileEnv, ConfigManager, ConfigOSEnv, ) config = ConfigManager([ # first check for environment variables ConfigOSEnv(), # then look in the .env file ConfigEnvFileEn...
StarcoderdataPython
1769260
"""Area under uplift curve""" import typing import numpy as np import pandas as pd import datatable as dt from h2oaicore.metrics import CustomScorer class AUUC(CustomScorer): _description = "Area under uplift curve" _maximize = True # whether a higher score is better _perfect_score = 2.0 # AUUC can be s...
StarcoderdataPython
1720695
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 10 14:59:37 2020 Copyright 2020 by <NAME>. """ # %% Imports. # Standard library imports: import numpy as np from scipy.sparse import csr_matrix # Chebpy imports: from chebpy.nla import sphankel # %% Test 1. col = np.array([1, 2, 3, 4]) H = sphan...
StarcoderdataPython
3255846
import curses # Initializing Curses screen = curses.initscr() # Options area, only one for this and that's starting colors curses.start_color() # Setting a variable to True for the while loop to loop through the menu until user quits bool = True while bool: # Ensuring the screen is cleared before loading the men...
StarcoderdataPython
1627470
import requests import datetime def get_price(start='2013-01-01', end=datetime.date.today().isoformat(), currency='USD'): r = requests.get('http://api.coindesk.com/v1/bpi/historical/close.json?currency={2}&start={1}&end={0}' .format(end, start, currency)) data = r.json()['bpi'] x = list(data.keys()) ...
StarcoderdataPython
1680239
<filename>pychron/git/hosts/gitlab.py<gh_stars>1-10 # =============================================================================== # Copyright 2016 <NAME> # # 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 ...
StarcoderdataPython
1762953
from .closed import keys as k from .closed import commands as c from .closed import modes as m import copy keys = copy.deepcopy(k) commands = copy.deepcopy(c) modes = copy.deepcopy(m) keys['a']['word'] = 'a' keys['b']['word'] = 'b' keys['c']['word'] = 'c' keys['d']['word'] = 'd' keys['e']['word'] = 'e' keys['f']['wor...
StarcoderdataPython
1626609
""" Performing Range Minimum Queries, Range Maximum Queries, Range Sum Queries in O(log(n)) using a prebuilt structure. Building a full binary tree and using it for Range Minimum Queries, Range Maximum Queries, Range Sum Queries (A full binary tree is a tree in which every node has either 0 or 2 children.) The construc...
StarcoderdataPython
12256
<reponame>gotcha/salt # -*- coding: utf-8 -*- ''' tests.unit.utils.filebuffer_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :codeauthor: :email:`<NAME> (<EMAIL>)` :copyright: © 2012 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. ''' # Import salt l...
StarcoderdataPython
3217724
# 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. from __future__ import absolute_import, division, print_function, unicode_literals import logging import math import random import torch imp...
StarcoderdataPython
4828997
<reponame>rohe/otest """ Assertion test module ~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by <NAME>. :license: APACHE 2.0, see LICENSE for more details. """ from future.backports.urllib.parse import parse_qs import json import inspect import traceback import sys from otest.events import EV_PROTOCOL_R...
StarcoderdataPython
174784
<reponame>nfirvine/netgeardisc import socket import time import sys if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'): print('netgeardisc <my IP>') sys.exit(1) else: me = sys.argv[1] p = b'000200000000000000000000000100000c07d2f20000000000000000000000000000000000000000' sout = socket.socket(socket...
StarcoderdataPython
1709993
import http.client from http.server import HTTPServer, BaseHTTPRequestHandler import ssl import socketserver from cgi import parse_header, parse_multipart from urllib.parse import parse_qs import http.client import logging logging.basicConfig(filename="log", filemode='a', ...
StarcoderdataPython
3238247
<filename>data/plots/src/plot_2D_electrochem.py<gh_stars>0 from utils import * import numpy import matplotlib.pyplot as plt import os, os.path from scipy.constants import k, e, electron_volt, epsilon_0 pixels = (512, 512) quantities = ("V", "c_p", "c_n", "zflux_cp", "zflux_cn") units = ("V", "mol/L", "mol/L", "mol/(...
StarcoderdataPython
1754040
<gh_stars>1-10 # -*- coding: utf-8 -*- {{{ # vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et: # # Copyright 2017, Battelle Memorial Institute. # # 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...
StarcoderdataPython
1793167
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): class GenderChoices(models.TextChoices): MALE = "M", "Male" FEMALE = "F", "Female" class MatchChoices(models.TextChoices): MALE = "M", "Male" FEMALE = "F", "Female" ...
StarcoderdataPython
4833121
<filename>DQM/DTMonitorClient/python/dtResolutionAnalysisTest_cfi.py import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester dtResolutionAnalysisTest = DQMEDHarvester("DTResolutionAnalysisTest", diagnosticPrescale = cms.untracked.int...
StarcoderdataPython
3263119
from flask import Blueprint participant = Blueprint('participant', __name__) from . import views # noqa
StarcoderdataPython
1692460
""" 搜索顺序 """ import sys # 导入搜索路径:["根目录",.....,] # 每次导入时,都会遍历该列表, # 如果导入路径与列表中记录的路径,能够找到文件,则导入成功 print(sys.path)
StarcoderdataPython
3355151
<reponame>iconnor/cowrie<filename>src/cowrie/test/test_cat.py # -*- test-case-name: Cowrie Test Cases -*- # Copyright (c) 2018 <NAME> # See LICENSE for details. """ Tests for general shell interaction and cat command """ import os from twisted.trial import unittest from cowrie.shell import protocol from cowrie.te...
StarcoderdataPython
1673823
# Copyright 2017-2020 EPAM Systems, Inc. (https://www.epam.com/) # # 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 appli...
StarcoderdataPython
1765138
import unittest from datetime import datetime from datetime import timedelta from programy.services.library.base import PythonAPIService from programy.services.library.base import PythonAPIServiceException from programy.services.config import ServiceConfiguration class PythonAPIServiceExceptionTests(unittest.TestCase...
StarcoderdataPython
1690101
<reponame>dcampos/nvim-ulf from .lfx import LFX, RequestHelper
StarcoderdataPython
1669829
<reponame>Pablo-RodriguezOrtiz/Small-projects # ------------------------------------------------------------------------ # # # Made with python 3.8.8 # # As professor requested, we used "/" to separate characters and "//" to separate words. # -----------------------------------------------------------------------...
StarcoderdataPython
3248505
<gh_stars>1-10 userdb="user" user_design="user" user_view="user" flowsdb="flows_bak" flows_design="flows" flows_view="flow" switches="switches_bak" switches_design="switches" switches_view="switch"
StarcoderdataPython
68611
from pyspark.sql import SparkSession spark = SparkSession.builder.appName("SparkSQL").getOrCreate() # header means we are using a header in the CSV File # inferSchema means to tell spark to try to figure it out the table Schema people = spark.read.option("header", "true").option("inferSchema", "true")\ .csv("file...
StarcoderdataPython
3343531
# CHECK-JQ: .scope == {} # CHECK-TREE: (#unit) ()
StarcoderdataPython
4827929
#!/bin/python ###################################### # Generate contact maps from bam files # and fragment lists # # Author: <NAME> (28/11/2014) ###################################### import os, sys, re import traceback from optparse import OptionParser import fileinput import datetime from readData import * from quic...
StarcoderdataPython
4806138
<reponame>team-cryptonewbies/crypto-contest-2021 import unittest from stack_processor.lsh256 import LSHDigest class TestLSH256Hash(unittest.TestCase): def test_digest(self): self.assertEqual( LSHDigest.digest(data=b"abc").hex(), "5fbf365daea5446a7053c52b57404d77a07a5f48a1f7c1963a08...
StarcoderdataPython
3292097
#!/usr/bin/env python3 # Add gnomAD's site only HT globals and row annotations to the 38 liftover import logging logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s') logger = logging.getLogger() logger.setLevel(logging.INFO) import hail as hl from hail_scripts.utils.hail_utils import write_ht, impo...
StarcoderdataPython
1656589
import glob import pandas as pd import random import os import shutil dftr = pd.read_csv('train.csv') dfvl = pd.read_csv('val.csv') dfts = pd.read_csv('test.csv') datas = {} for k, v in dftr.iterrows(): if v['label'] in datas: datas[v['label']].append(v['filename']) else: datas[v['label']] = ...
StarcoderdataPython
4842303
""" Generate drag-and-drop configuration files for PIC devices through device support scripts The generated device blob can be used to provide drag and drop programming support for kits with onboard debuggers """ # Python 3 compatibility for Python 2 from __future__ import print_function # args, logging import argpar...
StarcoderdataPython
1715401
import hydra from torch.utils.data import random_split import torchvision import torch import math from upcycle import cuda from gnosis.distillation.classification import reduce_ensemble_logits import copy from torch.utils.data import TensorDataset, DataLoader import random import os from torchvision.datasets.folder i...
StarcoderdataPython
4835568
from abc import ABCMeta, abstractmethod import six class Lakehouse(six.with_metaclass(ABCMeta)): # pylint: disable=no-init @abstractmethod def hydrate(self, context, table_type, table_metadata, table_handle): pass @abstractmethod def materialize(self, context, table_type, table_metadata, va...
StarcoderdataPython
3297809
from IPython.display import display import pandas from Datascrap import I_date,I_frequency,end,start,I_wordtocount,I_sentpolarity,I_sentsubjectivity,I_score,I_type # --------------------------------------------------------------------------------# print("Total Posts,Comments & Replies = " + str(len(I_date))...
StarcoderdataPython
1612781
# Generated by Django 3.2.7 on 2021-09-01 17:13 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='DemoModel', fields=[ ...
StarcoderdataPython
30772
import os import shutil from modulefinder import ModuleFinder def main(): temp_dir = "package_temp" if os.path.exists(temp_dir): shutil.rmtree(temp_dir) os.makedirs(temp_dir) for py in ["index.py", "notifier.py"]: src, dst = py, os.path.join(temp_dir, py) print("copy '%s' to '...
StarcoderdataPython
154620
from rest_framework import serializers from .models import Movie class MovieSerializer(serializers.ModelSerializer): class Meta: fields = ( "name", "plot", "year", "director", "actors", "image", "ratings", "url...
StarcoderdataPython
1790366
<reponame>unplugstudio/mezzanine-webinars import os import shutil import sys import tempfile import django from pathlib2 import Path # Path to the temp mezzanine project folder TMP_PATH = Path(tempfile.mkdtemp()) / "project_template" # Injected at the bottom of local_settings.py TEST_SETTINGS = """ # START INJECTED...
StarcoderdataPython
4809094
import tornado.ioloop import tornado.web from tornado.gen import coroutine from tornado_swirl import api_routes from tornado_swirl.swagger import Application, describe, restapi, schema, add_global_tag, add_security_scheme from tornado_swirl.openapi import security describe(title='Test API', description='Just things ...
StarcoderdataPython
1767996
<reponame>Rohith04MVK/Neutron-Bot import typing as t from abc import abstractmethod from collections import defaultdict from contextlib import suppress from dataclasses import field, make_dataclass from importlib import import_module import asyncpg from loguru import logger if t.TYPE_CHECKING: from bot.core.bot i...
StarcoderdataPython
1761262
# -*- coding: utf-8 -*- """ idfy_rest_client.models.company_info_difi_response This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ class CompanyInfoDifiResponse(object): """Implementation of the 'CompanyInfoDifiResponse' model. TODO: type model ...
StarcoderdataPython
3380843
#!/usr/bin/env python # 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...
StarcoderdataPython
1698156
""" This is an implementation of Generative Adversarial Imiation Learning See https://arxiv.org/abs/1606.03476 """ import torch import torch.nn as nn import torch.nn.functional as F from machina import loss_functional as lf from machina import logger from machina.algos import trpo, ppo_kl, ppo_clip from machina.utils...
StarcoderdataPython
90114
<reponame>ak-ustutt/GeCCo-public<gh_stars>0 from python_interface.gecco_interface import * new_target('TEST_ADD_UNITY',True) DEF_OP_FROM_OCC({ LABEL:"DUMMY_1", DESCR:'P,P|PP,PP|V,V|VV,VV|H,H|HH,HH' }) SET_HERMITIAN({ LABEL:"DUMMY_1", CA_SYMMETRY:+1}) DEF_ME_LIST({ LIST:'ME_...
StarcoderdataPython
1600563
<reponame>ealogar/servicedirectory ''' (c) Copyright 2013 Telefonica, I+D. Printed in Spain (Europe). All Rights Reserved. The copyright to the software program(s) is property of Telefonica I+D. The program(s) may be used and or copied only with the express written consent of Telefonica I+D or in accordance with the t...
StarcoderdataPython
60097
<reponame>timothydmorton/CCL from . import ccllib as lib from .pyutils import check import numpy as np class Pk2D(object): """A power spectrum class holding the information needed to reconstruct an arbitrary function of wavenumber and scale factor. Args: pkfunc (:obj:`function`): a function retu...
StarcoderdataPython
3389269
<reponame>wintercircle/django-easy-select2 from django.contrib import admin from django import forms from easy_select2 import select2_modelform from .models import Note, Category class NoteAdmin(admin.ModelAdmin): form = select2_modelform(Note) admin.site.register(Category) admin.site.register(Note, NoteAdmin...
StarcoderdataPython
3235791
<filename>mindspore/common/parameter.py<gh_stars>1-10 # Copyright 2020 Huawei Technologies Co., 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-...
StarcoderdataPython
4842707
# -*- coding: utf-8 -*- """Console script for dmriprep.""" import sys import click from . import run from . import io import os @click.command() @click.option('--participant-label', help="The label(s) of the participant(s) that should be" "analyzed. The label corresponds to...
StarcoderdataPython
1675434
<filename>homeassistant/components/yale_smart_alarm/entity.py """Base class for yale_smart_alarm entity.""" from homeassistant.const import CONF_NAME, CONF_USERNAME from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC from homeassistant.helpers.entity import DeviceInfo, Entity from homeassistant.he...
StarcoderdataPython
1649113
<gh_stars>0 #!/usr/bin/env python3 """ @author: <NAME> @email: <EMAIL> * CLASS MODULE * Contains the core classes needed for the Water.py main file: - Particle - Molecule (inherits the particle class) - Force (inherits the molecule class) - IntegratorNH (inherits the particle class) Latest update: July 12th 2...
StarcoderdataPython
4828514
class Solution: """ https://leetcode.com/problems/majority-element/ Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. ...
StarcoderdataPython
185194
<gh_stars>10-100 import json import os import subprocess import sys import glob import time import webbrowser import serial.tools.list_ports import socket import netifaces from random import randrange print("WUTUP!!!") def cls(): os.system('cls' if os.name=='nt' else 'clear') def Diff(li1, li2): return (lis...
StarcoderdataPython
3211548
<filename>simulation_site/simulation/models.py from django.db import models from django.core.urlresolvers import reverse from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Resource(models.Model): id = models.AutoField(primary_key=True) name = models.CharFie...
StarcoderdataPython
3301437
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license. """ # Generated by Django 3.1.4 on 2021-03-03 07:31 import core.utils.common from django.conf import settings from django.db import migrations, models...
StarcoderdataPython
36522
import tensorflow as tf from KENN2.layers.residual.KnowledgeEnhancer import KnowledgeEnhancer class Kenn(tf.keras.layers.Layer): def __init__(self, predicates, clauses, activation=lambda x: x, initial_clause_weight=0.5, save_training_data=False, **kwargs): """Initialize the knowledge base. :para...
StarcoderdataPython
1679126
# Distributed under the MIT License. # See LICENSE.txt for details. import numpy as np from Elasticity.ConstitutiveRelations.IsotropicHomogeneous import ( youngs_modulus, poisson_ratio) def displacement(x, length, height, bending_moment, bulk_modulus, shear_modulus): local_youngs_modulus = y...
StarcoderdataPython
1620475
<filename>cogs/misc.py<gh_stars>0 import discord from discord.ext import commands import random import typing from .utils import ids from .utils.lists import weapons, adjectives from .utils.helper import split_to_shorter_parts class MiscCog(commands.Cog, name="Misc"): def __init__(self, bot): self.bot = ...
StarcoderdataPython
3329775
<reponame>khchine5/vilma # -*- coding: UTF-8 -*- # Copyright 2017 <NAME> # License: BSD (see file COPYING for details) """ Base Django settings for Lino Vilma applications. """ from __future__ import print_function from __future__ import unicode_literals from lino.projects.std.settings import * from lino.api.ad impo...
StarcoderdataPython
3282098
''' Game of Life ''' class Game: def __init__(self): self.states = list() def new(self, seed): self.irange = len(seed) # convas i self.jrange = len(seed[0]) # convas j self.states.append(seed) # first step is the seed itself ''' Run only one step forward ''' def run_one...
StarcoderdataPython
1798478
# coding=utf-8 class Config: INPUT_DIR = "input" STOCK_ID_NAME_MAP_SHA = "input/common/stock_id_name_map/sha" STOCK_ID_NAME_MAP_SZ = "input/common/stock_id_name_map/sz" STOCK_ID_NAME_MAP_OPEN = "input/common/stock_id_name_map/open" CURRENT_HOLDED_PATH = "input/holded" STOCKS_PATH = "input/...
StarcoderdataPython
3314132
<reponame>YeffyCodeGit/LoginManager<filename>main.py<gh_stars>1-10 import re import hashlib def add(name, password): with open('users.txt', 'a') as f: f.write(f'{name}:{password}\n') def view(): with open('users.txt', 'r') as f: print('-------------------- USERS --------------------') l...
StarcoderdataPython
1677156
import json from datetime import datetime from instagram_private_api import (Client, ClientError, ClientLoginError, ClientCookieExpiredError, ClientLoginRequiredError, __version__ as client_version) import sys import os.path from utils.utils import * def onlogin_callback(api, new_s...
StarcoderdataPython
160027
<gh_stars>10-100 # # Beaglebone GPIO output pin driver # # Author: <NAME> # Copyright (c) 2015, Semcon Sweden AB # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted # provided that the following conditions are met: # 1. Redistributions of source code...
StarcoderdataPython
199441
<gh_stars>0 """ Test turning a bag into other forms. """ import simplejson from tiddlyweb.serializer import Serializer from tiddlyweb.model.bag import Bag from tiddlyweb.config import config from fixtures import bagfour, tiddler_collection, reset_textstore def setup_module(module): reset_textstore() modul...
StarcoderdataPython
1701686
from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class DataQualityOperator(BaseOperator): ui_color = '#89DA59' @apply_defaults def __init__(self, tables_check="", redshift_con...
StarcoderdataPython
1611646
from PIL import ImageColor PURPLE = 117, 112, 179 ORANGE = 217, 95, 2 GREEN = 27, 158, 119 def get_font_color(background_color): if not isinstance(background_color, tuple): background_color = ImageColor.getrgb(background_color) # calculate perceptive luminance r, g, b = background_color lumi...
StarcoderdataPython
91831
<reponame>titibike/PynamoDB """ An example using Amazon's Thread example for motivation http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SampleTablesAndData.html """ import logging from pynamodb.models import Model from pynamodb.attributes import ( UnicodeAttribute, NumberAttribute, UnicodeSetAttrib...
StarcoderdataPython
3279294
from ConfigParser import ConfigParser import os def get_user_pass(cred_profile, fpath=None): config = ConfigParser() if not fpath: fpath = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'api_creds.cfg') config.read(fpath) user = config.get(cred_profile, 'user') password = config....
StarcoderdataPython
19805
<filename>shoptimizer_api/optimizers_builtin/condition_optimizer.py # coding=utf-8 # Copyright 2020 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/l...
StarcoderdataPython
4834610
""" Scripts for analyzing the results. """ import numpy as np import pickle from DataProcessor import DataProcessor from utils_analysis import ( hc_analysis, plot_3d_B, differential_pathway, component_portion, classify_patients, component_func, plot_phylo, plot_patients_F) __author__ = "<NAME>" # Load dat...
StarcoderdataPython
3251278
<filename>Mesh/System/Entity/Concrete/Table.py import numpy as np from Mesh.System.Entity.Concrete import Concrete from Mesh.System.SpaceFactor import MatterType class Table(Concrete): identifier = 'tables' default_dimension = (5, 4, 4) default_orientation = (0, 1, 0) def __init__(self, uuid, dimens...
StarcoderdataPython
1752563
# MINLP written by GAMS Convert at 04/21/18 13:54:16 # # Equation counts # Total E G L N X C B # 202 152 0 50 0 0 0 0 # # Variable counts # x b i s1s s2s sc ...
StarcoderdataPython
179572
<reponame>NichCritic/pymud from pynlg.realizer import NounConjunction, NounPhrase, VerbPhrase, PrepositionalPhrase, Clause from pynlg.lexicon import Noun, Adjective, Verb class ObjectDescriber(object): def __init__(self, lexicon): self.lex = lexicon ''' Find the target in the provided tree, then...
StarcoderdataPython
119875
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'SponsorListPlugin' db.create_table('cmsplugin_sponsorlistplugin', ( ('cmsplugin_...
StarcoderdataPython