index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
6,400 | 5aa55a96e414ad6b3ceebbcbd71c23a1fd69f0d1 | from .FactorWarData import Get_FactorWar_Data |
6,401 | 4ef6002480fcaa514f41227978bae76f6e02c22d | name = input("Enter your name: ")
print("Hi buddy! Today we will play a game " + name + "!")
print("Are you ready?")
question = input("Are you ready ? Yes or no: ")
print(name + " we are starting!")
liste1 = ['My neighbor ', 'My girlfriend ', 'My boyfriend ', 'My dog ']
num = input("Enter a number: ")
... |
6,402 | 1861c394fb02643d2e6ac8362f3340f512ef6d72 | import gc
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from tqdm import tqdm
import cv2
import torch
from torch.utils.data import DataLoader
from torch import optim
from torch.optim import lr_scheduler
from dataset.car_dataset import CarDataset
from nn.netw... |
6,403 | 16e5a44cb4fbe71eaa9c1f5b00505578de0d2cea | from django.contrib import admin
# Register your models here.
from .models import HuyenQuan
admin.site.register(HuyenQuan)
|
6,404 | 74b1cdcb1aaf6cde7e8ce3eeb73cd82689719b00 | # apport hook for oem-config; adds log file
import os.path
def add_info(report):
if os.path.exists('/var/log/oem-config.log'):
report['OemConfigLog'] = ('/var/log/oem-config.log',)
|
6,405 | 751d2a07b97d080988c54511ca13a97a969e06bd | import pygame
import numpy as np
import random
from enum import Enum
from .config import *
class Actions(Enum):
FORWARD = 0
RIGHT = 1
LEFT = 2
BACK = 3
class MazeEnv():
''' TODO '''
def __init__(self, GW, GH, SW, SH):
global GRID_WIDTH, GRID_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT, BOX_WID... |
6,406 | dd9574ea08beb9bc5f1413afd63c751fd42cba67 | #!/usr/bin/env python3
from pexpect import pxssh
import time
s = pxssh.pxssh()
ip = "" #replace ip address
username= "" #replace username
password= "" #replace password
s.login (ip, username, password)
print ("SSH session login successful")
s.sendline ('application stop')
s.prompt() # match the prompt
print("S... |
6,407 | ab69f4d6afb96d86381bcf507d7810980446c6ea | import msvcrt
import random
import os
def clear():
''' It clears the screen.'''
os.system('cls')
def InitMatrix():
''' It initializes the matrix as a board game.'''
m = [[0 for i in range(4)] for j in range(4)]
for i in range(2):
x = random.randint(0, 3)
y = random... |
6,408 | 09b14705a6905470058b5eecc6dd0bb214975c66 | """IDQ Importer Exporter
This script defines Import and Export functions through which it can communicate with
a Informatica Model Repository.
It also provides some related functions, such as:
- Create IDQ folder
- Check in IDQ components
Parts by Laurens Verhoeven
Parts by Jac. Beekers
@Version: 20190... |
6,409 | dfd5915428dc8f15fb61c5d81f22dfecfe29af15 | from django.urls import reverse
from django.utils.translation import get_language
from drf_dynamic_fields import DynamicFieldsMixin
from geotrek.api.v2.serializers import AttachmentSerializer
from mapentity.serializers import MapentityGeojsonModelSerializer
from rest_framework import serializers as rest_serializers
fro... |
6,410 | 03943e146c0d64cfe888073e3a7534b6615b023f | import sys
from pcaspy import SimpleServer, Driver
import time
from datetime import datetime
import thread
import subprocess
import argparse
#import socket
#import json
import pdb
class myDriver(Driver):
def __init__(self):
super(myDriver, self).__init__()
def printDb(prefix):
global pvdb
print... |
6,411 | cd9d10a3ee3956762d88e76a951023dd77023942 | from Get2Gether.api_routes.schedule import schedule_router
from Get2Gether.api_routes.auth import auth_router
from Get2Gether.api_routes.event import event_router
|
6,412 | c234031fa6d43c19515e27c5b12f8e8338f24a1c | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if not head:
return head
fh = List... |
6,413 | d46cda5354640e1c87432d39a2e949d6db034edc | # Generated by Django 3.2 on 2021-04-21 13:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rate', '0003_auto_20210421_1316'),
]
operations = [
migrations.AlterField(
model_name='song',
name='overall_rating',
... |
6,414 | 28091b7251f980f3f63abdb03140edd0d789be8f | name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
x = list()
for line in handle:
line.split() ## unnesssecary
if line.startswith("From "):
x.append(line[line.find(" ")+1:line.find(" ",line.find(" ")+1)])
counts = dict()
for name in x:
if name not in co... |
6,415 | d60a2d4c819f701e8e439b8839415aa2838df185 | # https://www.acmicpc.net/problem/3584
import sys, collections
input = sys.stdin.readline
N = int(input())
for _ in range(N):
n = int(input())
arr = collections.defaultdict(list)
parent = [i for i in range(n + 1)]
for i in range(n - 1):
a, b = map(int, input().split())
arr[a].append(b)
... |
6,416 | e2e3b63deba20cd87fdfca81a9f67fa24891a1e0 | '''
Copyright (c) 2011 Jacob K. Schoen (jacob.schoen@gmail.com)
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, copy, modify,... |
6,417 | 43b519d7db2e46a0bf9317eddac1f5cf6b7b79e3 | import pandas as pd
import json
import spacy
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import NMF
nlp = spacy.load('en_core_web_sm')
list_data = []
list_data_only_reviews = []
list_data_reviewerid = []
result = []
l = []
for line in open('Automotive_5.json', 'r'):
li... |
6,418 | 760daa908ca92e7fb1393bdf28fee086dc1648ef | from collections import Counter
# Complete the isValid function below.
def isValid(s):
if not s:
return True
x = Counter(s)
print(x)
first_c = x.pop(s[0])
cnt = 0
for k, c in x.items():
if c != first_c:
if first_c == 1:
cnt += 1
firs... |
6,419 | 61ff5fae02d18d51595e8050d97244574e7d8af1 | from setuptools import setup
setup(
name='nodepool_harness',
version='0.1dev',
description='Nodepool harness',
packages=['nodepool_harness', 'statsd', 'apscheduler'],
install_requires=["PyYAML", "python-novaclient", "paramiko", "sqlalchemy"],
entry_points = {
'console_scripts': [
... |
6,420 | aacd5d671090c3305a53d62c3c6c25d4c033f42d | # Spelling bee NYT puzzle solver
with open('words.txt') as words_fh:
# Converts strips and lowercases lexicon (space seperated txt file)
# Use set to remove duplicates (decasing)
lexicon = set(list(map(lambda x: x.strip().lower(), words_fh.readlines())))
# NOTE: Could add a CLI to allow users to input... |
6,421 | 9290294b5df081ef0cae5450a9ea3baef789c041 | from .models import Owner, Vehicle
from rest_framework import viewsets, permissions
from .serializers import OwnerSerializer, VehicleSerializer
class OwnerViewSet(viewsets.ModelViewSet):
queryset = Owner.objects.all().order_by('id')
serializer_class = OwnerSerializer
permission_classes = [permissions.IsAu... |
6,422 | c796123fbbf3adcde59779a104dcafb30a673a79 | from elements import Node, Bar, Material, Group, Load
from pprint import pprint
# query
# next((e for e in result['coordinates']['nodes'] if e.n == int(el[0])), None)
class Reader():
def read(self, filePath):
"""
Reads text file with nodes and returns the result dict with all objects
and their nested p... |
6,423 | 775ac823f6784510fa919b08ee4150eb500710c4 | # coding: utf-8
"""
CityPay POS API
CityPay Point of Sale API for payment with card present devices including EMV readers and contactless POS readers. The API is available from https://github.com/citypay/citypay-pos-api The API makes it simple to add EMV and contactless card acceptance to iOS, Android, Tabl... |
6,424 | a8d52d81ef6538e9cb8a0a9cab7cd0a778454c8e | import json
from constants import *
from coattention_layer import *
from prepare_generator import *
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import LearningRateScheduler, ModelCheckpoint, Early... |
6,425 | 015b06d7f08f9de60a46d8428820333621732c53 | import os
def log(text, level=2, outFile='log.txt'):
text = str(text)
if level == 0:
return True
if level == 3:
with open(outFile, 'a') as logger:
logger.write(text)
logger.close()
print(text)
return True
if level == 2:
... |
6,426 | 629649abe9d855122a5db6d61a20735ceb89c5cf | from pathlib import Path
import eyed3
import csv
import sys
import filetype
import os
pathFile = Path('C:\\Users\\JORGE\\Music\\Vicente Garcia - Te Soñé (Lyric Video)(MP3_160K).mp3')
audiofile = eyed3.load(pathFile)
with open('loveMusic.csv', 'w', newline='') as csvFile:
fieldsName = ['nameFile', 'tittle', 'art... |
6,427 | 935853a4afdb50a4652e14913d0cdb251a84ea14 | from typing import Sized
import pygame
import time
from pygame.locals import *
import random
SIZE = 20
BACKGROUND = (45, 34, 44)
W = 800
H = 400
SCREEN = (W, H)
class Snake:
def __init__(self, parent_screen, length):
self.parent_screen = parent_screen
self.length = length
self.snake = pyg... |
6,428 | 39abda1dd8b35889405db1b3971917d2a34180e3 | #Matthew Shrago
#implementation of bisection search.
import math
low = 0
high = 100
ans = int((high + low)/2)
print "Please think of a number between 0 and 100!"
while ans != 'c':
#print high, low
print "Is your secret number " + str(ans) + "?",
number = raw_input("Enter 'h' to indicate the guess is too hi... |
6,429 | 819607d89035413fc2800e9f16222619a74a5d64 | from functools import wraps
import maya.cmds as mc
import maya.mel as mel
import pymel.core as pm
from PySide2 import QtCore, QtGui, QtWidgets
import adb_core.Class__multi_skin as ms
import adbrower
from CollDict import pysideColorDic as pyQtDic
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
import a... |
6,430 | 9761070a75b043f6cc9e6134e09810b215ccd0c0 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# 可写函数说明
def sum(arg1, arg2):
# 返回2个参数的和."
total = arg1 + arg2
print "函数内 : ", total
return total;
# 调用sum函数
total = sum(10, 20);
def nop():
pass
a = nop(); |
6,431 | 150603004a4b194a7c08f1f23e37c613aa3b883a | import Utility
import copy
class Ratio_Execution_Time:
utility = None
def __init__(self):
self.utility = Utility.Utility()
print("Successfully Found Ration Corrssponding to Execution Time")
def calculatePercentage(self,B,total,strr):
E = {}
for i in B:
... |
6,432 | aeb986360c6990f9375f2552cbdeef595af815b4 | import numpy as np
np.random.seed(1)
class MonteCarloGameDriver():
def __init__(self):
self.default_moves = np.array(['w','a','s','d'])
self.probability_distribution = np.array([.25,.25,.25,.25])
def run_game(self, simulation_size=20):
from game import GameLayout
from copy ... |
6,433 | 347bfb2d8809b55046f698620a690099cc83fb56 | import sys
import vector
import matrix
def convert_arg_to_list(arg):
try:
return [float(elem) for elem in arg]
except:
sys.exit("Invalid content inside {}".format(arg))
if __name__ == "__main__":
try:
vector1 = sys.argv[1].split(' ')
vector2 = sys.argv[2].split(' ')
exc... |
6,434 | 7b047ba110732d1b0a749bcbbaa9b55306ca2071 | # --- Do not remove these libs ---
from freqtrade.strategy.interface import IStrategy
from typing import Dict, List
from functools import reduce
from pandas import DataFrame
# --------------------------------
import datetime
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib
import numpy... |
6,435 | 326b2dcbef339aeb196bef23debad75fa079b121 | import string
import pandas as pd
import nltk
from nltk import word_tokenize
from nltk.stem import SnowballStemmer
from nltk.tokenize import WordPunctTokenizer
import json
from sklearn.model_selection import train_test_split
from keras.preprocessing.text import Tokenizer
import pickle
import re
import nlpaug.augmenter.... |
6,436 | b2944a95dbe25057155aaf6198a97d85b3bb620b | from typing import Dict, Tuple
import torch
from tqdm import tqdm
import schnetpack.properties as structure
from schnetpack.data import AtomsLoader
__all__ = ["calculate_stats"]
def calculate_stats(
dataloader: AtomsLoader,
divide_by_atoms: Dict[str, bool],
atomref: Dict[str, torch.Tensor] = None,
) ->... |
6,437 | b7d7b6c070f237f9ab59f3367417ecf2672fbaaf | """
Copyright (c) 2017- Sinergise and contributors
For the full list of contributors, see the CREDITS file in the root directory of this source tree.
This source code is licensed under the MIT license, see the LICENSE file in the root directory of this source tree.
"""
import numpy as np
import pytest
from numpy.test... |
6,438 | 66474b8cdca9a4aa48b8dc710d161a3a16495aed | import numpy as np
count = 0 # счетчик попыток
number = np.random.randint(1, 101) # загадали число
print("Загадано число от 1 до 100")
def game_core_v3(number):
'''Сначала устанавливаем любое random число, а потом уменьшаем или увеличиваем его в зависимости от того, больше оно или меньше нужного.
Функция... |
6,439 | 5a9e0b220d2c94aea7e3d67338771cf48c3aec8f | import os
import io
import yaml
from collections import OrderedDict
from rich.console import Console
from malwarebazaar.platform import get_config_path, get_config_dir
class Config(OrderedDict):
instance = None
def __init__(self):
ec = Console(stderr=True, style="bold red")
Config.ensure_pa... |
6,440 | c955057d7f8d5289898ecb96a290f5a7d241b787 | import pandas as pd
import matplotlib.pyplot as plt
import math
import seaborn as sns
import numpy as np
suv_data=pd.read_csv("F:/Development/Machine Learning/suv-data/suv_data.csv")
print(suv_data.head(10))
print("the no of passengers in the list is"+str(len(suv_data.index)))
sns.countplot(x="Purchased",data=suv_data... |
6,441 | 983473129bfd56138a615e0f5bdb1353e9c6d8af | import abc
import numpy as np
import ray
from tqdm.autonotebook import tqdm
from src.algorithm.info_theory.it_estimator import (CachingEstimator,
MPCachingEstimator)
from src.algorithm.utils import differ, independent_roll, union
class FeatureSelector(metaclass=ab... |
6,442 | 8b9336113f64a88eeabe6e45021938fac9efd1c6 | class Vehicle(object):
count_list = []
def __init__(self, registration_number):
self.registration_number = registration_number
Vehicle.count_list.append(self)
Vehicle.count = len(Vehicle.count_list) |
6,443 | 23d4619527b5fce7fed0b0a66d834e26bb984129 | import hive
from ..bind import Instantiator as _Instantiator
from ..event import bind_info as event_bind_info
bind_infos = (event_bind_info,)
def build_scene_instantiator(i, ex, args, meta_args):
bind_bases = tuple((b_i.environment_hive for b_i in bind_infos if b_i.is_enabled(meta_args)))
# Update bind env... |
6,444 | 61135a10adefd6ba8ffd63e997fa91ce9c78de06 | from setuptools import setup
setup(name = "dragonfab",
version = "1.3.0",
description = "Fabric support",
author = "Joel Pitt",
author_email = "joel@joelpitt.com",
url = "https://github.com/ferrouswheel/dragonfab",
install_requires = ['fabric', 'pip>=1.4', 'wheel'],
packages = ['dragonfab']... |
6,445 | 3cca7408eb88f91f295c581c29d3d1e95298f337 | r""" 测试dispatch
>>> from url_router.map import Map
>>> from url_router.rule import Rule
>>> m = Map([
... Rule('/', endpoint='index'),
... Rule('/foo', endpoint='foo'),
... Rule('/bar/', endpoint='bar'),
... Rule('/any/<name>', endpoint='any'),
... Rule('/string/<string:name>', endpoint='string'),
... |
6,446 | 47025a30d79341ff0819fe87638e35960a5fc87d | from typing import Union
from django.db.models import Q, Value
from django.db.models.functions import Lower, Replace, Trim
from .normalization import (
normalize_doi,
normalize_funkcja_autora,
normalize_grupa_pracownicza,
normalize_isbn,
normalize_kod_dyscypliny,
normalize_nazwa_dyscypliny,
... |
6,447 | bd06030ace665a0686c894a863e5c779b6d0931c | # -*- coding: utf-8 -*-
"""Chatbot learning
학습시 생성된 vocab 딕셔너리 파일을 Cindy ui 실행시 경로를 동일시 해주어야 연결성 있는 문장을 생성해줍니다.
"""
from tensorflow.keras import models
from tensorflow.keras import layers
from tensorflow.keras import optimizers, losses, metrics
from tensorflow.keras import preprocessing
import numpy as np
import pa... |
6,448 | 2500c3562819e4e85ce3cbc30e0ddf1b8437e0a2 | from django.contrib import admin
from lesson.models import ProgrammingEnvironment, Language, Lesson, LessonHint
# list_display - Show these fields for each model on the Admin site
# search_fields - Allow searching in these fields
# Register models for the Admin site
class ProgrammingEnvironmentAdmin(admin.ModelAdmin)... |
6,449 | 9a54ff8e7e8d6d46860cb6173f03c52655b30f43 | TheBeatles = ['John', 'Paul', 'George', 'Ringo']
Wings = ['Paul']
for Beatle in TheBeatles:
if Beatle in Wings:
continue
print Beatle
|
6,450 | 8c8b5c1ff749a8563788b8d5be5332e273275be3 | # Standard library
# Third party library
# Local library
from warehouse.server import run_server
from warehouse.server.config import log
if __name__ == "__main__":
log.initialize_logs()
run_server()
|
6,451 | 64cf6b03fb68be8a23c6e87c8d68d0a42db0eb54 | #!/usr/bin/env python3
# coding=utf-8
# title :paramiko_sftp.py
# description :
# author :JackieTsui
# organization :pytoday.org
# date :1/16/18 9:22 PM
# email :jackietsui72@gmail.com
# notes :
# ==================================================
# Import the module n... |
6,452 | 1aca1cf11d64374d0e0786e74c16567a4c5a1dec | class Queue:
def __init__(self):
self.head = None
self.tail = None
class Node:
def __init__(self, data):
self.data = data
self.next = None
def isEmpty(self):
return self.head is None
def peek(self):
return self.head.data if self.head i... |
6,453 | 7626202d1e3ec7321addbb028be2275b882efda2 | """
Unit Tests for endpoints.py
"""
import unittest
import os # pylint: disable=unused-import
from mock import patch, call
from github_approval_checker.utils import util # pylint: disable=unused-import
from github_approval_checker.utils.github_handler import GithubHandler # pylint: disable=unused-import
from github... |
6,454 | 66fe0a3b84773ee1d4f91d8fde60f1fc5b3d7e4c | import pickle
import numpy as np
import torch
import time
import torchvision
import matplotlib
import matplotlib.pyplot as plt
def load_cifar_data(data_files):
data = []
labels = []
for file in data_files:
with open(file, 'rb') as fo:
data_dict = pickle.load(fo, encoding='bytes')
... |
6,455 | d78fd8ebf9ef55700a25a9ce96d9094f1bfa564e | def main():
piso = largura * comprimento
volume_sala = largura * comprimento * altura
area = 2 * altura * largura + 2 * altura * comprimento
print(piso)
print(volume_sala)
print(area)
altura = float(input(""))
largura = float(input(""))
comprimento = float(input(""))
if __name__ == '__main__':... |
6,456 | 42c9e5039e2d5f784bf6405ea8bcaf7d6973ddcb | from mayan.apps.testing.tests.base import BaseTestCase
from .mixins import AssetTestMixin
class AssetModelTestCase(
AssetTestMixin, BaseTestCase
):
def test_asset_get_absolute_url_method(self):
self._create_test_asset()
self.test_asset.get_absolute_url()
|
6,457 | 2420c835ff91c1269cb16fca2e60e191e1e8ce13 | #!/usr/bin/env python
#-*- coding : utf-8 -*-
import string
import keyword
alphas = string.letters + '_'
nums = string.digits
keywords = keyword.kwlist
checklst = alphas + nums
print 'Welcome to the Identifier Checker v1.0'
myInput = raw_input('Identifier to test? ')
if myInput in keywords:
print 'Okay as a keywor... |
6,458 | a245cb1f232b152edf40b6399686c6811c522d99 | # common methods to delete data from list
fruits = ['orange', ' apple', 'pear', 'banana', 'kiwi']
#pop method
# fruits.pop(1)
# del
# del fruits[1]
# remove
# fruits.remove('banana')
# append, extend, insert
# pop, remove, del
print(fruits)
|
6,459 | 42d2be7544d2afb9580841422ae35e1a5621df52 | import abc
import math
import random
from typing import Union, Tuple
import numpy as np
from scipy import stats
from . import Rectangle, Line, Point, Shape
__all__ = ['get_critical_angle', 'Paddle', 'Ball', 'Snell', 'Canvas']
EPSILON = 1e-7
def get_critical_angle(s0: float, s1: float) -> Union[float, None]:
"... |
6,460 | 79141679bb2839de9d4a25b6c6c285905dddbb0d | #!/usr/bin/python
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
setup(
name="isc-dhcpd-parser",
version="0.1",
description="Parser for isc-dhcp config files (dhcpd.conf)",
author="Pavel Podkorytov",
author_email="pod.pavel@gmail.com",
classifiers=[
... |
6,461 | 536a67935527eb99bc0424613c9b931401db0b06 | from rest_framework import serializers
from .models import Twit, Comment, Message
from django.contrib.auth.models import User
class TwitSerializer(serializers.ModelSerializer):
class Meta:
model = Twit
fields = '__all__'
class CommentSerializer(serializers.ModelSerializer):
class Meta:
... |
6,462 | 397686964acbf640a5463a3a7095d85832545d9e | import re
def detectPeriod(data):
numWord = "[0-9,一二三四五六七八九十兩半]"
hourWord = "小時鐘頭"
minWord = "分鐘"
secWord = "秒鐘"
timePat = "["+numWord+"]+點?\.?["+numWord+"]*個?半?["+hourWord+"]*半?又?["+numWord+"]*["+minWord+"]*又?["+numWord+"]*["+secWord+"]*"
def main():
detectPeriod("我要去游泳一個小時")
if _... |
6,463 | 658532e1b81b025b8295bbf468dc01ecf12b922a | from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.stem import SnowballStemmer
import pandas as pd
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.tex... |
6,464 | 501ca508df5d72b0190b933f07c4bd505d7090c0 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from contextlib import contextmanager
import yaml
from omegaconf import OmegaConf
class CrypTenConfig:
... |
6,465 | 78615f6b020e2547e5d9a08d8b4c414184106bb3 | import pandas as pd
import time
from datetime import datetime
from sklearn import metrics
from sklearn import cross_validation
from sklearn.multiclass import OneVsRestClassifier
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.naive_bayes import MultinomialNB,BernoulliNB,GaussianNB
... |
6,466 | 6ea651e27620d0f26f7364e6d9d57e733b158d77 | import iris
import numpy as np
import matplotlib.pyplot as plt
import glob
import iris.analysis.cartography
import iris.coord_categorisation
import iris.analysis
import time
def my_callback(cube, field, filename):
cube.remove_coord('forecast_reference_time')
cube.remove_coord('forecast_period')
... |
6,467 | 60c862accbb9cda40ed4c45491f643f065e2868a | #!/usr/bin/env python
import os
from distutils.core import setup, Extension
import distutils.util
setup (name = 'pybanery',
version= '1.0',
description='Python interface for Kanbanery',
author = 'Pablo Lluch',
author_email = 'pablo.lluch@gmail.com',
py_modules = ['pybanery'],
... |
6,468 | 807b20f4912ab89bf73966961536a4cd4367f851 | # Generated by Django 3.0.1 on 2020-03-20 09:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('page', '0004_auto_20200320_1521'),
]
operations = [
migrations.AddField(
model_name='menu',
name='level',
... |
6,469 | a0349abb3a56ff4bc1700dbf0fa5a1fc2e3453ce | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class FlaskConfig(object):
SECRET_KEY = os.environ.get('FLASK_SECRET_KEY') or 'TuLAsWbcoKr5YhDE'
BOOTSTRAP_SERVE_LOCAL = os.environ.get('FLASK_BOOTSTRAP_SERVE_LOCAL') or True
APPLICATION_ROOT = os.environ.get('FLASK_APPLICATION_ROOT') or ''
... |
6,470 | cdaceb2d8804e08f0b35b9b65f2d06695efad002 | # Generated by Django 3.1.7 on 2021-03-28 01:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('details', '0002_auto_20210310_1421'),
]
operations = [
migrations.AlterModelOptions(
name='detail',
options={'get_latest_by'... |
6,471 | dc934f8db4e0c1113e1398b051b58369d909fff8 | from collections import deque
class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
def board2str(board: List[List[int]]) -> str:
return ''.join([str(board[i][j]) for i in range(2) for j in range(3)])
start = board2str(board)
bfs = deque([(start, 0)])
... |
6,472 | 80d1979c5767d0ff90f464651c9d0ca6d65effb2 | def foo(x, y=5):
def bar(x):
return x + 1
return bar(y * 2)
print(foo(3)) |
6,473 | 2d69a39be3931aa4c62cadff4cdfad76f6b32c59 | import face_recognition
from glob import glob
import os.path as osp
class FaceRecognitionLib(object):
"""
face_recognition library を利用した顔認証検証
"""
# クラス変数設定
__data_set_dir = './../../dataset/japanese' # データ・セットディレクトリ
__known_image_idx = (1,) # 既存画像のインデックス
... |
6,474 | 8f01934472805b5ad6dca328483a7ac79ae7748a | #This version assumes domains = train/test set
import numpy as np
from ..utils import Dataset
import math
import random
from .interface import TopicModel
from .man_model.models import *
from .man_model import utils
from .man_model.options import opt
import torch.utils.data as data_utils
from tqdm import tqdm
from colle... |
6,475 | dab53d10958b36cf75ab53bf30f744b1ed8a09b6 | from .authenticators import CookieAuthenticator, HeaderAuthenticator
from .paginators import LimitOffsetPaginator, PageNumberPaginator
from .views import * # pylint:disable=W0401
|
6,476 | f39130099ccf467623d65ac328fd02538044d36a | import copy
import datetime
from sacred import Experiment
from tqdm import tqdm
from mms_msg.databases.classical.full_overlap import WSJ2Mix
import paderbox as pb
import padertorch as pt
ex = Experiment('mixture_generator_create_json')
@ex.config
def defaults():
json_path = 'database.json'
database = {
... |
6,477 | 32066db8b43bc70c564cce5a33f50921285b3627 | #!/usr/bin/env python3
# coding: utf-8
# Time complexity: O()
# Space complexity: O()
import math
# 最大公约数 Greatest common divisor
def get_gcd(a, b):
if b == 0:
return a
print(a, b)
return get_gcd(b, a % b)
get_gcd(48, 30)
# 计算约数个数
# 时间复杂度 O(n)
def divisor1(num):
count = 0
for i in ran... |
6,478 | 9b94e8aed2b0be2771a38cf2d1cf391772f3a9f0 | class SimulatorInfo(object):
def __init__(self, name=None, device_type=None, sdk=None, device_id=None, sim_id=None):
self.name = name
self.device_type = device_type
self.sdk = sdk
self.device_id = device_id
self.sim_id = sim_id
|
6,479 | b48bc9475a8dc593ba858af8ed4e930ae290fd69 | from discord.ext import commands
import discord
import os
import random
bot = commands.Bot(command_prefix="!")
@bot.event
async def on_ready():
print(f"Logged in as {bot.user.name}")
@bot.command()
async def ping(ctx):
await ctx.send("pong")
# Lucky command, it picks a number between 0-50 and spams your dm'... |
6,480 | b99093fb13c59d4b9bb0a4f32fb62423d6752118 | # Generated by Django 3.0.8 on 2020-07-29 18:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('scenario', '0005_auto_20200729_1149'),
]
operations = [
migrations.RemoveField(
model_name='weapon',
name='vehicle',
... |
6,481 | 8425ee79fcb41799e5edbbab822f93dd40e39d8e | from collections import defaultdict
class Solution:
def multiply(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
output = [[0 for j in range(len(B[0]))] for i in range(len(A))]
rows = defaultdict(list)
cols = defaultdict(list)
for i in ran... |
6,482 | e1cc4e17bffcbbae3e7785e4c55acde167a8a50a | import os
import RPi.GPIO as GPIO
from google.cloud import firestore
import time
############Explicit Credential environment
path="/home/pi/Desktop/Parking.json"
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] =path
#GPIO starts
s1=2
s2=21
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(s1,GPIO.IN)
GPIO.... |
6,483 | 3153218fe1d67fdc1c1957ffcfdb380688c159c1 | from django.apps import AppConfig
class AutomationserverConfig(AppConfig):
name = 'automationserver'
|
6,484 | 70845ab4aab80d988a5c01d0b4fb76e63b800527 | import sys
byte = int(sys.argv[1])
qlty = float(sys.argv[2])
n = 0
while True:
o = sys.stdin.read(byte)
if qlty>(qlty*n)%1:
oo = o
sys.stdout.write(o)
else:
sys.stdout.write(oo)
if not o:
break
n=n+1 |
6,485 | 9f8fbfb8a9c849ca0e8881c479800c8e190e4a1c | import json
from logger import logger
def parse_json(text):
start = text.find("{")
end = text.find("}") + 1
try:
data = json.loads(text[start:end])
return data
except Exception:
logger.error("json解析失败:%s" % text)
|
6,486 | 0aad96de65cc125e5c026dfd72a9cc9f4ebd3dd2 | from nose.tools import with_setup, nottest
from tests.par_test_base import ParTestBase
from ProbPy import RandVar, Factor, ParFactor
class TestFactorMult(ParTestBase):
def __init__(self):
super().__init__()
def par_test_0(self):
"""
f(X), scalar
"""
for i in range(4)... |
6,487 | 22bf65a20f7398b82f528112d2ba50f1dccd465c |
class Thing3:
def __init__(self):
self.letters = 'xyz'
# print(Thing3.letters)
th = Thing3()
print(th.letters) |
6,488 | 15514d5636471b1a311641a40b6a00b81703cd2b | # Copyright (c) 2016, Xilinx, Inc.
# 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 must retain the above copyright notice,
# this list of ... |
6,489 | 5f4d83aa2b530417ecb1598510fb4778b111700b | #%% [markdown]
# # Look at intron-less gene enrichment in Cyte biased expressed genes.
# This is a quick look at if parimary spermatocyte biased genes are enriched in intronless genes.
# Yes this is what we see.
#%%
import os
import pickle
import numpy as np
import pandas as pd
from scipy.stats import fisher_exact, c... |
6,490 | 9e896d935cc57e580ed46cd501b41053bbaab38f | from datetime import datetime
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class BusLine(Base):
__tablename__ = "bus_lines"
id = Column(Integer, primary_key=True)... |
6,491 | 20d480517226cb7fbced765554a02fa5cbc29033 | import secrets
from pathlib import Path
HASHCAT_WPA_CACHE_DIR = Path.home() / ".hashcat" / "wpa-server"
ROOT_PRIVATE_DIR = Path(__file__).parent.parent
WORDLISTS_DIR = ROOT_PRIVATE_DIR / "wordlists"
WORDLISTS_USER_DIR = HASHCAT_WPA_CACHE_DIR / "wordlists" # user custom wordlists
RULES_DIR = ROOT_PRIVATE_DIR / "rules... |
6,492 | ab760ec4cbb9f616f38b0f0f2221987460c6f618 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 18 21:03:43 2019
@author: 00124175
"""
"""
读取txt文件
该文本中的分割符既有空格又有制表符('/t'),sep参数用'/s+',可以匹配任何空格。
"""
#header=None:没有每列的column name,可以自己设定
#encoding='gb2312':其他编码中文显示错误
#sep=',':用逗号来分隔每行的数据
#index_col=0:设置第1列数据作为index
import pandas as pd
data = pd.read_table("1206sjl.txt"... |
6,493 | 3bc9c6a66f749858ea5801202b0ac80755c1b347 | from sklearn.naive_bayes import *
from sklearn import svm
from sklearn.pipeline import Pipeline
from sklearn.metrics import classification_report, confusion_matrix
from optparse import OptionParser
from helper import FileHelper, Word2VecHelper, GraphHelper
import helper
from helper.VectorHelper import *
import os
impo... |
6,494 | 5890525b16b42578ac06e7ab2170c5613feea0a5 | # Benthic Parameters - USEPA OPP defaults from EXAMS
benthic_params = {
"depth": 0.05, # benthic depth (m)
"porosity": 0.65, # benthic porosity
"bulk_density": 1, # bulk density, dry solid mass/total vol (g/cm3)
"froc": 0, # benthic organic carbon fraction
"doc": 5, # benthic dissolved organic ... |
6,495 | f3895f38be29fb07903237d8846cc9d657b39ea9 | import numpy as np
import cv2
from pixcel import *
from scipy import ndimage
import math
from socket import *
from config import *
from time import time
def find_bounding_boxes(fimage, lables):
# initialize boxes array
boxes = []
for lable in lables:
# iterate all lables
# filter out i... |
6,496 | af152e0b739305866902ee141f94641b17ff03ea | """#########################################################################
Author: Yingru Liu
Institute: Stony Brook University
Descriptions: transer the numpy files of the midi songs into midi files.
(Cause the code privided by RNN-RBM tutorial to save midi
runs in python 2.7 but my ... |
6,497 | 69a3471ee8d2c317264b667d6ae0f9b500c6222f | from xml.dom import minidom
import simplejson as json
import re
camel_split = re.compile(r'(^[a-z]+|[A-Z][a-z]+|[a-z0-9]+)')
def get_items(xml):
for obj_node in xml.getElementsByTagName('item'):
obj = dict(obj_node.attributes.items())
if 'name' in obj:
obj['title'] = (' '.join(camel_sp... |
6,498 | 0ec3ca0f952dbc09c7a7a3e746c0aeab28ee9834 | from .base import BaseEngine
import re
class YandexSearch(BaseEngine):
base_url = "https://yandex.com"
search_url = "https://yandex.com/search/"
def get_params(self, query, **params):
params["text"] = query
params["p"] = None
return params
def next_url(self, soup):
if... |
6,499 | 2ecd234753fabbca2829dc86db2f740e371e4ea7 |
# coding: utf-8
# # Configuration
# In[1]:
CONNECTION_STRING = "mongodb://localhost:27017"
DATABASE_NAME = "off"
COLLECTION_NAME = "products"
# # MongDB connection
# In[2]:
from pymongo import MongoClient
from bson.code import Code
import plotly, pymongo
plotly.offline.init_notebook_mode()
from plotly.graph_obj... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.