id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3344040
"""Preference management for cloud.""" from ipaddress import ip_address from typing import List, Optional from homeassistant.auth.const import GROUP_ID_ADMIN from homeassistant.auth.models import User from homeassistant.core import callback from homeassistant.util.logging import async_create_catching_coro from .const...
StarcoderdataPython
97989
class MinStack: # Update Min every pop (Accepted), O(1) push, pop, top, min def __init__(self): self.stack = [] self.min = None def push(self, val: int) -> None: if self.stack: self.min = min(self.min, val) self.stack.append((val, self.min)) else: ...
StarcoderdataPython
27023
<reponame>oruebel/ndx-icephys-meta """ Module with ObjectMapper classes for the icephys-meta Container classes/neurodata_types """ from pynwb import register_map from pynwb.io.file import NWBFileMap from hdmf.common.io.table import DynamicTableMap from ndx_icephys_meta.icephys import ICEphysFile, AlignedDynamicTable ...
StarcoderdataPython
9610
<gh_stars>1-10 """ Test to verify performance of PVC creation and deletion for RBD, CephFS and RBD-Thick interfaces """ import time import logging import datetime import pytest import ocs_ci.ocs.exceptions as ex import threading import statistics from concurrent.futures import ThreadPoolExecutor from uuid import uuid4 ...
StarcoderdataPython
3384695
#ExrMerge v1.0 from nukepedia #Desarrollado por <NAME> (Zabander) 21-11-2014. #hacked by Rafal 1)removed the write node 2)added stringSplit to tidy the name to remove version, show, shot; 3) changed into class #todo , do noBeauty, make gui, new group name, bring back option to create write, fix error traps (i.e. if rea...
StarcoderdataPython
61209
# contains neither Process object nor execute() function
StarcoderdataPython
6479
<gh_stars>1-10 picamera import PiCamera from time import sleep import boto3 import os.path import subprocess s3 = boto3.client('s3') bucket = 'cambucket21' camera = PiCamera() #camera.resolution(1920,1080) x = 0 camerafile = x while True: if (x == 6): x = 1 else: x = x + 1 camera.start_preview() camera.start_recordi...
StarcoderdataPython
3360638
<gh_stars>0 from one_indiv_immed_fri import friend_besties from second_degree_fri import friend_second_besties from collections import defaultdict #adapted from University of Melbourne's sample solution def predict_attribute(friends, feat_dict, feature): """predict the target 'feature' from the set 'friends' base...
StarcoderdataPython
3386234
# Written by <NAME> # https://github.com/bo-yang/misc/blob/master/run_command_timeout.py import subprocess import threading """ Run system commands with timeout """ class Command(object): def __init__(self, cmd): self.cmd = cmd self.process = None self.out = "TIMEOUT" def run_command(...
StarcoderdataPython
3295830
''' Bluefruit_Onboard_Neopixel Illuminates the CPB's built-in NeoPixels (internally connected to pin 8). Developed for The Art of Making: An Introduction to Hands-On System Design and Engineering University of Pittsburgh Swanson School of Engineering v1.2 <NAME> 02/11/2022 Wheel() colorwheel function based on Adafruit'...
StarcoderdataPython
3292939
<reponame>neriat/envcon from .configuration import environment_configuration, configuration from .frozen import FrozenError __all__ = ["environment_configuration", "configuration", "FrozenError"]
StarcoderdataPython
95607
<gh_stars>0 import alsaaudio from math import pi, sin, pow import getch SAMPLE_RATE = 44100 FORMAT = alsaaudio.PCM_FORMAT_U8 PERIOD_SIZE = 512 N_SAMPLES = 1024 notes = "abcdefg" frequencies = {} for i, note in enumerate(notes): frequencies[note] = 440 * pow(pow(2, 1/2), i) # Generate the sine wave, centered at y...
StarcoderdataPython
71683
<reponame>DanPopa46/neo3-boa from __future__ import annotations import base64 from typing import Any, Dict, List, Optional from boa3.neo import from_hex_str, to_hex_str from boa3.neo3.core.types import UInt256 from boa3_test.tests.test_classes import transactionattribute as tx_attribute from boa3_test.tests.test_clas...
StarcoderdataPython
121464
import pandas as pd import itertools import numpy as np import pickle import os import argparse basePath=os.getcwd() def get_file_list(file_folder): # method one: file_list = os.listdir(file_folder) for root, dirs, file_list in os.walk(file_folder): return dirs,file_list parser = argparse.ArgumentPars...
StarcoderdataPython
18223
from .constants import SPECIAL_TOKENS try: import re2 as re except ImportError: import re def twitter_sentiment_token_matching(token): """Special token matching function for twitter sentiment data.""" if 'URL_TOKEN' in SPECIAL_TOKENS and re.match(r'https?:\/\/[^\s]+', token): return SPECIAL_TO...
StarcoderdataPython
3266545
# # -*- coding: utf-8 -*- # # Copyright (c) 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 app...
StarcoderdataPython
3391205
<filename>externals/director/src/python/ddapp/shallowCopy.py<gh_stars>0 def deepCopy(dataOb): newData = dataObject.NewInstance() newData.DeepCopy(dataObj) return newData def shallowCopy(dataObj): newData = dataObj.NewInstance() newData.ShallowCopy(dataObj) return newData
StarcoderdataPython
1665580
<filename>python/src/examples/node_ledbutton/node.py #!/usr/bin/python3 # import aiogrpc import asyncio import logging import grpc import signal import sys # pregenerated from proto file import wedge_pb2 import wedge_pb2_grpc from button import Button from led import Led CHANNEL_OPTIONS = [('grpc.lb_policy_name', 'p...
StarcoderdataPython
4821853
<reponame>fcoterroba/first_birthday_statistics_python import matplotlib.pyplot as plt # Make the arrays with the info meses = ["Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre", "Enero", "Febrero", "Marzo"] visitas = [816, 1034, 1101, 1250, 1604, 1983, 2468, 3021, 2867, 352...
StarcoderdataPython
1786318
<reponame>michaelfarinacci/tchack2016<filename>app.py from flask import Flask, redirect, url_for, render_template, request, flash import flask import os from os.path import join, dirname from dotenv import load_dotenv import braintree import json app = Flask(__name__) dotenv_path = join(dirname(__file__), '.env') loa...
StarcoderdataPython
1643745
<reponame>LordKBX/EbookCollection from checkpoint import * from files import * from content_table_editor import * from PyQt5 import QtCore from PyQt5 import QtGui from PyQt5 import QtWidgets sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from common.dialog import * from common.books i...
StarcoderdataPython
1635514
<gh_stars>100-1000 # Copyright 2019 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
StarcoderdataPython
3341024
# Generated by Django 2.2.10 on 2020-03-16 04:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('workflow', '0009_auto_20200306_1040'), ('workflow', '0009_projectstatus'), ] operations = [ ]
StarcoderdataPython
3323398
<filename>source/HTTP_Component/Sensors.py # # Date: 2/24/21 # File Name: Sensors.py # # Engineer: <NAME> # Contact: <EMAIL> # # Description: # This is a script intended to retrieve, parse and return data from network connected sensors. # # from urllib.request import urlopen import math METRIC = "mert...
StarcoderdataPython
22315
""" Defines models """ import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Function from torch.autograd import Variable from torch.nn.utils.rnn import pack_padded_sequence from torch.nn.utils.rnn import pad_packed_sequence def init_weights(m): if type(m) == nn.Linear or ...
StarcoderdataPython
1788033
import json import os import shutil from imskaper.experiment.experiment import experiment, read_Xy_data from imskaper.utils.classifiers import get_classifiers from imskaper.utils.features_selectors import get_features_selectors current_path = "tests" # os.path.dirname(os.path.abspath(__file__)) json_path = os.path.jo...
StarcoderdataPython
169544
<filename>AutotestWebD/all_urls/LittleToolUrl.py from django.conf.urls import url from apps.littletool.views import tool urlpatterns = [ #add page url(r'^littletool/jsoncn$', tool.jsoncn, name="LITTLETOOL_jsoncn"), ]
StarcoderdataPython
3343601
<reponame>ChadKillingsworth/sentry from __future__ import absolute_import from django.core.urlresolvers import reverse from mock import patch from sentry.models import ( AuthProvider, OrganizationMember, OrganizationMemberType ) from sentry.testutils import APITestCase class UpdateOrganizationMemberTest(APITest...
StarcoderdataPython
16511
<gh_stars>0 import numpy as np from scipy import constants measured_species = ["HMF", "DFF", "HMFCA", "FFCA", "FDCA"] all_species = measured_species.copy() all_species.extend(["H_" + s for s in measured_species]) all_species.extend(["Hx_" + s for s in measured_species]) def c_to_q(c): c_e = list() for i, ...
StarcoderdataPython
1795029
# -*- coding: utf-8 -*- # # Copyright (c) 2018-2019 <NAME> # # Distributed under MIT License. See LICENSE file for details. from __future__ import unicode_literals import factory # FAQ: `pyint` is everywhere because it is always [0..9999], so it # will be good enough for every integer-related field. def build_bigin...
StarcoderdataPython
111243
from typing import Optional, List from ..pattern import Pattern from ..pattern_recognizer import PatternRecognizer class IpRecognizer(PatternRecognizer): """ Recognize IP address using regex. :param patterns: List of patterns to be used by this recognizer :param context: List of context words to inc...
StarcoderdataPython
3286132
''' Created on 31 Mar 2017 @author: <NAME> <<EMAIL>> ''' from rdflib import URIRef, BNode, Literal, Graph, Namespace from rdflib.namespace import RDF, RDFS, XSD, OWL from Misc.datacheck import isfloat #Tuple of the form: (*camera id*:string, *camera lat*:string, *camera long*: string, # *OSM derived road name*:stri...
StarcoderdataPython
1681072
import os import warnings import numpy as np from scipy.spatial import distance from pycosmosac.molecule.cavity import Cavity from pycosmosac.param import data from pycosmosac.utils import elements BOND_SCALING = 1.2 def get_connectivity(mol, geometry=None): #TODO improve accuracy if geometry is None: ...
StarcoderdataPython
129127
<gh_stars>0 from UM.Settings.Models.InstanceContainersModel import InstanceContainersModel from unittest.mock import MagicMock, patch import pytest @pytest.fixture def instance_containers_model(container_registry): with patch("UM.Settings.ContainerRegistry.ContainerRegistry.getInstance", MagicMock(r...
StarcoderdataPython
153616
<filename>C++/testing/serverSock.py import socket #from threading import * HOST = '10.1.121.102' PORT = 65432 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print('connected by', addr) ...
StarcoderdataPython
122697
from .bot import Bot from .utils.logger import LogLevel __all__ = (LogLevel, Bot)
StarcoderdataPython
160071
#!/usr/bin/python2.4 # # Copyright 2010-2012 Google Inc. All Rights Reserved. """Renderscript Compiler Test. Runs subdirectories of tests for the Renderscript compiler. """ import filecmp import glob import os import re import shutil import subprocess import sys __author__ = 'Android' class Options(object): def...
StarcoderdataPython
3253603
<gh_stars>1-10 """ https://leetcode.com/explore/interview/card/top-interview-questions-hard/116/array-and-strings/827/ """ from typing import List # refrenced solution to arrive at this result class Solution: def product_except_self(self, nums: List[int]) -> List[int]: """ no division O(n)...
StarcoderdataPython
1713068
<gh_stars>0 import pytest from dynamodb_doctor import Model, String, ModelCreationException, Many ENDPOINT_URL = "http://localhost:58000" @pytest.mark.asyncio async def test_define_model_without_table(): with pytest.raises(ModelCreationException): class _(Model): name = String() @pytest.ma...
StarcoderdataPython
4809677
<filename>dprint/_impl.py import tokenize import inspect import token import sys import re import io import os _NAME_MATCHING_REGEX = re.compile(r'\bdprint\b') def dprint(value): """A simple printing debugging helper. Designed to be used on any expression, to print the value of an expression, without mo...
StarcoderdataPython
3222832
<filename>test/test_minimum_jerk_trajectory.py import numpy as np from movement_primitives.minimum_jerk_trajectory import MinimumJerkTrajectory from numpy.testing import assert_array_almost_equal def test_step_through_minimum_jerk_trajectory(): mjt = MinimumJerkTrajectory(3, 1.0, 0.01) mjt.configure(start_y=n...
StarcoderdataPython
3320544
from pynwb import TimeSeries import numpy as np from bisect import bisect, bisect_left def get_timeseries_tt(node: TimeSeries, istart=0, istop=None) -> np.ndarray: """ For any TimeSeries, return timestamps. If the TimeSeries uses starting_time and rate, the timestamps will be generated. Parameters ...
StarcoderdataPython
1605940
<filename>Site-Campus/sitecampus/migrations/0007_auto_20191121_1902.py<gh_stars>1-10 # Generated by Django 2.2.7 on 2019-11-21 19:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sitecampus', '0006_post_sutia'), ] operations = [ migra...
StarcoderdataPython
1647869
<filename>python/cugraph/cugraph/tests/conftest.py # Copyright (c) 2021, NVIDIA 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 #...
StarcoderdataPython
162911
<reponame>Aditya-aot/Web-Scraping-of-car24-in-Python<gh_stars>0 from bs4 import BeautifulSoup import pandas as pd import requests import re url = 'https://www.cars24.com/buy-used-honda-cars-delhi-ncr/' page = requests.get(url) soup = BeautifulSoup(page.text,'html.parser') Cars_dict = {} cars_no = 0 no_pag...
StarcoderdataPython
3297064
<filename>notes/migrations/0003_auto_20171008_1407.py # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-08 08:37 from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion from django.utils.timezone im...
StarcoderdataPython
1662390
<gh_stars>10-100 #!/usr/bin/env python # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2019 DataONE # # Licensed under the Apache Licens...
StarcoderdataPython
112886
from rest_framework import serializers from ..models import Anime, Movie, Show class AnimeSerializer(serializers.ModelSerializer): class Meta: model = Anime fields = '__all__' class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = '__all__' c...
StarcoderdataPython
1732014
import shap import warnings import pandas as pd import numpy as np import matplotlib.pyplot as plt try: import plotly.express as px import plotly.graph_objects as go except ModuleNotFoundError: _has_plotly = False _plotly_exception_message = ( 'Plotly is required to run this pydrift functionalit...
StarcoderdataPython
3375891
<filename>jes/jes-v5.020-linux/demos/turtle.py w = makeWorld(500, 500) t = makeTurtle(w) penUp(t) moveTo(t, int(500 / 3), 250) penDown(t) for i in range(0, 360): turn(t, 1) forward(t, 3)
StarcoderdataPython
1659550
import numpy as np import cv2 import matplotlib.pyplot as plt import pandas as pd from scipy.optimize import linear_sum_assignment from scipy import signal from sklearn.neighbors import KernelDensity import copy import os import utm import rasterio from CountLine import CountLine import sys sys.path.append('/home/gold...
StarcoderdataPython
3277682
# # @lc app=leetcode id=525 lang=python3 # # [525] Contiguous Array # # https://leetcode.com/problems/contiguous-array/description/ # # algorithms # Medium (40.05%) # Likes: 1821 # Dislikes: 106 # Total Accepted: 125.4K # Total Submissions: 313.1K # Testcase Example: '[0,1]' # # Given a binary array, find the ma...
StarcoderdataPython
3268576
<filename>apps/greencheck/views.py from datetime import date from datetime import timedelta from django.conf import settings from google.cloud import storage from django.views.generic.base import TemplateView class GreenUrlsView(TemplateView): template_name = "green_url.html" def fetch_urls(self): c...
StarcoderdataPython
172628
# 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 warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
StarcoderdataPython
142004
<reponame>zhengxiawu/XNAS import torch import numpy as np from torch.autograd import Variable def _concat(xs): return torch.cat([x.view(-1) for x in xs]) class Architect(object): def __init__(self, net, cfg): self.network_momentum = cfg.OPTIM.MOMENTUM self.network_weight_decay = cfg.OPTIM.WE...
StarcoderdataPython
81840
""" Various utility functions. """ from __future__ import absolute_import import re import string from Crypto.Random import random HASH_REGEXP = re.compile(r'^{([A-Z0-9]+)}(.*)$') def generate_password(length=12, ascii_lower=True, ascii_upper=True, punctuation=True, digits=True, strip_ambiguou...
StarcoderdataPython
10016
<filename>metabot2txt/display.py<gh_stars>0 import os def display_on_editor(text): with open('.metabot2txt', 'w') as f: f.write(text) os.system('gedit .metabot2txt') def display_list_on_editor(texts): if os.path.isfile('.metabot2txt'): os.remove('.metabot2txt') for text in texts...
StarcoderdataPython
4802399
"""Fixtures for cutty.repositories.domain.providers.""" from collections.abc import Callable from typing import Any from typing import Optional from cutty.filesystems.adapters.dict import DictFilesystem from cutty.filesystems.domain.path import Path from cutty.repositories.domain.locations import Location from cutty.r...
StarcoderdataPython
165824
<filename>demos/appengine/app.py """ Demonstration of Duo authentication on Google App Engine. To use, edit duo.conf, set gae_domain to an appropriate email domain, and visit /. """ import ConfigParser import logging from google.appengine.api import users from google.appengine.ext import webapp from google.appengine....
StarcoderdataPython
1726398
<gh_stars>0 my_name = 'scott' def print_name(): global my_name my_name = 'jen' print('Name inside of the function is', my_name) print_name() print('Name outside of the function is', my_name)
StarcoderdataPython
134059
<reponame>f0k/matplotlib<filename>examples/pylab_examples/tripcolor_demo.py """ Pseudocolor plots of unstructured triangular grids. """ import matplotlib.pyplot as plt import matplotlib.tri as tri import numpy as np import math # Creating a Triangulation without specifying the triangles results in the # Delaunay trian...
StarcoderdataPython
160618
from pathlib import Path ROOT_DIR = Path(__file__).parent.parent.parent DEFAULT_EMBED_COLOUR = 0x00CD99 # Dependant on above constants. from .loc import CodeCounter from .ready import Ready
StarcoderdataPython
163066
import magma as m from magma.testing import check_files_equal import os def test_inline_2d_array_interface(): class Main(m.Generator): @staticmethod def generate(width, depth): class MonitorWrapper(m.Circuit): io = m.IO(arr=m.In(m.Array[depth, m.Bits[width]])) ...
StarcoderdataPython
1694189
"""Helper functions for processing the schemas.""" from . import association from . import backref from . import clean from . import iterate from . import process
StarcoderdataPython
1670832
<reponame>mrcbarbier/diffuseclique from wagutils import * import itertools from statsmodels.nonparametric.smoothers_lowess import lowess import pickle from json import dump,load import scipy.linalg as la def reldist_type2(x, y): xm, ym = np.mean(x), np.mean(y) slope = np.mean((x - xm) * (y - ym) ** 2) / np....
StarcoderdataPython
4801213
# Generated by Django 2.0.8 on 2018-11-19 13:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('transformer', '0003_auto_20181114_1407'), ] operations = [ migrations.AlterField( model_name='package', name='proces...
StarcoderdataPython
3396250
<gh_stars>1-10 """ Helper Controller Class """ import logging import logging.config import os import multiprocessing import platform try: import queue except ImportError: import Queue as queue import signal import sys import time from helper import config, __version__ LOGGER = logging.getLogger(__name__) c...
StarcoderdataPython
139766
<filename>src/key.py from dataclasses import dataclass import uuid import os import re import base58 from typing import Optional from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 from cryptography.hazmat.primitives import hashes @dataclass class SymetricKeyProps: alg: str id: Optional[s...
StarcoderdataPython
1710406
# -*- coding: utf-8 -*- import logging import unittest from clarifai.rest import ClarifaiApp from clarifai.rest import Concept from clarifai.rest import Image as ClImage from clarifai.rest import ModelOutputInfo, ModelOutputConfig urls = [ "https://samples.clarifai.com/metro-north.jpg", 'https://samples.clarifai....
StarcoderdataPython
1780635
<reponame>bhaving07/pyup<filename>venv/lib/python3.7/site-packages/gitlab/tests/objects/test_groups.py """ GitLab API: https://docs.gitlab.com/ce/api/groups.html """ import pytest import responses import gitlab @pytest.fixture def resp_groups(): content = {"name": "name", "id": 1, "path": "path"} with resp...
StarcoderdataPython
128948
<filename>data/genuine/purge.py<gh_stars>1-10 #!/usr/bin/env python3 import argparse import itertools import logging import os import csv import re from data.genuine.utils import check_lang logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) if __name__ == "__main__": """...
StarcoderdataPython
1780342
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
StarcoderdataPython
1740719
<reponame>edupyter/EDUPYTER38 import sys assert sys.platform == "win32" from ctypes import byref, windll from ctypes.wintypes import DWORD, HANDLE from typing import Any, Optional, TextIO from prompt_toolkit.data_structures import Size from prompt_toolkit.win32_types import STD_OUTPUT_HANDLE from .base import Outpu...
StarcoderdataPython
151489
<reponame>xSakix/bayesian_analyses # multivariate lin regresion of heights vs weights import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy.stats import norm, uniform, multivariate_normal from scipy.interpolate import griddata import pymc3 as pm d = pd.read_csv('../../...
StarcoderdataPython
3220171
def if_chuck_says_so(): return not True
StarcoderdataPython
1785742
<reponame>gabrielmpp/climate_indices from subprocess import call import os import requests import numpy as np import pandas as pd from pandas.errors import EmptyDataError from datetime import datetime from copy import deepcopy SOURCES = ['NOAA', 'CPC'] PID = os.getpid() TMP_FILE_PATH = os.environ['HOME'] + f'/temp_fil...
StarcoderdataPython
3367830
print "How old are you brother ?" age = raw_input() # will get some text ;def print "How tall are you ?" height = raw_input() print "do you eat enough ?" eat = raw_input() print "So, you're a %r years old and %r tall guy that says : '%r' to the food, right ?" % (age, height, eat) # Nb: to get a number from the return...
StarcoderdataPython
1669910
<reponame>killua4564/2019-AIS3-preexam from pwn import * conn = remote("pre-exam-pwn.ais3.org", "10000") conn.recvuntil(".\n") payload = b"A" * 48 + p64(0x400687) conn.sendline(payload) conn.interactive()
StarcoderdataPython
3321275
# coding: utf-8 # Distributed under the terms of the MIT license. """ This file implements classes to store and manipulate electronic and vibrational DOS, with or without projection data. """ import warnings import copy import functools import numpy as np import scipy.integrate import scipy.interpolate from matador...
StarcoderdataPython
3293096
#!/usr/bin/env python # coding:utf-8 """merge_json.py""" import logging import time import os import json, csv import xlwt, xlrd from datetime import datetime from xlrd import xldate_as_tuple def get_logger(logname): """Config the logger in the module Arguments: logname {str} -- logger name Returns: ...
StarcoderdataPython
1642640
""" Divergence metric between two scores based on size of subgraph isomorphism. If two DAGs are the exact same, the subgraph isomorphism will be of maximum size and node divergence and edge divergence will be zero. """ import sys import os import json import argparse import numpy as np import networkx as nx def ge...
StarcoderdataPython
1611735
<reponame>sony-si/pytorch-CycleGAN-and-pix2pix import os.path from data.base_dataset import BaseDataset, scale_width_and_crop_height_func from data.image_folder import make_dataset from PIL import Image class ViewUnpairedDataset(BaseDataset): """ This dataset class loads unpaired datasets for a single a view. ...
StarcoderdataPython
3219565
<gh_stars>1-10 from .Job import Job, JobIdError from .ExpandedJob import ExpandedJob from .CollapsedJob import CollapsedJob
StarcoderdataPython
1644507
import os import pygraphviz as pgv import pytest data_path = os.path.join('tardis', 'plasma', 'tests', 'data') def test_write_dot(tmpdir, simulation_verysimple): fname = str(tmpdir.mkdir('test_dot').join('plasma.dot')) simulation_verysimple.plasma.write_to_dot(fname) actual = pgv.AGraph(fname).to_string(...
StarcoderdataPython
76220
from st2common.runners.base_action import Action import paho.mqtt.publish as publish import paho.mqtt.client as paho class PublishAction(Action): def __init__(self, config): super(PublishAction, self).__init__(config) # Sensor/Action Mismatch self._config = self.config self._clie...
StarcoderdataPython
54566
import datetime import utils import glob import os import numpy as np import pandas as pd if __name__ == '__main__': loaddir = "E:/Data/h5/" labels = ['https', 'netflix'] max_packet_length = 1514 for label in labels: print("Starting label: " + label) savedir = loaddir + label + "/" ...
StarcoderdataPython
3261965
# -*- coding: utf-8 -*- # Copyright (c) 2004-2015 Odoo S.A. # Copyright 2018-2019 <NAME> <https://it-projects.info/team/KolushovAlexandr> # License MIT (https://opensource.org/licenses/MIT). from odoo import api, fields, models class BaseConfigSettings(models.TransientModel): _inherit = "base.config.settings" ...
StarcoderdataPython
4811963
""" lights.py Code based upon: https://github.com/artem-smotrakov/esp32-weather-google-sheets class Lights controls LEDs that report the following: WiFi connection, error, high temperature level, discomfort exceeded 2021-0817 PP added discomfort, removed test """ import time from machine import Pin import lolin_d1min...
StarcoderdataPython
3360875
from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. BASE_PATH = os.path.dirname(os.path.abspath('manage.py')) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'botforms.settings') app = Celery(...
StarcoderdataPython
4825235
import tensorflow as tf import numpy as np from net.layers import _conv class ResNet(): def __init__(self, arch, layers, base_filters=64, is_training=False, use_bn=True): if arch == 'resnet18' or arch == 'resnet34': self.block = self.BasicBlock elif arch == 'resnet50' or arch =='resne...
StarcoderdataPython
4816435
import os import discord import sqlite3 from environs import Env from bgg import BGGCog from meetup import Meetup from discord.ext import commands from boardgamegeek import BGGClient from codenames import Codenames import logging from music import Music logging.basicConfig(level=logging.INFO) logger = logging.get...
StarcoderdataPython
3372026
T = int(input()) for i in range(T): input() cs, ec = [int(x) for x in input().split()] total = cs + ec IQs = [int(x) for x in input().split()] while len(IQs)<total: IQs += [int(x) for x in input().split()] csIQs = IQs[0:cs] ecIQs = IQs[cs:len(IQs)] total = 0 for x in csI...
StarcoderdataPython
3323043
<gh_stars>1-10 #!/usr/bin/python3 import os # Run a filesystem scan every day unless one is in progress. os.system("echo \"$(($RANDOM % 60)) $(($RANDOM % 24)) * * * /scan.sh 2>&1 >> /logs/fimscan.log \" > /root.crontab") os.system("fcrontab -u root /root.crontab") os.system("rm /root.crontab") # Perform a...
StarcoderdataPython
45493
<reponame>isabella232/ALM-SF-DX-Python-Tools ''' Bitbucket Server Interface ''' import urllib from modules.utils import INFO_TAG, WARNING_TAG, ERROR_LINE, SUCCESS_LINE, print_key_value_list from modules.git_server_callout import http_request from modules.comment_operations import get_last_comment, append_new_comments, ...
StarcoderdataPython
157750
from django.db import models # Create your models here. class Image(models.Model): image = models.ImageField(upload_to = 'gallery/') name = models.CharField(max_length=30) description = models.CharField(max_length=100) location = models.ForeignKey('location',on_delete = models.CASCADE) category = m...
StarcoderdataPython
93351
<gh_stars>1-10 from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey class Feed(models.Model): user = models.ForeignKey('auth.User', related_name='actions', on_delete=models.CASCADE, db_i...
StarcoderdataPython
1648059
<reponame>rakesh-chinta/Blender_Renderer import os import OpenGL OpenGL.ERROR_CHECKING = False from OpenGL.GL import * from OpenGL.GL import shaders from OpenGL.GL.ARB.bindless_texture import * class Voxelizer: src_dir = os.path.dirname(os.path.realpath(__file__)) shader_clear = 0 shader_voxelize = 0 ...
StarcoderdataPython
171751
<gh_stars>10-100 #! /usr/bin/env python3 # <<BEGIN-copyright>> # Copyright 2021, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: BSD-3-Clause # <<END-copyright>> from PoPs.quantities import quantity as quantityModule from PoPs.quantities import ...
StarcoderdataPython
3327895
<filename>prove_ethics.py #!/usr/bin/python import subprocess import json steps = { '1a1': """ all A ( is_only_in_itself(A) | is_only_in_another(A) ). """, # Note: the "exists" of predicate logic is not the "is" of Spinoza's # philosophy. I am having trouble explaining how I use prover9's "exists", # then. This coul...
StarcoderdataPython
1652335
from .sgd_optimization import * from .utils import * from .data_plotter import * """ pythonw -m ad_examples.common.test_sgd_optimization """ def generate_data(p=11, n=400): """ Generates non-linear multivariate data of dimension 'p'. The data is linear in parameters of the type: y = b0 + b1 * x +...
StarcoderdataPython