seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
600932748 | # -*- coding: utf-8 -*-
import unittest
from wosedon.context.document import Document
import corpus2
def leniter(i):
""" Lenght of any iterable """
return sum(1 for e in i)
class TestSentence(unittest.TestCase):
def setUp(self):
tagset = corpus2.get_named_tagset('nkjp')
cclreader = corpus2.Cc... | null | eniam_src/tools/wosedon/wosedon/tests/context/test_document.py | test_document.py | py | 1,319 | python | en | code | null | code-starcoder2 | 51 |
261422052 | #####################################################################################################
# LGBIO2050 - TP1 : PCA & ICA
# Helper Functions to plot signals
#####################################################################################################
import matplotlib.pyplot as plt
import numpy as n... | null | make_graphs.py | make_graphs.py | py | 6,610 | python | en | code | null | code-starcoder2 | 51 |
388138249 | from datetime import datetime
from cms.utils import get_page_from_request
from annoying.functions import get_config
def page_ancestors(request):
page = get_page_from_request(request)
ancestors_list = list()
if page:
ancestors_list = [ ance.reverse_id for ance in page.get_ancestors() if ance.reverse... | null | plugins/context_processors.py | context_processors.py | py | 582 | python | en | code | null | code-starcoder2 | 51 |
438098120 | from __future__ import print_function
import sys
from timeit import default_timer as timer
class Node(object):
""" DAG nodes with parents and children. """
def __init__(self, idx=None):
self.idx = idx # index in the DAG nlist
self.parents = []
self.children = []
self.level = 0... | null | src/dag.py | dag.py | py | 5,082 | python | en | code | null | code-starcoder2 | 51 |
562369743 | import pandas as pd
import numpy as np
import talib as ta
import tushare as ts
from matplotlib import rc
import re
import time
import requests
from bs4 import BeautifulSoup
rc('mathtext', default='regular')
buy_stock_info = []
# import seaborn as sns
# sns.set_style('white')
def getHTMLText(url):
try:
r... | null | Ta_Lib/ta_lib_jenkins.py | ta_lib_jenkins.py | py | 4,346 | python | en | code | null | code-starcoder2 | 51 |
264743949 | N = [1]
N.sort()
dictA = {}
loc =0
N_values=[]
N_keys=[]
for i in range(1,len(N)+2):
dictA[i]=0
print(dictA)
for i in N:
dictA[i]+=1
print(dictA)
for k,v in dictA.items():
N_values.append(v)
N_keys.append(k)
for i in range(len(N_values)):
if N_values[i]== 0:
loc = i
... | null | Missing integer.py | Missing integer.py | py | 441 | python | en | code | null | code-starcoder2 | 51 |
60878580 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {ListNode}
def deleteDuplicates(self, head):
helper = ListNode(0)
helper.next = head
left = helpe... | null | All Code/No.82 Remove_Duplicates_from_Sorted_List_II.py | No.82 Remove_Duplicates_from_Sorted_List_II.py | py | 769 | python | en | code | null | code-starcoder2 | 51 |
576440612 | import numpy as np
def softmax(X):
exps = np.exp(X)
return (exps.transpose() / np.sum(exps, axis=1)).transpose()
def cross_entropy(actual, predicted):
return -sum([actual[i] * np.log2(predicted[i]) for i in range(len(actual))])
def classify(predicted):
return np.argmax(predicted, axis=1) + 1
def... | null | Gradient/Gradient_classifier.py | Gradient_classifier.py | py | 1,431 | python | en | code | null | code-starcoder2 | 51 |
102554322 | import logging
import os
from collections import namedtuple
import numpy as np
import pandas as pd
import fenics as fe
import scipy as sp
from netCDF4 import Dataset, num2date
from metpy.units import units
import metpy.calc.thermo as thermo
from siphon.simplewebservice.wyoming import WyomingUpperAir
from letkf_forecast... | null | letkf_forecasting/letkf_forecasting.py | letkf_forecasting.py | py | 29,803 | python | en | code | null | code-starcoder2 | 51 |
477285979 | #!/usr/bin/python
# -*- coding:utf-8 -*-
from Web import db
import hashlib
from datetime import datetime
from Web.models import *
from decimal import *
import xlrd
if __name__ == '__main__':
db.drop_all()
db.create_all()
# 系统菜单
# m = Menu(name='用户管理',link='#',url='',pid=1,published=True,order=0)
... | null | db_init.py | db_init.py | py | 4,262 | python | en | code | null | code-starcoder2 | 51 |
631946645 | # Installation requirements prior to using this rule:
# 1) pip binary: `pip`
# 2) For pypi package with C extensions or system dependecies,
# make sure to build on host with same setup or build in docker
# Binary dependencies needed for pypi repo setup
DEPS = ["pip", "sed", "basename"]
def _execute(ctx, command):... | null | tools/rules/pypi_repository.bzl | pypi_repository.bzl | bzl | 6,929 | python | en | code | null | code-starcoder2 | 51 |
84085395 | # coding=utf-8
# Copyright 2020 The Meta-Dataset 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 by applicable ... | null | meta_dataset/learners/metric_learners.py | metric_learners.py | py | 9,685 | python | en | code | null | code-starcoder2 | 51 |
368834505 | from matplotlib.pyplot import *
import scipy.special as sp
def plt_3d(x, y, z):
fig = figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, label='title',cmap='viridis', edgecolor='none')
show()
def integral(n, step_f, rs_f, ys_f, rs_F):
# first dimension - x
r_2d = np.b... | null | lab2package/main3.py | main3.py | py | 1,776 | python | en | code | null | code-starcoder2 | 51 |
305755709 | #!/usr/bin/python3
#Imports
import argparse
import os
import pyvisgraph as vg
import svggen
import minkowski
def ensure_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
def numtotime(num):
num = round(abs(num))
hours = num // 3600... | null | Aufgabe1-Implementierung/main.py | main.py | py | 4,478 | python | en | code | null | code-starcoder2 | 51 |
248284098 | import numpy as np
import os
import sys
import torch
import torch.nn as nn
import torch.optim as optim
class Job(object):
"""
A class used to bundle train/test data together with the model to be fit.
Attributes
----------
model : torch.nn.Module
Pytorch model to fit
loaders : dict
... | null | aether/job.py | job.py | py | 5,876 | python | en | code | null | code-starcoder2 | 51 |
308379667 | import random
from datetime import datetime
# Stores Music library and returns appropriate songs
RED_LOW = range(1000,1004)
RED_MID = range(1,60)
RED_HIGH = range(61,85)
ORANGE_LOW = []
ORANGE_MID = [1, 8, 12]
ORANGE_HIGH = [7, 11]
YELLOW_LOW = []
YELLOW_MID = [5]
YELLOW_HIGH = [6]
GREEN_LOW = []
GREEN_MID = [7]
GREE... | null | songs.py | songs.py | py | 2,109 | python | en | code | null | code-starcoder2 | 51 |
245101287 | # Given a string containing only digits, restore it by returning all possible valid IP address combinations.
#
# Example:
#
# Input: "25525511135"
# Output: ["255.255.11.135", "255.255.111.35"]
# 这个题可以运用dfs,那么回溯算法的循环和终止条件是什么呢?
#
# IP地址由四部分构成,可以设置一个变量segment,当segment = 4时,可结束循环,将结果添加到列表中;
#
# 每个部分数值均值... | null | src/93_Restore_IP_Addresses.py | 93_Restore_IP_Addresses.py | py | 1,167 | python | en | code | null | code-starcoder2 | 51 |
25023949 | import requests
from iNaturalist.Common import convertToObservationResults
def get_all_observations_for_taxon(taxon_id):
observations = []
page_num = 1
while True:
url = 'https://api.inaturalist.org/v1/observations?taxon_id=' + str(taxon_id) + '&per_page=200&order=desc&order_by=created_at&page=' + ... | null | iNaturalist/ApiRequests.py | ApiRequests.py | py | 711 | python | en | code | null | code-starcoder2 | 51 |
398243948 | from src.classes.dataProcessor import dataProcessor
from src.classes.kNN import kNN as kNN
data = dataProcessor()
learningData = data.processData('./data/iris.data.learning')
testingData = data.processData('./data/iris.data.test')
X_test = data.deleteLabels(testingData)
kNN = kNN(3,learningData)
unsetLabels = kNN.pre... | null | src/data/src/main.py | main.py | py | 470 | python | en | code | null | code-starcoder2 | 51 |
43097129 | #!/usr/bin/env python
# encoding: utf-8
import os
import inspect
import subprocess
import asyncio
import datetime
import json
import re
from functools import partial
from operator import is_not
class XCodeBuildArgs(object):
name = None
scheme = None
device = None
config = 'Debug'
udid = None
... | null | run.py | run.py | py | 11,643 | python | en | code | null | code-starcoder2 | 51 |
237125913 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
'''
搜狐新闻标题爬虫
'''
import requests
from bs4 import BeautifulSoup
# 获取页面内容并存提取保存
res = requests.get('http://news.sina.com.cn/china/')
res.encoding = 'utf-8'
# print(res.text.txt)
soup = BeautifulSoup(res.text, 'lxml')
# print(soup)
# 获取网页 时间,标题,网页
for news in soup.select... | null | A_库的分类/BeautifulSoup_yhz/实例2 - 搜狐网页提取.py | 实例2 - 搜狐网页提取.py | py | 649 | python | en | code | null | code-starcoder2 | 51 |
595917651 |
# -*- coding: utf-8 -*-
from copy import deepcopy
from scipy.stats import norm
import numpy as np
from sklearn.model_selection import StratifiedKFold, cross_val_predict, KFold
from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, roc_auc_score
from base import RANDOM_STATE
########################... | null | metrics_getter.py | metrics_getter.py | py | 4,000 | python | en | code | null | code-starcoder2 | 51 |
354093144 | import sys
import pickle
try:
TasksFile = open('tasks.txt', 'rb')
# LoadedTasks contains the tasks and their Done status as a boolean
# it's structured like : [['Task Description',True],['Task2 Description',False]]
LoadedTasks = pickle.load(TasksFile)
except EOFError:
LoadedTasks = []
if len(sys.a... | null | day-3/main.py | main.py | py | 2,641 | python | en | code | null | code-starcoder2 | 51 |
115320370 | #django
from .models import *
#combine statistics
def all_statistics(clean_sur):
#statistics -- forename
forenames_hist = names_forenames_hist.objects.filter(surname=clean_sur).values('surname','forename','sex')
forenames_cont = names_forenames_cont.objects.filter(surname=clean_sur).values('surname','fore... | null | kde/statistics.py | statistics.py | py | 4,552 | python | en | code | null | code-starcoder2 | 51 |
643970079 | # Copyright 2014-2015 Canonical Limited.
#
# 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 ... | null | hooks/charmhelpers/fetch/python/rpdb.py | rpdb.py | py | 1,910 | python | en | code | null | code-starcoder2 | 51 |
201695972 | ## This code is rewritten based on previous work of
## BRUNEL, Nicolas et WANG, Xiao-Jing.
## "Effects of neuromodulation in a cortical network model of object working memory dominated by recurrent inhibition"
## Journal of computational neuroscience, 2001, vol. 11, no 1, p. 63-85.
## ---------------------------------... | null | LIF/Excitatory_inhibitory_model.py | Excitatory_inhibitory_model.py | py | 5,484 | python | en | code | null | code-starcoder2 | 51 |
185476884 | # Studentnumber : 1716390
# Class : V2C
class TrieWord:
"""
Constructor of the TrieWord class.
Word is the value of the TrieNode.
Frequency is the amount of times that word occurs in the Trie.
"""
def __init__(self, word, frequency):
self.word = word
self.frequency = frequency
class TrieNode:
"""
Constru... | null | Week_3/trie.py | trie.py | py | 6,131 | python | en | code | null | code-starcoder2 | 51 |
190995763 | import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
df = pd.read_csv('data.csv')
app = dash.Dash()
year_options = []
for year in df['year'].unique():
year_options.append({'la... | null | dash_basic/4_dash_with_realdata.py | 4_dash_with_realdata.py | py | 1,638 | python | en | code | null | code-starcoder2 | 51 |
67070939 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from datetime import datetime
from bdinterface import BDInterface
class UserManagerDB(object):
def __init__(self):
self.bd = BDInterface()
def get_user(self, email):
try:
self.bd.connec... | null | wsgi/model.py | model.py | py | 3,774 | python | en | code | null | code-starcoder2 | 51 |
146222736 | # Faça um programa que leia uma quantidade indeterminada de números positivos e conte quantos deles estão nos seguintes intervalos: [0-25], [26-50], [51-75] e [76-100]. A entrada de dados deverá terminar quando for lido um número negativo.
a, b, c, d = 0, 0, 0, 0
n = 0
while (n > -1):
n = int(input('Informe um va... | null | Repetition/42.py | 42.py | py | 738 | python | en | code | null | code-starcoder2 | 51 |
455684647 | def unCaesar(huruf,n):
a = ord((huruf))
b = a - n
c = chr(b)
return c
while True:
print("="*50)
print("A. Masukan file terenskripsi sandi caesar")
print("B. Ubah menjadi normal")
print("C. Selesai")
first = str(input("Pilihan : "))
print("-"*50)
try:
if (first == "A"... | null | Praktikum 10/7.py | 7.py | py | 2,410 | python | en | code | null | code-starcoder2 | 51 |
46435043 | # Given N numbers: the first number in the input is N, after that N integers are given.
# Count the number of zeros among the given integers and print it.
# You need to count the number of numbers that are equal to zero, not the number of zero digits.
sum=0
for i in range (int(input())):
i=int(input())
if i==... | null | Simple Examples/The number of zeros.py | The number of zeros.py | py | 348 | python | en | code | null | code-starcoder2 | 51 |
549900055 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
The BBMQ server is required to accept 2 connections. one from the producer and one from the consumer.
Each topic will have one queue. Topic is an abstraction basically for a queue. The name 'Topic' is inspired from apache kafka
Producer: Publisher of the messages
Con... | null | bbmq/server/bbmq_server.py | bbmq_server.py | py | 21,218 | python | en | code | null | code-starcoder2 | 51 |
70092208 | import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}',r'\usepackage{siunitx}'] #
from scipy.optimize import curve_fit
x = np.array([17.869,15.306,13.840,12.707,11.889,11.181,10.575,10.041,9.598,9.190... | null | 102/Werte/plot.py | plot.py | py | 845 | python | en | code | null | code-starcoder2 | 51 |
580470912 | import unittest
import gold as target
class Tester(unittest.TestCase):
def test_ex(self):
adjacency = {
0: [2],
1: [1],
2: [0, 3, 4],
3: [2, 4],
4: [2, 3, 6],
5: [6],
6: [4, 5]
}
self.assertEqual(target.calc... | null | 12/test_gold.py | test_gold.py | py | 384 | python | en | code | null | code-starcoder2 | 51 |
359484083 | # coding=utf-8
from __future__ import absolute_import
from .routes import urlpatterns
from utils.verify import verify_token
from errors.base_errors import APIError
from flask import Blueprint, request, current_app
from utils.base_utils import make_json_response, route_inject
bp_name = "user"
user_api_endpoints = [
... | null | server/blueprints/user/main.py | main.py | py | 762 | python | en | code | null | code-starcoder2 | 51 |
5341423 | import numpy
import matplotlib.pyplot as plt
import torch
def plot_head_map(mma, target_labels, source_labels):
fig, ax = plt.subplots()
heatmap = ax.pcolor(mma, cmap=plt.cm.Blues)
# put the major ticks at the middle of each cell
ax.set_xticks(numpy.arange(mma.shape[1]) + 0.5, minor=False)
ax.set... | null | tools/visualize_attention.py | visualize_attention.py | py | 1,488 | python | en | code | null | code-starcoder2 | 51 |
550881477 |
import pytest
from swarm64_tpc_toolkit import stats
@pytest.fixture
def stats_fixture():
netdata_url = 'http://fake-netdata:19999'
disk = 'some_disk'
return stats.Stats(netdata_url, disk)
def test_make_columns():
metrics = ['foo', 'bar']
columns_expected = [*stats.BASE_COLUMNS]
columns_e... | null | tests/test_stats.py | test_stats.py | py | 1,694 | python | en | code | null | code-starcoder2 | 50 |
318817187 | #!/bin/python3
# https://www.hackerrank.com/challenges/alternating-characters/problem
import sys
def alternatingCharacters(s):
# Complete this function
num_delete = 0
c_curr = s[0]
for c in s[1:]:
if c == c_curr:
num_delete += 1
c_curr = c
return num_delete
q = int(in... | null | hackerrank/algorithms/strings/alternating_characters.py | alternating_characters.py | py | 435 | python | en | code | null | code-starcoder2 | 50 |
394416571 | from django.conf.urls import include, url
from myapp.api.views import User1View,User1DetailView,User1LoginView
app_name ='myapp'
urlpatterns=[
url(r'^$',User1View.as_view(),name='user'),
# url(r'^upload/',views.upload,name='upload'),
url(r'^login/',User1LoginView.as_view(), name='login'),
# url(r'^... | null | myapp/api/urls.py | urls.py | py | 508 | python | en | code | null | code-starcoder2 | 50 |
564267520 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import division
import os
import pytest
from astropy.table import Table
import numpy as np
from mica.archive import aca_l0, asp_l1
from Ska.Numpy import interpolate
has_l0_2012_archive = os.path.exists(os.path.join(aca_l0.CONFIG['data_root... | null | mica/archive/tests/test_aca_l0.py | test_aca_l0.py | py | 4,259 | python | en | code | null | code-starcoder2 | 50 |
142022268 | '''Module used to communicate and interact with player.
import as c'''
import pygame
from pygame.locals import *
import globvar as g
import utilities as u
class Interaction:
'''Class representing an interaction with the player'''
def __init__(self, interaction_type, question_str, text_str, min_char_count... | null | Game/communication.py | communication.py | py | 10,199 | python | en | code | null | code-starcoder2 | 50 |
20541919 | #!/usr/bin/env python3
"""
The MIT License (MIT)
Copyright (c) 2017 Erik Perillo <erik.perillo@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 l... | null | att/upeek/upeek/infer.py | infer.py | py | 5,854 | python | en | code | null | code-starcoder2 | 51 |
114639253 | from ghetto_manim import *
import time
# Suppress scientific notation
np.set_printoptions(suppress=True)
# Special Shape Classes
class Arrow(ParamShapeGroup):
def __init__(self, x0, y0, x1, y1, color, fill_p=0., curve_place=0.5, curve_amount=0, start=0, stop=1):
curve = CurvedLine(x0, y0, x1, y1, color, -... | null | 2D Animation/Automata Scratch.py | Automata Scratch.py | py | 4,846 | python | en | code | null | code-starcoder2 | 51 |
297549485 | from flask import render_template, redirect, url_for, request, Blueprint, flash
from app import *
import psycopg2
personal_b = Blueprint('personal_b', __name__, template_folder="templates")
@personal_b.route("/personal/add", methods=["GET", "POST"])
def personal_add():
if request.method == "GET":
return render_tem... | null | blueprints/personal.py | personal.py | py | 3,857 | python | en | code | null | code-starcoder2 | 51 |
417646417 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from typing import Callable, Any
from context import in3120
def data_path(filename: str):
return "../data/" + filename
def simple_repl(prompt: str, evaluator: Callable[[str], Any]):
from timeit import default_timer as timer
import pprint
printer ... | null | tests/repl.py | repl.py | py | 5,674 | python | en | code | null | code-starcoder2 | 51 |
568310842 | # -*- coding: utf-8 -*-
""" Import Best data """
import MySQLdb
import MySQLdb.cursors
from datetime import date
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from catalog.models import Rental, RentalPrice, CatalogImage, RentalImagePage, Region, RegionPage, Mode... | null | catalog/management/commands/import_rental.py | import_rental.py | py | 5,915 | python | en | code | null | code-starcoder2 | 51 |
568869424 | # ctypes: is a foreign function library for Python. It provides C compatible data types,
# and allows calling functions in DLLs or shared libraries.
# It can be used to wrap these libraries in pure Python.
import os
import ctypes
from scipy import integrate
from scipy import LowLevelCallable
import numpy... | null | source/test_python_in_c/p_b_lib.py | p_b_lib.py | py | 2,076 | python | en | code | null | code-starcoder2 | 51 |
269328851 | from typing import List, Generator, Any
import luigi
from exasol_integration_test_docker_environment.lib.base.flavor_task import FlavorBaseTask
from exasol_integration_test_docker_environment.lib.base.json_pickle_target import JsonPickleTarget
from exasol_integration_test_docker_environment.lib.data.database_credentia... | null | exaslct_src/exaslct/lib/tasks/test/run_db_test_in_directory.py | run_db_test_in_directory.py | py | 2,691 | python | en | code | null | code-starcoder2 | 51 |
262590487 | import numpy as np
import os.path as osp
import tensorflow as tf
import gym
import time
from core import ReplayBuffer
from spinup.algos.tf1.td3 import core
from spinup.algos.tf1.td3.core import get_vars
from spinup.user_config import DEFAULT_DATA_DIR
from spinup.utils.logx import EpochLogger
from spinup.utils.test_pol... | null | spinup/algos/tf1/td3/td3_goal_2vs2.py | td3_goal_2vs2.py | py | 27,230 | python | en | code | null | code-starcoder2 | 51 |
104642087 | # This program simualtes the backend of a ticket purchasing system
# Price per visitor is $5
# Price per member is $3.50
# You are to do the following
# 1. Identify all banned visitors with a filter call
# 2. Determine the memberships status of all applicants
# 3. Calculate the total price for all eligible visitors
#... | null | 1-python-question.py | 1-python-question.py | py | 3,295 | python | en | code | null | code-starcoder2 | 51 |
629201190 | import inspect
import numpy as np
import os
from unittest import TestCase
from fitbenchmarking import mock_problems
from fitbenchmarking.controllers.base_controller import Controller
from fitbenchmarking.controllers.controller_factory import ControllerFactory
from fitbenchmarking.controllers.dfo_controller import DFOC... | null | fitbenchmarking/controllers/tests/test_controllers.py | test_controllers.py | py | 10,749 | python | en | code | null | code-starcoder2 | 51 |
472058748 | """Trains a ResNet on the CIFAR10 dataset.
ResNet v1
Deep Residual Learning for Image Recognition
https://arxiv.org/pdf/1512.03385.pdf
ResNet v2
Identity Mappings in Deep Residual Networks
https://arxiv.org/pdf/1603.05027.pdf
"""
from __future__ import print_function
import keras
from keras.layers import Dense, Conv... | null | chapter3/cifar10-resnet.3.2.1.py | cifar10-resnet.3.2.1.py | py | 7,922 | python | en | code | null | code-starcoder2 | 51 |
409562073 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp import models, fields, api, _
class ResPartner(models.Model):
_inherit = 'res.partner'
pan_no = fields.Char('PAN Number')
gst_no = fields.Char('GST Number')
| null | gst/models/partner.py | partner.py | py | 285 | python | en | code | null | code-starcoder2 | 51 |
145846894 | #%%
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.optimize import fsolve
import phd.viz
_, palette = phd.viz.phd_style()
sns.set_palette('magma')
# Define functions to be used in figure
def pact(IPTG, K_A, K_I, e_AI):
'''
Computes the probability that a repressor is active... | null | src/chapter_06/code/ch6_figS5.py | ch6_figS5.py | py | 3,787 | python | en | code | null | code-starcoder2 | 51 |
517261063 | import numpy as np
import math
from src.PCA import PCA
from src.procrustes import Procrustes
from src.tooth import Tooth
class ModelFitter:
def fitModel(self, target_tooth, model):
self.procrustes = Procrustes()
self.pca = PCA()
eigenvectors = model.getEigenvectors()
Y ... | null | src/modelFitter.py | modelFitter.py | py | 1,216 | python | en | code | null | code-starcoder2 | 51 |
639465008 | #!/usr/bin/env python3
# vim: set fileencoding=utf-8 :
from __future__ import print_function
import sys
import gc
import resource
import re
import logging
import time
import os
import codecs
import itertools
from datetime import timedelta
from optparse import OptionParser
import numpy as np
from scipy import sparse ... | null | inc-gram.py | inc-gram.py | py | 8,973 | python | en | code | null | code-starcoder2 | 51 |
433897581 | from turtle import TurtleScreen, RawTurtle, TK
from time import sleep
class Ventana():
def __init__(self, titulo, alto, ancho):
assert isinstance(titulo, str)
assert isinstance(alto, int) and alto > 0
assert isinstance(ancho, int) and ancho > 0
self.root = TK.Tk()
self.r... | null | laberinto.py | laberinto.py | py | 2,825 | python | en | code | null | code-starcoder2 | 51 |
56631208 | """empty message
Revision ID: 840daf4878a2
Revises: 6fb829e3b6f1
Create Date: 2019-02-06 15:44:35.760937
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '840daf4878a2'
down_revision = '6fb829e3b6f1'
branch_labels = None
depends_on = None
def upgrade():
# ... | null | migrations/versions/840daf4878a2_.py | 840daf4878a2_.py | py | 2,079 | python | en | code | null | code-starcoder2 | 50 |
68212656 | from django.http import Http404
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import cache_page
from wp_main.utilities import responses, utilities
from wp_main.utilities.wp_logging import logger
#from misc.models import wp_misc
from misc import tools as misctools
_log = logg... | null | misc/views.py | views.py | py | 1,715 | python | en | code | null | code-starcoder2 | 50 |
601940313 | import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x200')
# entry放在window上面
# 如果要设置为密码的形式,则将show='*'
e = tk.Entry(window, show=None)
e.pack()
# 设置插入方式为insert,即光标处插入
def insert_point():
var = e.get()
t.insert('insert', var)
# 设置插入方式为end,即尾部插入
def insert_end():
var = e.get... | null | tkdemo2/demo2.py | demo2.py | py | 829 | python | en | code | null | code-starcoder2 | 50 |
259890367 | from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import font as tkfont
import tkinter.messagebox
import os
import sqlite3
############################################################################################################################################################... | null | SIS2.py | SIS2.py | py | 27,452 | python | en | code | null | code-starcoder2 | 50 |
639915911 | """"Indigo UI URLs
Copyright 2015 Archive Analytics Solutions
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 agree... | null | indigo-web/indigo_ui/urls.py | urls.py | py | 1,758 | python | en | code | null | code-starcoder2 | 50 |
83059798 | #importing modules
import numpy as np
import pandas as pd
from apyori import apriori
#importing the csv dataset
dataset = pd.read_csv('animeDataSet.csv')
#converting the genre column datatype to string
dataset.genre = dataset.genre.astype('str')
#appending the values of genre column in dataset to a list
genre_list=[... | null | AprioriCode.py | AprioriCode.py | py | 795 | python | en | code | null | code-starcoder2 | 50 |
485603035 | import asyncio
import json
import logging
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from functools import wraps
from pathlib import Path
from typing import List, Optional, Tuple
import attr
from .datcore import DatcoreClient
from .models import FileMetaData, FileMetaDataE... | null | services/storage/src/simcore_service_storage/datcore_wrapper.py | datcore_wrapper.py | py | 6,736 | python | en | code | null | code-starcoder2 | 51 |
602885216 | from pprint import pprint
import json
import constants as constants
class ReferenceUtil(object):
def GetAbilityReferenceDict(self, abilityRefPath):
# Convert ability json file to ability json object
with open(abilityRefPath, 'r', encoding='utf-8-sig') as json_file:
abilityRefJson = json_file.read()
ability... | null | reference_util.py | reference_util.py | py | 1,169 | python | en | code | null | code-starcoder2 | 51 |
64330095 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('claims', '0004_invoice_taxes'),
]
operations = [
migrations.AlterField(
model_name='invoice',
name='... | null | claims/migrations/0005_auto_20151221_0904.py | 0005_auto_20151221_0904.py | py | 702 | python | en | code | null | code-starcoder2 | 51 |
84769913 | import random
answer = random.randint(1,30+1)
trial = 5
guess = 0
user_name = input("Hi, What's your name?: ")
def question():
while True:
try:
guess = int(input("Hi, " + str(user_name) + ". Guess the number 1 to 30.: "))
except ValueError:
print("Wrong type. Try again.")... | null | first/numguess.py | numguess.py | py | 793 | python | en | code | null | code-starcoder2 | 51 |
480770290 | # -*- coding: utf-8 -*-
import pandas as pd
import scipy.io as sio
import numpy as np
import matplotlib.pyplot as plt
data = sio.loadmat('CaseDataAll.mat')
market_data = pd.read_csv('market.csv')
eom = data["a_EOM"]
mon = data["Mon_Yield"]
size = data["Mon_SizeAll"]
market_return = market_data['Mkt_Rf']
risk_free = ma... | null | figure2.py | figure2.py | py | 1,415 | python | en | code | null | code-starcoder2 | 51 |
144398348 | height = float(input('身長をm単位で入力して下さい'))
weight = int(input('体重をkg単位で入力して下さい'))
bmi = weight / height **2
print(bmi)
if bmi < 18.5:
print('瘦せ型')
elif bmi >= 18.5 and bmi < 25:
print('普通')
else:
print('肥満体') | null | PycharmProjects/Tutorial_Excercise/bmi.py | bmi.py | py | 286 | python | en | code | null | code-starcoder2 | 51 |
531588895 | # Copyright (C) 2013 Lindley Graham
"""
This module contains methods used in calculating the volume of water present in
an ADCIRC simulation.
.. todo:: Some of these routines could be parallelized.
"""
import numpy as np
quad_faces = [[0, 1], [1, 2], [2, 0]]
def total_volume(domain, elevation):
"""
Calcul... | null | polyadcirc/pyADCIRC/volume.py | volume.py | py | 5,111 | python | en | code | null | code-starcoder2 | 50 |
377646224 | from hashlib import md5
from sslyze.server_connectivity_tester import ServerConnectivityTester, \
ServerConnectivityError, ConnectionToServerTimedOut
from sslyze.ssl_settings import TlsWrappedProtocolEnum
from sslyze.plugins.openssl_cipher_suites_plugin import Sslv20ScanCommand, \
Sslv30ScanCommand, Tlsv10Scan... | null | SSLChecker/sharedcode/scanner.py | scanner.py | py | 3,122 | python | en | code | null | code-starcoder2 | 50 |
361581330 | import argparse
import json
import sys
import redis
from pystdlib.uishim import get_selection
from pystdlib.shell import term_create_window, tmux_create_window
from pystdlib import shell_cmd
parser = argparse.ArgumentParser(description="Execute command over SSH.")
parser.add_argument("--choices", dest="show_choices... | null | modules/localnfra/networking/scripts/sshmenu.py | sshmenu.py | py | 1,880 | python | en | code | null | code-starcoder2 | 50 |
409449202 | #!/usr/bin python3
from collections import OrderedDict
from teacher import PiggyParent
import sys
import time
class Piggy(PiggyParent):
'''
*************
SYSTEM SETUP
*************
'''
def __init__(self, addr=8, detect=True):
PiggyParent.__init__(self) # run the parent constructor
... | null | student.py | student.py | py | 9,303 | python | en | code | null | code-starcoder2 | 50 |
329883173 | import os
BASE_DIR = os.path.dirname(__file__)
PROXY_PATH = None
REFRESH_PROXY_EACH = 30 # seconds
USER_AGENTS_PATH = os.path.join(BASE_DIR, 'support', 'ualist')
PROXY_TYPE = os.getenv('PROXY_TYPE', 'SOCKS5')
LOG_LEVEL = 'INFO'
LOG_MAX_FILE_BYTES = 1 * 1024 * 1024
LOG_BACKUP_COUNT = 50
LOG_FILE_PATH = 'logs'
| null | scrapyard/settings.py | settings.py | py | 315 | python | en | code | null | code-starcoder2 | 51 |
130394863 | #!/usr/bin/env python
from geometry_msgs.msg import Twist, Vector3
from sensor_msgs.msg import LaserScan
from neato_node.msg import Bump
import rospy
import tty
import select
import sys
import termios
class Control_Robot():
def __init__(self):
""" Initialize the robot control, """
rospy.init_nod... | null | warmup_project/scripts/teleop.py | teleop.py | py | 2,883 | python | en | code | null | code-starcoder2 | 51 |
48298201 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 19 16:14:26 2020
@author: hp
"""
n=input('Enter a positive integer number:')
def collatz(number):
r = int(number) % 2
if r == 0:
return int(number) // 2
else:
return 3 * int(number) + 1
while n !=1:
print(collatz(n))
n = collatz(n) | null | Practical5/collatz.py | collatz.py | py | 316 | python | en | code | null | code-starcoder2 | 51 |
542718591 | #!/usr/bin/python
import os
# envsensor_observer configuration ############################################
# Bluetooth adaptor
BT_DEV_ID = 0
# time interval for sensor status evaluation (sec.)
CHECK_SENSOR_STATE_INTERVAL_SECONDS = 5
INACTIVE_TIMEOUT_SECONDS = 60
# Sensor will be inactive state if there is no adver... | null | envsensor/conf.py | conf.py | py | 367 | python | en | code | null | code-starcoder2 | 51 |
385539697 | # 10-8. Cats and Dogs: Make two files, cats.txt and dogs.txt. Store at least three
# names of cats in the first file and three names of dogs in the second file. Write
# a program that tries to read these files and print the contents of the file to the
# screen. Wrap your code in a try-except block to catch the FileNotF... | null | exercises/chapter-10/cats_and_dogs.py | cats_and_dogs.py | py | 873 | python | en | code | null | code-starcoder2 | 51 |
445159429 | class Solution(object):
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
m, n=len(s), len(t)
dp=[0]*(n+1)
dp[0]=1
for i in xrange(1, m+1):
for j in xrange(n, 0, -1):
dp[j]=dp[j]+(dp[j-1] if ... | null | 115-Distinct-Subsequences/solution.py | solution.py | py | 411 | python | en | code | null | code-starcoder2 | 51 |
411601710 | #%% INFO
# Simple script to fetch block info from a Substrate node using:
# https://github.com/paritytech/substrate-api-sidecar
#
import requests
import json
import time
import pickle
import argparse
class Sync:
def __init__(self, endpoint, write, use_json, start_block, end_block, continue_sync, fprefix):
# User in... | null | sync.py | sync.py | py | 6,835 | python | en | code | null | code-starcoder2 | 51 |
468736630 | #
# Used for detecting stage two, namely to see if yellow plug has been plugged
#
import feature_detetor
org_size = 0
detected_x = 0
detected_y = 0
def set_params(x,y,size_org):
global detected_x
global detected_y
global org_size
detected_x = x
detected_y = y
org_size = size_org
def retrie... | null | stage_2_main.py | stage_2_main.py | py | 718 | python | en | code | null | code-starcoder2 | 51 |
73269817 | from os import listdir,path
from pickle import load
from face_recognition import load_image_file,face_locations,face_encodings
import face_training
from collections import namedtuple
import time
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
face = namedtuple('face', 'picname predictions distance neighbors')
def predict... | null | servingstatic/face_detection_and_matching.py | face_detection_and_matching.py | py | 2,357 | python | en | code | null | code-starcoder2 | 51 |
233393608 | ###################################
########batch_generator############
###################################
import numpy as np
def chunker(seq, size=32):
# It will cut seq(a list) into lots of pieces, and len(every piece) = size
# e.g. chunker([1,2,3,4,5],2) = [1,2]->[3,4]->[5]
return (seq[pos:pos + size]... | null | StatisticalLearning/DataGenarator/utils.py | utils.py | py | 2,207 | python | en | code | null | code-starcoder2 | 51 |
506097719 | # Find the first occurence of elememts in array using binray search
def BS_first_occur(arr,n,x):
low =0
high= n-1
result = -1
while(low<=high):
mid = low+(high-low)//2
if x ==arr[mid]:
result=mid
high= mid-1
elif x<arr[mid]:
high= mid-1
else:
low= mid+1
return result
arr ... | null | Binary Search/bs_first_occur.py | bs_first_occur.py | py | 396 | python | en | code | null | code-starcoder2 | 51 |
506119430 | from bs4 import BeautifulSoup
import pandas as pd
import os
import lxml
import settings
def grade(name, points_per_test, comments, ok):
#Grade Results
results= {q[:-3]:ok.grade(q[:-3]) for q in os.listdir("tests") if q.startswith('q')}
#If running locally with lots of notebooks load the grades.
df = pd.D... | null | notebooks/grade.py | grade.py | py | 1,334 | python | en | code | null | code-starcoder2 | 51 |
536054091 | from typing import Tuple, List, Dict
from environments.environment_abstract import Environment, State
import random; random.seed(0)
def policy_evaluation_step(env: Environment, states: List[State], state_vals: Dict[State, float],
policy: Dict[State, List[float]], discount: float) -> Tuple[f... | null | assignments_code/assignment2.py | assignment2.py | py | 1,389 | python | en | code | null | code-starcoder2 | 51 |
225519986 | import gym
from gym.wrappers import Monitor
import itertools
import numpy as np
import os
import random
import sys
import tensorflow as tf
import time
from lib import plotting
from lib.dqn_utils import *
from collections import deque, namedtuple
# make enviroment
env = gym.envs.make("Breakout-v0")
# Atari Actions: 0... | null | rl/RL - TOY - DQN and its siblings - tf & torch/dqn.py | dqn.py | py | 12,899 | python | en | code | null | code-starcoder2 | 51 |
633978450 | from django.urls import path
from api import views
urlpatterns = [
path('companies/', views.companies),
path('companies/<int:pk>/', views.company),
path('companies/<int:pk>/vacancies/', views.company_vacancies),
path('vacancies/', views.vacancies),
path('vacancies/<int:pk>', views.vacancy),
pa... | null | week11/hh_back/api/urls.py | urls.py | py | 367 | python | en | code | null | code-starcoder2 | 51 |
313248666 | # Copyright (C) 2014-2015 New York University
# This file is part of ReproZip which is released under the Revised BSD License
# See file LICENSE for full license details.
"""Entry point for the reprounzip utility.
This contains :func:`~reprounzip.reprounzip.main`, which is the entry point
declared to setuptools. It i... | null | reprounzip/reprounzip/pack_info.py | pack_info.py | py | 8,750 | python | en | code | null | code-starcoder2 | 51 |
245882454 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import phonenumber_field.modelfields
class Migration(migrations.Migration):
dependencies = [
('investor', '0030_merge'),
]
operations = [
migrations.AlterField(
model_nam... | null | api/investor/migrations/0031_auto_20141120_0432.py | 0031_auto_20141120_0432.py | py | 6,330 | python | en | code | null | code-starcoder2 | 51 |
237568197 | from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image
from screenfactory import ScreenFactory
GAME_PREFIX = "cellid"
class CellScreen(ScreenFactory):
def __init__(self, **kwargs):
super(CellScreen, self).__init__(GAME_PREFIX, **kwargs)
self.parse()
class CellButton(Button... | null | minigame/cell.py | cell.py | py | 742 | python | en | code | null | code-starcoder2 | 51 |
302040004 | # -*- coding: utf-8 -*-
import scrapy
from tools.tools_r.smt.smt_getcid import get_cid,get_prama
from gm_work.items import GmWorkItem
import json
from scrapy_redis.spiders import RedisSpider
class SmtGoodsSpider(RedisSpider):
goods_num = 0
name = 'smt_goods'
allowed_domains = ['aliexpress.com']
start_... | null | gm_work/gm_work/spiders/smt_goods.py | smt_goods.py | py | 6,532 | python | en | code | null | code-starcoder2 | 51 |
77928708 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: Mark
# datetime: 2020/9/24 9:40
# filename: _scorecard
# software: PyCharm
import math
import numpy as np
import pandas as pd
from pydantic import confloat
from ..base import BaseEstimator
from ..base import ModelMixin
from . import SKlearnLogisticRegression
from... | null | mldesigntoolkit/mldesigntoolkit/modules/modeling/_scorecard.py | _scorecard.py | py | 9,866 | python | en | code | null | code-starcoder2 | 51 |
191600124 | from subprocess import Popen
from os.path import exists
from time import sleep
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
def rename_hostname(hostname):
if 'ccd' not in hostname:
messagebox.showerror('', 'Invalid hostname')
return 0
mainframe.pack_forget()
... | null | Rename Hostname.py | Rename Hostname.py | py | 3,282 | python | en | code | null | code-starcoder2 | 51 |
417449304 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
File Name: depth_oil
Author:
Date: 2018/9/30 0030
Description: 深度优先搜索分油解
From https://wenku.baidu.com/view/b22b422a580102020740be1e650e52ea5518cea1.html
"""
import copy
global num
class oil(object):
def __init__(self,... | null | qq/depth_oil.py | depth_oil.py | py | 3,978 | python | en | code | null | code-starcoder2 | 51 |
650595375 | # encoding: utf-8
"""
Tämä on kesken
"""
import os
import sys
import traceback
import uuid
import hashlib
import random
import string
import re
import datetime
import csv
import alusta_tietokanta
import couch
from WhipAroundRegistry import WarApp
etunimet_path = os.path.join(os.path.dirname(os.path.realpath(__file_... | null | WhipAroundRegistry/scripts/alusta_testitietokanta_csvsta.py | alusta_testitietokanta_csvsta.py | py | 11,806 | python | en | code | null | code-starcoder2 | 51 |
489008567 | from __future__ import print_function
import os
import sys
import time
import json
import logging
import logging.config
from collections import defaultdict
from argparse import ArgumentParser
from pkg_resources import resource_filename
from . import get_actions, notify
# The error you get for a nonexistent file is di... | null | trello_hipchat/cli.py | cli.py | py | 3,851 | python | en | code | null | code-starcoder2 | 51 |
115932440 | import os
with open("hightemp.txt","r") as file, open("col1.txt","w") as output1 , open("col2.txt","w") as output2:
for line in file.readlines():
columns = line.split('\t')
first_column = columns[0] + "\n"
output1.write(first_column)
print(first_column)
second_column = column... | null | bambi/chapter02/knock12.py | knock12.py | py | 479 | python | en | code | null | code-starcoder2 | 51 |
398307102 | from random import randint
from .errors import RedisKeyError
from .datatypes import RedisSortable, Comparable, SetOperatorMixin
class ZOrder(object):
"""
Enum with supported sort orders of ZSet
"""
def __new__(self):
return ZOrder
@property
def ASC(self):
return 0
@proper... | null | redis_natives/zset.py | zset.py | py | 12,655 | python | en | code | null | code-starcoder2 | 50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.