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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
1457996365 | n = int(input())
colors = "ROYGBIV"
res = ""
for i in range(n):
res += colors[i % 7]
if len(res) > 7:
for idx, c in enumerate(res[-3:], n-3):
cs = ''.join([ x if x not in res[idx-3:idx] + res[:3-(n-idx)+1] else '' for x in colors])
if idx < 7:
s = set(res[:idx])
cs = [c f... | userr2232/PC | Codeforces/B/78.py | 78.py | py | 388 | python | en | code | 1 | github-code | 13 |
74175411538 | import main
import sys
miss_you_tests = [
{
'expected': 'Andy loves you so much!',
'slots': {
'person': { 'value': 'me' },
'verb': {'value': 'loves'}
}
},
{
'expected': 'Andy adores you so much!',
'slots': {
'person': { 'value': 'you' },
'verb': {'value': 'adores'}
... | andrewmacheret/a1-alexa-functions | src/lambda/test.py | test.py | py | 817 | python | en | code | 1 | github-code | 13 |
18713673673 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isSubStructure(A: TreeNode, B: TreeNode) -> bool:
def dfs(A,B) -> bool :
if not B :
return True
if not A or A.val != B.val :
return False
return dfs... | russellgao/algorithm | dailyQuestion/2020/2020-10/10-04/python/solution.py | solution.py | py | 808 | python | en | code | 3 | github-code | 13 |
74831756496 | # -*- coding: utf-8 -*-
'''
概念:一种保存数据的格式
作用:可以保存本地的json 文件,也可以将json串进行传输,
通常将json称为轻量级的传输方式
json文件组成:
{} 代表对象
[] 代表列表
: 代表键值对
, 分隔两个部分
'''
'''
1.loads针对内存对象,即将Python内置数据序列化为字串
2.load针对文件句柄
3.dumps
4.dump
json.dumps : dict转成str
json.dump是将python数据保存成json
json.loads:str转成dict
json.load是读取json数据... | AWangHe/Python-basis | 18.PaChong/7.json讲解.py | 7.json讲解.py | py | 1,549 | python | zh | code | 0 | github-code | 13 |
8390677815 | class Settings(object):
'''存储所有设置的类'''
# 定义画面帧率
def __init__(self):
'''初始化游戏的设置'''
self.FRAME_RATE = 60
self.screen_width = 600
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_speed_factor = 8
self.bullet_speed_factor = 12
... | yiyayiyayoaaa/pygame-alien | setting.py | setting.py | py | 537 | python | en | code | 0 | github-code | 13 |
25522881623 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
Description: MySQLDB 工具
Author: jingyu
Date: 2022-01-16 14:23:43
LastEditors: Please set LastEditors
LastEditTime: 2022-01-19 01:05:11
'''
from .BaseDB import BaseDB
import MySQLdb
class MySQLDB(BaseDB):
def __init__(self, host, port, user, passwd, db, charset='u... | jingyucute/docker-flask-celery | py_toolkits/db/MySQLDB.py | MySQLDB.py | py | 13,579 | python | en | code | 0 | github-code | 13 |
20683127771 | import random
print("welcome to rock paper and scissor project")
print()
# Rock Paper Scissors ASCII Art
# Rock
rock = ("""
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
""")
# Paper
paper = ("""
_______
---' ____)____
______)
_______)
_______)
---... | Ayaz-75/Updated-game-Rock-Scissor-and-paper | rock_paper_scissors.py | rock_paper_scissors.py | py | 1,710 | python | en | code | 0 | github-code | 13 |
70213127698 | #!/usr/bin/python
# input files
# ####################
BASE_DIR = '/home/jcchen/hgst/hdd_spc'
# BASE_DIR = 'D:/HGST/MFG/processing/HDD_WEBSPC_CR'
CR_FOLDER = BASE_DIR + '/PN16575'
SPECIFICATION_XLS = CR_FOLDER + '/spec' + '/HDD SPC Monitoring Parameter Specification rev.5.5.xlsx'
MASTER_XLS = CR_FOLDER + '/spec' + '... | jccode/spcrobot | settings.py | settings.py | py | 907 | python | en | code | 0 | github-code | 13 |
70114096019 | """Tests for Institute api"""
from django.urls import resolve, reverse
from rest_framework.test import APIClient
from rest_framework import status
from institute import views
from .test_base import TestData
INSTITUTE_URL = reverse("instituteapi:institute-list")
def get_detail_url(pk):
"""Return the detail url ... | himansrivastava/django-logging | institute/tests/test_institute.py | test_institute.py | py | 2,802 | python | en | code | 0 | github-code | 13 |
3079525479 | import numpy as np
from calc_covariance_matrix import elements_of_covariance_matrix
from estimators_fabric import EstimatorsFabric
from source_trace import SourceTrace
class CTATrace:
"""Класс, описывающий трассу ЕМТ"""
__slots__ = ("number",
"ticks",
"coordinates",
... | Igor9rov/TrackingAndIdentificationModel | Model/ModelCP/cta_trace.py | cta_trace.py | py | 8,244 | python | ru | code | 0 | github-code | 13 |
6627891139 | from modulefinder import packagePathMap
from fastapi import APIRouter, Response, Depends, HTTPException, status
from starlette.status import HTTP_201_CREATED
from schemas.input_schema import InputSchema
from config.db import engine
from models.input import inputs
from typing import List
import secrets
from fastapi.secu... | neof0x/proyecto | routes/input.py | input.py | py | 3,764 | python | en | code | 1 | github-code | 13 |
27022026503 | import os
import re
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import math
import random
import skimage.io
import skimage.transform
import skimage.filters
import skimage.feature
import skimage.morphology
import scipy.ndimage.morphology
import skimage.mea... | esvazas/cv_bachelor | image_processing/logic/identification.py | identification.py | py | 42,653 | python | en | code | 0 | github-code | 13 |
42659440354 | import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 4500))
str = input('give a string')
s.send(str.encode('utf-8'))
print(s.recv(1024).decode('utf-8'))
s.close()
| AatirNadim/Socket-Programming | functional_socket/client.py | client.py | py | 205 | python | en | code | 0 | github-code | 13 |
39740395027 | import operator
from collections import defaultdict
from django.utils.translation import gettext_lazy as _
from django.forms import formset_factory
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.utils import timezone
from .views_common import *
ItemsPerPage = 50
def getPaginator... | esitarski/RaceDB | core/series.py | series.py | py | 22,736 | python | en | code | 12 | github-code | 13 |
9475240082 | # "Here we would need to know the account position to know if we can make a trade or not.\n",
# "1. We need to know if we can afford to buy. This means do we have enough cash to make a buy\n",
#"2. We need to know how much we need to sell of the current position of the asset that
# we are interested in. How much do we... | cpalmer712/Algo_trading | PaperTrading.py | PaperTrading.py | py | 2,050 | python | en | code | 0 | github-code | 13 |
12327917831 | import scrapy
from ..items import ScrapyProjectItem
class MaoyanSpider(scrapy.Spider):
name = "maoyan"
allowed_domains = ["maoyan.com"]
start_urls = ["https://m.maoyan.com/board/4"]
'''
pipeline中如果用with保存内容用w写入,在终端中用 -o data.csv测试不会内容覆盖,会进行附加操作 -> 'a'
'''
def parse(self, response):
... | lll13508510371/Scrapping | Scrapy_Project/Scrapy_Project/spiders/maoyan.py | maoyan.py | py | 2,272 | python | zh | code | 0 | github-code | 13 |
37292548825 | # File: probe.py
# Description: Space probe that can be placed into an environment
# Last Modified: May 9, 2018
# Modified By: Sky Hoffert
from lib.sensor import TemperatureSensor
class Probe():
'''Probe that can be placed in an environment'''
def __init__(self, environment=None):
self... | skyhoffert/sandbox_sockets | lib/probe.py | probe.py | py | 820 | python | en | code | 0 | github-code | 13 |
8560083256 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import tensorflow as tf
from tensorflow.contrib import rnn
# In[2]:
import pandas as pd
graph = tf.Graph()
# In[3]:
data=pd.read_csv("samples/allAtt_onehot_large_train.csv")
dataT=pd.read_csv("samples/allAtt_onehot_large_test.csv")
print(data.head())
print(data.s... | housan321/-deep_football | LSTM_predict_football/LSTM.py | LSTM.py | py | 2,658 | python | en | code | 0 | github-code | 13 |
15015644786 | from six.moves import reduce
import tensorflow as tf
import numpy as np
from tensorflow.python.ops.metrics_impl import _streaming_confusion_matrix
def recall(labels, predictions, num_classes, pos_indices=None, weights=None, average='micro'):
"""
Multi class recall for Tensorflow
:param labels : (tf.in... | koc-lab/turkishlegalner | src/utilities.py | utilities.py | py | 10,552 | python | en | code | 1 | github-code | 13 |
16596022385 | from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import SignupForm, UserUpdateForm, ProfileImageUpdateForm
# Create your views here.
def register(request):
if request.method == "POST":
form = SignupFor... | Ngotrangdh/Kanbancha | users/views.py | views.py | py | 1,616 | python | en | code | 0 | github-code | 13 |
17041435364 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.WithdrawExtend import WithdrawExtend
class AlipayFundWalletWithdrawModel(object):
def __init__(self):
self._amount = None
self._biz_scene = None
self.... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AlipayFundWalletWithdrawModel.py | AlipayFundWalletWithdrawModel.py | py | 4,217 | python | en | code | 241 | github-code | 13 |
1420745241 | def collatzSequence():
print('input a number')
num = int(input())
while num != 1:
if num % 2 == 0:
num = num // 2
print(num)
continue
elif num % 2 != 0:
num = num * 3 + 1
print(num)
continue
print(1)
collatzSequence()
| Mandyiee/pythonPracticeProjects | collatzSequence.py | collatzSequence.py | py | 246 | python | en | code | 0 | github-code | 13 |
72545244819 | # create by fanfan on 2017/10/17 0017
# create by fanfan on 2017/10/17 0017
import numpy as np
import tensorflow as tf
import pickle
import re
from collections import Counter
import itertools
from HAN_network.Chinese_Sentiment_Classification import settings
import os
from tqdm import tqdm
PAD = '_PAD'
UNK = '_UNK'
d... | fanfanfeng/nlp_research | HAN_network/Chinese_Sentiment_Classification/data_util.py | data_util.py | py | 7,115 | python | en | code | 8 | github-code | 13 |
14058784795 | import numpy as np
import sys
def get_units(variable):
"""
Returns a string of appropriate units for different variable
Parameters
-----------
variable : string
name of variable. Acceptable values are aperture, permeability, and transmissivity
Returns
----------
un... | Laok123dawda/dfnworks | pydfnworks/pydfnworks/dfnGen/generation/hydraulic_properties.py | hydraulic_properties.py | py | 20,499 | python | en | code | 0 | github-code | 13 |
31904166783 | import torch
from torch.nn.functional import cross_entropy
class LargeMarginCosineLossLayer(torch.nn.Module):
def __init__(self, feature_dim, label_nums, margin):
super(LargeMarginCosineLossLayer, self).__init__()
self.params = torch.nn.Parameter(torch.randn((feature_dim, label_nums)))
sel... | yangyubuaa/customize_loss | lmcl_loss.py | lmcl_loss.py | py | 1,112 | python | en | code | 1 | github-code | 13 |
38586767007 | from django import forms
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives
from django.utils.translation import ugettext_lazy as _
from django.template.loader import get_template
from django.template import Context
class ContactUs(forms.Form):
your_name = forms.CharField(m... | StepanPilchyck/Neutrino | static_page/forms.py | forms.py | py | 1,387 | python | en | code | 0 | github-code | 13 |
25113439325 | a=input("Enter the string ")
b=input("Enter the word to be removed ")
e=[]
c=a.split(' ')
d=b.split(' ')
length=len(c)
for i in c:
if i not in d:
e.append(i)
z=[]
for j in e:
if j not in z:
z.append(j)
c1=e.count(j)
fre=(c1/length)*100
print(j,fre)
| kishoredevr/Python | removing word in sen.py | removing word in sen.py | py | 315 | python | en | code | 0 | github-code | 13 |
43243076202 | #====================================================================================
# Lista CAP239B - Prof. Reinaldo Rosa
# Aluno: Leonardo Sattler Cassara
# Exercicio 7.2
#====================================================================================
# Importacoes
#-----------... | leosattler/Mat.-Comp.-I-B | Exercises/Exercise7/7.2/grupo_pmnoise/exercise_7_2_grupo_pmnoise.py | exercise_7_2_grupo_pmnoise.py | py | 2,855 | python | en | code | 0 | github-code | 13 |
953134472 | # Load CSV using Pandas from URL
from pandas import read_csv
filename = "../doc/pima-indians-diabetes.data.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(filename, names=names)
print(data.shape)
print(data.dtypes)
peek = data.head(20)
print(peek)
| nhancv/ml-14days | src/day3.py | day3.py | py | 303 | python | en | code | 1 | github-code | 13 |
71605850259 | import logging
from time import sleep
import loggerScript
logger = logging.getLogger(__name__)
from flask import Flask, request
logger.warning("Created Flask and Request")
import json
logger.warning("Imported JSON")
from camera import Camera
logger.warning("Imported Camera")
from main import Main
logger.warning("Impo... | mehulgoel873/EMONITOR | backend/server.py | server.py | py | 2,116 | python | en | code | 0 | github-code | 13 |
37406432663 | import asyncio
from timeit import default_timer
from aiohttp import ClientSession
import aiohttp
import yaml
import aws_lambda_logging
import logging
import time
import botocore.config
import boto3
import slackweb
import ast
import datetime
import json
# JSON logger initialisation
logger = logging.getLogger()
from aws... | Servana/aws-lambda-pinger | pinger_template.py | pinger_template.py | py | 6,411 | python | en | code | 4 | github-code | 13 |
29651880983 | from __future__ import absolute_import, print_function, unicode_literals
__metaclass__ = type
__all__ = [
'ManualInstallCruft',
'MarkLangpacksManuallyInstalledPlugin',
]
import logging
from janitor.plugincore.cruft import Cruft
from janitor.plugincore.i18n import setup_gettext
from janitor.plugincore.plugin... | GalliumOS/update-manager | janitor/plugincore/plugins/langpack_manual_plugin.py | langpack_manual_plugin.py | py | 1,778 | python | en | code | 4 | github-code | 13 |
21891674834 | import grokpy
import unittest
from grok_test_case import GrokTestCase
from grokpy.exceptions import GrokError
class DataSourceFieldTestCase(GrokTestCase):
def setUp(self):
self.f = grokpy.DataSourceField()
def testGoodInstantiation(self):
'''
Basic object instantiation
'''
# Instantiate the... | Komeil1978/grok-py | tests/unit/test_data_source_field.py | test_data_source_field.py | py | 4,424 | python | en | code | 0 | github-code | 13 |
30828672504 | import math, sys
import maya.api.OpenMaya as om
import maya.api.OpenMayaUI as omui
import maya.api.OpenMayaAnim as oma
import maya.api.OpenMayaRender as omr
from maya.OpenMaya import MGlobal
import pymel.core as pm
from zMayaTools.menus import Menu
from zMayaTools import maya_helpers, node_caching
# This is insane. T... | zewt/zMayaTools | plug-ins/zRigHandle.py | zRigHandle.py | py | 21,095 | python | en | code | 102 | github-code | 13 |
19478327688 | import string, random, os, json, msvcrt, time, encoder, decoder
# Hehecoin Miner
# Ryan Earll
# ryangearll@gmail.com
# @ryanxea
VERSION = "1.5"
DATEUPDATED = "6/22/2017"
os.system('color a')
def getKey(): # Returns the key.txt as a string
with open("key.txt", "r") as f:ret = f.r... | dxeheh/hehecoin | miner.py | miner.py | py | 3,124 | python | en | code | 0 | github-code | 13 |
27847044124 | from django.shortcuts import render, get_object_or_404
from .models import Book
from .forms import BookForm
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from .serializers import BookSerializer
from django.http.response import JsonResponse
# Create your views here.
... | ruthwik34/BookApp-Backend-Django | books/views.py | views.py | py | 2,833 | python | en | code | 0 | github-code | 13 |
17113947004 | import logging.config
import sys
from os import environ, makedirs, path
from agr_literature_service.lit_processing.data_ingest.utils.file_processing_utils import load_pubmed_resource_basic
from agr_literature_service.lit_processing.utils.sqlalchemy_utils import create_postgres_session
from agr_literature_service.lit_p... | alliance-genome/agr_literature_service | agr_literature_service/lit_processing/data_ingest/pubmed_ingest/pubmed_update_resources_nlm.py | pubmed_update_resources_nlm.py | py | 2,900 | python | en | code | 1 | github-code | 13 |
3342518713 | import sys
sys.path.append("..")
import extend
from ctypes import *
import os
import numpy as np
from subprocess import check_output
import tempfile
import platform
if platform.system()=="Linux":
check_output("gcc -std=c99 -fPIC -c times.c", shell=True)
check_output("gcc -shared times.o -o times.so", shell=Tru... | szsdk/KSS | test/extend_test.py | extend_test.py | py | 970 | python | en | code | 0 | github-code | 13 |
9985390320 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import sys
import time
import codecs
from logging import FileHandler
import logging.config
basedir = os.path.abspath(os.path.dirname(__file__))
logdir = os.path.join(basedir, 'logs')
logini_path = os.path.join(basedir, 'log.ini')
if not os.path.exists(logdir):
... | abrance/mine | wait/autotest.2020.03.16/log.py | log.py | py | 2,976 | python | en | code | 0 | github-code | 13 |
26881003251 | from lxml import html
import requests
import sys
import re
import urllib
import cgi
menuURLs = []
# get Kanji, Katakana Pairs
# crawl デジタル大辞泉 on コトバンク,
# to crawl other dictionaries on the website,
# just change "4032" to the number of キーワード一覧 pages of the dictionary,
# and change "daijisen" to the dictionary name
... | shitian-ni/jpn_crawl | kanji-kana/kotoba.py | kotoba.py | py | 1,754 | python | en | code | 2 | github-code | 13 |
42084420673 | class BinarySearchTree(object):
def __init__(self, root):
self.root = root
def insert(self, data):
bstn = self.root
while bstn != None:
# If the data is less than the current nodes data go to the left
# down the tree because of the BST invariant.
if d... | rwerthman/citc | 4.5/python/binary_tree.py | binary_tree.py | py | 2,430 | python | en | code | 0 | github-code | 13 |
74663821777 | # Nama : Agung Mubarok
# NIM : 0110120196
# Kelas: Sistem Informasi - 05
def jumlah_batas(nums, batas):
# Variabel hasil yang menampung nilai awal 0
hasil = 0
# Membuat perulangan apakah i terdapat di dalam parameter nums
for i in nums:
# Jika i/isi dari parameter nums lebih besar dari parameter batas
... | agung10/List | main.py | main.py | py | 4,445 | python | id | code | 0 | github-code | 13 |
34424984701 | # Project 3 - Calcudoku Solver
#
# Name: Justin Mo
# Instructor: Brian Jones
# Section: 17
from solver_funcs import *
def get_cages():
index = 1
number_of_cages = int(input("Number of cages: "))
list_of_entries = list('')
while index <= number_of_cages:
cage_number = input("Cage number {:d}: ".form... | ohnoitsjmo/cpe101 | cpe101projects/101project03/solver_draft.py | solver_draft.py | py | 3,082 | python | en | code | 0 | github-code | 13 |
74852811856 | # -*- coding: utf-8 -*-
import csv
import logging
from django.core.management.base import BaseCommand
from django.conf import settings
from geonames.downloader import Downloader
from geonames.models import Country
logger = logging.getLogger(__name__)
# municipality_levels is a dictionary that tells for some coun... | davidegalletti/django_geonames_cities | geonames/management/commands/synchgeonamescountries.py | synchgeonamescountries.py | py | 1,873 | python | en | code | 0 | github-code | 13 |
36581291392 | """
Define and check rules for a film object.
"""
# Rules for the film object
parse_options = {
'type': 'film',
'runtime_min': 80,
'runtime_max': 140,
'inlude_unkown_runtime': False,
'score_range_min': '6.9',
'score_range_max': '10.0',
'include_unknown_score': False,
'year_range_oldest'... | hastagAB/Awesome-Python-Scripts | IMDBQuerier/parser_config.py | parser_config.py | py | 2,690 | python | en | code | 1,776 | github-code | 13 |
71690603219 | from accounts.decorators import admin_only, allowed_users, unauthorized_user
from django.shortcuts import render, redirect
from .models import *
from .forms import *
from django.forms import inlineformset_factory
from .filters import OrderFilter
from django.contrib.auth.forms import UserCreationForm
from django.contrib... | Joepolymath/customer-management-system | accounts/views.py | views.py | py | 6,780 | python | en | code | 0 | github-code | 13 |
23606167769 | #@ type: compute
#@ dependents:
#@ - func2
#@ - func3
#@ corunning:
#@ mem1:
#@ trans: mem1
#@ type: rdma
import struct
import pickle
from typing import List
TRAIN_SIZE = 60000
SIZE = 28
BATCH_SIZE = 1000
OUTPUT = "data/image_store"
def binarization(img: List[List[int]]) -> List[List[int]]:
"""
... | zerotrac/CSE291_mnist | Mnist_test/func1.py | func1.py | py | 3,365 | python | en | code | 2 | github-code | 13 |
11228614174 | # hard
class Solution:
def distinctSubseqII(self, s: str) -> int:
def _inner_func(depth, couples, s, prefix=''):
level_couple = []
for index, one in enumerate(s):
couple = prefix + one
if couple not in couples:
couples.add(couple)
... | Tritium-leo/leetcode_pratice | _doing_job/test_940.py | test_940.py | py | 798 | python | en | code | 1 | github-code | 13 |
44250666811 | # coding: utf-8
from wordcloud import WordCloud
import jieba
# 打开文本
text = open('lyb.txt').read()
# 加载停用词表
stop_word_set = set()
with open('stop_words.txt', 'r') as f:
for line in f:
word = line.strip()
if word not in stop_word_set:
stop_word_set.add(word)
print(stop_word_set)
#... | ylhao/wordcloud | lyb_2.py | lyb_2.py | py | 733 | python | en | code | 1 | github-code | 13 |
11262615875 | import hashlib
import json
import logging
from tamperfree.browser import ProxiedBrowser
from tamperfree.tor_process import TorProcess
logger = logging.getLogger(__name__)
class MismatchedHashes(object):
def __init__(self, hashes, wrong_hashes):
self.hashes = hashes
self.wrong_hashes = wrong_hashes... | Tethik/tamperfree | tamperfree/verify.py | verify.py | py | 3,463 | python | en | code | 1 | github-code | 13 |
13629366547 |
from typing import Dict, Optional
from ..extraCode.location import HexPoint, Resource
from ..extraCode.util import isNotNone, JsonSerializable, ArgumentMissingError, NotSetupException, AlreadySetupException
from ..extraCode.modifiers import Placeable, Ownable, Purchaseable
from ..playerCode.player import Player
from ... | hydrogen602/settlersPy | gameServer/mapCode/lineMapFeatures.py | lineMapFeatures.py | py | 2,445 | python | en | code | 0 | github-code | 13 |
22237183726 | from __future__ import absolute_import, division, print_function
import pytest
from inspire_hal.factory import create_app
@pytest.fixture(scope='session')
def app():
"""
Deprecated: do not use this fixture for new tests, unless for very
specific use cases. Use `isolated_app` instead.
Flask applicat... | inspirehep/inspire-hal | tests/unit/conftest.py | conftest.py | py | 985 | python | en | code | 0 | github-code | 13 |
31078506343 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Advent of Code 2020 day 15 module."""
try:
from tqdm import tqdm
HAS_TQDM = True
except ImportError:
HAS_TQDM = False
def run(start):
numbers = {}
turn = 0
for n in start:
yield n
numbers[n] = (None, turn)
turn += 1
... | pmrowla/aoc2020 | day15.py | day15.py | py | 1,618 | python | en | code | 0 | github-code | 13 |
39740109887 | import os
import datetime
import xlsxwriter
from django.utils.translation import gettext_lazy as _
from . import utils
from .models import *
from .add_excel_info import add_excel_info
data_headers = (
'Bib', 'Status', 'Date',
'LastName', 'FirstName',
'Gender',
'DOB',
'City', 'StateProv',
'License',
'UCIID',
)... | esitarski/RaceDB | core/get_number_set_excel.py | get_number_set_excel.py | py | 1,543 | python | en | code | 12 | github-code | 13 |
70170628177 | from PIL import Image
import torch
from torch.utils.data import Dataset, DataLoader
import random
from graph_algo import uniq_edges
import numpy as np
from functools import reduce
import operator
import yajl
from torchvision import transforms
class pairwise_dataset(Dataset) :
'''Uses image_list and adjacency_list f... | bvraghav/rivet | dataset.py | dataset.py | py | 5,913 | python | en | code | 1 | github-code | 13 |
6606344232 | __author__ = "Timo Konu \n Severi Jääskeläinen \n Samuel Kaiponen \n Heta " \
"Rekilä \n Sinikka Siironen \n Juhani Sundell"
__version__ = "2.0"
import widgets.gui_utils as gutils
import widgets.binding as bnd
from modules.element import Element
from typing import Set
from typing import List
from PyQt5... | JYU-IBA/potku | dialogs/measurement/depth_profile_ignore_elements.py | depth_profile_ignore_elements.py | py | 2,234 | python | en | code | 7 | github-code | 13 |
42275566699 | """
Test ion functionality
"""
import astropy.units as u
import numpy as np
import pytest
import fiasco
from fiasco.util.exceptions import MissingDatasetException
temperature = np.logspace(5, 8, 100)*u.K
@pytest.fixture
def ion(hdf5_dbase_root):
return fiasco.Ion('Fe 5', temperature, hdf5_dbase_root=hdf5_dbase... | wtbarnes/fiasco | fiasco/tests/test_ion.py | test_ion.py | py | 14,663 | python | en | code | 18 | github-code | 13 |
24769689499 | """Collision_Callback.py
This is the base component for all collision components. Because it calls
owner's on_collision callback, it allows components derived from it to react to
that callback. It also takes care of tracking sprite group names, so that PUG
can give the user a nice dropdown of all group names used... | sunsp1der/pug | pig/components/collision/Collision_Callback.py | Collision_Callback.py | py | 3,307 | python | en | code | 0 | github-code | 13 |
2547526877 | from packages.Board import Board
class Game:
def __init__(self):
print('Game instance')
self.board = Board()
self.board.draw_squares([
'o', 'o', 'X',
'', 'X', 'o',
'X', '', 'x'
])
self.board.on_mouse_click(self._mouse_click_handler)
... | rafaeltmbr/tic-tac-toe | src/packages/Game.py | Game.py | py | 613 | python | en | code | 0 | github-code | 13 |
5948004290 | import pandas as pd
from scipy.sparse import csr_matrix
from sklearn.neighbors import NearestNeighbors
import pickle
#load data
users = pd.read_csv('datasets/BX-Users.csv', sep=";", error_bad_lines=False, encoding='latin-1')
books = pd.read_csv('datasets/BX-Books.csv', sep=";", error_bad_lines=False, encoding='latin-1... | tenwang10/Library | RecommendationSystem.py | RecommendationSystem.py | py | 2,477 | python | en | code | 0 | github-code | 13 |
3302411007 | from collections import Counter
from numpy import arange, delete, setdiff1d
from sklearn.model_selection import train_test_split as sk_train_test_split
from sklearn.utils import safe_indexing
from text_categorizer import pickle_manager
from text_categorizer.constants import random_state
from text_categorizer.logger imp... | LuisVilarBarbosa/TextCategorizer | text_categorizer/train_test_split.py | train_test_split.py | py | 4,312 | python | en | code | 0 | github-code | 13 |
40740259957 | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# Встроенные модули
import time, sys, subprocess
from threading import Thread
# Внешние модули
try:
import psycopg2
except ModuleNotFoundError as err:
print(err)
sys.exit(1)
# Внутренние модули
try:
from mod_common import *
except ModuleNotFoundError as err:
... | surarim/nifard | mod_traffic_nftables.py | mod_traffic_nftables.py | py | 4,215 | python | ru | code | 0 | github-code | 13 |
14734375605 | '''
328. Odd Even Linked List
Solution:
'''
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
odd = None
even = None
even_head = None
itr = None
if head and head.next and head.next.next:
odd = head
even... | messiel12pr/LeetCode | Python/Medium/Odd_Even_Linked_List.py | Odd_Even_Linked_List.py | py | 795 | python | en | code | 1 | github-code | 13 |
74166916819 | """
This script takes csv file of the drone trajectory dataset with the following header
timestamp,tx,ty,tz,qx,qy,qz,qw
* it takes only the tx,ty,tz points and and populate two numpy arrays,
u_in: (N, 3*window_size_u)
y_meas; (N, 3*window_size_y)
* then it saves the prepared dataset to be trained by the Dyno... | mzahana/dynonet_trajectory_prediction | prep_dynonet_dataset.py | prep_dynonet_dataset.py | py | 11,254 | python | en | code | 1 | github-code | 13 |
37090059162 | h = int(input ("What is your height (cm)?"))
w = int(input ("What is your weight (kg)?"))
h_m = h/100
BMI = w / (h_m*h_m)
print ("BMI: ", BMI)
if BMI <16:
print ("Severly underweight")
elif BMI <= 18.5:
print ("Underweight")
elif BMI <= 25:
print ("Normal")
elif BMI <= 30:
print ("overweight")
else:
... | Nampq281/phamquynam-fundamentals-c4e21 | session02/homework02/serious_1.py | serious_1.py | py | 336 | python | en | code | 0 | github-code | 13 |
498785317 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as imagemodels
import torch.utils.model_zoo as model_zoo
from torchvision import models
from cfg.Pretrain.config import cfg
class Resnet18(imagemodels.ResNet):
def __init__(self, embedding_dim=1024, pretrained=False):
... | xinshengwang/S2IGAN | models/ImageModels.py | ImageModels.py | py | 9,307 | python | en | code | 40 | github-code | 13 |
31084184932 |
from treeBinarySearch import NodeABB
if __name__ == '__main__':
def preOrdemArbin(node:NodeABB):
if node is not None:
print(node._data)
if node._esq is not None:
preOrdemArbin(node._esq)
if node._dir is not None:
preOrdemArbin(node._dir... | vlrosa-dev/estrutura-dados-python | 06-struct-data-TreeBinarySearch/main.py | main.py | py | 4,488 | python | pt | code | 1 | github-code | 13 |
70010089937 | #battle_functons.py
import random
from colorama import init, Fore, Style
init(autoreset=True)
import textwrap
import shutil
from adventure_pkg.character_functions import Character
from adventure_pkg.monster_battle_functions import Monster
columns, _ = shutil.get_terminal_size()
class Combat_Actions:
d20 = [x + ... | hikite1/Adventure-Story | adventure_pkg/battle_functions.py | battle_functions.py | py | 4,464 | python | en | code | 0 | github-code | 13 |
25542540141 | import os
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Literal
from tinydb import Query, TinyDB
@dataclass
class Registrador:
nomeuser: str # Por qual nome deseja ser chamado
user_ident: int # Numero de usuário no telegram
data: str # Data em que foi realizado o r... | cleytonfs777/emendastelebot | data2/datamanager.py | datamanager.py | py | 1,890 | python | pt | code | 0 | github-code | 13 |
17058191374 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class PrintModel(object):
def __init__(self):
self._device_id = None
self._enable = None
self._name = None
self._printer_id = None
self._printer_type = None
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/PrintModel.py | PrintModel.py | py | 2,738 | python | en | code | 241 | github-code | 13 |
20593217130 | bunker_dict = {items : {} for items in input().split(', ')}
for _ in range(int(input())):
item, product, params = input().split(' - ')
quan, qual = [ int(x[x.index(':') + 1:]) for x in params.split(';')]
bunker_dict[item][product] = (quan, qual)
print('Count of items:', sum([sum(x[0] for x in tuple(v.v... | byAbaddon/Advanced-Course-PYTHON-May-2020 | 4.1 Comprehensions - Exercise/09. Bunker.py | 09. Bunker.py | py | 1,224 | python | en | code | 0 | github-code | 13 |
4321611571 | ###############################################################################
# Copyright (C) 2018, 2019, 2020 Dominic O'Kane
###############################################################################
from FinTestCases import FinTestCases, globalTestCaseMode
from financepy.utils.date import set_date_format... | domokane/FinancePy | tests_golden/TestFinDate.py | TestFinDate.py | py | 8,660 | python | en | code | 1,701 | github-code | 13 |
72857924819 | #User function Template for python3
class Solution:
# Version 1: Greedy
# Start from the smallest number and subtract K for this.
# For the following numbers, try to subtract first, then keep the same, then increase K.
# Since we start from the smallest number and try to make the number small first, so ... | john35452/GFG_Weekly_Coding_Contest | gfg-weekly-coding-contest-104/Distinct Elements.py | Distinct Elements.py | py | 727 | python | en | code | 0 | github-code | 13 |
33760309721 | import numpy as n, matplotlib.pyplot as p
from mpl_toolkits.axes_grid.axislines import SubplotZero
from random import random
# fig = p.figure(1)
# ax = SubplotZero(fig, 111)
# fig.add_subplot(ax)
# for direction in ["xzero", "yzero"]:
# ax.axis[direction].set_axisline_style("-|>")
# ax.axis[direction].set_visib... | HERA-Team/hera_sandbox | ygz/simu/legend_sens.py | legend_sens.py | py | 2,060 | python | en | code | 1 | github-code | 13 |
16402778170 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
# Description:
import hashlib
from typing import (
List
)
__all__ = ['md5', 'md5file', 'sha1', 'sha256', 'sha512', 'short']
code_map = (
'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' ... | wxnacy/wpy | wpy/hashs.py | hashs.py | py | 2,090 | python | en | code | 0 | github-code | 13 |
38462324919 | import numpy as np
import pytest
from hypothesis import given, HealthCheck, settings
from PyDynamic.signals import Signal
from test.test_signal_class.conftest import signal_inputs
@given(signal_inputs())
@settings(
deadline=None,
suppress_health_check=[
*settings.default.suppress_health_check,
... | Met4FoF/Code | PyDynamic/test/test_signal_class/test_signal_raise_error_on_wrong_inputs.py | test_signal_raise_error_on_wrong_inputs.py | py | 1,226 | python | en | code | 0 | github-code | 13 |
22686978712 | # Name:
# Section:
# strings_and_lists.py
from tokenize import Double
print("********** Exercise 2.7 **********")
def sum_all(number_list):
# number_list is a list of numbers
total = 0
for num in number_list:
total += num
return total
# Test cases
print ("sum_all of [4, ... | omerAtique/Python | Python_MIT_courseware_Homeworks_and_projects/stringsAndLists.py | stringsAndLists.py | py | 2,990 | python | en | code | 0 | github-code | 13 |
37631096172 | # author: ICL-U
"""
Validate the weakness detection.
"""
import argparse
import io
import logging
import sys
import subprocess
import os
import shutil
from shapely.geometry import Point # pylint: disable=import-error
from shapely.geometry.polygon import Polygon # pylint: disable=import-error
from deeplab_mgr import ... | wasn-lab/Taillight_Recognition_with_VGG16-WaveNet | src/utilities/weakness_detection/calc_validation.py | calc_validation.py | py | 11,849 | python | en | code | 2 | github-code | 13 |
8585850765 | import json
from urllib.request import urlopen
import tweepy
import re
import time
# DATA ---------------------------------------------------------------------------------------------------------------
# Musix Match API data
musixmatchAPI_KEY = ""
# Twitter account API data
twitterConsumerKey = ""
twitterConsumerSec... | dvilelaf/SpaceRocksBot | SpaceRocksBot.py | SpaceRocksBot.py | py | 3,408 | python | en | code | 2 | github-code | 13 |
19150462524 | import plotly.graph_objects as go
from game_model import BALL_RADIUS, TABLE_DIMENSIONS, POCKET_COORDINATES
def draw_circle(fig, coordinates, color, r=BALL_RADIUS):
fig.add_shape(type="circle",
xref="x", yref="y",
x0=(coordinates[0] - r), y0=(coordinates[1] - r), x1=(coordinates... | Enrico-Call/virtual-pool-coach | strategy/draw.py | draw.py | py | 2,230 | python | en | code | 0 | github-code | 13 |
71817579218 | import os
import json
# Parses metadata from a file and returns it in a dictionary
def parse_metadata(filename):
# Does the file exist?
if not os.path.isfile(filename):
raise FileNotFoundError("Metadata JSON not found.")
with open(filename, "r") as file:
data = file.read()
file.close... | Greg4cr/PythonUnitTestGeneration | src/file_utilities.py | file_utilities.py | py | 2,073 | python | en | code | 1 | github-code | 13 |
9868561034 | from django.shortcuts import render,get_object_or_404,redirect
from catalog.models import *
from django.http import HttpResponse
from django.conf import settings
from product.models import *
from felixuser.models import Profile
from django.db.models import F,Avg
from .forms import *
city_slug = City.slug
cat_slug = Ca... | LevupCompany/beton | catalog/views.py | views.py | py | 7,200 | python | en | code | 0 | github-code | 13 |
5415744853 | from data.shared import getcwd, p
from time import sleep
def coin(scale_size):
hero_sheet_image = p.image.load(getcwd() + '\\sprites\\coin\\coin_sprite_sheet.png').convert()
hero_sheet_image.set_colorkey(hero_sheet_image.get_at((0, 0)))
hero_sheet_image = p.transform.scale(hero_sheet_image, scale... | DannyGersh/Maze-of-doooom | sprites/coin.py | coin.py | py | 1,419 | python | en | code | 0 | github-code | 13 |
13328046299 | # Калькулятор
print("Буква q будет закрывать программу")
while True:
s = input("Знак (+,-,*,/,%): ")
if s == "q":
break
if s in ('+', '-', '*', '/', '%'):
if s == '%':
print("x - число от которог берём %")
print("y - процент, который берём")
x = float(input("x= "))
y = float(input("y=... | elenashestakova/project_01 | sort.py | sort.py | py | 8,213 | python | ru | code | 0 | github-code | 13 |
29404053888 | # *********************************************************
# Program: TL15_G01.py
# Course: PSP0101 PROBLEM SOLVING AND PROGRAM DESIGN
# Tutorial Section: TL15 Group: G1
# Trimester: 2215
# Year: 2022/23 Trimester 1
# Member_1: 1221101160 | MUHAMMAD NABIL NAUFAL BIN MD ZAID
# Member_2: 1211112042 | GOH ROU LOU
# Membe... | mnanwarmz/python-uni-uber-like | TL15_G01.py | TL15_G01.py | py | 1,541 | python | en | code | 0 | github-code | 13 |
31228320427 | def infinity_gen(input_list):
len_list = len(input_list)
if len_list == 0:
raise ValueError(
'В функцию infinity_gen не может быть передан пустой список!'
)
left = 0
right = len_list - 1
while True:
yield input_list[left]
if right > left:
yield... | palmage/Homework | Solution1.py | Solution1.py | py | 1,287 | python | ru | code | 0 | github-code | 13 |
70865462417 | import pandas as pd
import numpy as np
class Information:
def __init__(self):
#用户、电影、评分总数
self.user_number = 943
self.movie_number = 1682
self.rating_number = 100000
self.age_bin = [0,18,25,35,60,100]
def load_info(self):
# 读入用户信息
user_names = ['... | haolin-nju/ExploreML100k | main.py | main.py | py | 8,892 | python | en | code | 0 | github-code | 13 |
43077350682 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/4/11 11:11
# @Author : guoyankai
# @Email : 392759421@qq.com
# @File : detect.py.py
# @software: PyCharm
import cv2
import time
import numpy as np
import torch
from torch.autograd.variable import Variable
from models.models import PNet, RNet, ONet
f... | Guo-YanKai/mtcnn | core/detect.py | detect.py | py | 6,838 | python | en | code | 1 | github-code | 13 |
18749410425 | #!/usr/bin python3.5
import random
import time
from itertools import chain
import matplotlib.pyplot as plt
from collections import deque
from copy import deepcopy
class Queue(object):
"""
Queue wrapper implementation of deque
"""
def __init__(self, arg=list()):
self._queue = deque(arg)
de... | MohamedAbdultawab/FOC_RiceUniv | algorithmic-thinking-1/module-2-project-and-application/02_application-2-analysis-of-a-computer-network/main.py | main.py | py | 13,373 | python | en | code | 0 | github-code | 13 |
41118952771 | import pytest
from _pytest.config import PytestPluginManager, hookimpl
from pytest_richtrace.plugin import PytestRichTrace
def pytest_addoption(parser: pytest.Parser, pluginmanager: PytestPluginManager) -> None:
"""
Add options to the pytest command line for the richtrace plugin
:param parser: The pytest... | sffjunkie/pytest-richtrace | src/pytest_richtrace/__init__.py | __init__.py | py | 1,431 | python | en | code | 0 | github-code | 13 |
40113417411 | import tarfile
# Define the path to the TAR archive
tar_file_path = 'example.tar.gz'
# Specify the target directory where you want to extract the files
target_directory = 'extracted_files/'
# Create a context manager using the 'tarfile.open' method
with tarfile.open(tar_file_path, 'r:gz') as tar:
# List the cont... | fdac23/ChatGPT_Insecure_Code_Analysis | All Generated Codes/CWE-22/CWE-22_ILP-3c.py | CWE-22_ILP-3c.py | py | 606 | python | en | code | 0 | github-code | 13 |
36334421836 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 4 14:27:45 2019
@author: isaacscarrott
"""
#Import the correct variables
from numpy import linalg, array, dot, identity, asarray, asmatrix
from pandas import read_csv
from matplotlib.pyplot import plot, figure, xlim, ylim, title, legend, savefig
... | isaac-scarrott/Ridge-Regression-K-Means | Ridge Regression/RidgeRegression.py | RidgeRegression.py | py | 2,858 | python | en | code | 0 | github-code | 13 |
11411327047 | import pandas as pd
import numpy as np
from collections import Counter
from sklearn.manifold import TSNE
def _uni_counts_embedder(data, **kwargs):
if 'index_col' not in kwargs:
index_col = data.trajectory.retention_config['index_col']
else:
index_col = kwargs['index_col']
if 'event_col' no... | Demiurgy/retentioneering-tools | retentioneering/core/feature_extraction.py | feature_extraction.py | py | 4,227 | python | en | code | 0 | github-code | 13 |
26581079014 | import numpy as np
import math
import copy
def check_precision(a, eps):
if abs(a) < abs(eps):
return 0
return a
def is_diagonal_matrix(x):
return np.count_nonzero(x - np.diag(np.diagonal(x))) == 0
def get_p_q_indexes(A):
max_abs = 0
max_i = 0
max_j = 0
for i in range(len(A)):
... | robertadriang/CalculNumeric2022 | Tema5/main.py | main.py | py | 5,455 | python | en | code | 0 | github-code | 13 |
71071810259 | # resnets + fpn
import math
import torch
import torch.nn as nn
from torchsummary import summary
from nets.resnets import resnet18, resnet34, resnet50, resnet101, resnet152
from nets.efficientnet import EfficientNet as EffNet
from nets.darknet import darknet53
from nets.deform_conv import DeformConv2d
from torchstat imp... | stjuliet/CenterLoc3D | nets/fpn.py | fpn.py | py | 14,237 | python | en | code | 10 | github-code | 13 |
70551296338 | import pygame
from time import time
from fonctions import *
from constantes import *
class Ballon(pygame.sprite.Sprite): #initialisation des variables, vitesse définie par la puissance
def __init__(self, x, y, angle, vitesse):
super().__init__()
self.image = pygame.image.load("ressources/... | Baptistekeunbroek/Projet-Transverse-L1 | Projet Transverse/Classes/Ballon.py | Ballon.py | py | 1,529 | python | fr | code | 0 | github-code | 13 |
3860935511 |
x = [2]
for i in range(3,105000,2):
is_prime=True
for j in x[1:]:
if i%j==0:
is_prime=False
if is_prime==True:
x.append(i)
print(x)
tmp = []
for i in x:
tmp.append(str(i))
print(tmp[10000])
| lemonwisard/project-euler | problem6.py | problem6.py | py | 207 | python | en | code | 0 | github-code | 13 |
70102270739 | import pygame
import cv2
import os
import random
from .music import Music
import smrc.utils
pygame.init()
# Initialize the joysticks
pygame.joystick.init()
# root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'media')
# # /home/kai/optimize_tool/smrc/media
# # print(f'root_dir = {root_dir}')
# prin... | cyoukaikai/ahc_ete | smrc/utils/annotate/game_controller.py | game_controller.py | py | 11,736 | python | en | code | 2 | github-code | 13 |
70494407379 | import requests
from bs4 import BeautifulSoup
import json
# Set your custom user agent
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
# Send a GET request to the URL with the custom user agent
url = "https://www.proflowers.com/... | wasemalwisy/Task-2-Proflowers-Scraper | final flowers .py | final flowers .py | py | 2,370 | python | en | code | 0 | github-code | 13 |
7041944010 | import eqsig
from eqsig import sdof
import numpy as np
from o3seespy import opy
from o3seespy import cc as opc
def get_inelastic_response(mass, k_spring, f_yield, motion, dt, xi=0.05, r_post=0.0):
"""
Run seismic analysis of a nonlinear SDOF
:param mass: SDOF mass
:param k_spring: spring stiffness
... | o3seespy/o3seespy | tests/binary/test_sdof.py | test_sdof.py | py | 4,628 | python | en | code | 16 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.