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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
19160015551 | """
Contains author & document records in dict() form for self-contained testing
"""
import contextlib
import copy
import time
from collections import defaultdict
from itertools import zip_longest
from unittest.mock import MagicMock
import path_finder
from cache.cache_buddy import CacheMiss, AUTHOR_VERSION_NUMBER, \
... | svank/appa-backend | appa/tests/mock_backing_cache.py | mock_backing_cache.py | py | 9,020 | python | en | code | 0 | github-code | 36 |
70714190504 | #!/usr/bin/env python
# coding: utf-8
# ## Import des librairies
# In[2]:
import numpy as np
import pandas as pd
from pandas_profiling import ProfileReport
import matplotlib.pyplot as plt
import plotly.offline as py
import seaborn as sns
import plotly.graph_objs as go
import plotly
import plotly.figure_factory as ... | bg-mohamed/RFS677-Y | Machine Learning/Machine_Learning_Classification.py | Machine_Learning_Classification.py | py | 31,870 | python | fr | code | 1 | github-code | 36 |
4788623202 | from pytz import timezone
from datetime import datetime
import re
from urllib.parse import urlparse, urljoin
from flask import request, escape, Request
import tiktoken
from werkzeug.datastructures import ImmutableMultiDict
class HTTPMethodOverrideMiddleware(object):
allowed_methods = frozenset([
'GET',
... | mkmenta/chatgpt-research | utils.py | utils.py | py | 3,525 | python | en | code | 0 | github-code | 36 |
73997230824 | import unittest
from HomeWorks.Lesson_4.common.constants import *
from HomeWorks.Lesson_4.client import show_presence, proc_answer
# Класс с тестами
class TestClass(unittest.TestCase):
# тест коректного запроса
def test_def_presense(self):
test = show_presence()
# время необходимо приравнять... | spoliv/Client_Server_Apps_28.10.2019 | HomeWorks/Lesson_4/unit_tests/test_client.py | test_client.py | py | 1,235 | python | ru | code | 0 | github-code | 36 |
2884377589 | # -*- coding: utf8 -*-
__author__ = 'yqzhang'
from utils.util import get_requests, form_post,login,get_code_token
def detail(gooids):
login('0086','18810432995')
url='https://jf.lagou.com/integral/mall/goods/detail.json'
data={'goodsId':gooids}
return get_requests(url=url,remark='商品详情',data=data)
# de... | Ariaxie-1985/aria | api_script/jianzhao_web/gouinH5/detail.py | detail.py | py | 334 | python | en | code | 0 | github-code | 36 |
39983047311 | # Assignment-008/6 (Prime Numbers)
# 💡Objective:
# To improve your control flow statement skills
# and to raise your awareness of some algebraic knowledge.
# Write a Python code on any IDE,
# push it up to your GitHub repository
# and submit the GitHub page address link
# in addition to your code (answer) as a ... | MattCon70/mypython | assigments/primenumbers2.py | primenumbers2.py | py | 1,107 | python | en | code | 0 | github-code | 36 |
2353697076 | import os
import dotenv
from telethon import sync
_users_cache = set() # to avoid double DMs
dotenv.load_dotenv()
MESSAGE_TEMPLATE = os.getenv("AUTO_DM")
CURSOR_FILE = "cursor.txt"
def _read_cursor() -> int:
if os.path.exists(CURSOR_FILE):
with open(CURSOR_FILE) as file:
return int(file.re... | rebryk/supertelega | dm.py | dm.py | py | 1,280 | python | en | code | 15 | github-code | 36 |
43427847703 | from .common import deploy
def _parse_sub(subparsers):
parser = subparsers.add_parser("rtt_isolated",
help="Round-trip time for each node in isolation (only node on network)")
return parser
def _main(args, script_fmt):
cmd_list = [
"cd mqtt-benchmark",
script_fmt.format(pub="to... | arjunr2/mqtt-benchmark | bench_scripts/rtt_isolated.py | rtt_isolated.py | py | 405 | python | en | code | 0 | github-code | 36 |
3285451205 | from commands.CleanBuildCommands.SignApkCommand import SignApkCommand
from parsers.SignApkParser import SignApkParser
class SignApkCommandBuilder:
def __init__(self, pathToBuildUtil):
assert pathToBuildUtil is not None
self.pathToBuildUtil = pathToBuildUtil
def isSignApk(self, line):
assert line is not None... | TouchInstinct/BuildScript | scripts/TouchinBuild/CommandBuilders/SignApkBuilder.py | SignApkBuilder.py | py | 697 | python | en | code | 1 | github-code | 36 |
29551084642 | '''
E->E+T|T
T->T*F|F
F->(E)|A
A->1A|2A|3A|4A|5A|6A|7A|8A|9A|0|1|2|3|4|5|6|7|8|9|ε
'''
'''
E->EOE|(E)|A
O->+|-|*
A->1A|2A|3A|4A|5A|6A|7A|8A|9A|0|1|2|3|4|5|6|7|8|9|ε
'''
#还是消除简单左递归
#重写LR0和SLR1中的TABLE以及ANALYSE函数,条理更清晰
import copy
LAN = {}
FIRST = {}
EXLAN = []
ITEM = []
DICT = {}
DFA = [] #[0]为代表 其中[0][0]为项目字符串,[0][1... | xbyige/LL1-LR0-SLR1-LR1_Parser | lr1.py | lr1.py | py | 10,054 | python | en | code | 1 | github-code | 36 |
74473655465 | from inspect import getsource
from IPython.core.display import HTML, display
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
_formatter = HtmlFormatter()
def get_source(obj, preprocess=None):
# comments = f'# decorated by: {obj.decorated_by}\n... | krassowski/jupyter-helpers | jupyter_helpers/source.py | source.py | py | 983 | python | en | code | 45 | github-code | 36 |
38075654293 | # https://quera.ir/problemset/293/
a = int(input())
b = int(input())
if a == 1 and b == 1:
pass
elif a == 1 and b == 2:
print(2)
elif a == 2 and b == 2:
print(2)
else:
if a == 1 or a == 2:
print(2)
if a % 2 == 0:
start_point = a+1
else:
if a == 1:
start_poin... | MohammadNPak/quera.ir | اعداد اول/python/solution1.py | solution1.py | py | 686 | python | en | code | 40 | github-code | 36 |
73574822824 |
def community_similarity(l1, l2):
totalElementos = 0
similaridade = 0
for lista1 in l1:
taml1 = len(lista1)
totalElementos += taml1
setl1 = set(lista1)
maiorSemelhanca = 0
for lista2 in l2:
setl2 = set(lista2)
common = setl1.intersection(setl... | dudu-miranda/tp-redesComplexas | comparacaoComunidades.py | comparacaoComunidades.py | py | 1,014 | python | pt | code | 0 | github-code | 36 |
30000519084 |
#Function to calculate pairs
def returnPairs(mylist):
pairs=0
myset=set()
for i in range(0,len(mylist)):
occur=0
if mylist[i] in myset:
continue
for j in range(i+1,len(mylist)):
if mylist[i]==mylist[j]:
occur+=1
myset.add(mylist[i]... | shyamkrishnan1999/python-projects | mockvita2/digit_pairs.py | digit_pairs.py | py | 1,137 | python | en | code | 0 | github-code | 36 |
22825492843 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: gpu.py
# Author: jian<jian@mltalker.com>
from __future__ import unicode_literals
import os
import re
# from antgo.utils.utils import change_env
import subprocess
import time
import numpy as np
class GPU(object):
def __init__(self):
try:
content = subp... | jianzfb/subgradient | subgradient/core/gpu.py | gpu.py | py | 4,831 | python | en | code | 0 | github-code | 36 |
28969560543 | from django.contrib import admin
from ..models import Player
class PlayerAdmin(admin.ModelAdmin):
list_display = (
'name',
'lastname',
'birth_date',
'team',
'photo',
'position',
'player_number',
'is_first_team',
)
admin.site.register(Player, P... | dexer13/rebus-project | world_cup/admin/player_admin.py | player_admin.py | py | 332 | python | en | code | 0 | github-code | 36 |
14761513002 | def _mimport(name, level=1):
try:
return __import__(name, globals(), level=level)
except:
return __import__(name, globals())
import ctypes as _C
_ver=_mimport('version')
_exc=_mimport('mdsExceptions')
#### Load Shared Libraries Referenced #######
#
_MdsShr=_ver.load_library('MdsShr')
#
######... | bcao19/my-python-code | MDSplus/descriptor.py | descriptor.py | py | 8,565 | python | en | code | 0 | github-code | 36 |
30012376702 |
__author__ = 'rockie yang'
import os
from os import path, listdir
from hanzi2pinyin import hanzi2pinyin
def name_converter(old):
pinyin = hanzi2pinyin(old)
remove_unconverted_chars = pinyin.encode('ascii', 'ignore').decode('ascii')
return remove_unconverted_chars
def tranform(root_path, the_path):
... | rockie-yang/mp3 | mp3.py | mp3.py | py | 4,280 | python | en | code | 0 | github-code | 36 |
27502593085 | #!/usr/bin/env python
# coding: utf-8
# In[33]:
import pandas as pd
import streamlit as st
import requests
# In[34]:
username = 'ContainiumTE'
token = 'RRopW0EJvVEcfS5EGt1rxxswfGF5IfzU3Bh4VkPHS10'
github_session = requests.Session()
github_session.auth = (username,token)
# In[30]:
st.title("Discontinuity W... | ContainiumTE/discontinuity_refinement | Discontinuity_Selector.py | Discontinuity_Selector.py | py | 18,910 | python | en | code | 0 | github-code | 36 |
41566426879 | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_readonly(host):
f = '/mnt/ro/hello-ro'
with host.sudo('test'):
c = host.run('touch %s', f)
assert c.rc == 1
ass... | ome/ansible-role-nfs-mount | molecule/default/tests/test_default.py | test_default.py | py | 640 | python | en | code | 14 | github-code | 36 |
15857631571 | import shutil
import os
from os.path import exists
import glob
import random
x_path = '../images/'
y_path = './'
if not exists(y_path + 'train'):
os.mkdir(y_path + 'train')
if not exists(x_path + 'train'):
os.mkdir(x_path + 'train')
def duplicate_im_and_ann(y_fname, amount):
x = 0
while x < amount:... | fastai-trash-team/TACO-data-preprocessing | replicate.py | replicate.py | py | 4,744 | python | en | code | 0 | github-code | 36 |
71685398505 | __author__ = 'apple'
from turtle import *
from random import randint
K = 20
def reg(szer, n): # szerokość regału, liczba półek
start_position(szer, n)
regal(szer, n)
fd(K)
for _ in range(n):
polka(szer // K - 2)
up(7)
def polka(k):
rect(k * K, 6*K, "white")
pendown()
f... | chinski99/minilogia | 2015/etap 2/reg.py | reg.py | py | 1,142 | python | hu | code | 0 | github-code | 36 |
16528703119 | from scipy import signal
from pywebio.input import *
from pywebio.output import *
from pywebio import start_server
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import io
def fig2img(fig):
"""
Converts a Matplotlib figure to a PIL Image and return it
"""
buf = io.BytesIO()
... | tirthajyoti/PyWebIO | apps/bode.py | bode.py | py | 4,531 | python | en | code | 9 | github-code | 36 |
889427858 | from connection import create_connection
import numpy as np,numpy.random
from numpy.core.fromnumeric import size
import requests
from bson.objectid import ObjectId
from tag_classes import classifications
import random
def random_classification():
random_classifcations = {}
for tag in classifications.keys():
... | saarthakbabuta1/loan-agreement | classify.py | classify.py | py | 1,858 | python | en | code | 0 | github-code | 36 |
20031150368 | #encoding: utf-8
#description: 数字序号下的粗抽取
from __future__ import print_function
import os
import re
def produce_filename(targetdir):
targetnames = os.listdir(targetdir)
for name in targetnames:
if '.txt' == name[-4:]:
print("//"*20,name,"//"*20)
print(name,'OK')
attr_... | Wilson-ZHANG/AttributeExtraction | find_numNo.py | find_numNo.py | py | 3,557 | python | en | code | 2 | github-code | 36 |
27478835009 | # 1 задание
my_list = [1, 1.2, None, True, 'Text', ['list'], {'key_1':'Val_1'}]
for itam in my_list:
print(type(itam))
# 2 задание
my_list2 = input('Введите элементы списка через запятую: ')
my_list2 = my_list2.split(',')
print(my_list2)
my_list2_len = len(my_list2) if len(my_list2) % 2 ==0 else len... | Glen1679/GeekBrains | Homework2.py | Homework2.py | py | 4,241 | python | ru | code | 0 | github-code | 36 |
22846496457 | from DatabaseContextManager import DatabaseContextManager
def create_table_jobs():
query = """CREATE TABLE `jobs`(
`id` integer NOT NULL AUTO_INCREMENT,
`company_id` integer,
`category_id` integer,
`job_title` varchar(255),
`salary` DECIMAL(50, 2),
`description` varchar(255),
`location... | Zydrunas-Sir/RemoteJob | TasksInMySQL/Jobs.py | Jobs.py | py | 1,790 | python | en | code | 0 | github-code | 36 |
28984078467 | import sys
input = sys.stdin.readline
n = int(input())
m = list(map(int, input().split()))
answer = []
for i in range(n):
answer.insert(i-m[i], i+1)
print(*answer)
| youkyoungJung/solved_baekjoon | 백준/Bronze/2605. 줄 세우기/줄 세우기.py | 줄 세우기.py | py | 182 | python | en | code | 0 | github-code | 36 |
11532738343 | OpacInfo = provider(
doc = "opa cli toolchain",
fields = ["opa", "capabilities_json", "builtin_metadata_json", "opa_signer"],
)
def _opa_toolchain_impl(ctx):
toolchain_info = platform_common.ToolchainInfo(
opacinfo = OpacInfo(
opa = ctx.executable.opa,
capabilities_json = ct... | ticketmaster/rules_opa | opa/private/opa_toolchain.bzl | opa_toolchain.bzl | bzl | 1,292 | python | en | code | 4 | github-code | 36 |
20681014178 | __author__ = 'elmira'
import numpy as np
import itertools
from matplotlib import mlab
import re
with open('corpus1.txt', encoding='utf-8') as f:
news = f.read()
with open('corpus2.txt', encoding='utf-8') as f:
anna = f.read()
anna_sentences = re.split(r'(?:[.]\s*){3}|[.?!]', anna)
news_sentences = re.split(r... | elmiram/homework | seminar9/task1 (2 points)/genre-by-letters.py | genre-by-letters.py | py | 2,438 | python | en | code | 0 | github-code | 36 |
7183231615 | #!/usr/bin/env python3
"""Finds the optimal number of clusters"""
import numpy as np
kmeans = __import__('1-kmeans').kmeans
variance = __import__('2-variance').variance
def optimum_k(X, kmin=1, kmax=None, iterations=1000):
"""Provides info for optimal cluster number"""
if not isinstance(X, np.ndarray) or len(... | JohnCook17/holbertonschool-machine_learning | unsupervised_learning/0x01-clustering/3-optimum.py | 3-optimum.py | py | 1,126 | python | en | code | 3 | github-code | 36 |
20580965010 | from django import forms
from .models import Recipe
from channel.models import Channel
class RecipeForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(RecipeForm, self).__init__(*args, **kwargs)
if self.instance.id:
self.fields['trigger_channel'].initial = self.instance.t... | theju/dtwt | recipe/forms.py | forms.py | py | 650 | python | en | code | 9 | github-code | 36 |
39398980966 | # Python Project B
# Multinomial Naive Bayes
# By
# Valdar Rudman
# R00081134
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import matplotlib.pyplot as plt
import numpy as np
# Read a file in and split on the white space
def readFile(source):
return open(source).read... | ValdarRudman/Multinomial-Naive-Bayes | Multinomial Naive Bayes.py | Multinomial Naive Bayes.py | py | 5,233 | python | en | code | 0 | github-code | 36 |
29207899758 | # Definition for a QuadTree node.
class Node:
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
... | sakshi5250/6Companies30Days | INTUIT/Question11.py | Question11.py | py | 1,293 | python | en | code | 0 | github-code | 36 |
41763630844 | import random
from terminaltables import AsciiTable
import curses
GAME_TITLE = "`•.,¸¸ [ JEU DU TAQUIN ] ¸¸,.•´"
# Nombre de cases par côté
TAQUIN_SIZE = 4
# Valeur de la case vide
EMPTY_CASE_VALUE = ""
# Taquin correct, dans l'ordre
CORRECT_SOLUTION = [list(a) for a in zip(*[iter(list(range(1, TAQUIN_SIZE ** 2)) ... | martync/taquin-py | taquin.py | taquin.py | py | 3,373 | python | en | code | 0 | github-code | 36 |
4801788061 | from django.contrib.auth import get_user_model
from django.test import TestCase, Client
from django.urls import reverse
from django.utils import timezone
from manager.models import Task, TaskType
class TaskPublicTest(TestCase):
def test_task_list_public(self):
res = self.client.get(reverse("manager:task-... | kovaliskoveronika/task_manager | manager/tests/test_views_task.py | test_views_task.py | py | 3,088 | python | en | code | 0 | github-code | 36 |
7979146061 | # -*- coding: utf-8 -*-
"""
Fenêtre de gestion des notes
Par Geoffrey VENANT et Antoine CASTEL
En classe 2PD2
"""
import tkinter as tk
import definition as df
import Tkinter_GN_ajt as tkgnajt
def open_gn (fenetre_parent):
#Initialisation des paramètres de la fenêtre
fenetre_GN =... | antoinecstl/Grand-Projet-2021-2022 | grand_projet/Tkinter_GN.py | Tkinter_GN.py | py | 2,693 | python | en | code | 0 | github-code | 36 |
4392041881 | import json
import base64
import pymongo
import time
from json.encoder import JSONEncoder
from azure.storage.queue import (
QueueClient,
BinaryBase64EncodePolicy,
BinaryBase64DecodePolicy
)
azure_storage_account = None
mongo_connect = None
queue = "test"
queue = "general-image-2-crawl"
cookies ... | harveyaot/AlphaTaiBai | scripts/send_imageurl2crawl.py | send_imageurl2crawl.py | py | 2,867 | python | en | code | 24 | github-code | 36 |
6123605649 | import pandas as pd
import time
import numpy as np
from AI.models import NLPModel
# Architecture of the Muser Data Builder
class MuserDataBuilder:
# The constructor instantiates all the variables that would be used throughout the class
def __init__(self, sp, conn):
self.sp = sp
self.conn = co... | CUTR-at-USF/muser-data-analysis | AI/muserdatabuilder.py | muserdatabuilder.py | py | 2,889 | python | en | code | 0 | github-code | 36 |
41852000033 | from flask import send_file, Flask, redirect, render_template, url_for
# from crypt import methods
import logging
from nltk.stem import WordNetLemmatizer
from fuzzywuzzy import fuzz
from nltk.corpus import wordnet
import nltk
from flask import send_from_directory, Flask, request, render_template, url_for, redirect, j... | Rohit-S-Singh/Research-Project | app.py | app.py | py | 9,288 | python | en | code | 0 | github-code | 36 |
15062131417 | import requests
import pandas
import datetime_translator
brandIds = { 202, 88, 31, 123, 101, 122, 36, 48, 135 }
data = {}
for brandId in brandIds:
headers = { 'User-Agent': '', 'content-type': 'application/json' }
jsonData = '{"variables":{"area":"salt-lake","brandId":%d,"countryCode":"US","criteria":{"locat... | ryanbarlow1/cheapest_gas_prices | get_gas_prices.py | get_gas_prices.py | py | 2,836 | python | en | code | 0 | github-code | 36 |
41214332774 | """ In this script I load both the original openML and the abello ones. Then I print the elements of abello which are not
in the original openML. This is because in the original openML table there are only the active ones. """
import pandas as pd
# It checks if lst1 is contained in lst2
def sublist(lst1, lst2):
... | josephgiovanelli/openML-datasets-profiling | tests/check_abello_active.py | check_abello_active.py | py | 1,048 | python | en | code | 0 | github-code | 36 |
16505504555 | from nltk.tag.hmm import *
import codecs
import statistics
import numpy as np
from sklearn.metrics import confusion_matrix
import metrics
from metrics import EditDistance
from hmm import HMM
from memm import MEMM
from crf_word import CRF as CRF_WORD
from crf_sentence import CRF as CRF_SENT
from rnn import Encoder as RN... | albert-shalumov/nlp_proj | test.py | test.py | py | 4,674 | python | en | code | 1 | github-code | 36 |
30453697938 | import struct
import random
def get_checksum(msg: bytes) -> int:
checksum = 0
for i in range(0, len(msg), 2):
part = (msg[i] << 8) + (msg[i + 1])
checksum += part
checksum = (checksum >> 16) + (checksum & 0xffff)
return checksum ^ 0xffff
class IcmpPack:
def __init__(self, icmp_t... | OxyEho/icmp-traceroute | icmp.py | icmp.py | py | 881 | python | en | code | 0 | github-code | 36 |
71877366824 | #!/usr/bin/env python
# coding: utf-8
import sys
import io
import json
import numpy as np
from matplotlib import pyplot as plt
from tensorflow import keras
import tensorflow as tf
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
from pathlib import Path
import cv2
import... | DanilKonon/Seismic_Data_Inpainting | unet_autoencoder.py | unet_autoencoder.py | py | 22,825 | python | en | code | 0 | github-code | 36 |
6347790339 | def readPropertiesFile():
configDict = dict(line.strip().split('=') for line in open('config.properties'))
# print(H["application.name"])
for key in configDict:
print(key + "<---------->" + configDict[key])
print("Operating System Name : ", configDict["os.name"])
if __name__ == "__main... | debjava/py-read-properties-file | main.py | main.py | py | 352 | python | en | code | 0 | github-code | 36 |
74974903784 | """empty message
Revision ID: 3c8f0856b635
Revises: a7b5e34eac58
Create Date: 2018-02-24 13:05:25.721719
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '3c8f0856b635'
down_revision = 'a7b5e34eac58'
branch_labels = None
depends_on = None
def upgrade():
# ... | LDouble/cernet_ipv6_server | migrations/versions/3c8f0856b635_.py | 3c8f0856b635_.py | py | 911 | python | en | code | 0 | github-code | 36 |
35020634837 | # Jordan Callero
# Project Euler
# May 4, 2016
# This function will sum all of the positive integers which
# can not be written as the sum of two abudant numbers.
# Note: An abundant number is a number where the factors added
# together is larger than the number itself.
def nonAbuSum():
abudantList... | jgcallero/projectEuler | Problem_023/Non-abundant Sums.py | Non-abundant Sums.py | py | 1,220 | python | en | code | 0 | github-code | 36 |
22502437388 | # -*- coding: utf-8 -*-
__docformat__ = "restructuredtext en"
"""
list actions
File: obj_list_act.py
Copyright: Blink AG
Author: Steffen Kube <steffen@blink-dx.com>
"""
import os
from blinkapp.code.lib.main_imports import *
from blinkapp.code.lib.app_plugin import gPlugin
from blinkapp.code.... | qbicode/blinkdms | blinkdms/ADM/plugin/obj_list_act.py | obj_list_act.py | py | 8,003 | python | en | code | 0 | github-code | 36 |
18446560206 | # -*- coding: utf-8 -*-
"""
@author: DongXiaoning
"""
import numpy as np
import operator
import collections
import sklearn.datasets
# compute gini index
def compute_gini(group):
m,n = group.shape
data = group[:,:-1]
label = group[:,-1]
dict_label = collections.Counter(label)
group_... | xndong/ML-foundation-and-techniques | Decision stump/decision_stump.py | decision_stump.py | py | 3,428 | python | en | code | 0 | github-code | 36 |
40588074038 | import cadquery as cq
from math import sin, pi
import numpy as np
plateRadius = 15
plateCenterHole = 4
pinRadius = 3.5/2
pinInter = 18
SCALE= 100 # scale profile dimentions
# input data from csv file of wing profile
data = np.genfromtxt('data/s7075-il.csv',delimiter=',')
pts = data[9:89]
# if we can normalize vectors... | Opezdol/pohhmann | src/cooling/carlson.py | carlson.py | py | 2,475 | python | en | code | 0 | github-code | 36 |
74197853543 | from collections.abc import Iterable
from circkit import Circuit, Operation, Node
import logging
log = logging.getLogger("Transformer")
class Transformer:
"""Base transformer class."""
START_FROM_VARS = False
source_circuit: Circuit = None
current_node: Node = None
current_operation: Operation... | hellman/ches2022wbc | circkit/transformers/core.py | core.py | py | 5,704 | python | en | code | 18 | github-code | 36 |
72788289704 | import subprocess
import re
import os.path
import sheetFeeder as gs
def main():
saxon_path = 'saxon-9.8.0.12-he.jar'
xslt1_path = 'ead_merge.xsl'
xslt2_path = 'ead_cleanup_1.xsl'
xslt3_path = 'ead_cleanup_2.xsl'
data_folder1 = '/path/to/exported/legacy/ead/files'
data_folder2 = '/path/to/as... | cul/rbml-archivesspace | ead_merge/ead_merge.py | ead_merge.py | py | 3,727 | python | en | code | 6 | github-code | 36 |
8828088539 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import cv2
import math
import numpy as np
class trackerPoint(object):
def __init__(self, x, y, size, frame):
# KCF tracker init
self.tracker = cv2.TrackerKCF_create()
self.bbox = (x-size/2, y-size/2, size,size)
self.tracker.init(frame, self.bbo... | ThibaudMZN/GeneralWork | ArmAngleCalculation/ArmAngle.py | ArmAngle.py | py | 3,041 | python | en | code | 0 | github-code | 36 |
5255273641 | import os
from re import I
import sys
from openpyxl import Workbook
from openpyxl.styles import Border, Side, PatternFill, Font, Alignment
from datetime import datetime
sys.path.insert(0, os.path.abspath('..\\pycatia'))
from pycatia import catia
from pycatia.enumeration.enumeration_types import cat_work_mode_type
ca... | kang851216/CATIA_macro | manufacturing and process list_adding drawing list_test.py | manufacturing and process list_adding drawing list_test.py | py | 24,204 | python | en | code | 0 | github-code | 36 |
1528415930 |
import cv2
import tensorflow as tf
import numpy as np
import glob
import os
import time
import argparse
import configparser
from auto_pose.ae import factory, utils
parser = argparse.ArgumentParser()
parser.add_argument("experiment_name")
parser.add_argument("-f", "--file_str", required=True, help='folder or filena... | logivations/AugmentedAutoencoder | auto_pose/test/encoder_inference.py | encoder_inference.py | py | 2,190 | python | en | code | 1 | github-code | 36 |
35387136484 | #!/usr/bin/env python3
from sys import stderr
from multilanguage import Env, Lang, TALcolors
from TALinputs import TALinput
from TALfiles import TALfilesHelper
import os
import random
import networkx as nx
import vertex_cover_lib as vcl
import matplotlib
import multiprocessing
# METADATA OF THIS TAL_SERVICE:
args_li... | romeorizzi/TALight | example_problems/tutorial/vertex_cover/services/check_approx_vc_driver.py | check_approx_vc_driver.py | py | 10,368 | python | en | code | 11 | github-code | 36 |
21121065737 | """File system hook for the S3 file system."""
from builtins import super
import posixpath
try:
import s3fs
except ImportError:
s3fs = None
from . import FsHook
class S3Hook(FsHook):
"""Hook for interacting with files in S3."""
def __init__(self, conn_id=None):
super().__init__()
s... | jrderuiter/airflow-fs | src/airflow_fs/hooks/s3_hook.py | s3_hook.py | py | 2,720 | python | en | code | 16 | github-code | 36 |
4855310925 | #!/usr/bin/python
# -*- coding: utf-8 -*
from fabric.api import *
from fabric.context_managers import *
from fabric.contrib.console import confirm
from fabric.contrib.files import *
from fabric.contrib.project import rsync_project
import fabric.operations
import time,os
import logging
import base64
from getpass import ... | zzlyzq/speeding | funcs/rabbitmq.py | rabbitmq.py | py | 5,005 | python | en | code | 1 | github-code | 36 |
26299614326 |
### ===== Load libraries =====
from langchain.document_loaders.csv_loader import CSVLoader
from langchain.embeddings import CacheBackedEmbeddings, HuggingFaceEmbeddings
from langchain.vectorstores import FAISS
from langchain.storage import LocalFileStore
from langchain.text_splitter import TokenTextSplitter
from lang... | Valkea/Omdena_Falcon | deployment02/backend/llm_setup.py | llm_setup.py | py | 5,289 | python | en | code | 1 | github-code | 36 |
770438494 | #Import libraries
import scipy.io as spio
from scipy import fftpack
import matplotlib.pyplot as plt
import numpy as np
#Process the dataset into samples
def process_positions(dataset, positions):
output_range = 10
classification_input = []
for position in positions:
lower = position - ... | khb00/peak_classifier_and_detector | TimeFreq.py | TimeFreq.py | py | 1,337 | python | en | code | 0 | github-code | 36 |
69889167786 | import torch
import torch.nn as nn
from attention import MultiheadedAttention
from feed_forward import PositionWiseDenseNetwork, LayerNorm
class DecoderBlock(nn.Module):
def __init__(self,
key_dim: int = 64,
embedding_dim: int = 512,
heads_number: int = 8,
... | KolodziejczykWaldemar/Transformers | decoder.py | decoder.py | py | 4,651 | python | en | code | 0 | github-code | 36 |
22625649989 | import pygame
import random
import time
#飞机大战
#手机上单手操作游戏
#屏幕长方形
# **************************我方飞机
class Hero(object):
def __init__(self, _screen, _x, _y):
self.image = pygame.image.load("images\hero.gif")
self.rect = self.image.get_rect()
self.width = self.rect.width
self.height = se... | gaicigame99/GuangdongUniversityofFinance-Economics | airplaneWar/黄海辉/飞机大战.py | 飞机大战.py | py | 7,173 | python | en | code | 3 | github-code | 36 |
3825597824 | """A setuptools based setup module.
See:
https://packaging.python.org/guides/distributing-packages-using-setuptools/
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
# Arguments marked as "Required" below must be... | kneczaj/android-emulator-docker | setup.py | setup.py | py | 1,553 | python | en | code | 0 | github-code | 36 |
21054969908 | import numpy as np
from scipy.special import logsumexp, gammaln
from astropy import constants, units as au
from astropy.units import Quantity
Gauss = 1e-4 * au.T
au.set_enabled_equivalencies(au.dimensionless_angles())
def pad_with_absorbing_boundary_conditions(k2, k02, N, *coords, dn_max=0.05):
if dn_max is None... | Joshuaalbert/born_rime | born_rime/potentials.py | potentials.py | py | 7,396 | python | en | code | 1 | github-code | 36 |
7060266333 | # Hen1 Problem
# Student B
HENS = 4
DAYS = 7
grand_sum = 0
for i in range(DAYS):
day_sum = sum(int(s) for s in input('Enter eggs laid by each hen for day {}: '.format(i + 1)).split(','))
print('Day {} {} egg(s)'.format(i + 1, day_sum))
grand_sum += day_sum
print()
print('Average number of eggs ... | ceucomputing/automarker | test2/student_B/HEN1_B.py | HEN1_B.py | py | 421 | python | en | code | 1 | github-code | 36 |
40027862614 | # Created on 12/5/15
if __name__ == '__main__':
f_input = []
with open("input.txt") as f:
f_input = f.readlines()
total = 0
for line in f_input:
check1 = False
check2 = False
for i in range(len(line) - 2):
if line[i] == line[i + 2]:
check1 =... | liamrahav/adventofcode-2015 | day5/day5_part2.py | day5_part2.py | py | 740 | python | en | code | 0 | github-code | 36 |
72394020264 | # 1 Вычислить числить число c заданной точностью d
# Пример:
# - при d = 0.001, π = 3.141
# Ввод: 0.01
# Вывод: 3.14
# Ввод: 0.001
# Вывод: 3.141
import math
print(math.pi)
num = float(input("Введите число: "))
def schet_znakov(number_to_count):
count = 0
while number_to_count % 1 != 0:
... | ArtemTomilov13/python | python/seminar4/1.py | 1.py | py | 521 | python | ru | code | 0 | github-code | 36 |
27541539070 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Travis Anderson"
"""
This is for contacting twitter, and watching a specific user or word
"""
import logging
import tweepy
import time
import os
import datetime
from threading import Thread
import threading
logger = logging.getLogger(__name__)
exit_flag =... | tander29/backend-slackbot | twitbot.py | twitbot.py | py | 4,752 | python | en | code | 0 | github-code | 36 |
4887469879 |
instructions = []
with open("input.txt", "r") as f:
instructions = [[op, int(arg)] for op,arg in (line.split(" ") for line in f)]
# Returns a (bool, int) tuple, the first bool indicating whether or not the
# program halted normally, the second int being the accumulator.
#
# Fun fact: this function is impossi... | OskarSigvardsson/adventofcode2020 | day8/day8.py | day8.py | py | 1,862 | python | en | code | 0 | github-code | 36 |
3521482660 | import pytest
import yaml
from meltano.core.behavior.canonical import Canonical
definition = {
# a, b, …, z
chr(ord("a") + i): i if i % 2 else None
for i in range(10)
}
class TestCanonical:
@pytest.fixture
def subject(self):
return Canonical(**definition)
def test_canonical(self, sub... | learningequality/meltano | tests/meltano/core/behavior/test_canonical.py | test_canonical.py | py | 3,836 | python | en | code | 1 | github-code | 36 |
37591561830 | #!/usr/bin/env python
'''
Rutgers Data Science Homework Week 3, Assignment #1
To run this script:
pybank.py [--summary_file=SUMMARY_FILE] input_file_1 input_file_2 ...
<Chan Feng> 2018-02
'''
import os
import csv
from argparse import ArgumentParser
_SUMMARY_FILE = 'pybank_summary.txt'
_SUMMARY_... | feng443/RUDSWeek3 | PyBank/pybank.py | pybank.py | py | 3,904 | python | en | code | 0 | github-code | 36 |
21871433231 | import jieba,re
#去除标点
def get_text(file_name):
with open(file_name, 'r', encoding='utf-8') as fr:
text = fr.read()
#删除的标点
del_ch = ['《',',','》','\n','。','、',';','"',\
':',',','!','?',' ']
for ch in del_ch:
text = text.replace(ch,'')
return text
file_name = 'comment.txt'
... | 2412322029/bilibili-spyder | 词频.py | 词频.py | py | 1,370 | python | en | code | 0 | github-code | 36 |
32886590499 | import discord
from discord.ext import commands
from discord.ui import Select, View
from discord.ext.commands import bot
from discord import app_commands
class Select(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="НАВИГАЦИЯ: команды до игры", value="1", emoji="📜", description="Ком... | FoxSweets/PhasmoBot | cogs/help.py | help.py | py | 3,732 | python | ru | code | 0 | github-code | 36 |
37502296937 | # https://school.programmers.co.kr/learn/courses/19344/lessons/242261
from collections import deque
dire = [[-1, 0], [1, 0], [0, -1], [0, 1]]
def CHECK(a, b, g):
return not (0 <= a < len(g) and 0 <= b < len(g[0]))
def BFS(graph, visit, RB):
global answer
que = deque()
RB.extend([0, False, False])
... | junsgi/Algorithm | BFS_DFS/기출문제 4번_BFS.py | 기출문제 4번_BFS.py | py | 2,756 | python | en | code | 0 | github-code | 36 |
72838543143 |
exec(open("init_notebook.py").read())
from helper import *
import time
client = connectToClient()
world = client.get_world()
spectator = set_camera_over_intersection(world)
extent = carla.Vector3D(x=100, y=100)
location = carla.Location(x=80, y=-133, z=0)
bounding_box = carla.BoundingBox(location, extent)
rotation =... | jawadefaj/SIP-CARLA | CARLA/PythonAPI/tutorial/position_camera.py | position_camera.py | py | 585 | python | en | code | 0 | github-code | 36 |
71648501864 |
from PIL import Image, ImageDraw
import random as rd
import imageio
def create_simple_tile(size: int, bg_color:str, fg_color: str) -> Image:
tile_img = Image.new("RGB", (size, size))
tile_img_draw = ImageDraw.Draw(tile_img)
tile_img_draw.rectangle([(0, 0), (size, size)], fill = bg_color)
tile_img_draw... | antigones/py-truchet | truchet.py | truchet.py | py | 1,782 | python | en | code | 0 | github-code | 36 |
10495520006 | from django.test import TestCase
from djlotrek.templatetags.djlotrek_filters import (
key,
is_in,
is_not_in,
get_class,
get_sorted,
media_url,
regex_match,
)
class TemplateFiltersTestCase(TestCase):
def test_key(self):
"""
templatefilter key is use for get value from d... | lotrekagency/djlotrek | tests/test_templatefilters.py | test_templatefilters.py | py | 2,463 | python | en | code | 7 | github-code | 36 |
74229865385 | import configparser
from pathlib import Path
from flask import Flask
from flask_restful import Resource, Api
import sqlite3
from todo import DB_WRITE_ERROR, SUCCESS
DEFAULT_DB_FILE_PATH = Path.cwd().joinpath(
"." + Path.cwd().stem + "_todo.db"
)
def get_database_path(config_file: Path) -> Path:
"""Return th... | CR-Lough/todo_app | core/src/todo/database.py | database.py | py | 1,220 | python | en | code | 0 | github-code | 36 |
21200837689 | # coding: utf-8
import websocket
from threading import Thread
import time
from secrets import token_hex
from hashlib import sha256
import hmac
import json
class RealtimeAPIWebsocket:
def __init__(self, logger, parameters, public_handler, private_handler):
self.logger = logger
self._parameters = pa... | PP-lib/BFS | BFS-X/libs/realtimeapi.py | realtimeapi.py | py | 5,448 | python | en | code | 2 | github-code | 36 |
27031060369 | import subprocess
import sys
import json
from workflow import Workflow3
log = None
GITHUB_SLUG = 'tilmanginzel/alfred-bluetooth-workflow'
def _read_devices():
proc = subprocess.Popen(['./blueutil', '--paired', '--format=JSON'], stdout=subprocess.PIPE)
devices_raw = json.loads(proc.stdout.read())
blueto... | tilmanginzel/alfred-bluetooth-workflow | alfred_bluetooth_workflow.py | alfred_bluetooth_workflow.py | py | 1,825 | python | en | code | 188 | github-code | 36 |
19665159792 | from flask import Flask, render_template
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required, current_user, AnonymousUser, roles_required
from flask.ext.security.utils import *
from flask.ext.security.confirmable import *
fro... | rparikh42790/roverpass1 | kickstart.py | kickstart.py | py | 2,047 | python | en | code | 0 | github-code | 36 |
32138192143 | import discord
from discord.ext import commands
import response
import re
import logging
from get_token import get_token
imageKWS = ['img','imgs','image','images','pic','pics','pictures','picture']
class botName(commands.Bot):
intents = discord.Intents.default()
def __init__(self):
super().__init__(command_... | benwen2511/chatGBT-discord-bot | main.py | main.py | py | 2,311 | python | en | code | 7 | github-code | 36 |
17567102459 | # URI Problem Link: https://www.urionlinejudge.com.br/judge/en/problems/view/1011
# Programmed by Marufur Rahman.
radius = int(input())
pi = 3.14159
volume = float(4.0 * pi * (radius* radius * radius) / 3)
print("VOLUME = %0.3f" %volume) | MarufurRahman/URI-Beginner-Solution | Solutions/URI-1011.py | URI-1011.py | py | 241 | python | en | code | 1 | github-code | 36 |
2251885893 | import math
import numpy as np
import pygame as pg
def box_l2_loss(obj1, obj2):
r1 = np.array([obj1.rect.x, obj1.rect.y, obj1.rect.width, obj1.rect.height])
r2 = np.array([obj2.rect.x, obj2.rect.y, obj2.rect.width, obj2.rect.height])
return np.linalg.norm(r1 - r2)
def move_from_vector(vector):
angle, speed ... | thbeucher/Games | life_games/utils.py | utils.py | py | 1,395 | python | en | code | 0 | github-code | 36 |
26510682653 | #!/usr/bin/python3
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This pro... | patins1/raas4emf | build/mac/blender/blender.app/Contents/MacOS/2.64/scripts/modules/bl_i18n_utils/clean_po.py | clean_po.py | py | 3,338 | python | en | code | 1 | github-code | 36 |
27980759583 | """
Simulated Annealing Class
"""
import pickle
import random
import math
import numpy as np
import sklearn
import pandas as pd
import configparser
import random
from pathlib import Path
import joblib
from Utils.attack_utils import get_constrains
from Models.scikitlearn_wrapper import SklearnClassifier
from Utils.da... | adiashk/search_AI_project | Simulated_Annealing.py | Simulated_Annealing.py | py | 17,737 | python | en | code | 0 | github-code | 36 |
7504092122 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import WebDriverException
import time
from django.test import LiveServerTestCase
MAX_WAIT = 10
class NewVisitorTest(LiveServerTestCase):
'''New visitor test'... | ollko/tdd_book | functional_tests/tests.py | tests.py | py | 2,043 | python | en | code | 0 | github-code | 36 |
933471323 | import abc
from neutron import quota
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import resource_helper
from neutron.common import exceptions as qexception
from neutron.plugins.common import constants
UOS_SERVICE_PROVIDER = 'uos:service_provider'
UOS_NAME = 'u... | CingHu/neutron-ustack | neutron/extensions/uosfloatingipset.py | uosfloatingipset.py | py | 6,685 | python | en | code | 0 | github-code | 36 |
21546274042 | #!/Users/shounak/anaconda3/bin/python3
#This program plots histograms to depict genome-wide methylation patterns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import argparse
import matplotlib
import matplotlib.axes
matplotlib.rcParams['font.family']="monospace"
matplotlib.rcParams['font.monosp... | lanl/DNA_methylation_analysis | Genome_meth_ratio_distribution histograms.py | Genome_meth_ratio_distribution histograms.py | py | 2,883 | python | en | code | 0 | github-code | 36 |
5091344976 | import numpy as np
import time
from ezGraph import *
from jStats import *
# Finite Difference Model
#on and off flow
#PARAMETERS
dt = 1
nsteps = 100
r = 2.25 # radius (cm)
Qin = 30 # Volume inflow rate (dV/dt) : (cubic cm/s)
h = 0 #intial height (cm)
k = 0.15 #outflow rate constant
# EXPERIMENTAL DATA
y_modeled ... | joydunne/waterTube | ezGraph/step-wiseInflow.py | step-wiseInflow.py | py | 1,092 | python | en | code | 0 | github-code | 36 |
71578894183 | #!/usr/bin/env python
from __future__ import print_function
import vtk
def main():
# Create a square in the x-y plane.
points = vtk.vtkPoints()
points.InsertNextPoint(0.0, 0.0, 0.0)
points.InsertNextPoint(1.0, 0.0, 0.0)
points.InsertNextPoint(1.0, 1.0, 0.0)
points.InsertNextPoint(0.0, 1.0, 0.0... | lorensen/VTKExamples | src/Python/GeometricObjects/PolygonIntersection.py | PolygonIntersection.py | py | 1,059 | python | en | code | 319 | github-code | 36 |
18764507379 | """
Given a list of UQ course codes, crawl the UQ course website and scrape
information pertaining to said course.
"""
import sys
import requests
from bs4 import BeautifulSoup
# Headers for making web requests look like a real user (or they may be
# rejected by the UQ website)
headers = requests.utils.default_headers... | tompoek/uq-course-prereqs-viz | data-crawler/crawl.py | crawl.py | py | 1,826 | python | en | code | 0 | github-code | 36 |
29226135271 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from pymongo import MongoClient
import numpy as np
from tqdm import tqdm
def insertInfo(df):
client = MongoClient('mongodb://localhost:27017/')
infodb = client.Infodb
userInfo = infodb.userInfo
for index, instance in tqdm(df.iterrows(), total=df.sha... | inhye6-6/project_face_authentication | connect_db.py | connect_db.py | py | 1,131 | python | en | code | 0 | github-code | 36 |
39253734345 | from functools import reduce
from collections import Counter
import math
import operator
import numpy as np
class SpamHamClassifier(object):
def __init__(self, training_data, vocabulary_size,
compute_mutual_information, lambda_constant=0):
self._num_training_data = len(training_data)
... | jvmsangkal/spam-filter-py | spamfilter/classifier.py | classifier.py | py | 6,440 | python | en | code | 1 | github-code | 36 |
32766043528 | #!/urs/bin/python
#-*- coding:utf8 -*-
from bs4 import BeautifulSoup as bs
import urllib
import re
import json
import os
def get_musicid(url):
#url='http://music.baidu.com/top/dayhot'
html = urllib.urlopen(url).read()
soup = bs(html,'lxml',from_encoding='utf8')
urls = soup.findAll('a',href=re.compile(r'/so... | carloszo/Carlos_python | Crawler/BaiduMusicCrawler.py | BaiduMusicCrawler.py | py | 1,916 | python | en | code | 0 | github-code | 36 |
1593336231 | # program1
a = ['banana', 'apple', 'microsoft']
for i in range(len(a)):
for j in range(i + 1):
print(a[i])
# progam 2
'''
a = range(1, 100)
total = 0
for b in a:
if b % 3 == 0 or b % 5 == 0:
print (b)
total += b
print total
'''
# program 4
'''
total = 0
for i in range(1, 100):
... | Parth-Ps/python | for_loop.py | for_loop.py | py | 914 | python | en | code | 0 | github-code | 36 |
1846312 | def read_graph(vertex_number, edge_number):
graph = [[float('+inf')] * vertex_number for i in range(vertex_number)]
for i in range(edge_number):
v1, v2, w = map(int, input().split())
graph[v1][v2] = w
if i < vertex_number:
graph[i][i] = 0
return graph
def floy... | andrewsonin/4sem_fin_test | _16_floyd_warshall.py | _16_floyd_warshall.py | py | 707 | python | en | code | 0 | github-code | 36 |
40978312177 | # pylint: disable=E0401,E0611
import os
import json
script_dir = os.path.dirname(__file__)
from helpers.DataService import DataService
from models.InputData import InputData
from models.OutputData import OutputData
from models.DataResult import DataResult
from models.Encoder import Encoder
from models.Decoder import ... | AtLeastITry/seq2seq-keras-chatBot | train.py | train.py | py | 2,470 | python | en | code | 2 | github-code | 36 |
42886474434 | import logging
from json import JSONDecodeError
from typing import Dict, Any
import requests
from .exceptions import TrefleException
from .models import Result
class RestAdapter:
def __init__(self, token: str,
logger: logging.Logger = None):
"""
Constructor for RestAdapter
... | Overlrd/trefle | src/trefleapi/rest_adapter.py | rest_adapter.py | py | 2,929 | python | en | code | 1 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.