id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
133903
# Copyright 2019 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
StarcoderdataPython
3281224
<gh_stars>1-10 def fill_matrix(matrix1,matrix2): q = 0 matrix_res = [] for i in range(len(matrix1)): matrix_res.append([]) for z in range(len(matrix1[i])): matrix_res[i].append(0) while q < len(matrix1): matrix_res[i][z] += matrix1[i][q] * matrix2[q][z...
StarcoderdataPython
1743212
<gh_stars>1-10 import pandas as pd import re from .constants import * import logging _log = logging.getLogger(__name__) _OXFORD_PATH = 'https://oxcgrtportal.azurewebsites.net/api/CSVDownload' COLUMN_NAMES = { 'School closing': 'npi_school_closing', 'Workplace closing': 'npi_workplace_closing', 'Cancel p...
StarcoderdataPython
3256838
<gh_stars>0 from datetime import datetime from dateutil.tz import tzlocal import json import logging import re from urllib import urlencode from urllib2 import urlopen DATETIME_REGEX = re.compile('\D*(\d+)\D*') logger = logging.getLogger(__name__) class ODataReader(object): """A simple OData reader that is capab...
StarcoderdataPython
56916
#!/usr/bin/env python3 # vim: set ft=python:sw=4:ts=4 import os import sys # This location is set within the Dockerfile. sys.path.insert(0, '/opt/infra/lib') from infra import ( load_definitions_file, parse_args, get_org_repo, cleanup_boilerplate, write_tf_backend_file, write_tfvars_file, ...
StarcoderdataPython
3343922
<reponame>ceprio/xl_vb2py import math, time def getLatLong(): "Returns URL for day/night picture" # Define some 'constants' ClientRecieveTime=time.time() * 1000 # QueryTimeZone = 10 QueryTimeZone = -time.timezone/3600 QueryTimeZoneOffsetMin = QueryTimeZone * 60 NISTSendTimeGMTms = ClientRec...
StarcoderdataPython
199470
<reponame>diCagri/content import demistomock as demisto from CommonServerPython import * '''IMPORTS''' import requests import base64 # disable insecure warnings requests.packages.urllib3.disable_warnings() '''INTEGRATION PARAMS''' API_TOKEN = demisto.params().get('apitoken') URL_BASE = demisto.params().get('url') USE...
StarcoderdataPython
19330
<filename>site_crawler/cleaner/cleaner.py<gh_stars>10-100 import csv import re import string import html class Cleaner: def __init__(self): self.remove_punctuations = str.maketrans('', '', string.punctuation) def read_csv(self,csv_name): cleaned_text = [] with open('../data/twitter_dat...
StarcoderdataPython
3233516
<filename>pandas1 - Introduction to Pandas/pandas2 - DataFrame Structure.py<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Tue May 16 15:58:26 2017 @author: azkei The DataFrame is a tabular data structure similar to the spreadsheet. This data structure is designed to extend the case of the Series to multiple dimens...
StarcoderdataPython
1778011
import numpy as np from scipy.stats import cauchy import matplotlib.pyplot as plt n = 1000 distribution = cauchy() fig, ax = plt.subplots() data = distribution.rvs(n) if 0: ax.plot(list(range(n)), data, 'bo', alpha=0.5) ax.vlines(list(range(n)), 0, data, lw=0.2) ax.set_title("{} observations from the Cau...
StarcoderdataPython
3230375
<gh_stars>0 # Copyright 2016 OpenStack Foundation # # 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
129840
from copy import deepcopy def get_median(values): """ Given an unsorted list of numeric values, return median value (as a float). Note that in the case of even-length lists of values, we apply the value to the left of the center to be the median (such that the median can only be a value from the list of valu...
StarcoderdataPython
3386235
print("Hey Nigga! \n welcome to tic tac toe") print("who do you want to play with?\n") mode=str(input("type - 'Human' or 'computer'\n ").upper()) def HumanvsHuman(): theBoard = {"1": '1', "2": '2', "3": '3', "4": '4', "5": '5', "6": '6', "7": '7', "8": '8', "9": '9'} print("Now p...
StarcoderdataPython
129232
import os from django.conf import settings from django.test import override_settings from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APITestCase from model_mommy import mommy from ..models import User, SequenceAnnotation, Document, Role, RoleMapping from .....
StarcoderdataPython
90799
<reponame>peekxc/tallem # %% Imports from tallem import TALLEM from tallem.dimred import * from tallem.cover import * from tallem.distance import dist from tallem.samplers import landmarks from tallem.datasets import * import matplotlib.pyplot as plt # %% Load frey faces import pickle ff = pickle.load(open('/Users/...
StarcoderdataPython
1743485
<filename>django_loki/__init__.py """ MIT License Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, co...
StarcoderdataPython
1629263
""" Need to pip install azure-storage-blob Working to get an example loader from azure """ from azure.storage.blob import BlobServiceClient, generate_account_sas, ResourceTypes, AccountSasPermissions, ContainerClient, BlobClient import pandas as pd from collections import defaultdict if __name__ == "__main__": ...
StarcoderdataPython
55779
<filename>Model using Optical flow/evaluate.py import numpy as np import torch from climatehack import BaseEvaluator from optical_flow_model import get_flow_images device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print("Running on: {}".format(str(device).upper())) #For Debugging class E...
StarcoderdataPython
39345
<reponame>cc1-cloud/cc1 # -*- coding: utf-8 -*- # @COPYRIGHT_begin # # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland # # 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 Licens...
StarcoderdataPython
11540
from __future__ import division import itertools import json import math import os import random import shutil import subprocess import sys durationA = str(5) durationB = str(4) durationC = str(1) def main(): if len(sys.argv) > 1: nbDepth = int(sys.argv[1]) if nbDepth < 2 : nbDept...
StarcoderdataPython
1700791
<gh_stars>1-10 #!/usr/bin/python # -*- coding: utf-8 -*- import ujson from typing import Dict, Tuple, List, Set, Union, Optional, Any from pyutils.progress_utils import Timer from experiments.evaluation_metrics import DataNodeMode from semantic_labeling import create_semantic_typer from semantic_modeling.assembling.a...
StarcoderdataPython
1637853
<reponame>frbry/django-sortedone2many # -*- coding: utf-8 -*- from itertools import chain from django import forms from django.template.loader import render_to_string from django.utils.encoding import force_text from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from sortedm...
StarcoderdataPython
3254127
import os import sys import numpy as np from bocd import BOCD_BayesianLinearRegression from vbs import print_log, BeamSearchHelper, get_beam_search_helper from bayes_linear_regression import BayesLinReg def vbs_filter(x_train_set, y_train_set, x_test_set, y_test_set, config): dataset = config['dataset'] num_f...
StarcoderdataPython
1770474
<gh_stars>0 from distutils.core import setup requires = [ 'websocket_client', 'PyYAML', ] setup( name='GeminiDataService', version='0.1.0', author='<NAME>', author_email='<EMAIL>', packages=['geminidata.service','geminidata'], scripts=['geminidata-service.py'], url='', license='LICENS...
StarcoderdataPython
139140
import os, sys, numpy from scipy.interpolate import RectBivariateSpline, interp2d from scipy.optimize import curve_fit from matplotlib import cm from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg from matplotlib.figure import Figure try: from mpl_toolkits.mplot3d import Axes3D # necessario per caric...
StarcoderdataPython
3364631
"""Bempp direct solver interface.""" # pylint: disable=invalid-name def compute_lu_factors(A): """ Precompute the LU factors of a dense operator A. This function returns a tuple of LU factors of A. This tuple can be used in the `lu_factor` attribute of the lu function so that the LU d...
StarcoderdataPython
3265076
import datetime import logging import os import dateparser import pandas as pd import plaid from flask import jsonify from flask import render_template, request, flash from config.files import files from self_finance.back_end.data import Data from self_finance.constants import BankSchema from self_finance.constants i...
StarcoderdataPython
1782916
<filename>calculator-with-gui/Libraries/NewWindow.py import tkinter as tk # GUI Library import os from PIL import ImageTk # Allows for window icon from PIL import Image # Allows for window icon from .Menus import Menu # Program menu from . import Entry # Calculation entry box from . import Numbers ...
StarcoderdataPython
4838212
<gh_stars>10-100 #! /usr/bin/python # -*- coding: utf-8 -*- import numpy as np __all__ = [ 'Sampler', 'BatchSampler', 'RandomSampler', 'SequentialSampler', 'WeightedRandomSampler', 'SubsetRandomSampler', ] class Sampler(object): """Base class for all Samplers. All subclasses should i...
StarcoderdataPython
3267423
import cv2 import os from matplotlib import pyplot as plt from model import * from utils import * import os import time import logging import argparse import numpy as np import random from numpy import expand_dims from keras.preprocessing.image import load_img, img_to_array import tensorflow as tf def main(): pa...
StarcoderdataPython
3349084
<filename>python_developer_tools/cv/scheduler/warmup_lr_scheduler.py # !/usr/bin/env python # -- coding: utf-8 -- # @Author zengxiaohui # Datatime:8/18/2021 9:19 AM # @File:warmup_lr_scheduler.py import math import warnings from functools import partial, wraps from bisect import bisect_right from torch.optim import Op...
StarcoderdataPython
1625112
<reponame>ozemsbg/Mitty __version__ = '2.28.3'
StarcoderdataPython
3243706
from .home import *
StarcoderdataPython
3360371
<reponame>metakirby5/tron-ai<gh_stars>0 #!/usr/bin/python """Template for your tron bot""" import tron import random def which_move(board): return tron.NORTH # you do not need to modify this part for board in tron.Board.generate(): tron.move(which_move(board))
StarcoderdataPython
1690077
<filename>caluma/workflow/tests/test_visibilities.py import pytest from ...form import models as form_models from ...form.schema import Answer, Document from .. import models from ..schema import Case, WorkItem from ..visibilities import AddressedGroups @pytest.mark.parametrize( "work_item__addressed_groups,size...
StarcoderdataPython
160312
import sys import os from pathlib import Path from PyQt5.QtCore import QThread, pyqtSignal from PyQt5.QtWidgets import QApplication, QWidget, QToolTip, QPushButton, QGridLayout, QLineEdit, QLabel from PyQt5.QtGui import QFont from utils import get_chat, get_chat_contents, text_to_speech os.chdir(sys.path[0...
StarcoderdataPython
3250374
# -*- coding: utf-8 -*- from .focal_loss import * from .iou_loss import * from .cross_entropy_loss import * from .bce_with_logits_loss import * from .gfocal_loss import * from .mse_loss import * from .smooth_l1_loss import *
StarcoderdataPython
103263
<gh_stars>0 import argparse from pRestore.stuff import Stuff from pRestore.backup import Backup from pRestore.restore import Restore Stuff.print_logo() description = 'pRestore is a software used to make backup of file permissions and restore them in case of disaster' parser = argparse.ArgumentParser(description=des...
StarcoderdataPython
128641
import numpy as np from .lanczos import lanczos_resample_three, lanczos_resample_one def invert_affine_transform_wcs(u, v, wcs): """Invert a galsim.AffineTransform WCS. The AffineTransform WCS forward model is [u, v] = Jac * ([x, y] - origin) + world_origin where the `*` is a matrix multiplica...
StarcoderdataPython
43535
<filename>data/english_tweets/preprocess_tweets.py import csv import re import string def remove_chars(text): # remove links pattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') text = pattern.sub('', text) # remove tags text = re.sub(r'\w*@\w*', '...
StarcoderdataPython
3220182
<filename>Contacts/migrations/0005_auto_20180303_0307.py<gh_stars>0 # Generated by Django 2.0.2 on 2018-03-03 03:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Contacts', '0004_auto_20180303_0304'), ] operations = [ migrations.Alter...
StarcoderdataPython
1755262
<reponame>nabint/profiles-rest-api<filename>profiles_api/views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework import viewsets from rest_framework import filters f...
StarcoderdataPython
198771
<filename>src/olympia/addons/migrations/0018_auto_20200803_1311.py # Generated by Django 2.2.14 on 2020-08-03 13:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('addons', '0017_addonreviewerflags_notified_about_expiring_delayed_rejections'), ] ...
StarcoderdataPython
70808
<reponame>pseudonym117/kernel-graphql<gh_stars>1-10 from . import riotapi @riotapi.route('/') def index(): return 'hello world!'
StarcoderdataPython
134822
from flask import Flask, session app = Flask(__name__) app.secret_key = " "
StarcoderdataPython
3250006
# coding: utf-8 # # Setup Notebook # In[2]: # Standard library import os import sys sys.path.append("../src/") # Third party imports import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns # In[3]: # Customizations sns.set() # matplotlib defaults # Any tweaks that normally ...
StarcoderdataPython
3282931
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import json import logging import os from dataclasses import dataclass from pants.backend.go.target_types import GoModSourcesField from pants.backend.go...
StarcoderdataPython
50853
from typing import List from webbrowser import get from fastapi import APIRouter, Response from .schemas import TodoItem, TodoPayload, UserPayload #,User #-----Agregado jtortolero----- from sqlalchemy.orm import Session from fastapi import Depends, HTTPException, status from .models import Item, User from .utils impor...
StarcoderdataPython
1784650
<filename>services/sms/config.py import os class BaseConfig: """Base configuration""" DEBUG = False TESTING = False TWILIO_ACCOUNT_SID=os.environ['TWILIO_ACCOUNT_SID'] TWILIO_AUTH_TOKEN=os.environ['TWILIO_AUTH_TOKEN']
StarcoderdataPython
1751040
<reponame>JoanAzpeitia/lp_sg # Copyright (c) 2013 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you in...
StarcoderdataPython
4806383
from django import template from django.db.utils import OperationalError from django.contrib.auth import get_user_model from django.contrib.auth.models import Group register = template.Library() @register.filter(name='has_group') def has_group(user, group_name): """ Function to know if a user belong to ...
StarcoderdataPython
1624263
<filename>Calibration/HcalCalibAlgos/python/gammaJetAnalysis_cfi.py import FWCore.ParameterSet.Config as cms from RecoJets.Configuration.RecoJets_cff import * from RecoJets.Configuration.RecoPFJets_cff import * from CommonTools.ParticleFlow.pfNoPileUp_cff import * GammaJetAnalysis = cms.EDAnalyzer('GammaJetAnalysis', ...
StarcoderdataPython
1750623
# Tests of the quasiisothermaldf module from __future__ import print_function, division import numpy #fiducial setup uses these from galpy.potential import MWPotential, vcirc, omegac, epifreq, verticalfreq from galpy.actionAngle import actionAngleAdiabatic, actionAngleStaeckel from galpy.df import quasiisothermaldf aAA...
StarcoderdataPython
3251938
import _init_paths import os import os.path as osp import caffe from caffe import layers as L, params as P from caffe import tools from caffe.model_libs import * def caffenet_body(net, data, post, is_train): # the net itself net['conv1'+post], net['relu1'+post] = conv_relu(net[data], 11, 96, stride=4, is_t...
StarcoderdataPython
1622996
<gh_stars>0 #!/usr/bin/python2 #coding=utf-8 #================ #OPEN SOURCE :) #AUTOR : ☆ RAKA ☆ ™︻®╤───────═◍➤ #GITHUB : Bangsat-XD #================ import os try: import concurrent.futures except ImportError: print "\033[93;1m\n FUTURES MODULE NOT INSRALL...!" os.system("pip install futures" if os.name == "...
StarcoderdataPython
1747304
<reponame>Maltimore/garage from garage.np.algos import CMAES from garage.np.baselines import LinearFeatureBaseline from garage.sampler import OnPolicyVectorizedSampler from garage.tf.envs import TfEnv from garage.tf.experiment import LocalTFRunner from garage.tf.policies import CategoricalMLPPolicy from tests.fixtures ...
StarcoderdataPython
3231399
<filename>core/management/commands/import_test_data.py from django.core.management.base import BaseCommand, CommandError import pprint import os from core.management.commands.create_gui import add_required_data_to_db import elasticsearch class Command(BaseCommand): def handle(self, *args, **options): a...
StarcoderdataPython
34605
import numpy as np from .image_transforms import mat_to_gray def rgb2hcv(Blue, Green, Red): """transform red green blue arrays to a color space Parameters ---------- Blue : np.array, size=(m,n) Blue band of satellite image Green : np.array, size=(m,n) Green band of satellite image...
StarcoderdataPython
1638948
#sed 's/^/"/ ; s/$/",/ ; s/Tile // ; s/:",/":[/ ; s/"",/],/ ; s/\./0/g ; s/#/1/g ' < advent-20.raw > advent-20.py m={ "1217":[ "0100001001", "1010000111", "1101000010", "1100011100", "1110010010", "0100011000", "1010011000", "1000101100", "1001100001", "0110100100", ], "2357":[ "0000010101", "1000010001", "00000001...
StarcoderdataPython
1653463
<gh_stars>0 #Done by <NAME> in 04/07/2020 """ Start with your program from Exercise 9-1 (page 162). Add an attribute called number_served with a default value of 0. Create an instance called restaurant from this class. Print the number of customers the restaurant has served, and then change this value and print it aga...
StarcoderdataPython
3299155
# stdlib import json import re import traceback from typing import Any, Dict, Optional # libs import netaddr # local from bin import RouterMixin, utils import settings ADDRESS_NAME_SUB_PATTERN = re.compile(r'[\.\/:]') class RouterScrub(RouterMixin): def run(self): self.run_router() def prompt(self)...
StarcoderdataPython
60182
<reponame>Brownie-in-Motion/libwherey from django.contrib import admin from django.urls import path from django.conf.urls import url import web.views urlpatterns = [ path('admin/', admin.site.urls), url(r"^$", web.views.homepage), url(r"^about$", web.views.about), url(r"^api/libraries/(?P<pk>[0-9]+)$...
StarcoderdataPython
4802117
''' Created on 29.11.2016 @author: simon ''' from plugins import plugins from PyQt4 import QtGui,QtCore from ctools.filters import IIR from scipy.signal.filter_design import iirfilter class BandPass(object): ''' Plugin for PyDaq which adds some filters (iir and fft) ''' def __init__(self, app): ...
StarcoderdataPython
3288405
''' Write a program to get integers m and n (n is an even number), then display m lines of the output. Each line shows n symbols. The first half (1 to n / 2) of each line displays ‘>’ and the second half (n / 2 + 1 through n) display ‘<’. ''' m, n = map(int, input().split()) for _ in range(m): print('>'*(n//2), '<...
StarcoderdataPython
101452
<filename>help/help.py from os import path, system, name def clear(): """ Clear console function os-independent :return: NoneType """ if name == 'nt': system('cls') else: system('clear')
StarcoderdataPython
4806574
import math import tensorflow import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_addons as tfa import json import os import time from ftfy import fix_text #:os.chdir('../') import pickle import numpy as np import string, os from gensim.models import KeyedVectors import gensim.downloader as api...
StarcoderdataPython
1777759
<filename>docs/generate-readme.py # Run this as a pre-commit script. # Will be a no-op unless docs have changed. # # Takes readme-generator.md and creates: # 1. A jekyll-ready markdown file with includes for dynamic github pages # 2. A github-ready markdown file with images for static pages import os import sys ...
StarcoderdataPython
126247
<reponame>HOTNSPICY12/InviteFuckKwel import amino, concurrent.futures import os print("\t\033[1;31m GCINVITEBOT\n\n") print("\t\033[1;32m Script by \033[1;36mMr.COMRADE \n\n") print("\t\033[1;32m Again fixed by: \033[1;36mPRINCE OF PERSIA \n\n") client = amino.Client() email = input("Email: ") password = input("Passwo...
StarcoderdataPython
82333
import sys import time import random from .address import Address __all__ = [ 'NameServers', 'NoNameServer', ] class NoNameServer(Exception): pass class IterMixIn: def iter(self): if not self.data: raise NoNameServer return iter(self.data) def success(self, item): pass ...
StarcoderdataPython
2238
class SeqIter: def __init__(self,l): self.l = l self.i = 0 self.stop = False def __len__(self): return len(self.l) def __list__(self): l = [] while True: try: l.append(self.__next__()) except StopIteration: ...
StarcoderdataPython
1627295
import argparse import atexit import boto3 import botocore.exceptions import cgi import datetime import elasticsearch import io import json import os import psycopg2 import re import requests # XXX: C4-211 should not be needed but is // KMP needs this, too, until subrequest posts work import signal import structlog im...
StarcoderdataPython
15277
<gh_stars>1-10 #Main Sedov Code Module #Ported to python from fortran code written by <NAME> and <NAME> #Original Paper and code found at http://cococubed.asu.edu/papers/la-ur-07-2849.pdf import numpy as np from globalvars import comvars as gv from sedov_1d import sed_1d from sedov_1d_time import sed_1d_...
StarcoderdataPython
1760713
<reponame>ob/remote import logging import re import sys from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from functools import wraps from pathlib import Path from typing import List, Optional, Union import click from .configuration import WorkspaceConfig from .configurati...
StarcoderdataPython
76235
<reponame>Udbhavbisarya23/owtf<gh_stars>1000+ """ owtf.managers.plugin ~~~~~~~~~~~~~~~~~~~~ This module manages the plugins and their dependencies """ import imp import json import os from owtf.models.plugin import Plugin from owtf.models.test_group import TestGroup from owtf.settings import PLUGINS_DIR from owtf.util...
StarcoderdataPython
1602226
<gh_stars>1-10 import factory from .. import db from ..model.bookmark import Bookmark, Tag, Link from ..model.user import User class SQLAlchemyGetOrCreateOptions(factory.alchemy.SQLAlchemyOptions): def _build_default_options(self): return super(SQLAlchemyGetOrCreateOptions, self)._build_default_options() ...
StarcoderdataPython
171456
from collections import defaultdict, deque from datetime import datetime def find_high_score(player_num, last_marble_value): """ >>> find_high_score(7, 25) 32 >>> find_high_score(10, 1618) 8317 >>> find_high_score(13, 7999) 146373 >>> find_high_score(17, 1104) 2764 >>> find_hig...
StarcoderdataPython
156152
# coding: utf-8 # In[7]: import numpy as np from sklearn import cluster from scipy.cluster.vq import whiten k = 50 kextra = 10 num_recs = 645 seed = 2 segment_file = open('bird_data/supplemental_data/segment_features.txt', 'r') ##clean line = segment_file.readline() line = segment...
StarcoderdataPython
3355363
import cv2 import os import glob import argparse import numpy as np from matplotlib import pyplot as plt from scipy import ndimage as ndi from skimage.segmentation import watershed from skimage.feature import peak_local_max def segment(img, mask): mask = cv2.bitwise_not(mask) img_masked = cv2.bitwise_and(img,...
StarcoderdataPython
3331702
"""Sub-module with utilities to make experiments easier to write.""" from embiggen.utils.abstract_models import ( AbstractClassifierModel, AbstractEmbeddingModel, EmbeddingResult, AbstractModel, get_models_dataframe, get_available_models_for_node_label_prediction, get_available_models_for_ed...
StarcoderdataPython
3308804
# Copyright 2020 StreamSets Inc. # # 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 writi...
StarcoderdataPython
1751932
from __future__ import print_function import collections import math import numpy as np import random import tensorflow as tf from six.moves import range from assignment5_word2vec.dataset import vocabulary_size, loadDataset data, count, dictionary, reverse_dictionary = loadDataset() class BatchGenerator(): def _...
StarcoderdataPython
3224207
<filename>python/chapter-7/shovel_consumer.py ############################################### # RabbitMQ in Action # Chapter 5 - Shovel Test Consumer # # Requires: pika >= 0.9.5 # # Author: <NAME> # (C)2011 ############################################### import json import sys import pika def msg_rcvd(channel, met...
StarcoderdataPython
1697356
<filename>src/preprocessing.py from input import * # creating train, and dev set train = df.loc[:900] # trainig set dev = df.loc[901:] # development set to test overfitting print(train.shape, dev.shape) print(train.target.value_counts()) print(dev.target.value_counts()) # creating dependent and independent matrix of...
StarcoderdataPython
112087
<filename>tests/test_matrix_props/test_is_square.py """Test is_square.""" import numpy as np from toqito.matrix_props import is_square def test_is_square(): """Test that square matrix returns True.""" mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) np.testing.assert_equal(is_square(mat), True) def te...
StarcoderdataPython
72126
"""Module for interacting with the Comet Observations Database (COBS).""" from io import StringIO import re from pathlib import Path from appdirs import user_cache_dir from astropy.time import Time import mechanize import numpy as np import pandas as pd from . import PACKAGEDIR, log # Where to store COBS data? CACH...
StarcoderdataPython
1679362
import json from ansible.module_utils._text import to_bytes, to_text try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() def update_list(a, *args, **kw): data = {k:kw[k] for k in kw.keys() if k != 'index'} for k in data: a[kw['index']][k]...
StarcoderdataPython
1719367
#!/usr/bin/env python3 import os, sys, shutil, configparser if os.name == "nt": import _winapi home = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] else: home = os.environ["HOME"] def confirm(question, default="y"): default = default.lower() if default == "y": options = "Y/n" else...
StarcoderdataPython
14723
<reponame>LuckysonKhaidem/ProjectAlpha from abc import ABCMeta, abstractmethod from typing import TypeVar, Generic, List S = TypeVar('S') R = TypeVar('R') """ .. module:: Operator :platform: Unix, Windows :synopsis: Templates for operators. .. moduleauthor:: <NAME> <<EMAIL>> """ class Operator(Generic[S, R])...
StarcoderdataPython
39605
from inspect import isawaitable from sanic import Sanic from sanic.response import redirect, json, text from sanic.exceptions import SanicException from sanic_plugin_toolkit import SanicPluginRealm from sanic_oauthlib.client import oauthclient def create_oauth(app): realm = SanicPluginRealm(app) try: ...
StarcoderdataPython
1636091
import rppFile import PySimpleGUI as sg import os.path from tryouts import mywindow def printstruct(struct, indent): print("%s%s children" % ((" " * indent), len(struct))) for child in struct: if isinstance(child, sg.Element): print("%sElement %s %s" % ((" " * indent), child.tag, child.at...
StarcoderdataPython
158656
<reponame>olivierverdier/odelab from __future__ import division import numpy as np from . import NonHolonomic class Robot(NonHolonomic): def position(self,u): return u[:4] def velocity(self, u): return u[4:8] def lag(self,u): return u[8:10] def codistribution(self, u): q2 = self.position(u)[2] cod =...
StarcoderdataPython
3235278
<gh_stars>0 from pkgutil import extend_path from .client import APIClient __path__ = extend_path(__path__, __name__) __all__ = ['APIClient']
StarcoderdataPython
3377469
<gh_stars>10-100 import collections import numpy as np import torch import torch.nn as nn from torch.nn import functional as F from simnet.lib.net.models import simplenet from simnet.lib.net.post_processing import segmentation_outputs, depth_outputs, pose_outputs, obb_outputs MODEL_SEM_SEG_HEAD_IN_FEATURES = ['p2', ...
StarcoderdataPython
13294
<reponame>kwu83tw/freezer # (c) Copyright 2014,2015 Hewlett-Packard Development Company, L.P. # # 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
3333162
<filename>flowcat/utils/time_timers.py<gh_stars>1-10 """ Basic functions for working with timestamps and timing functions. """ import time import datetime import contextlib import collections import numpy as np TIMESTAMP_FORMAT = "%Y%m%d_%H%M%S" def str_to_date(strdate: str) -> datetime.date: return datetime.da...
StarcoderdataPython
169382
# coding=utf-8 import redis import requests from lxml import etree import pymysql import threading from config import logger import re from User_Agent import User_Agent import random class Meeting: # 保留organizer 和 organizer_id两个字段,一个方便链表查询,一个方便直接读取,且可能读取不到组织信息 title = "" url = "" start_date = "" en...
StarcoderdataPython
1740809
<reponame>andrecianflone/wolf __author__ = 'max' from wolf.modules.dequantization.dequantizer import DeQuantizer, UniformDeQuantizer, FlowDeQuantizer
StarcoderdataPython
3287673
# -*- encoding: utf-8 -*- """ Copyright (c) 2019 - present AppSeed.us """ # Imports from flask import Flask # manage the app from sqlalchemy import create_engine # used to detect if table exists from flask_sqlalchemy import SQLAlchemy # manage the database import click ...
StarcoderdataPython
3228374
import flamethrower.autograd.call as call import numpy as _np notrace_functions = [ _np.ndim, _np.shape, _np.iscomplexobj, _np.result_type ] def wrap_namespace(old, new): unchanged_types = {float, int, type(None), type} for name, obj in old.items(): if obj in notrace_functions: new[nam...
StarcoderdataPython
11295
<reponame>robobe/pygazebo import concurrent import time import math import sys import asyncio import logging from . import msg from .parse_error import ParseError from . import DEBUG_LEVEL logger = logging.getLogger(__name__) logger.setLevel(DEBUG_LEVEL) async def _wait_closed(stream): assert(sys.version_info.ma...
StarcoderdataPython