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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
9770951786 | class Repository:
import os.path
global surveys, question_file
path = os.path.dirname(__file__) + r'.\data'
try:
surveys = open(path + r"\first_survey.csv", "a+")
surveys.seek(62)
question_file = open(path + r"\questions.txt", "r")
except FileNotFoundError:
raise File... | Matixo55/SimplePoll | repository/repository.py | repository.py | py | 922 | python | en | code | 0 | github-code | 13 |
7092489107 | class Solution(object):
def minAbsoluteDifference(self, nums, x):
minimo=-1
for i in range(len(nums)):
for j in range(len(nums)):
if abs(i - j) >= x:
if minimo==-1:
minimo=abs(nums[i] - nums[j])
elif ... | alexandreborgmann/leetcode | MinimumAbsoluteDifferenceBetweenElements.py | MinimumAbsoluteDifferenceBetweenElements.py | py | 661 | python | en | code | 0 | github-code | 13 |
34799497172 | #coding:utf-8
import os
def text_save(content,filename,mode='a'):
# Try to save a list variable in txt file.
file = open(filename, mode)
for i in range(len(content)):
file.write(str(content[i])+'\n')
file.close()
# file_dir = "/home/zx/desktop/华谊化工/"
def get_files(file_dir):
namelist = [... | Xiehuaiqi/python_script | cutimage/makedir1.py | makedir1.py | py | 631 | python | en | code | 0 | github-code | 13 |
11502353956 | import socket
import os
import time
class UDPPing:
udp_ip = ""
udp_port = 0
packet_loss = 0
packet_count = 0
message = ""
sock = None
def __init__(self, udp_ip='ibiza.dcc.ufla.br', udp_port=5002, packet_count=20, message="Default"):
self.udp_ip = udp_ip
self.udp_port = udp_... | francislz/college_codes | computer_networks/tp_ping/UDPPing.py | UDPPing.py | py | 2,034 | python | en | code | 2 | github-code | 13 |
11576947844 | import spacy
import json
from tqdm import tqdm
nlp = spacy.load('en_core_web_sm')
# dataset_dir = '/home/hoang/Datasets/MIMIC/'
dataset_dir = '/home/hoang/Datasets/NLMCXR/'
count_sentence = json.load(open(dataset_dir + 'count_sentence.json', 'r'))
np_count = {}
for k,v in tqdm(count_sentence.items()):
doc = nlp(... | ginobilinie/xray_report_generation | tools/nounphrase_extractor.py | nounphrase_extractor.py | py | 576 | python | en | code | 58 | github-code | 13 |
19469004255 | skates = int(input('\nВведите кол-во коньков: '))
skates_list = []
count = 0
for s in range(1,skates+1):
print('Введите размер',s,'человека: ',end='')
skates_list.append(input())
legs = int(input('\nВведите кол-во людей: '))
legs_list = []
for l in range(1,legs+1):
print('Введите размер',l,'человека: ',end... | TurovD/Skillbox_Tasks | 17_List_methods/07_roller_skates/main.py | main.py | py | 736 | python | ru | code | 0 | github-code | 13 |
9088455740 | #https://www.acmicpc.net/problem/13707
#백준 13707번 합분해 2 (DP)
#import sys
#input = sys.stdin.readline
INF = int(1e9)
n, k = map(int, input().split())
dp = [[0]*(k+1) for _ in range(n+1)]
for i in range(1,n+1):
for j in range(1,k+1):
if i == 1 :
dp[i][j] = j
else:
dp[i][j] = ... | MinsangKong/DailyProblem | 08-16/3-1.py | 3-1.py | py | 392 | python | en | code | 0 | github-code | 13 |
26413075167 | n=int(input())
k=9
a=[]
if n<10:
print(10+n)
else:
while k>1:
if n%k==0:
a.append(str(k))
n=n//k
else:
k=k-1
b=a[::-1]
print(''.join(b)) | PREMSAI2K1/code1 | smallestnumber.py | smallestnumber.py | py | 205 | python | en | code | 0 | github-code | 13 |
42588814503 | #!/usr/bin/python3
from os import read
import socket
import threading
import sys
class server_INFO(object):
def __init__(self,IP,port) -> None:
self.IP=str(IP)
self.port=int(port)
def main():
if len(sys.argv) < 3:
print(f"\tUsage {sys.argv[0]} <IP> <Port> ")
exit(-1)
... | axde954e6/NCTU-Intro.2_NP | NP/mid/0712534/P2/client.py | client.py | py | 1,085 | python | en | code | 0 | github-code | 13 |
36146557716 | #!/usr/bin/env python3
import argparse
import atexit
import logging
import os
import random
import requests
import string
import subprocess
import sys
import tempfile
import time
from packaging import version
sys.path.append(f"{os.path.abspath(os.path.dirname(__file__))}/..") # noqa
from lib.commands import ssh, scp... | xcp-ng/xcp-ng-tests | scripts/install_xcpng.py | install_xcpng.py | py | 10,440 | python | en | code | 3 | github-code | 13 |
21571761016 | import params
from google.cloud import datastore, storage, logging
import time
import pickle
import hashlib
import sys
import numpy as np
import portfolioGeneration
import portfolio
import dataAck
import warnings
import numpy as np
import pandas as pd
warnings.filterwarnings("ignore")
import multiprocessing as mp
impo... | SignalBuilders/walkforwardTrader | fastAutomaticPortfolioDataCache.py | fastAutomaticPortfolioDataCache.py | py | 2,690 | python | en | code | 1 | github-code | 13 |
16882491331 | from selenium.webdriver.support.ui import WebDriverWait
from tests.Pages.Components.HeaderComponent import HeaderComponent
from tests.Pages.Components.FooterComponent import FooterComponent
from tests.Pages.Components.AsideFilterSortComponent import AsideFilterSortComponent
from tests.config import blog_list_url
from s... | stsiwo/python-selenium-testing | tests/Pages/BlogListPage.py | BlogListPage.py | py | 2,528 | python | en | code | 0 | github-code | 13 |
73607343696 | import os
import sys
import urllib.parse
import warnings
from flask import Response
import flask_frozen
import click
from ._deployment import deploy as deploy_
from ._shutdown import ShutdownableFreezer, inject_shutdown
def port_option():
return click.option(
'--port', type=int, default=8003,
he... | pyvec/elsa | elsa/_cli.py | _cli.py | py | 5,710 | python | en | code | 27 | github-code | 13 |
40414084010 | from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_volume
short_description: Create/Delete Cinder Volumes
e... | RavindraSingh12/Ansible-Runner | venv/lib/python3.6/site-packages/ansible/modules/cloud/openstack/os_volume.py | os_volume.py | py | 7,700 | python | en | code | 2 | github-code | 13 |
11867518761 | import random
class Mp3calar ():
def __init__(self):
self.sarkilar = []
self.calansarki = ""
self.sesduzeyi = 50
self.mp3durumu = True
self.kacsarkivar = 0
self.controller()
self.anamenu()
def controller (self):
if self.calansarki ... | zaFer234/Temel-Python-Projeleri | mp3 çalar.py | mp3 çalar.py | py | 5,017 | python | tr | code | 0 | github-code | 13 |
27961748602 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 16:52:51 2020
@author: pradeep
"""
import pandas as pd
import numpy
from numpy import diff
import matplotlib.pyplot as plt
from scipy import signal
from scipy.fftpack import fft, fftshift
import pylab
#import cv2
import scipy.ndimage as ndimage
from ... | pradeeps147/Inv-kinematics-Biomachanical- | smoothing.py | smoothing.py | py | 4,734 | python | en | code | 0 | github-code | 13 |
73469392336 | import pandas as pd
import numpy as np
from skimage.io import imread
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from tqdm import tqdm
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn import Linear, Re... | AugustusXie-rgb/mask_PUF | Resnet_model.py | Resnet_model.py | py | 8,907 | python | en | code | 0 | github-code | 13 |
74024682579 | #!/usr/bin/env python
from websocket import create_connection
import json
# import subprocess
import os
"""
Prerequisites:
Choco - https://chocolatey.org/install#install-with-cmdexe
Python3 - choco install python
Websocket - pip install websocket-client
"""
ip = "10.8.30.11"
directory = "2019vision"
command = "cd {};... | FRC830/2019vision | upload_code.py | upload_code.py | py | 935 | python | en | code | 0 | github-code | 13 |
24398402441 | from django.shortcuts import render,redirect,get_object_or_404
from django.views import generic
from . import models
from . import forms
from accounts import models as accounts_models
from django.urls import reverse_lazy,reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins ... | stachurski2k4/GamesZoNe | gameszone/games/views.py | views.py | py | 3,265 | python | en | code | 0 | github-code | 13 |
35265550526 | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect, JsonResponse
from django.template import loader
from django.urls import reverse
from django.views import View
from django.utils import timezone
from .models import Question, Choice
from .models i... | BakJunGoen/python_study_django | study_django/mysite/polls/views.py | views.py | py | 5,893 | python | en | code | 0 | github-code | 13 |
71454083217 | print()
from openpyxl import Workbook
from openpyxl.drawing.image import Image
wb = Workbook()
ws = wb.active
# ImportError: You must install Pillow to fetch image objects
# 추가 라이브러리 필요 : pip install Pillow
img = Image("./RPAbasic/excel/dog.jpg")
ws.add_image(img, "C3")
wb.save("./RPAbasic/excel/image.xlsx")
print... | HwangJuu/pythonsource | RPAbasic/excel/14_image.py | 14_image.py | py | 341 | python | en | code | 0 | github-code | 13 |
19466026425 | # Did not work locally. Test accepted.
import string
from string import maketrans, lowercase as lc, uppercase as uc
def rot13(message):
tran = maketrans(lc + uc, lc[13:] + lc[:13] + uc[13:] + uc[:13])
return message.translate(tran)
def main():
new_mess = rot13("Test")
print(new_mess)
if _... | turo62/exercise | exercise/codewar/rot13_bp.py | rot13_bp.py | py | 353 | python | en | code | 0 | github-code | 13 |
36785429920 | import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import torch
from torch.nn.parameter import Parameter
import torchvision
import kornia as K
def plot_tensor(t):
plt.imshow(np.array(t.permute(1,2,0)))
def kornia_rotation(img, degrees):
# unsqueeze img... | TomBekor/AugmentationsLearning | utils.py | utils.py | py | 4,550 | python | en | code | 0 | github-code | 13 |
32757351479 | from twilio.rest import Client
TWILIO_SID = '' # Add in your Twilio's SID
TWILIO_AUTH_TOKEN = '' # Add in your Twilio's Auth token
TWILIO_VIRTUAL_NUMBER = "" # Add in your Twilio's virtual number
TWILIO_VERIFIED_NUMBER = "" # Add in your phone number to send to
class NotificationManager:
def __init__(... | fells/100-Days-Challenge | Day39/notification_manager.py | notification_manager.py | py | 649 | python | en | code | 1 | github-code | 13 |
23082930384 | #Exercício Python 56: Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas.
#No final do programa, mostre: a média de idade do grupo, qual é o nome do homem mais velho e quantas mulheres têm menos de 20 anos.
age = 0
mediage = 0
velho = 0
nomevelho = ''
mav = 0
for p in range(1, 5):
print('----- {}ª ... | nicole-pereira/Python-Desafios | ex056.py | ex056.py | py | 948 | python | pt | code | 0 | github-code | 13 |
3283502993 | import logging
import argparse as arg
# ---------------------
# Logging
# ---------------------
log = logging.getLogger('daikon')
# ---------------------
# Classes
# ---------------------
class Parser(object):
def __init__(self, version):
self._version = version
self._main = None
def setu... | neogenix/daikon | daikon/parser.py | parser.py | py | 5,564 | python | en | code | 56 | github-code | 13 |
41736759785 | import sshconnect
import Initializer
import time
import threading
names = Initializer.language
server_settings = Initializer.server_settings
client_settings = Initializer.client_settings
frame = None
ssh = None
def run(fr):
global frame, ssh
frame = fr
ssh = sshconnect.ssh
try:
ssh.exec_com... | fire-neuron/CopyGram | tracer.py | tracer.py | py | 4,829 | python | en | code | 1 | github-code | 13 |
3876677585 | import argparse
import os
from src.lfr.run_benchmark import evaluate_clustering_results
def eval_lfr_k_n_mu(avg_degree_list, n_list, methods, metric='ami', base_path='./'):
base_path = base_path + '/' if base_path[-1] != '/' else base_path
i = 0
num_benchmark_sets = len(n_list) * len(avg_degree_list)
... | synwalk/synwalk-analysis | src/scripts/evaluate_lfr.py | evaluate_lfr.py | py | 3,835 | python | en | code | 7 | github-code | 13 |
31625816434 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 22 17:46:36 2016
@author: ajaver
"""
import pandas as pd
import os
import tables
import numpy as np
import matplotlib.pylab as plt
from collections import OrderedDict
from scipy.signal import savgol_filter
from scipy.signal import medfilt
import sys
sys.path.append('/Us... | ver228/work-in-progress | work_in_progress/join_trajectories_next_gen/_old/try2joinTrajectoriesInt.py | try2joinTrajectoriesInt.py | py | 11,448 | python | en | code | 0 | github-code | 13 |
29859731817 | from intelmq.lib.bot import ExpertBot
try:
from geolib import geohash
except ImportError:
geohash = None
class GeohashExpertBot(ExpertBot):
"""Compute the geohash from longitude/latitude information, save it to extra.(source|destination)"""
overwrite: bool = False
precision: int = 7
def init... | certtools/intelmq | intelmq/bots/experts/geohash/expert.py | expert.py | py | 1,166 | python | en | code | 856 | github-code | 13 |
27967884298 | #!python3
"""DJZ Char Counter
Usage:
dzjcount.py [--dir <folder>]
Options:
-h --help Show this screen.
--version Show version.
-d --dir Specify the folder to store DZJ files
"""
import os
import sys
import glob
import re
import math
import statistics as sta
# Global Data
DATA = {
"name": "... | jfding/dzj-zizhong | dzjcount.py | dzjcount.py | py | 9,913 | python | en | code | 0 | github-code | 13 |
74189502417 | from airflow.contrib.hooks.aws_hook import AwsHook
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class StageToRedshiftOperator(BaseOperator):
ui_color = '#358140'
template_fields = ("s3_key",)
copy_sql = """
... | guptrakeshk/my_music_store_airflow | plugins/operators/stage_redshift.py | stage_redshift.py | py | 2,173 | python | en | code | 1 | github-code | 13 |
9936849467 | from flask import Flask, request
from re import match
from requests import get, post
from keys import APP_ID, API_KEY
app = Flask(__name__)
@app.route('/symptoms', methods=['GET'])
def symptoms():
return {'symptoms': infermedica_symptoms}, 200
@app.route('/diagnosis', methods=['POST'])
def diagnosis():
ar... | arnavs-0/PocDoc-API | api.py | api.py | py | 2,065 | python | en | code | 2 | github-code | 13 |
17521164587 | from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from scipy.stats import norm
import seaborn as sns
import textwrap
def ConductAnomalyDetection(dataframe,
list_of_predictor_variables,
anomaly_threshold=0.95,
... | KyleProtho/AnalysisToolBox | Python/DataProcessing/ConductAnomalyDetection.py | ConductAnomalyDetection.py | py | 4,936 | python | en | code | 0 | github-code | 13 |
39109969402 | import time, pickle
from asynch_mb.logger import logger
from asynch_mb.workers_multi_machines.base import Worker
import ray
@ray.remote(num_cpus=3)
class WorkerPolicy(Worker):
def __init__(self, model_ps, policy_ps, name, exp_dir, n_itr, stop_cond):
super().__init__(name, exp_dir, n_itr, stop_cond)
... | zzyunzhi/asynch-mb | asynch_mb/workers_multi_machines/metrpo/worker_policy.py | worker_policy.py | py | 4,765 | python | en | code | 12 | github-code | 13 |
39373150746 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 4 12:25:15 2022
@author: admin
"""
import json
import pandas as pd
import numpy as np #We will use often for linear algebra, arras, etc.
import matplotlib.pyplot as plt
#Method 1 to read json data
json_file = open("loan_data_json.json")
data = json.load(... | emerk101/PythonandTableau | Blue_Bank.py | Blue_Bank.py | py | 4,266 | python | en | code | 0 | github-code | 13 |
13947324733 | # python3
'''
BugCam-run.py
BugCam monitors timelapse photography experiments.
It checks a Dropbox folder's pictures, and sends Slack messages if it
finds problems:
- No new picture in specified time period.
- Significantly different brightness from one picture to the next.
TO_DO
- Add apscheduler listener: https://a... | nataquinones/BugCam | BugCam-run.py | BugCam-run.py | py | 11,003 | python | en | code | 1 | github-code | 13 |
24306788924 | import pandas
import pathlib
import numpy
from os import listdir, stat, makedirs
from os.path import isfile, isdir, join, basename, exists
from itertools import chain
from scipy.stats import mannwhitneyu
from scipy.stats import shapiro
MINIMUM_COMMIT_NUMBER = 100
DATA_DIR = 'data'
CACHE_DIR = '__cache__'
HDF5_CAC... | kabinja/suit-smells-replication-package | data.py | data.py | py | 6,924 | python | en | code | 0 | github-code | 13 |
2345871027 | # 문자열 = 'hello world, my name is python'
# 정수 = 314
# 실수 = 3.14
# for i in 문자열:
# print(i, end=' ')
# i = 0
# while i < len(문자열):
# print(문자열[i], end=' ')
# i += 1
# 문제 : 문자열에서 알파벳 o 의 갯수를 알려주세요
문자열 = 'hello world, my name is python'
a = 0
for i in 문자열:
if i == 'o':
a += 1
print(a)
month ... | mymymymyyy/python_korea | day03_5.py | day03_5.py | py | 1,249 | python | ko | code | 0 | github-code | 13 |
14204585379 | import time
import os
import requests
import datetime
from bs4 import BeautifulSoup as Soup
from django.core.management.base import BaseCommand
from django.db import IntegrityError, OperationalError
import asyncio
import aiohttp
import logging
from server.utils import getRange
from server.models import Faculties, Grou... | rikkaar/Bonch-back | server/management/commands/parse.py | parse.py | py | 15,423 | python | ru | code | 0 | github-code | 13 |
7023627884 | from Help import *
from FileHelp import *
#################################################
# specific functions #
#################################################
def StoreData_toPath(Data : dict, filename : str, path="", sort_alphabetic=False):
if path:
filename = path_join(path, fi... | savejeff/ProjektPraktikum_TUD_AUT_QuadTorque | Python/FileModule.py | FileModule.py | py | 3,931 | python | en | code | 0 | github-code | 13 |
38668182440 | from constants import *
import techniques_app
import techniques_test
import copy
class Engine:
def __init__(self, board, test):
self.board = board
if not test:
self.solved = self.solve_app()
self.board = self.solved[0]
self.states = self.solved[1]
elif tes... | kamil20018/SudokuSolver | engine.py | engine.py | py | 1,763 | python | en | code | 1 | github-code | 13 |
37677087015 | import datetime
from openpyxl import load_workbook
from openpyxl.styles import NamedStyle, Alignment, Border, Side
# Playing with data in work schedule .xlsx
wb = load_workbook('shift_schedule1.xlsx')
ws1 = wb['Monday']
ws1['C2'] = datetime.date.today()
try:
date_style1 = NamedStyle(name='datetime', number_form... | AndreiRekaev/Python-practice | 100daysofcode/70-72 openpyxl/schedule_automation.py | schedule_automation.py | py | 1,572 | python | en | code | 0 | github-code | 13 |
16879822667 | from locale import MON_12
def rotate_matrix(m):
n = len(m)
for layer in range(n // 2):
start, end = layer, n - layer - 1
for i in range(start, end):
temp = m[layer][i]
m[layer][i] = m[n - i - 1][layer]
m[n - i - 1][layer] = m[n - layer - 1][n - i - 1]
... | melanietai/leetcode-practice | matrix/rotate_matrix.py | rotate_matrix.py | py | 1,784 | python | en | code | 0 | github-code | 13 |
4506651180 | """Test cases for the models module."""
import json
from typing import Any
import pytest
from haversine import Unit
from haversine import haversine
from helium_api_wrapper import DataObjects as DataObjects
from pytest_mock import MockFixture
from helium_positioning_api.DataObjects import Prediction
from helium_positi... | emergotechnologies/helium-positioning-api | tests/test_models.py | test_models.py | py | 2,385 | python | en | code | 7 | github-code | 13 |
36221409657 | #!/usr/bin/env python3
import csv
import sys
from datetime import datetime
with open(sys.argv[1], encoding='utf-8-sig') as csvfile:
reader=csv.reader(csvfile)
headers_line=next(reader)
headers=dict()
for i in range(len(headers_line)):
headers[headers_line[i]]=i
print('Date,Payee,Category... | Swandog/parse_ipass_csv | bin/parse.py | parse.py | py | 808 | python | en | code | 0 | github-code | 13 |
11583193939 | """Top level configurations for the app."""
import os
_BASEDIR = os.path.abspath(os.path.dirname(__file__))
# Autowaiter settings
BASE_URL = '127.0.0.1:5000'
# Filesystem
def guarantee_existence(dirs):
'''
For each directory in the given list, create it if it does not already exist
'''
for dirname i... | davidzheng814/auto-waiter | config.py | config.py | py | 1,225 | python | en | code | 0 | github-code | 13 |
30335891410 | import pandas as pd
from sklearn.model_selection import train_test_split
import joblib
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
print('Cargando archivo csv...')
data = pd.read_csv('./data/google_play_store_apps_reviews_training.csv')
data.head()
def pre... | damiancipolat/Python_emotional_analysis | app_reviews_english/model_generator.py | model_generator.py | py | 1,109 | python | en | code | 0 | github-code | 13 |
47006020464 | def aroonlow2(a1='Close',val1=None,df=None):
ar,df[ar]='Close_ah',None
e1=val1+1; s1=df[a1].shape[0]-1
for i in range(s1,e1,-1):
lis=df[a1][i-val1:i+1]
m1=max(lis)
for counter, value in enumerate(lis):
if (value==m1) :pos=counter
df[ar][i]=100*pos/val1
ya=(df[a1][200:s1]).ma... | aa3110/python-trading | biblio/trade/tmp/_t_aroonhigh2.py | _t_aroonhigh2.py | py | 481 | python | en | code | 1 | github-code | 13 |
29232286627 | from . import Customer
from . import Product
from . import Address
from . import Payment
from . import Quote
from . import Order
from .PaymentMethod import Eft as EftPayment
from .Config import Config
class Factory:
def __init__(self, dydb=None):
self.__dydb = dydb
def order_from_quote(self, quote: ... | Venus713/RPS | libs/models/mpc/Factory.py | Factory.py | py | 2,893 | python | en | code | 0 | github-code | 13 |
7092534837 | from typing import List
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
w=[0,0,0]
for v in nums:
w=[
w[0]+(v!=1),
min(w[:2])+(v!=2),
min(w)+(v!=3)
]
return min(w)
objeto = Solution()
... | alexandreborgmann/leetcode | SortingThreeGroups.py | SortingThreeGroups.py | py | 377 | python | en | code | 0 | github-code | 13 |
34030512339 | # Filename: q3_find_gcd.py
# Author: Justin Leow
# Created: 22/2/2013
# Modified: 22/2/2013
# Description: Uses a recursive function to compute gcd
##8
##5
def gcd(m,n):
if(m%n==0):
return n
else:
return gcd(n,m%n)
print(gcd(24,16))
print(gcd(255,25)) | JLtheking/cpy5python | practical04/q3_find_gcd.py | q3_find_gcd.py | py | 282 | python | en | code | 0 | github-code | 13 |
27110602819 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cryptapp', '0008_auto_20160116_1004'),
]
operations = [
migrations.CreateModel(
name='contact',
fiel... | aditi73/cryptic-mining | cryptapp/migrations/0009_contact.py | 0009_contact.py | py | 809 | python | en | code | 2 | github-code | 13 |
19000634905 | import csv
films = []
strikedOffFilms = {}
if __name__ == '__main__':
# CREATING LIST OF FILMS
print("Creating list of films... ", end='')
with open('films.txt', encoding="utf-8") as filmsFile:
for line in filmsFile:
films.append(line.strip())
print("Success")
# IMPORTING CSV..... | bchan061/bracket | reducer.py | reducer.py | py | 1,689 | python | en | code | 0 | github-code | 13 |
14793281123 | import pygame
class Shop:
def __init__(self):
self.image = pygame.image.load(r'img/Return_button.jpg')
self.pos = (0, 0)
self.image1 = pygame.image.load(r'img/Click.jpg')
self.pos1 = (50, 100)
self.image2 = pygame.image.load(r'img/yron_v_second.jpg')
self.... | Anakkobitskaya/click | Shop.py | Shop.py | py | 1,412 | python | en | code | 0 | github-code | 13 |
13613939580 | class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def merge(self, intervals):
if len(intervals) == 0:
return []
check_point = []
for interval in intervals:
check_point.append((interv... | clovery410/mycode | leetcode_review/56merge_intervals.py | 56merge_intervals.py | py | 857 | python | en | code | 1 | github-code | 13 |
39182440691 | from django.urls import path
from .views import (
GradeView,
SubjectCreateView,
SubjectEditView,
ChaptersCreateView,
ChapterEditView,
ChapterListView,
SubjectListView,
QuestionCreateView,
QuestionEditView,
QuestionList,
QuestionPaperView,
frquestion,
load_subject_ch... | santhiya107/school | academics/urls.py | urls.py | py | 1,292 | python | en | code | 0 | github-code | 13 |
33346604050 | class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
domain_counts= collections.defaultdict(int)
for domains in cpdomains:
score, _, domain = domains.partition(' ')
score = int(score)
domain_counts[domain] += score
... | BradleyGenao/LeetCode-Solutions | subdomain-visit-count/subdomain-visit-count.py | subdomain-visit-count.py | py | 629 | python | en | code | 0 | github-code | 13 |
40131214450 | from collections import deque as dq
import copy
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
#그래프 그리기
graph = [[-1 for _ in range(n + 2)]]
for i in range(m):
tmp = [-1]
for j in range(n):
tmp.append(0)
tmp.append(... | dlwlstks96/codingtest | LeetCode/62_Unique Paths.py | 62_Unique Paths.py | py | 1,229 | python | en | code | 2 | github-code | 13 |
29403849533 | import requests
# 获取请求的URL
url = "http://127.0.0.1:9000/api/mgr/sq_mgr/"
# 获取请求头信息, 以 字典 的格式来传递
header = {"Content-Type": "application/x-www-form-urlencoded"}
# 获取请求参数, 以字符串的格式传递
payload = 'action=modify_course&id=5724&newdata={"name":"初中化学","desc":"初中化学课程","display_idx":"4"}'
# 模拟发送put请求,requests库调用put()方法模拟发送请求
r... | testzhaoxudong/API_atuo_day1 | 模拟put请求_请求参数以字符串的格式传递.py | 模拟put请求_请求参数以字符串的格式传递.py | py | 701 | python | zh | code | 0 | github-code | 13 |
17059477194 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.BoxExclusiveBase import BoxExclusiveBase
from alipay.aop.api.domain.BoxOrderStatusInfo import BoxOrderStatusInfo
from alipay.aop.api.domain.BoxExclusiveKeyword import BoxExclusiveKe... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/SearchBrandBoxInfo.py | SearchBrandBoxInfo.py | py | 8,604 | python | en | code | 241 | github-code | 13 |
7855332654 | # -*- coding: utf-8 -*-
import shutil
from pathlib import Path
dir_icons = Path(__file__).absolute().parent.joinpath("icons")
dir_asset = Path("/Users/sanhehu/Downloads/Asset-Package_01312023.d59bb3e1bf7860fb55d4d737779e7c6fce1e35ae")
dir_service =[path for path in dir_asset.iterdir() if path.name.startswith("Archite... | MacHu-GWU/aws_icons-project | move.py | move.py | py | 1,050 | python | en | code | 0 | github-code | 13 |
396465681 | #Para seguir colaborando en esta misión de salvar al planeta, necesitamos que elabores
# un programa en Python que dado el tamaño de un pez indique si su organismo está
# contaminado. Para ello tendremos 4 opciones:
#Tamaño Normal: Mensaje "Pez en buenas condiciones"
#Tamaño por debajo de lo Normal: Mensaje "Pez co... | AndreaF5rnandez/Python | Condicionales/Ejer2.py | Ejer2.py | py | 1,033 | python | es | code | 0 | github-code | 13 |
5647461545 | import plyvel
import os
username = os.environ['USERNAME']
# get the machine name from windows environment variables
machine_name = os.environ['COMPUTERNAME']
# C:\Users\alex.fielder\AppData\Local\Microsoft\Edge\User Data\Profile 4\Local Storage\leveldb
# leveldb_data_path = 'C:/Users/' + username + '/AppData/Local/Mic... | AlexFielder/Scripts | CmdLine/DedupeAndGroupOneTab.py | DedupeAndGroupOneTab.py | py | 1,111 | python | en | code | 2 | github-code | 13 |
4122126635 |
import base64
import sys, neat, math, time, sqlite3
from matplotlib import pyplot as plt
import pygame as py
# constant variables
screen_size = [1280, 720]
border_colour = (255, 255, 255, 255)
car_size_x = 35
car_size_y = 35
class Car:
def __init__(self):
self.sprite = py.image.load('sr... | jayCleverly/Neural-Cars | src/main/sim/simulations.py | simulations.py | py | 12,540 | python | en | code | 1 | github-code | 13 |
4122930755 | import torch
from torch_geometric.loader import DataLoader
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support
from sklearn.metrics import accuracy_score, f1_score,roc_auc_score,classification_report
import os, pickle
import time
from datetime import datetime
def joint_loss(opt,outputs,labels... | dswang2011/DocGraph4LM | src/GNNs/trainer.py | trainer.py | py | 8,271 | python | en | code | 0 | github-code | 13 |
28250132556 | import asyncio
TAX_RATE = 0.05
COMBO_DISCOUNT = 15 # in %
class Order:
def __init__(self, inventory):
self.inventory = inventory
self.items = {
"Burgers": {"quantity": 0},
"Sides": {"quantity": 0},
"Drinks": {"quantity": 0},
}
self.subtotal = 0
... | avk-ho/programming_exp | python/projects/async_point_of_sale_system/order.py | order.py | py | 8,647 | python | en | code | 0 | github-code | 13 |
22765593874 | import json
from django.shortcuts import render
from django.views import View
from django.db import transaction
from django.http import JsonResponse
from django.db.models import Q
from boards.models import Board, Image
class BoardCreateView(View):
def post(self, request):
try:
... | jinatra/pedalgrade | boards/views.py | views.py | py | 2,986 | python | en | code | 0 | github-code | 13 |
38340279703 | #!/bin/env python
"""
This script fills up 10 rows of HTML table using the file
RowTemplate.html
with random values, currently.
"""
TEMPLATE = "RowTemplate.html"
PAGE_TEMPLATE = "NewbooTemplate.html"
PAGE_OUTPUT = "NewbooTabled.html"
def one_row(product_rank, product_image, product_link, product_name,
... | eddebc/deeps-server | gen_table.py | gen_table.py | py | 1,184 | python | en | code | 0 | github-code | 13 |
70220886418 | import numpy as np
import pandas as pd
import sys
import os
def write_ans(ans, ansfile):
print("Writing answer to %s" % ansfile)
import csv
with open(ansfile, "w") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["id", "label"])
for i in range(1, len(ans)+1):
wr... | timlee0119/NTU-Machine-Learning-2019 | income_prediction/best.py | best.py | py | 1,342 | python | en | code | 0 | github-code | 13 |
71276692178 | from __future__ import print_function # use Python 3.0 printing
'''Procedure'''
#1-5 N/A
'''Part 1: Conditionals'''
#6a. This returns true since the first part returns true and the second part
#returns true as well. Since the compound keyword being used is and, the final
#out put is true since true and true is ... | Anshul2004/pythonPer2_2018-2019 | 1.3.3/Kashyap_1.3.3.py | Kashyap_1.3.3.py | py | 3,813 | python | en | code | 0 | github-code | 13 |
16656700610 | import numpy as np
import matplotlib.pyplot as plt
import itertools
import fractions
from fractions import Fraction
from numpy import *
px = []
py = []
def perp( a ) :
b = empty_like(a)
b[0] = -a[1]
b[1] = a[0]
return b
def seg_intersect(a1,a2, b1,b2) :
da = a2-a1
db = b2-b1
dp = a1-b1... | recap/pizza-cutting | random_pizza_cuts.py | random_pizza_cuts.py | py | 4,425 | python | en | code | 0 | github-code | 13 |
33164100920 | import mysql.connector
mydb = mysql.connector.Connect(
host = "localhost",
port = 3306,
user = "root",
password = "",
database = "giveaway"
)
mycursor = mydb.cursor()
def write_user(val):
sql = "insert into users_bot(name,surname,age,city,address,phonenumber,email) values(%s,%s,%s,%s,%s,%s,%s)... | AmanmyrzaZhussipkhan/abaigiveawaybot | venv/include/finals.py | finals.py | py | 2,099 | python | en | code | 0 | github-code | 13 |
12110985283 | '''
占位符的使用
'''
import tensorflow as tf
plhd = tf.placeholder(tf.float32,[None,3]) #N行3列
data = [[1,2,3],
[4,5,6],
[7,8,9]]
#执行占位符时,必须传入具体数据,否则报错
with tf.Session() as sess:
print(sess.run(plhd,feed_dict={plhd:data}))
| 15149295552/Code | Month06/day15/08_placeholder.py | 08_placeholder.py | py | 297 | python | en | code | 1 | github-code | 13 |
39217510132 | from feature_extraction import Featurizer
from model import Model
from sleeptor import Sleeptor
import pandas as pd
from keras.models import load_model
def main():
featurizer = Featurizer()
train = False
if(train):
images, labels = featurizer.extrac_images()
print(images.shape)
prin... | jsanch81/Sleeptor2 | main.py | main.py | py | 716 | python | en | code | 0 | github-code | 13 |
71179041938 | #!/usr/bin/env python3
import argparse
import os
import subprocess
import yaml
import sys
import re
import json
# Arguments section
parser = argparse.ArgumentParser()
parser.add_argument('template', help='yaml template describing the project',
default='template.yaml')
parser.add_argument('--dst-dir', help='the de... | Kaskeeeee/ts-project-initializer | ts-project-init.py | ts-project-init.py | py | 4,988 | python | en | code | 0 | github-code | 13 |
16129259053 | #!/usr/bin/python
"""
Purpose: Reading(Parsing) XML
"""
from pprint import pprint
try:
import untangle
except ModuleNotFoundError as ex:
print(repr(ex))
from os import system
system("pip install untangle --user")
import untangle
obj = untangle.parse("books.xml")
# print(obj)
# print(dir(obj))
# ... | udhayprakash/PythonMaterial | python3/11_File_Operations/02_structured_files/02_xml/01_xml/f_parse_xml.py | f_parse_xml.py | py | 596 | python | en | code | 7 | github-code | 13 |
74880943058 | import pytest
import seismic_zfp
import segyio
SGZ_FILE = 'test_data/small_4bit.sgz'
SGY_FILE = 'test_data/small.sgy'
def test_read_trace_header():
with seismic_zfp.open(SGZ_FILE) as sgzfile:
with segyio.open(SGY_FILE) as sgyfile:
for trace_number in range(-5, 25, 1):
sgz_head... | equinor/seismic-zfp | tests/test_header-accessors.py | test_header-accessors.py | py | 1,416 | python | en | code | 57 | github-code | 13 |
40131464620 | # -*- coding: utf-8 -*-
from collections import deque as dq
n, m = map(int, input().split())
idxList = list(map(int, input().split()))
# n, m = 10, 10
# idxList = [1, 6, 3, 2, 7, 9, 8, 4, 10, 5]
q = [0 for _ in range(n)]
q = dq(q) #deque 선언
for i in idxList:
q[i-1] = i
moveCount = 0
for target in idxLi... | dlwlstks96/codingtest | 백준/자료구조_1021_회전하는 큐.py | 자료구조_1021_회전하는 큐.py | py | 1,958 | python | ko | code | 2 | github-code | 13 |
26053209548 | """
学籍:1213033903
氏名:玉城洵弥
内容:オイラー
"""
import matplotlib
import matplotlib.pyplot as plt
from math import *
def draw(x, y, a, b):
fig = plt.figure()
graph = fig.add_subplot()
graph.plot(x, y)
graph.plot(a, b)
graph.scatter(x, y, s=30)
plt.show()
def f1(t, Y1, Y2):
return Y2
def f2(t, ... | gusuku-oknw/Numerical_analysis | 094.Eular.py | 094.Eular.py | py | 974 | python | en | code | 0 | github-code | 13 |
22654989229 | from datetime import timedelta
import requests
import pandas as pd
import logging
from azure.storage.blob import BlobServiceClient
from azure.core.exceptions import AzureError
from io import StringIO
import credentials
from s3connector import azure_connection_string
import timeit
start_time = timeit.default_timer()
#... | ernestprovo23/algov5 | commodities/company_overviews.py | company_overviews.py | py | 4,475 | python | en | code | 0 | github-code | 13 |
17028421055 |
def GreedySearch(SymbolSets, y_probs):
"""Greedy Search.
Input
-----
SymbolSets: list
all the symbols (the vocabulary without blank)
y_probs: (# of symbols + 1, Seq_length, batch_size)
Your batch size for part 1 will remain 1, but if you plan to use your
... | sabrinazhong98/CMU-Deep-Learning | hw3p1/mytorch/search.py | search.py | py | 8,135 | python | en | code | 1 | github-code | 13 |
72626135378 | import argparse
import torch
from torchvision import datasets, transforms
from sklearn.metrics import roc_curve, auc
import os
import numpy as np
import matplotlib.pyplot as plt
import MVTec_loader as mvtec
from gradcam import GradCAM
# for dataloader check: pin pin_memory, batch size 32 in original
mean = 0.
... | Ikea-179/Interpretable-Visual-Anomaly-Detection | Stage2 Model & Experiment/Data Augmentation/mean.py | mean.py | py | 1,271 | python | en | code | 1 | github-code | 13 |
37526433655 | #!/usr/bin/env python3
"""===============================================================================
FILE: forhabits/kostil/calorie-mate.py
USAGE: ./forhabits/kostil/calorie-mate.py
DESCRIPTION:
OPTIONS: ---
REQUIREMENTS: ---
BUGS: ---
NOTES: ---
AUTHOR: Alex Leontiev... | nailbiter/pyassistantbot2 | calorie-mate.py | calorie-mate.py | py | 915 | python | en | code | 0 | github-code | 13 |
18252925094 | import cv2
import numpy as np
img = cv2.imread('xray.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_gaussian = cv2.GaussianBlur(gray, (3, 3), 0)
kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])
kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
img_prewittx = cv2.filter2D(img_gaussian, -1,... | arilumintang/Python-Image-Processing-using-opencv | Program/prewitOperator.py | prewitOperator.py | py | 593 | python | en | code | 1 | github-code | 13 |
24089412710 | """Unit tests for wordpress_rest.py."""
import urllib.request, urllib.parse, urllib.error
from flask import get_flashed_messages
from oauth_dropins.webutil.util import json_dumps, json_loads
from oauth_dropins.wordpress_rest import WordPressAuth
from werkzeug.routing import RequestRedirect
from flask_app import app
f... | snarfed/bridgy | tests/test_wordpress_rest.py | test_wordpress_rest.py | py | 6,874 | python | en | code | 649 | github-code | 13 |
18480657996 | # -*- coding: utf-8 -*-
"""
Created 20.01.2021
@author: Gustavo Hernandez-Mejia
"""
from funct_shifts_sympt_wall import *
import matplotlib.pyplot as plt
# import math
# from pylab import *
# from mpl_toolkits.mplot3d import axes3d
import numpy as np
import pandas as pd
import random
# from matplotl... | GustavoHdezM/Parallel_test | shifts_sympt_wall.py | shifts_sympt_wall.py | py | 22,889 | python | en | code | 0 | github-code | 13 |
23728078655 | import cv2
import os
from datetime import datetime
class TimelapseEngine:
def __init__(self, output_directory: str,
resolution_width: int = 1920, resolution_height: int = 1088,
number_of_ramp_frames: int = 150):
self._cap = cv2.VideoCapture(0)
self._num_of_ramp_fr... | esceer/timelapse-script | src/utils/timelapse.py | timelapse.py | py | 3,031 | python | en | code | 0 | github-code | 13 |
6636281330 | import inflect
def main():
names = get_names()
p = inflect.engine()
print("Adieu, adieu, to ", end="")
print(p.join(names))
def get_names():
list_names = []
while True:
try:
list_names.append(input("Name: "))
except EOFError:
print()
ret... | Larfie/CS50 | adieu/adieu.py | adieu.py | py | 342 | python | en | code | 1 | github-code | 13 |
10038334907 | import smtplib
from email.mime.text import MIMEText
body = "This is a test email. How are you?"
msg = MIMEText(body)
msg['From'] = "alaminsrk3@gmail.com"
msg['To'] = "noonesp86@gmail.com"
msg['Subject'] = "Hello"
server = smtplib.SMTP('smtp.gmail.com', 587)
# for secured connection
server.starttls()
server.login("... | parvez86/PythonLearn | networking/emailclient.py | emailclient.py | py | 422 | python | en | code | 0 | github-code | 13 |
22102393292 | from collections import deque
from typing import Union, List
import torch
from torch import nn
from torch.distributions import Categorical
import torch.nn.functional as F
from agents.a2c import A2CAgent
from configs import Config
from utils import to_one_hot
class A2CAgentSwim(A2CAgent):
def __ini... | Jlevan25/rl | agents/a2c_poolswim.py | a2c_poolswim.py | py | 4,447 | python | en | code | 0 | github-code | 13 |
24632814419 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import ruamel.yaml
class Database(dict):
yaml = ruamel.yaml.YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
def __init__(self, filename, default={}):
self.filename = filename
if not os.path.isfile(filename):
... | artemk1337/NetflixShareBot | database.py | database.py | py | 686 | python | en | code | 0 | github-code | 13 |
7734928356 | import xlrd
from common import models
def load(filename, version, volume, rootname):
vol = models.BookVolume.objects.get(name=volume, version__name=version)
wb = xlrd.open_workbook(filename)
sheet = wb.sheets()[0]
root = models.CourseTree.objects.create(volume=vol, name=rootname, level=0)
parent_... | fishmacs/yhbbg | bookbag/portal/coursetree.py | coursetree.py | py | 1,334 | python | en | code | 0 | github-code | 13 |
6948929184 | from typing import *
class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
idx=0
tem=0
res=[]
while idx<len(target):
tem+=1
res.append('Push')
while tem!=target[idx]:
res.append('Pop')
tem+=1
... | Xiaoctw/LeetCode1_python | 栈/用栈操作构建数组_1441.py | 用栈操作构建数组_1441.py | py | 503 | python | en | code | 0 | github-code | 13 |
29436952478 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import List
def convert_to_absolute(number: float) -> float:
return number if number > 0 else number * -1 # Connaitre cette syntaxe pour l'examen (peut-être demandé)
def use_prefixes() -> List[str]:
prefixes, suffixe = 'JKLMNOPQ', 'ack'
List = ... | INF1007-2021A/c03_ch5_exercices-sebroy-6 | exercice.py | exercice.py | py | 3,477 | python | en | code | 0 | github-code | 13 |
71254488017 | import requests # pip install requests
import json
from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field, validator # pip install pydantic
from tenacity import retry, stop_after_attempt, wait_fixed # pip install tenacity
fr... | eykamp/deq_tools | deq_tools/__init__.py | __init__.py | py | 7,701 | python | en | code | 0 | github-code | 13 |
39130112036 | import json
from os import PathLike
from pathlib import Path
from typing import Dict, Type, Union
import yaml
from ...models.archive import ThreadInfo
from .archive import LocalArchive
from .detect import detect_archive_version
from .v2 import AV2LocalArchive, av2_load_threadInfo_json, av2_load_users_json
from .v3 im... | 283375/tieba-thread-archive | src/tieba_thread_archive/local/archive/load.py | load.py | py | 1,912 | python | en | code | 2 | github-code | 13 |
73111810257 | import math
# 5
# Write a function that accepts string from user and print all permutations of that string.
print("!!!TASK 5!!!")
from itertools import permutations
def find_permutations(str):
char_list = [str[i] for i in range(0, len(str))]
char_list.sort()
prms = permutations(char_list)
for permutat... | Amayakof/PP2 | lab3/functions/5.py | 5.py | py | 389 | python | en | code | 0 | github-code | 13 |
37867006400 | from django.urls import include, path, re_path
from django.views.generic import TemplateView
from auth_users.views import current_user, change_user_data
urlpatterns = [
path('auth/', include('djoser.urls')),
path('auth/', include('djoser.urls.jwt')),
path('auth/', include('djoser.social.urls')),
path(... | jorgemustafa/gerenciador-de-investimentos | auth_users/urls.py | urls.py | py | 662 | python | en | code | 0 | github-code | 13 |
16027445054 | # 배열최소합
# SWEA 난이도 D3
# N x N 배열
# N 개의 숫자를 골라 합이 최소가 되도록
# 세로로 같은 줄에서 두 개 이상의 숫자를 고를 수 없다.
# 인덱스 배열을 받아 각 줄마다 인덱스 요소들의 합을 반환하는 함수
def select_sum(nums, graph):
total = 0
for row, i in enumerate(nums):
total += graph[row][i]
return total
def dfs(depth, n, visited, nums, graph):
global answer
... | joonann/ProblemSolving | python/202308/16/배열최소합.py | 배열최소합.py | py | 1,046 | python | ko | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.