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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
29779893290 | """
Take input N orders and output a sorted list of customers along with their orders.
Each order is a string containing "Customer - Pizza Name - Quantity" in the given format.
"""
def make_orders(ord_count, orders):
for i_ord in range(1, ord_count + 1):
order = input(f'{i_ord}-ый заказ: ').split()
... | AfoninSV/python_scripts | pizza_orders.py | pizza_orders.py | py | 1,002 | python | en | code | 0 | github-code | 36 |
12365029657 | import pandas as pd
import numpy as np
import pylab
from PIL import Image
from PIL import ImageOps
from conv_net.dataset import BaseDataset
from os import listdir
from os.path import isfile, join
class Dataset(BaseDataset):
def read_validation_set(self):
return self._read_image_set("validation_set_resize",... | gozmo/diabetes | read_files.py | read_files.py | py | 2,480 | python | en | code | 0 | github-code | 36 |
72152970345 | import os, glob, math
import numpy as np
import tensorflow as tf
from PIL import Image
from myutils_tf import bwutils
def save_4ch_to_3ch(path_pixel_shift):
print(path_pixel_shift)
files = glob.glob(os.path.join(path_pixel_shift, '*.npy'))
# print(files)
for idx, file in enumerate(files):
if... | samsungexpert/snu | myinference_srgb2raw_tf.py | myinference_srgb2raw_tf.py | py | 4,612 | python | en | code | 1 | github-code | 36 |
20510618819 | # Author: Vlad Niculae <vlad@vene.ro>
# License: GNU LGPL v3
import numpy as np
from numpy.testing import assert_array_equal
from ad3 import factor_graph as fg
def test_sequence_dense():
n_states = 3
transition = np.eye(n_states).ravel()
graph = fg.PFactorGraph()
vars_expected = [0, 1, None, None,... | andre-martins/AD3 | python/ad3/tests/test_sequence.py | test_sequence.py | py | 929 | python | en | code | 68 | github-code | 36 |
75104144745 | from math import factorial
def count_differences(adapters):
one_count, three_count = 0, 0
current_rating = 0
adapters.sort()
for x in set(adapters):
if x - current_rating == 1:
one_count += 1
elif x - current_rating == 3:
three_count += 1
current_rating ... | itsmeichigo/Playgrounds | AdventOfCode2020/Day10/day10.py | day10.py | py | 1,320 | python | en | code | 0 | github-code | 36 |
4705074588 | import functools
import pandas as pd
import numpy as np
import periodictable as pt
from pathlib import Path
from tinydb import TinyDB, Query
from .transform import formula_to_elemental
from ..util.meta import pyrolite_datafolder
from ..util.database import _list_tindyb_unique_values
import logging
logging.getLogger(__... | skerryvore/pyrolite | pyrolite/mineral/mindb.py | mindb.py | py | 4,362 | python | en | code | null | github-code | 36 |
26716825256 | """
Support for random optimizers, including the random-greedy path.
"""
import functools
import heapq
import math
import numbers
import time
from collections import deque
from random import choices as random_choices
from random import seed as random_seed
from typing import Any, Dict, Generator, Iterable, List, Option... | dgasmith/opt_einsum | opt_einsum/path_random.py | path_random.py | py | 14,478 | python | en | code | 764 | github-code | 36 |
74876486825 | t=int(input())
while(t):
t-=1
a=str(input())
n=len(a)
a=list(a)
if(n%2==1):
a1=a[0:n//2]
a2=a[n//2+1:n]
#print(a1,a2)
else:
a1=a[0:n//2]
a2=a[n//2:n]
#print(a1,a2)
a1.sort()
a2.sort()
if(a1==a2):
print("YES")
else:
p... | anirudhkannanvp/CODECHEF | Practice/LAPIN.py | LAPIN.py | py | 331 | python | en | code | 0 | github-code | 36 |
2796043458 | import argparse
import os
from glob import glob
import json
import jellyfish
from text_extraction import Rectangle, AUTHOR_LABEL, DESCRIPTION_LABEL
import re
import pandas as pd
from tqdm import tqdm
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input-folder", required=True, help="Folder with the json file")... | paulguhennec/Cini-Project | Process-Images/ocr_evaluation.py | ocr_evaluation.py | py | 4,367 | python | en | code | null | github-code | 36 |
21333145497 | '''
Copyright 2022 Airbus SAS
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 writing, sof... | os-climate/witness-core | climateeconomics/sos_wrapping/sos_wrapping_witness/invest_discipline.py | invest_discipline.py | py | 6,662 | python | en | code | 7 | github-code | 36 |
74601336743 | import mysql.connector
from enc_dec import *
# MySQL 연결 설정
config = {
}
def upsert_db(file_id, share_doc_url):
# MySQL 연결
conn = mysql.connector.connect(**config)
cursor = conn.cursor()
# 조회할 데이터
file_id_to_search = file_id # 조회할 파일 ID에 맞게 수정
# 데이터 조회 쿼리
select_query =... | HanJaeWon621/docToPdf | db_insert.py | db_insert.py | py | 3,527 | python | ko | code | 0 | github-code | 36 |
24643182429 | import pyautogui
import time
# Locating the game window
pyautogui.alert('Put the mouse pointer over the top left corner of the game then press "Enter"')
TOP_LEFT = pyautogui.position()
pyautogui.alert('Put the mouse pointer over the bottom right corner of the game then press "Enter"')
BOT_RIGHT = pyautogui.position... | Furrane/voxelbot | main.py | main.py | py | 2,768 | python | en | code | 0 | github-code | 36 |
74059611623 | from configs import ssd300 as cfg
import torch
import torchvision.transforms as transforms
def base_transform(size):
transform = transforms.Compose([
transforms.Resize(size),
transforms.ToTensor()
])
return transform
class BaseTransform:
def __init__(self, size, mean):
self.si... | alswlsghd320/SSD_pytorch | datasets/transforms.py | transforms.py | py | 2,372 | python | en | code | 1 | github-code | 36 |
40126491559 | import json
from typing import Any, Dict, List, Optional, Set
from clairvoyance.entities import GraphQLPrimitive
from clairvoyance.entities.context import log
from clairvoyance.entities.primitives import GraphQLKind
class Schema:
"""Host of the introspection data."""
def __init__(
self,
quer... | nikitastupin/clairvoyance | clairvoyance/graphql.py | graphql.py | py | 12,718 | python | en | code | 785 | github-code | 36 |
36963468353 | import setuptools
with open("README.md") as fh:
long_description = fh.read()
setuptools.setup(
name="pysqueezebox",
version="0.7.1",
license="apache-2.0",
author="Raj Laud",
author_email="raj.laud@gmail.com",
description="Asynchronous library to control Logitech Media Server",
long_des... | rajlaud/pysqueezebox | setup.py | setup.py | py | 572 | python | en | code | 10 | github-code | 36 |
17796457144 | from __future__ import absolute_import, division, print_function, unicode_literals
import uuid
from contextlib import contextmanager
from pants.backend.codegen.thrift.java.java_thrift_library import JavaThriftLibrary
from pants.backend.codegen.thrift.java.thrift_defaults import ThriftDefaults
from pants.build_graph.t... | fakeNetflix/twitter-repo-pants | tests/python/pants_test/backend/codegen/thrift/java/test_thrift_defaults.py | test_thrift_defaults.py | py | 2,046 | python | en | code | 0 | github-code | 36 |
36955645899 | import os
import helper, wiredtiger, wttest
from wtscenario import make_scenarios
# test_prefetch01.py
# Test basic functionality of the prefetch configuration.
class test_prefetch01(wttest.WiredTigerTestCase):
new_dir = 'new.dir'
conn_avail = [
('available', dict(available=True)),
('not-a... | mongodb/mongo | src/third_party/wiredtiger/test/suite/test_prefetch01.py | test_prefetch01.py | py | 2,236 | python | en | code | 24,670 | github-code | 36 |
23195728404 | from django.http import HttpResponse
from django.shortcuts import render
from config import settings
#from email.message import EmailMessage
from django.core.mail import EmailMessage
# Create your views here.
def home(request):
return render(request,"index.html")
def send_email(request):
if request.method=='... | utkir-dev/Send-Email | smtp/views.py | views.py | py | 855 | python | en | code | 0 | github-code | 36 |
5603935400 | from django.urls import path
from . import views
app_name = 'base'
urlpatterns = [
path('home/', views.landing_page, name='home'),
path('school_registered/', views.school_list_page, name='school_registered'),
path('contact_us/', views.contact_us_page, name='contact_us'),
]
| zuri-training/Project-My-Debtors-Team-38 | SDM/base/urls.py | urls.py | py | 293 | python | en | code | 2 | github-code | 36 |
4872107449 | import pyriemann
import mne
from mne.io import read_raw_gdf
import scipy
from scipy import signal
from scipy.signal import butter, filtfilt, sosfiltfilt
import os
import pickle
import sklearn
import seaborn as sns
import matplotlib
import matplotlib as mpl
mpl.use('Qt5Agg') # for using pyplot (pip install... | Kyungho-Won/PyRiemann-with-OpenViBE | train_MI_Riemann.py | train_MI_Riemann.py | py | 4,441 | python | en | code | 0 | github-code | 36 |
7789477007 | #1st example
'''class Base:
def Fun():
print("Hello World")
class Derive(Base):
def AnotherFun():
print("Bye World")
obj=Derive()
obj.Fun()
obj.AnotherFun()'''
#2nd example
#-----------------------------------
class Bank:
acno=0
name=''
branch=''
balance=0.0
def Input(... | diamondzxd/Python-classes | 07th session/1.py | 1.py | py | 1,099 | python | en | code | 0 | github-code | 36 |
35387023504 | #!/usr/bin/env python3
import os
from sys import argv, exit
from pathlib import Path
import vertex_cover_lib as vcl
EXACT_LIMIT = 80
def main(num_vertices, num_edges, seed, weighted, approx, file_full_extension):
# Automatic cast:
num_vertices = int(num_vertices)
num_edges = int(num_edges)
seed = int(... | romeorizzi/TALight | example_problems/tutorial/vertex_cover/gen/randgen_1_basic.py | randgen_1_basic.py | py | 1,595 | python | en | code | 11 | github-code | 36 |
34301681133 |
import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from dateutil import parser
import numpy as np
import pandas as pd
import datetime
df_ferrara = pd.read_csv('WeatherData/ferrara_270615.csv')
df_milano = pd.read_csv('WeatherData/milano_270615.csv')
df_mantov... | eternity-phoenix/Private | 气象数据分析/气象线性分析.py | 气象线性分析.py | py | 4,432 | python | zh | code | 0 | github-code | 36 |
6790838721 | from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericRelation
from model_utils.models import TimeStampedModel
from files.mixins import UploadedFileMixin
from permis... | tomasgarzon/exo-services | service-exo-core/forum/models/post.py | post.py | py | 6,189 | python | en | code | 0 | github-code | 36 |
23563814386 | import keyboard
import time
import PySimpleGUI as sg
from threading import Thread,Event
from queue import Queue
from os.path import join,exists,pardir
import webbrowser
import logging
from urllib import request
from urllib.parse import quote
from setting import Setting
setting = Setting()
if setting.m... | kaktuswald/inf-notebook | main.pyw | main.pyw | pyw | 34,382 | python | en | code | 4 | github-code | 36 |
1522352511 | import cv2, time, pandas
from datetime import datetime
firstFrame = None
statusList = [None, None]
times = []
contourCount = []
frameCount = []
avgContour = []
contCStart = 0 #indicator to start recording contour area
video = cv2.VideoCapture(0, cv2.CAP_DSHOW)
df = pandas.DataFrame(columns=["Start","End"]... | Caseyar95/MotionDetectingWebcam | VideoCapture2.py | VideoCapture2.py | py | 3,169 | python | en | code | 0 | github-code | 36 |
9036950970 | from datetime import datetime
from sqlalchemy import Column, String, Integer, Float, DateTime, select, delete
from sqlalchemy.exc import IntegrityError, NoResultFound
from sqlalchemy.ext.asyncio import AsyncSession
from app.services.database import Base
class TokenInfo(Base):
__tablename__ = "TokenInfo"
crea... | treybrooks/TopCryptosAPI | api/app/models.py | models.py | py | 1,243 | python | en | code | 0 | github-code | 36 |
11538129042 | """
Sandbox URL Configuration
"""
from django.conf import settings
from django.conf.urls import url
from django.views.generic.base import TemplateView
from sandbox.views import BasicSampleFormView, ModesSampleFormView
urlpatterns = [
# Dummy homepage to list demo views
url(r'^$', TemplateView.as_view(
... | sveetch/djangocodemirror | sandbox/urls.py | urls.py | py | 947 | python | en | code | 31 | github-code | 36 |
34699362669 | def cookbook_read():
with open('cookbook.txt') as file:
lines = file.readlines()
cook_book = {}
for num, line in enumerate(lines):
if line == '\n':
continue
elif num == 0 or lines[num-1] == '\n':
ingridients = []
for ingr in lines[num+2:num+2+int(lines[num+1])]:
ing... | sirifox/-2.1.files- | 2.1.files.py | 2.1.files.py | py | 1,382 | python | en | code | 0 | github-code | 36 |
361601527 | import pandas as pd
import glob
import functools
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn import decomposition
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
#from plotnine import *
#from matplotlib.mlab import PCA
# LOAD THE DATA
#data = ... | deprekate/goodorfs_experimental | scripts/pca_all.py | pca_all.py | py | 1,954 | python | en | code | 0 | github-code | 36 |
20324309262 | # -*- coding: utf-8 -*-
from django import forms
from bson.objectid import ObjectId
#from lib import get_db
class rich_form(forms.Form):
def as_read(self):
rt=''
for k,v in self.cleaned_data.iteritems():
rt+='<tr><td>'
rt+=str(self.field[k].label)
rt+='</td><td>'
if type(v)==list:
for... | raynardj/terminus | major/share/upgrade/forms.py | forms.py | py | 1,011 | python | en | code | 0 | github-code | 36 |
32033182710 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@author:ai
@file:rootNet.py
@time:2020/06/01
"""
import traceback
import warnings
from collections import defaultdict
import arrow
import pandas as pd
from configs.riskConfig import FUTURE_ENDS
from tradingSystem import Order
from configs.Database import mysql, Databas... | Joey2634/MultiFactorFramework | tradingSystem/CATS/catsserverapi/UseAITrading/rootNet.py | rootNet.py | py | 11,539 | python | en | code | 0 | github-code | 36 |
11538242087 | from PIL import Image, ImageDraw
cella = 75
def rect(x1, y1, x2, y2, col):
dib.polygon([(x1, y1), (x2, y1), (x2, y2), (x1, y2)], col)
def cercle(x, y, col):
dib.ellipse([cella*x + 25, cella*y + 25, cella*x + 49, cella*y + 49], col)
c = int(input())
f = int(input())
img = Image.new('RGB', (cella*c, cella*f... | oicatalana/solucions_oicat_2019 | concurs_classificatori2/pb6.py | pb6.py | py | 1,255 | python | en | code | 1 | github-code | 36 |
8265346084 | import csv
import os
import sys
from typing import List
from termcolor import colored
from tqdm import tqdm
from .binaryds import BinaryDs
MINIMUM_FEATURES: int = 32
csv.field_size_limit(sys.maxsize)
def run_preprocess(input_dir: List[str], category: int, output_dir: str,
openc: bool, features: ... | inoueke-n/optimization-detector | src/preprocess.py | preprocess.py | py | 7,391 | python | en | code | 3 | github-code | 36 |
5561637675 | def longest_consecutive_subsequence(input_list):
input_list=sorted(input_list)
temp_start=-1
temp_end=-1
temp_count=1
start=-1
end=-1
count=1
for i in range(len(input_list)-1):
if temp_start==-1:
if input_list[i]-input_list[i+1] == -1 :
temp_start=i
temp_end=i+1
temp_count=temp_count+1
else:
... | sripriya-potnuru/implementations-of-algorithms-and-datastructures | python/array/longest_consecutive_subsequence.py | longest_consecutive_subsequence.py | py | 1,101 | python | en | code | 0 | github-code | 36 |
26460686216 | # Read file from Big.inp
f = open('Big.inp', 'r')
node_file = open('big_node.txt', 'w')
edge_file = open('big_edge.txt', 'w')
pump_file = open('big_pump.txt', 'w')
read_format = ''
node_id = 0
edge_id = 0
pump_id = 0
source = []
outlet = []
node_map = {}
node_str = ''
edge_str = ''
curve_str = ''
edge_map = {}
for... | MartinSuGJ/water_pipe | code/data_clean/water_instances_convert_new_new.py | water_instances_convert_new_new.py | py | 4,306 | python | en | code | 1 | github-code | 36 |
71578947943 | # !/usr/bin/env python
import vtk
def get_program_parameters():
import argparse
description = 'Highlighting a selected object with a silhouette.'
epilogue = '''
Click on the object to highlight it.
The selected object is highlighted with a silhouette.
'''
parser = argparse.ArgumentParser(descript... | lorensen/VTKExamples | src/Python/Picking/HighlightWithSilhouette.py | HighlightWithSilhouette.py | py | 4,453 | python | en | code | 319 | github-code | 36 |
30922250366 | #!/usr/bin/env python
# from __future__ import division
import numpy as np
import message_filters
from matplotlib import pyplot as plt
import imutils
from time import time, sleep
# import os
from sensor_msgs.msg import Image
from geometry_msgs.msg import Point, Pose, Quaternion, Vector3
from cv_bridge import CvBridge,... | tkurtiak/Project4b | matchfeat_old.py | matchfeat_old.py | py | 12,217 | python | en | code | 0 | github-code | 36 |
16556808242 | # Create a 2D matrix that acts as a workspace where a robot can move, ( eg: 1-> free space, 0-> obstacle). Create a function to insert obstacles at required/given coordinates. Write functions that can move the robot's(represent robot with other characters or numbers) position in the workspace. Write a function to visua... | ms-jagadeeshan/mars_task_2 | qn5.py | qn5.py | py | 2,574 | python | en | code | 0 | github-code | 36 |
6394243793 | import re
# Your sentence
sentence = "David and Lucy walk one mile to go to school every day at 8:00AM when there is no snow."
# The regular expression
time_regex = r"\b\d{1,2}:\d{2}(AM|PM)?\b"
# Search for the time in the sentence
time_match = re.search(time_regex, sentence)
if time_match:
# If the time was fo... | GranDiego117/KBAI | SentenceReadingAgent/test.py | test.py | py | 470 | python | en | code | 0 | github-code | 36 |
71504143463 | from django.shortcuts import render
from django.http import HttpResponse
from zipfile import ZipFile, is_zipfile, Path
import os
from outlook_msg import Message
import pandas as pd
import numpy as np
import re
import nltk
import spacy
from string import punctuation
import extract_msg
nltk.download('punkt')
from nltk.t... | TheThinker01/AiEmailClassifier | server/views.py | views.py | py | 24,603 | python | en | code | 1 | github-code | 36 |
28068367502 | import sys
input = sys.stdin.readline
def lower_bound(arr, start, end, n):
while start < end:
mid = (start + end) // 2
if arr[mid] < n:
start = mid + 1
else:
end = mid
return end
n = int(input())
a = list(map(int, input().split()))
answer = []
for num in a:
... | hwanginbeom/algorithm_study | 1.algorithm_question/9.Binary_Search/114.Binary_Search_gyeonghyeon.py | 114.Binary_Search_gyeonghyeon.py | py | 533 | python | en | code | 3 | github-code | 36 |
43552330299 | import pytest
from rest_framework import status
from tests.factories import JobFactory
@pytest.mark.django_db
def test_selection_create(client, user_access_token):
user, access_token = user_access_token
job_list = JobFactory.create_batch(10)
data = {
"name": "Название подборки",
"items":... | VyacheslavTim/Lesson31 | tests/selection/selection_test.py | selection_test.py | py | 750 | python | en | code | 0 | github-code | 36 |
25947127488 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def deepestLeavesSum(self, root: TreeNode) -> int:
max_sum = 0
stack = [root]
while stack:
... | dzaytsev91/leetcode-algorithms | medium/1302_deepest_leaves_sum.py | 1302_deepest_leaves_sum.py | py | 669 | python | en | code | 2 | github-code | 36 |
40290054155 | from flask import Flask, request, jsonify
from flask_cors import CORS
import re
from escpos.printer import Network
import base64
import os
app = Flask(__name__)
CORS(app)
@app.route('/text/<addr>', methods=['GET','POST'])
def print_text(addr):
data, printer, message = setup_for_command(request, addr)
if me... | Christophersuazop/printer_proxy | main.py | main.py | py | 3,827 | python | en | code | 0 | github-code | 36 |
37241864515 | #!/usr/bin/python3
"""
Run this with:
python3 -m http.server --cgi
"""
import cgitb
cgitb.enable(format="text")
from helper import get_input, json
# user_input = get_input()
test_data = {
"firstName": "John",
"lastName": "Smith",
"age": 27
}
# Will give you JSON output in the console
print(json.dumps(tes... | Alexico1969/Points-Sandbox | cgi-bin/api.py | api.py | py | 415 | python | en | code | 0 | github-code | 36 |
35396554268 | from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from abc import abstractmethod, abstractproperty
from contextlib import contextmanager
import os
import tempfile
from twitter.common.collections import maybe_list
fro... | fakeNetflix/square-repo-pants | src/python/pants/backend/jvm/tasks/jar_task.py | jar_task.py | py | 12,978 | python | en | code | 0 | github-code | 36 |
13348205900 | import dpnp.config as config
# from dpnp.dparray import dparray
from dpnp.dpnp_array import dpnp_array
import numpy
import dpctl.tensor as dpt
if config.__DPNP_OUTPUT_DPCTL__:
try:
"""
Detect DPCtl availability to use data container
"""
import dpctl.tensor as dpctl
except Im... | LukichevaPolina/dpnp | dpnp/dpnp_container.py | dpnp_container.py | py | 1,686 | python | en | code | null | github-code | 36 |
7424080764 | from plot_cryptosystems import plot_cryptosystems_single_dim, sns
from cryptosystems import SIGN_DF, max_abs_scaler, np
import matplotlib
df = SIGN_DF
p = sns.color_palette("Paired")
sns.set(context='paper', palette=sns.color_palette("Paired"))
sns.set_style(sns.axes_style("ticks"),
{'axes.grid': True})
... | crest42/ma | loes20/Dokumentation/src/plot_bar_ratio_cycles_bytes_signature.py | plot_bar_ratio_cycles_bytes_signature.py | py | 840 | python | en | code | 0 | github-code | 36 |
22209534047 | # -*- coding: utf-8 -*-
"""
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 3 of the License,
or (at your option) any later version.
This program is distributed in... | terual/sbcc | module/functions.py | functions.py | py | 2,415 | python | en | code | 2 | github-code | 36 |
27049180203 | from datetime import datetime
from django.core.management.base import BaseCommand
from django.utils.timezone import now
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.utils.translation import gettext as _
from imap_tools import MailBox, AND
from filebrowser.... | andywar65/project_repo | blog/management/commands/fetch_article_emails.py | fetch_article_emails.py | py | 2,479 | python | en | code | 2 | github-code | 36 |
2063174381 | # -*- coding: utf-8 -*-
"""
@title: test_convert_spectra.py
@description: Example Python script to test the spectra data converter and to test reloading the converted spectra data
@author: chrisarcadia
@created: 2018/10/26
"""
import Bruker
import matplotlib.pyplot as pyplot
import h5py
import numpy
# C... | scale-lab/AcidBaseNetworks | simulations/chemcpupy/automation/Bruker/test_convert_spectra.py | test_convert_spectra.py | py | 1,382 | python | en | code | 0 | github-code | 36 |
72084597543 | from setuptools import setup, find_packages
with open("requirements.txt") as f:
content = f.readlines()
requirements = [x.strip() for x in content if "git+" not in x]
setup(name='chord-cleaning',
description='creating a set of standardized chords from data',
install_requires=requirements,
packag... | emilycardwell/chord-cleaning | setup.py | setup.py | py | 341 | python | en | code | 0 | github-code | 36 |
4000738437 | import argparse
import math
from pathlib import Path
import random
import sys
import numpy as np
import pandas as pd
TRAIN_POOL_FILEPATH = "../../outputs/data_generation/train_pool.tsv"
TRAIN_FILEPATH_FS = "../../outputs/data_generation/{}/run_{}/round_{}/train.tsv"
TO_PREDICT_FILEPATH_FS = "../../outputs/data_gener... | IBPA/SemiAutomatedFoodKBC | src/data_generation/prepare_training_data.py | prepare_training_data.py | py | 8,371 | python | en | code | 1 | github-code | 36 |
31724432420 | # Предложение with служит для упрощения конструкции try/finally
# Вначале блока with вызывается метод __enter__
# Роль части finally играет обращение к методу __exit__
from unittest.mock import patch
class LookingGlass:
def __enter__(self):
import sys
self.original_write = sys.stdout.write
... | GrigorevEv/grade_2 | python/context_manager/handwritten.py | handwritten.py | py | 997 | python | ru | code | 0 | github-code | 36 |
25167990666 | """
Assignment: Programming Project 4: Client / Server Chat
File: Configuration
Description: Configuration file for both server and client scripts.
A list of constants.
Dependencies: None
Course: CS 372
Section: 400
Module: 10
Name: Marc... | MHValdez/Socket_Server_and_Client_Chat | config.py | config.py | py | 853 | python | en | code | 0 | github-code | 36 |
13329932727 | import json
from channels.generic.websocket import WebsocketConsumer
from django.contrib.auth.models import User
from gestion_admin.models import Article, Historique
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.user = User.objects.get(username=self.scope["user"])
self.historiqu... | meryem1994/chatbot-project | user/consumers.py | consumers.py | py | 1,526 | python | en | code | 0 | github-code | 36 |
12062872784 | def divisors(num, primes):
if num == 1:
return 1
elif num == 2: return 2
else:
divisors = 2
divlist = [1, num]
for divisor in primes:
if divisor ** 2 <= num:
if num % divisor == 0:
if divisor ** 2 == num:
divisors += 1
... | rgertenbach/Project-Euler-Python | Euler 12.py | Euler 12.py | py | 1,477 | python | en | code | 0 | github-code | 36 |
75118097702 | #!/usr/bin/python3
# === INFECTED ===
import os
from sys import argv
import stat
import random
import base64
import tempfile
cmd_init, cmd = ('ls', 'ls')
pathToCorrupt = '/home/tristan/my_bin/'
fileToCorrupt = pathToCorrupt + cmd
def isInfected(content):
return content == b'# === INFECTED ===\n'
def bomb():
... | GLMF/GLMF201 | Libs_et_Modules/easy_install_v2.py | easy_install_v2.py | py | 2,566 | python | en | code | 2 | github-code | 36 |
32365954378 | import json, random
from random import shuffle
out = open("_12bad.json", "a")
lines = [line for line in open("bad.json").readlines()]
lines = lines[:12307]
for line in lines:
out.write(line)
| masteroppgave/topic_model | filter.py | filter.py | py | 196 | python | en | code | 0 | github-code | 36 |
31739800389 | from multiprocessing import Process
import time
class MyProcess(Process):
def __init__(self,name):
super().__init__()
self.name=name
def run(self):
print("%s is running" % self.name)
time.sleep(1)
print("%s is done" % self.name)
if __name__=="__main__"... | bigcpp110/python_learning | 并发编程/process_class.py | process_class.py | py | 400 | python | en | code | 1 | github-code | 36 |
7056045662 | # class MyRangeInterator:
# def __init__(self,stop):
# self.number = 0
# self.stop = stop
#
# def __next__(self): #不能直接传递到函数要先传给类
# self.number += 1
# if self.number < self.stop:
# return self.number
# else:
# raise StopIteration()
class MyRange:... | haiou90/aid_python_core | day16/exercise_personal/06_exercise.py | 06_exercise.py | py | 583 | python | en | code | 0 | github-code | 36 |
6369818660 | '''
This script compiles the requirements for the bot and runs it on a loop
It should also contain the functions of the bot
'''
from config import *
from core import *
import telegram
import datetime
import time
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, \
ConversationHandler, CallbackQ... | ollayf/leobot | main.py | main.py | py | 6,203 | python | en | code | 2 | github-code | 36 |
846869458 | import argparse
import json
import os
from datetime import datetime
from statistics import mean
import chainer
import chainerrl
import numpy as np
from chainerrl.wrappers import CastObservationToFloat32, ScaleReward
from estimator import RecoNet, ThreatEstimator
from q_func import RPDQN, QFunction, RPQFunction
from u... | pfnet-research/rp-safe-rl | circuit/run.py | run.py | py | 6,662 | python | en | code | 7 | github-code | 36 |
15139442018 | from lexikanon import HyFI
from lexikanon.stopwords import Stopwords
def test_stopwords():
print(HyFI.get_caller_module_name())
cfg = HyFI.compose_as_dict("stopwords")
print(cfg)
cfg["nltk_stopwords_lang"] = "english"
stop = Stopwords(**cfg)
print(stop)
print(list(stop))
assert len(sto... | entelecheia/lexikanon | tests/lexikanon/stopwords/test_stopwords.py | test_stopwords.py | py | 532 | python | en | code | 0 | github-code | 36 |
19757364925 | #! usr/bin/env/python
# Cache Enforcer (for Spotify)
# Spotify took away the option for controlling the cache size, so I'm doing it for them.
# Written by Josh Chan
import os
import shutil
# CONSTANTS
TARGET_DIR = "/Users/joshuapaulchan/Library/Caches/com.spotify.client/Data/" # currently, mac only
SIZE_ALLOWANCE = 1... | joshpaulchan/tidy | beatdown-spotify.py | beatdown-spotify.py | py | 1,744 | python | en | code | 0 | github-code | 36 |
72482584103 | from fhcrc_pathology.OneFieldPerSpecimen import OneFieldPerSpecimen
import global_strings as gb
class HighRiskFinding(OneFieldPerSpecimen):
''' extract other, high risk findings (atypia, etc) '''
__version__ = 'HighRiskFinding1.0'
def __init__(self):
super(HighRiskFinding, self).__init__()
... | esilgard/BreastMR | fhcrc_pathology/breast/HighRiskFinding.py | HighRiskFinding.py | py | 757 | python | en | code | 0 | github-code | 36 |
22016755038 | import pandas as pd
import numpy as np
from scipy.io import savemat
import os
def csv_to_spm_vectors(csv_path):
for root, dirs, files in os.walk(csv_path):
for name in files:
if name.endswith(".csv"):
csv_file = os.path.join(root, name)
df = pd.read_csv(csv_fil... | paradeisios/old_thesis_code | PPI_analysis/utils/csv_to_spm_vectors.py | csv_to_spm_vectors.py | py | 1,283 | python | en | code | 0 | github-code | 36 |
4289870302 | # consul_client.py
import consul
import socket
import time
import threading
import json
import re
import random
from flask import Flask
from typing import Dict, List, Union
from dzmicro.utils import compare_dicts
class WatchKVThread(threading.Thread):
def __init__(self, uuid: str, is_platform: bool) -> None:
... | dzming-git/DzMicro | dzmicro/utils/network/consul_client.py | consul_client.py | py | 9,967 | python | en | code | 1 | github-code | 36 |
23164271375 | from PIL import Image, ImageOps
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import time
import pandas as pd
# import json
from IPython.display import clear_output
torch.set_pri... | jain-aniket/attentiveness-flask | testtorchloading.py | testtorchloading.py | py | 1,388 | python | en | code | 0 | github-code | 36 |
1409824498 | import threading
import time
from subprocess import Popen, PIPE, CalledProcessError
from redis import Redis
from rq import Queue
import sys
import os
import shutil
# Connect to Redis
redis_conn = Redis(host='localhost', port=6379, db=0)
# Create an RQ queue
queue = Queue(connection=redis_conn)
def read_output(pipe, ... | ASparkOfFire/fastapi-rq-example | job.py | job.py | py | 1,772 | python | en | code | 0 | github-code | 36 |
40097713775 | import flask
import os
import zipfile
from docx.api import Document
from flask import request, jsonify
from flask_s3 import *
from io import BytesIO
from werkzeug.utils import secure_filename
import boto3
from s3_credential import *
import pypandoc
from bs4 import BeautifulSoup
from datetime import datetime
import json... | ActiKnow/docx-to-html-json | index.py | index.py | py | 9,727 | python | en | code | 0 | github-code | 36 |
8604753979 | import telebot
from telebot import types
import config
import values
import sqlite3
# Registration BOT using TOKEN
bot = telebot.TeleBot(config.TOKEN)
# Registration DB
db = sqlite3.connect('DB/catalog.db', check_same_thread=False)
sql = db.cursor()
# For reading USER's HEIGHT
def height(message, word):
weight ... | Abrahamlink/body-bot | bot.py | bot.py | py | 10,450 | python | en | code | 0 | github-code | 36 |
2767696238 | from gym import Env
from gym.spaces import Discrete, Box
import numpy as np
import random
import numpy as np
from functions import Junction
env = Junction() # creating the enviornment
action_size = env.action_space.n
print("Action size ", action_size)
state_size = env.observation_space.n
print("State size ", state_... | Shashwatbokhad/Traffic-light-control-using-Reinforcement-learning | rl_model.py | rl_model.py | py | 5,286 | python | en | code | 1 | github-code | 36 |
44396105133 | import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow_datasets as tfds
import os
if __name__ == '__main__':
tfds.disable_progress_bar()
train_ds, validation_ds, test_ds = tfds.load(
"cats_vs_dogs",
data_dir=os.path.expandus... | jk983294/morph | book/tensorflow/models/transfer.py | transfer.py | py | 3,632 | python | en | code | 0 | github-code | 36 |
25617944185 | import numpy as np
from bs4 import BeautifulSoup
import pandas as pd
import requests
import time
import json
from tomlkit import array
URL = "https://covid19.riau.go.id/pantauan_data_kasus"
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389... | mfalfafa/scrape-covid19-data-riau | scraper.py | scraper.py | py | 1,975 | python | en | code | 0 | github-code | 36 |
74431864103 | from fastapi import FastAPI
import requests
import uvicorn
app = FastAPI()
@app.get("/")
async def get_product():
req=requests.get("https://world.openfoodfacts.org/api/v0/product/3033491270864.json")
if req.status_code==200:
res=req.json()
return(res)
if __name__=='__main__':
uvicorn.run(a... | apollineguerineau/TP5 | main.py | main.py | py | 352 | python | en | code | 0 | github-code | 36 |
74105436582 | import sqlite3
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from datetime import datetime as dt
from sklearn.externals import joblib
start_time = dt.now()
# data loading
conn = sqlite3.connect("textarray.db")
cur = conn.cursor()
query = '''SELECT * fro... | kirilenkobm/ML_examples | RandomForestClf.py | RandomForestClf.py | py | 1,335 | python | en | code | 0 | github-code | 36 |
30838346418 | from flask import Blueprint, current_app, request, make_response, jsonify
from ..models.User import User
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
jwt_required,
)
import traceback
auth_bp = Blueprint('auth_bp', __name__)
# registrater user
@auth_bp.route('/user/registrat... | conradsuuna/uac-computer-competency | app/controllers/users.py | users.py | py | 4,056 | python | en | code | 0 | github-code | 36 |
72766865064 | import numpy as np
import random
import csv
class traintest:
def __init__(self,cnames,instx=0):
self.train=[]
self.test=[]
self.cnames=cnames
self.ofiles=[]
for j in range(len(self.cnames)):
tfname='friends/train_'+self.cnames[j].lower()+'.txt'
pf=open(tfname,'w')
self.ofiles.append(pf)
self.in... | arnab64/slugbot | feature_extraction/train_test/9_separate_train_test.py | 9_separate_train_test.py | py | 2,759 | python | en | code | 1 | github-code | 36 |
35578454600 | class cookie:
pass
a = cookie()
b = cookie()
print(type(a))
print(type(b))
class FourCal:
#first = 0
#second = 0
def setdata(self,first,second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
c = FourCal()
c... | kamkm01/20190615python | python_basic/class_test.py | class_test.py | py | 508 | python | en | code | 0 | github-code | 36 |
3458614577 | class Solution(object):
def largeGroupPositions(self, s):
"""
:type s: str
:rtype: List[List[int]]
"""
res = []
stack = []
for index, ele in enumerate(s):
if not stack: #stack is empty
stack.append(ele)
else:
... | pi408637535/Algorithm | com/study/algorithm/daily/830. Positions of Large Groups.py | 830. Positions of Large Groups.py | py | 2,159 | python | en | code | 1 | github-code | 36 |
31113872518 | """
The main script that serves as the entry-point for all kinds of training experiments.
"""
from __future__ import annotations
import logging
from functools import partial
from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, Sequence, Tuple, Union
import torch
from al.core.data.collators import Joi... | saifullah3396/doc_al | src/al/core/training/vaal_trainer.py | vaal_trainer.py | py | 15,573 | python | en | code | 0 | github-code | 36 |
6215124822 | from rodi import RoDI
import time
robot = RoDI()
def reubicar():
robot.move_stop()
robot.pixel(20,0,0)
robot.move_backward()
time.sleep(0.1)
robot.move_left()
time.sleep(0.5)
robot.move_forward()
time.sleep(0.5)
def ataque():
robot.move(100,100)
while True:
try:
dist... | devpbeat/bootcamp | rob.py | rob.py | py | 921 | python | es | code | 0 | github-code | 36 |
14007726581 | import torch
import torch.nn as nn
import os
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, Dataset
import wandb
from PIL import Image
import numpy as np
from tqdm import tqdm
from torch.optim.lr_scheduler import ExponentialLR
class Encoder(nn.Module):
def __init__(self, ... | s183920/02582_Computational_Data_Analysis_Case2 | autoencoder.py | autoencoder.py | py | 6,011 | python | en | code | 0 | github-code | 36 |
25127011115 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
****************************************
* coded by Lululla & PCD *
* skin by MMark *
* 26/03/2023 *
* Skin by MMark *
****************************************
# --------------------#
# I... | Belfagor2005/xxxplugin | usr/lib/enigma2/python/Plugins/Extensions/xxxplugin/Sites/freearhey.py | freearhey.py | py | 5,713 | python | en | code | 0 | github-code | 36 |
71335895783 | def cycleDetection(edges, n, m):
# Write your code here.
# Return "Yes" if cycle id present in the graph else return "No".
white, grey ,black = range(3)
adjList = []
for x in range(n+1):
adjList.append([])
for u, v in edges:
adjList[u].append(v)
adjList[v].append(u)
... | architjee/solutions | CodingNinjas/Detect Cycle in Undirected Graph.py | Detect Cycle in Undirected Graph.py | py | 1,323 | python | en | code | 0 | github-code | 36 |
2343066126 | import pygame
import Config
import random
import math
import entities
from entity import Entity
class Meteor(Entity):
def __init__(self, img):
self.x = random.randint(0, Config.WIDTH)
self.y = 0
self.size = random.randint(20, 65)
self.speed = random.randint(3, 5)
... | Krakozaybr/Meteorro | cooperate/meteor.py | meteor.py | py | 3,997 | python | en | code | 0 | github-code | 36 |
17381398214 | """
Implementation of the human and machine policies in the paper
"""
from copy import copy
import random
import numpy as np
import math
import torch
from collections import defaultdict
from environments.env import Environment, GridWorld
from networks.networks import ActorNet
class Agent:
"""
Agent supercla... | ElenStr/human-machine-switching | agent/agents.py | agents.py | py | 14,470 | python | en | code | 0 | github-code | 36 |
75216777705 | from joblib import load
pipeline1 = load('assets/xgb1.joblib')
pipeline2 = load('assets/xgb2.joblib')
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from xgboost imp... | tigju/Amazon-Deforestation-Prediction-App | pages/predictions.py | predictions.py | py | 4,861 | python | en | code | 1 | github-code | 36 |
40364806637 | import os
import subprocess
from testbot.executors.env_test import EnvironmentTestExecutor
from testbot.executors.errors import ExecutorError
from testbot.task import BotTask
class ScriptEnvironmentTestExecutor(EnvironmentTestExecutor):
def __init__(self, task: BotTask, submission_id: int, test_config_id: int):
... | tjumyk/submit-testbot | testbot/executors/env_test_script.py | env_test_script.py | py | 2,449 | python | en | code | 0 | github-code | 36 |
15178487279 | import warnings
from . import AWSHelperFn, AWSObject, AWSProperty
warnings.warn("This module is outdated and will be replaced with "
"troposphere.dynamodb2. Please see the README for "
"instructions on how to prepare for this change.")
class AttributeDefinition(AWSHelperFn):
def __in... | farazrehman/aws-resources | CloudFormation/nash/lib/python2.7/site-packages/troposphere/dynamodb.py | dynamodb.py | py | 2,681 | python | en | code | 0 | github-code | 36 |
31833081682 | import pytest
from bs4 import BeautifulSoup
import nerdtracker_client.constants.stats as ntc_stats
from nerdtracker_client.scraper import (
create_scraper,
parse_tracker_html,
retrieve_page_from_tracker,
retrieve_stats,
retrieve_stats_multiple,
)
class TestScraper:
@pytest.mark.slow
@pyte... | cesaregarza/Nerdtracker_Client | nerdtracker_client/tests/test_scraper.py | test_scraper.py | py | 2,972 | python | en | code | 0 | github-code | 36 |
476733440 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import array, os, re
import numpy as np
import math
import sys
# some useful constants
c = 299792458 # speed of light (m/sec)
m_per_au = 1.49598e11 # meters per astronomical unit
au_per_pc = 3600 * 180 / np.... | cmancone/easyGalaxy | ezgal/utils.py | utils.py | py | 15,023 | python | en | code | 14 | github-code | 36 |
1154715752 | import os
from flask import Flask
from src.models import migrate, db
from src.command import data_load_command
from src.api import api
config_variable_name = 'FLASK_CONFIG_PATH'
default_config_path = os.path.join(os.path.dirname(__file__), 'config/local.py')
os.environ.setdefault(config_variable_name, default_confi... | shano/document_keyword_analysis | app.py | app.py | py | 849 | python | en | code | 0 | github-code | 36 |
32365176970 | from __future__ import with_statement
import os
import sys
try:
import gevent
import gevent.monkey
gevent.monkey.patch_all(dns=gevent.version_info[0] >= 1)
except ImportError:
gevent = None
print >>sys.stderr, 'warning: gevent not found, using threading instead'
import errno
import socket
import t... | hadidonk/hxsocks | hxsserver.py | hxsserver.py | py | 23,258 | python | en | code | 0 | github-code | 36 |
41133433788 | from cryptography.fernet import Fernet
import os
from pathlib import Path
default_path = Path("/home/Diode/Dicot/VisionIOT/main")
if not os.path.exists(default_path):
os.makedirs(default_path)
filen = os.path.join(default_path, "app.dat")
open(filen, 'w').close()
forread = open(filen)
content = fo... | imdiode/PythonExper | home4.py | home4.py | py | 502 | python | en | code | 0 | github-code | 36 |
74552041385 |
def hr():
print('─' * 20)
def l():
print('\n')
def _():
l()
hr()
l()
def jaccard(v1,v2):
# πρώτη συνάρτηση ομοιότητας, jaccard
union = len(v1)
count = 0
for i in range(len(v1)):
if(v1[i]):
if(v2[i]):
count = count + 1
jaccard = count/un... | Apostolos172/uom | s7/Information Retrieval and Search Engines/recommender/irTheoryExample.py | irTheoryExample.py | py | 3,271 | python | en | code | 0 | github-code | 36 |
11262269606 | from tkinter import *
root = Tk()
# 创建一个Canvas,设置其背景色为白色
cv = Canvas(root, bg='white')
d = {1: PIESLICE, 2: CHORD, 3: ARC}
for i in d:
cv.create_arc(
(10, 10 + 60 * i, 110, 110 + 60 * i),
style=d[i], # 指定样式
start=30, # 指定起始角度
extent=30 # 指定角度偏移量
)
cv.pack()
root.mainloop()
# ... | weiyinfu/learnTkinter | 画布/create_arc.py | create_arc.py | py | 443 | python | zh | code | 1 | github-code | 36 |
36532411991 | #The code base on https://github.com/zergtant/pytorch-handbook
import torch # pytorch 实现
import torch.nn as nn
import numpy as np #处理矩阵运算
'''
1 logistic回归会在线性回归后再加一层logistic函数的调用,主要
用于二分类预测
2 使用UCI German Credit 数据集
german.data-numeric 是已经使用numpy 处理好的数值化数据,
可以直接numpy 调用
'''
# 第一步:读取数据
data=np.loadtxt("ge... | BrandonHoo/Deep-Learning-Practice-Project | Logistic_Regression_practice.py | Logistic_Regression_practice.py | py | 2,774 | python | zh | 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.