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
2311755172
import logging import pathlib import requests import os from pathlib import Path from typing import Dict from PIL.Image import Image from result import Result, Ok, Err, Some from definitions import EXT_API_SAVE_QUOTE_URL, EXT_API_OUTPUT_URL from models import ImRequest _logger = logging.getLogger(__name__) class ...
lcapuano-app/quote-image-generator
src/imquote/qt_im_utils.py
qt_im_utils.py
py
3,700
python
en
code
0
github-code
6
32148869393
#!/bin/python3 import math import os import random import re import sys # Complete the rotLeft function below. def rotLeft(a, d): vestige = a[:d] append = a[d:] print(vestige) print(append) append.reverse() for ele in append: vestige.insert(0,ele) return vestige if __name__ ==...
mihirp1/HackerRank_Algorithms_Problems
arrays-leftrotation/solution.py
solution.py
py
609
python
en
code
0
github-code
6
34181662048
import json import time from collections import defaultdict current = 2370 maxGame = 2426 import datetime import matplotlib.pyplot as plt MERCY_ULT_TIME = 20 from pathlib import Path ult_timers = { 'doomfist':4, 'genji':6, 'mccree': 6, 'pharah': 3, 'reaper': 3, 'soldier':6, 'mercy':6, '...
Cheraws/AnalyzingOWL
stat_collector.py
stat_collector.py
py
14,816
python
en
code
0
github-code
6
43972979596
import argparse import re # CPT tools from wp_tools import CPTLink def parse_inputs(text,file,galaxy_mode=False): """ Parses the inputs of a text box and new line separated pacc file """ accs = [] if text: if re.search(("__cn__"),str(text[0])): acc = text[0] spli...
TAMU-CPT/galaxy-tools
tools/wp_analysis/wp_data.py
wp_data.py
py
3,447
python
en
code
5
github-code
6
30153335935
# -*- coding: utf-8 -*- """ Created on Sun Mar 19 11:52:30 2023 @author: moureaux pierre """ import numpy as np from abc import ABC, abstractmethod from numpy import linalg as LA """The abstract finite difference class""" class FiniteDifferences(object): def __init__(self, r0, T, sigma, alpha, beta,...
PierreMoureaux/Securities-finance-derivatives---Wilmott-s-program-of-study-Finite-difference
6 - TRS on Bonds and interest rate dependencies/Python code/TRS on Bond.py
TRS on Bond.py
py
7,469
python
en
code
0
github-code
6
37016298011
"""ASE LAMMPS Calculator Library Version""" from __future__ import print_function import os import ctypes import operator import sys import numpy as np from numpy.linalg import norm from lammps import lammps from ase.calculators.calculator import Calculator from ase.data import atomic_masses from ase.atoms import s...
libAtoms/pymatnest
lammpslib.py
lammpslib.py
py
38,515
python
en
code
26
github-code
6
39672826344
import protocol import pytest class TestBitstream: @pytest.mark.parametrize( "s,val", [ ("", []), ("1", [0x10000000]), ("01", [0x01000000]), ("0102", [0x01020000]), ("0102030405", [0x01020304, 0x05000000]), ], ) def test_...
cmatsuoka/aoc
2021 - submarine/16 - bitstream protocol/test_protocol.py
test_protocol.py
py
1,376
python
en
code
0
github-code
6
21998646716
from typing import List from collections import defaultdict class Solution: def countPairs(self, deliciousness: List[int]) -> int: maxsum = max(deliciousness) * 2 pairs = 0 dd = defaultdict(int) for i in deliciousness: s = 1 while s <= maxsum: ...
hangwudy/leetcode
1700-1799/1711. 大餐计数.py
1711. 大餐计数.py
py
456
python
en
code
0
github-code
6
22083768955
def DisappearanceOfIntegers (A, Q, M, t, N): out=[] en=N//2 on=N-en for x in range(Q): time=t[x]%(2*N) pos=M[x] if time==0: ans=pos elif time==N: ans=-1 elif time<N: if time<=on: if pos<=time: ...
vamshipv/code-repo
NOKIA/4.py
4.py
py
1,144
python
en
code
0
github-code
6
2375158470
class Employee: def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary def __str__(self): return f"{self.name}, {self.age}, {self.salary}" class EmployeesManager: def __init__ (self): self.employees = [] def add_new_e...
mariamelwirish/Employee_System
Employees System.py
Employees System.py
py
4,002
python
en
code
0
github-code
6
42063972724
import mysql.connector from mysql.connector import Error # Configuración de la conexión a MySQL config = { 'user': 'root', 'password': 'Mafer159159', 'host': 'localhost', } try: connection = mysql.connector.connect(**config) if connection.is_connected(): cursor = connection.cursor() cursor.exe...
maferfarfan21/Juegos
flask/crud/main.py
main.py
py
1,308
python
es
code
0
github-code
6
20844744315
import os import random from PIL import Image from torch.utils.data import Dataset from torchvision import transforms class Images(Dataset): def __init__(self, folder, size, is_training, downsample=False, preload=False): """ I assume that all images in the folder have size at least `size`...
TropComplique/SRFeat-pytorch
input_pipeline.py
input_pipeline.py
py
2,160
python
en
code
0
github-code
6
23308286546
import stanza from headline_retriever import load_articles, collect_articles, save_articles from textblob import TextBlob from datetime import date NLP = stanza.Pipeline(lang='en', processors='tokenize,mwt,pos,lemma,ner') END_DATE = date(2020, 3, 27) # the chosen last day to retrieve article headlines # in place m...
NoahBlume/nlp_project
pre_processor.py
pre_processor.py
py
2,997
python
en
code
0
github-code
6
9803009738
from __future__ import division from pydub.utils import make_chunks import re import sys from google.cloud import speech import pyaudio from six.moves import queue from io import BytesIO from pydub import AudioSegment from multiprocessing import Process # You can choose voices from https://cloud.google.com/text-to-spe...
EHowardHill/speak-easy
basic-runtime.py
basic-runtime.py
py
7,631
python
en
code
0
github-code
6
31406415884
''' Emily Lee SoftDev1 pd6 K#25 -- Getting More REST 2018-11-15 ''' import json import urllib.request from flask import Flask,render_template app=Flask(__name__) @app.route("/") def Hello_world(): url_stub="http://www.asterank.com/api/skymorph/search?target=" target="J99TS7A" req=urllib.request.url...
ecrystale/leeE
25_rest/app.py
app.py
py
628
python
en
code
0
github-code
6
17915780851
import smtplib import re import sys import getpass import random import math import time import os from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.header import Header import socket socket.setdefaulttimeout(10) """ created by sayansree paria verson<1....
Sayansree/email_spammer
spammer1.0.py
spammer1.0.py
py
3,987
python
en
code
0
github-code
6
4964092483
import math def gap(g, m, n): b_prime = 0 for i in range(m,n): if isPrime(i): if(i - b_prime) == g: return [b_prime, i] b_prime = i return None def isPrime(n): for i in range(2,int(math.sqrt(n)+1)): if n % i == 0: return False ret...
bluecloud1102/codility
code/gap_in_primes/gap_in_primes.py
gap_in_primes.py
py
328
python
en
code
0
github-code
6
44673837506
from ListasRefNodoFinalAbstract import ListaRefNodoFinalAbstract from Nodo import Nodo class ListaRefNodoFinal(ListaRefNodoFinalAbstract): def __init__(self): self.inicio= None self.fin = None self.cuantos=0 #Metodo que egresa true si la lista esta vacia y false en otro...
MichelleeD/Tarea-3-DBM
ListasRefNodoFinal.py
ListasRefNodoFinal.py
py
4,135
python
es
code
0
github-code
6
37756152880
i=int(input("Enter the number:")) a=i sum=0 while i>0: sum=sum+(i%10)*(i%10)*(i%10) i=i//10 if a==sum: print(a,"is armstrong number") else: print(a,"is not armstrong number") # 0,1,153,370,371,407
Bhavana-thakare/loop
Armstrong numbers.py
Armstrong numbers.py
py
222
python
en
code
0
github-code
6
42420664031
import requests, json url = 'https://sandbox.techops.engineering/Demand/v1/Surveys/BySurveyNumber/4592039' params = "" headers = {'Content-type': 'application/json', 'Authorization' : 'YOUR_API_KEY_HERE', 'Accept': 'text/plain'} response = requests.get(url, data=params, headers=headers) print(response.content.decode()...
ajay-ar30/lucidcodesproject
week5/survey_get.py
survey_get.py
py
398
python
en
code
0
github-code
6
74553900026
# Exam 1 Practice #6/11/2017 #In this program I will write a program that helps calculate #the shipping charges for a shipping company #First, Define the main function and greet the user def main(): print('Hello, this is the Fast Freight Shipping Company') print('This program will help you calculate the cost o...
BijanJohn/Python
ACC/Exam_1_review_shipping_charges.py
Exam_1_review_shipping_charges.py
py
894
python
en
code
0
github-code
6
14468056163
''' A binary tree is given such that each node contains an additional random pointer which could point to any node in the tree or null. Return a deep copy of the tree. The tree is represented in the same input/output way as normal binary trees where each node is represented as a pair of [val, random_index] where: va...
loganyu/leetcode
problems/1485_clone_binary_tree_with_random_pointer.py
1485_clone_binary_tree_with_random_pointer.py
py
3,196
python
en
code
0
github-code
6
25945686355
#!/usr/bin/env python # coding=utf-8 # author = ruiruige # email = whx20202@gmail.com import web from jx3wj.common.rest.rest_base import resources from jx3wj.common.rest.dto.dto import deco_dump_to_str from jx3wj.common.log import log as logging from jx3wj.common.db.crud import select from jx3wj.common.db.do.item imp...
ruiruige/myifttt
myifttt/mgmt/items/items.py
items.py
py
1,893
python
en
code
1
github-code
6
5834659983
from rick.filter import registry as filter_registry, Filter import inspect TYPE_FIELD = 1 TYPE_RECORD = 2 TYPE_RECORDSET = 3 def field(**kwargs): """ Spec wrapper for Field :param type: str field type :param label: str field label :param value: optional predefined value :param required: bool...
oddbit-project/rick
rick/form/field.py
field.py
py
4,282
python
en
code
0
github-code
6
5086805014
DOCUMENTATION = ''' --- module: cisco_asa_network_objectgroup author: Patrick Ogenstad (@networklore) version: 1.0 short_description: Creates deletes or edits network object-groups. description: - Configures network object-groups requirements: - rasa options: category: description: - Th...
networklore/ansible-cisco-asa
library/cisco_asa_network_objectgroup.py
cisco_asa_network_objectgroup.py
py
10,509
python
en
code
30
github-code
6
31365864132
from propagator import scheduler from propagator import Propagator, Cell from propagator.primitives import * from propagator.content.interval import Interval from propagator.content.supported import Supported from propagator.decorators import compound from propagator.logging import debug, warn, error, info """ A propa...
duasfl8r/propagator.py
examples/dependencies.py
dependencies.py
py
5,062
python
en
code
32
github-code
6
39607784723
import os import logging from django.core.management.base import BaseCommand from django.core.management.base import CommandError from core import batch_loader from core.management.commands import configure_logging configure_logging('process_coordinates_logging.config', 'process_coordinates_%s.log'...
open-oni/open-oni
core/management/commands/process_coordinates.py
process_coordinates.py
py
1,291
python
en
code
43
github-code
6
27064968458
from .common import * import os DEBUG = True MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR,"media/") STATIC_ROOT = os.path.join(BASE_DIR,"sfiles/") STATICFILES_DIRS = (os.path.join(BASE_DIR,"static/"),) TIME_ZONE = "Asia/Kolkata" ALLOWED_HOSTS = ["127.0.0.1","admin.as.com","api.as.com","192.168.0.6","192.1...
digivaarta/efs_backend
src/settings/dev.py
dev.py
py
5,762
python
en
code
0
github-code
6
37681986889
# from IPython.display import clear_output # Starting game def play_game(): play = None while play not in ['Y', 'N']: play = input('Play Game? (Y / N) ').upper() if play == 'Y': return True return False # Players selecting symbols to play X or O def select_symbol(): # clear_output() print(chr(27)+'[2j...
paul-b19/python-tic-tac-toe
tic_tac_toe.py
tic_tac_toe.py
py
2,279
python
en
code
0
github-code
6
20594488232
import torch import torch.nn as nn def domain_loss(visual_domain_logits, textual_domain_logits): criterion = nn.CrossEntropyLoss() batch_size = visual_domain_logits.shape[0] visual_domain_labels = torch.zeros(batch_size).long().cuda() textual_domain_labels = torch.ones(batch_size).long().cuda() lo...
CCNU-DigitalLibrary/CCNU-DigitalLibrary
MCM-HC/lib/models/losses/domain_loss.py
domain_loss.py
py
467
python
en
code
0
github-code
6
15892112680
from argparse import ArgumentParser import os import logging from sys import stdin, stdout import yaml import gc import torch from probing.inference import Inference class NotAnExperimentDir(ValueError): pass def find_last_model(experiment_dir): model_pre = os.path.join(experiment_dir, 'model') if os....
juditacs/probing
src/probing/batch_inference.py
batch_inference.py
py
4,385
python
en
code
3
github-code
6
26466276605
""" This file contains Arm interface and its implemented classes. Users (typically Bandits) interact with Arms through the pull() method, which: - returns a reward value - advances state of the arm's parameters (if valid) """ import numpy as np class Arm: """ A bandit arm Should keep track of ...
solstat/bandits
arm.py
arm.py
py
2,980
python
en
code
0
github-code
6
3989607811
from typing import Any, Dict, List, Self, Union from attrs import define as _attrs_define from attrs import field as _attrs_field from ..constants.trading import ( ConditionalCloseOrderType, OrderType, SelfTradePreventionStrategy, TimeInForce, Trigger, TypeOrder, ) from ..security import get_n...
tlg7c5/kraken-connector
kraken_connector/schemas/add_standard_order_request_body.py
add_standard_order_request_body.py
py
13,908
python
en
code
0
github-code
6
19382433412
"""Support for Atome devices connected to a Linky Energy Meter.""" import asyncio from .const import DATA_COORDINATOR, DOMAIN PLATFORMS = ["sensor"] DATA_LISTENER = "listener" async def async_setup(hass, config): """Set up the KeyAtome component.""" # hass.data[DOMAIN] = {DATA_COORDINATOR: {}, DATA_LISTENE...
jugla/keyatome
custom_components/keyatome/__init__.py
__init__.py
py
1,759
python
en
code
22
github-code
6
36341347314
# 한 개의 회의실이 있는데 이를 사용하고자 하는 N개의 회의에 대하여 회의실 사용표를 만들려고 한다. # 각 회의 I에 대해 시작시간과 끝나는 시간이 주어져 있고, 각 회의가 겹치지 않게 하면서 회의실을 사용할 수 있는 회의의 최대 개수를 찾아보자. # 단, 회의는 한번 시작하면 중간에 중단될 수 없으며 한 회의가 끝나는 것과 동시에 다음 회의가 시작될 수 있다. # 회의의 시작시간과 끝나는 시간이 같을 수도 있다. 이 경우에는 시작하자마자 끝나는 것으로 생각하면 된다. # 그리디 알고리즘을 이용 import sys N = int(sys.stdin.readli...
jujinyoung/CodingTest
bakjjun_codingTest/1931.py
1931.py
py
1,022
python
ko
code
0
github-code
6
11032880428
#Знакомство с языком Python (семинары). Урок 3. Данные, функции и модули в Python # 4. Напишите программу, которая будет преобразовывать десятичное число в двоичное. # Пример: 45 -> 101101, 3 -> 11, 2 -> 10 import random decNumber = 2 #random.randint(0, 2**100) binNumber = str(bin(decNumber)).replace("0b", "") print...
VeraNic/Python-practic
Prac3_4DecToBin.py
Prac3_4DecToBin.py
py
485
python
ru
code
0
github-code
6
24639710236
import pandas as pd from matplotlib import pyplot as plt # plt.rcParams["figure.figsize"] = [12, 6] plt.rcParams.update({'font.size': 11}) plt.rcParams["font.family"] = "Times New Roman" ############################ Model 1 ####################3 resnet50 = pd.read_csv(r'Dataset/resnet50.csv') resnet50VAccu = resnet50...
Mehedi-Bin-Hafiz/Rotten-fruit-detection-by-deep-learning
Graph/lineGraph.py
lineGraph.py
py
842
python
en
code
1
github-code
6
9152769558
from django.urls import path from . import views urlpatterns = [ path('',views.Home.as_view(),name='Home'), path(r'stock/<str:Name>',views.Show_Details.as_view()), path('ajax/get-info',views.get_info), path('ajax/get-nifty',views.get_nifty), path('ajax/get-topstocks',views.get_topstocks), path('...
Pggeeks/Live-StockScrenner-Django
stockapp/urls.py
urls.py
py
379
python
en
code
1
github-code
6
21904300234
import os from pathlib import Path import click import numpy as np import tensorflow as tf from waymo_open_dataset.dataset_pb2 import Frame from waymo_open_dataset.utils import frame_utils, transform_utils, range_image_utils from waymo_open_dataset import dataset_pb2 from utils import save_frame, save_points from vis...
friskit-china/waymo-open-dataset-visualizer
main.py
main.py
py
11,384
python
en
code
1
github-code
6
23608824174
#Calculates the distance to the nearest massive galaxy def distance_to_nearest_host(data): distances = [] hostrvirs = [] for i in range(len(data)): s = data['sim'].tolist()[i] if s=='h148' or s=='h229' or s=='h242' or s=='h329': # if sat simulation, find distance to halo 1 ...
CharlotteRuth/python_analysis
distance_to_nearest_host.py
distance_to_nearest_host.py
py
2,633
python
en
code
0
github-code
6
89150854
# --usage: print usage def usage(): print('Usage: python3 marvin-data/marvin.py --building|--setup|--testing') exit(1) # --building: build the project def building(): import json import subprocess with open('project-data/definition.json', 'r') as json_file: with open('marvin-data/build_logs...
Lqvrent/SharedMarvin
Marvin/marvin.py
marvin.py
py
5,567
python
en
code
16
github-code
6
7167175651
T = int(input()) dp = [0, 0] * 41 dp[0] = [1, 0] dp[1] = [0, 1] N_List = [] for _ in range(T): N_List.append(int(input())) maxNum = max(N_List) for i in range(2, maxNum+1): dp[i] = [dp[i-2][0] + dp[i-1][0], dp[i-2][1] + dp[i-1][1]] # 바텀 업 for num in N_List: print(dp[num][0],dp[num][1])
donchanee/Algorithm-PS
백준/1003.py
1003.py
py
315
python
en
code
0
github-code
6
20501710133
from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger, TensorBoard, ReduceLROnPlateau from tensorflow.keras import layers, models fro...
aleksioprime/facerecognition
training_cnn.py
training_cnn.py
py
8,710
python
ru
code
0
github-code
6
25442839211
from src.server.server import Server import logging logger = logging.getLogger('fmu_logger') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s_%(name)s_%(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) class W...
jwayneroth/mpd-touch
web/web.py
web.py
py
607
python
en
code
5
github-code
6
8708427284
#/!/bin/python import struct import sys import binascii Signature = '\x89PNG\r\n\x1a\n' #fichier_source, fichier_cible, fichier_dest, cle_chiffrement, algo = sys.argv[1:6] fichier_source = 'date.txt' fichier_cible = 'ressource.PNG' fichier_dest = 'cyber.PNG' cle_chiffrement = 'test12345' algo = 'aes' i...
buzagi/projet-pong
1.py
1.py
py
1,547
python
fr
code
2
github-code
6
7055484203
from time import sleep from onvif import ONVIFCamera exec(open("./fix_zeep.py").read()) class Camera(object): def __init__(self, ip, login, password, port = 80): # Подключение self.mycam = ONVIFCamera(ip, port, login, password) # Создание сервиса для управления движением self....
Maden23/CameraAudioKeyboard
ptzcamera.py
ptzcamera.py
py
3,524
python
ru
code
1
github-code
6
26776110880
"""Exceptions interface. Exceptions allow for ignoring detected issues. This is commonly done to suppress false positives or to ignore issues that a group has no intention of addressing. The two types of exceptions are a list of filenames or regular expressions. If using filename matching for the exception it is requ...
sscpac/statick
statick_tool/exceptions.py
exceptions.py
py
10,625
python
en
code
66
github-code
6
71226766908
import unittest from typing import Optional from unittest import TestCase from parameterized import parameterized from robotlib.mathutils import Clipper, LinearExtrapolator class TestClipper(TestCase): @parameterized.expand([ # [min_value, max_value, x, expected_y] [-5, 10, 0, 0], [-5, 1...
austin-bowen/robotlib
test/python/robotlib_tests/test_mathutils.py
test_mathutils.py
py
3,217
python
en
code
0
github-code
6
33526660433
#Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta. abertos=0 fechados=0 expressão=input("Digite a expressão:") for c in expressão: if c=="(": abertos+=1 elif ...
cauavsb/python
mundo-3-py/ex12.py
ex12.py
py
470
python
pt
code
0
github-code
6
74221859388
# Thanks to Ethan (@sherbondy) for the awesome idea of using CSG! # Much slower than the other version, but it uses like 1/3 of the geometry # Refactored version. slightly slower but more readable. import bpy import mathutils bpy.ops.object.select_all(action='DESELECT') pos = bpy.context.scene.cursor_location bpy.o...
elfakyn/Blender-iterated-fractals
menger_csg2.py
menger_csg2.py
py
1,646
python
en
code
0
github-code
6
811951116
# Top View of Binary Tree # Given a pointer to the root of a binary tree, print the top view of the binary tree. # The tree as seen from the top the nodes, is called the top view of the tree. # For example : # 1 # \ # 2 # \ # 5 # / \ # 3 6 # \ # 4 # Top View : 1 2...
Saima-Chaity/Leetcode
Tree/TopViewOfBinaryTree.py
TopViewOfBinaryTree.py
py
882
python
en
code
0
github-code
6
8397560124
import copy import numpy as np from scipy.spatial.distance import cdist class Server: def __init__(self, parameters): super().__init__() self.k = parameters['kernel_size'] self.alpha = 1.0 self.d_out = parameters['d_out'] # centers, spreads, w and b can be broadcast to clie...
VeritasXu/FDD-EA
libs/Server.py
Server.py
py
3,052
python
en
code
7
github-code
6
33350944365
#%% import os import gc import sys import pickle from time import time import datatable as dt import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import torch import torch.nn as nn from torch import optim from sklearn.metrics import roc_auc_score from sklearn.model_selection i...
scaomath/kaggle-riiid-test
sakt/debug_sakt_2.py
debug_sakt_2.py
py
20,260
python
en
code
0
github-code
6
7874634889
import numpy as np import json import os import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D class LatentConverter(): def __init__(self, places_path): place_list = [] place2idx = {} with open(places_path, encoding='utf-8') as f: for p_idx, place in enumerate(json.load(f)): place = tu...
e841018/DinnerSelector
preprocessing/LSI.py
LSI.py
py
4,229
python
en
code
0
github-code
6
37078019949
end_points = ['.', '?', '!'] # 문장을 구별할 식별표(마침표, 물음표, 느낌표) def cnt_end_points(str): # 문장 개수 세는 함수 cnt = 0 for _ in str: if _ in end_points: cnt += 1 return cnt def is_name(name): # 숫자가 없고 첫글자는 대문자이고 나머지는 소문자인지 확인하여 이름인지 아닌지 boolean값 반환하는 함수 length = len(name) if length == 1: ...
JeonggonCho/algorithm
SWEA/D3/7675. 통역사 성경이/통역사 성경이.py
통역사 성경이.py
py
1,756
python
ko
code
0
github-code
6
1501952186
from numpy import * import matplotlib.pyplot as plt import functions data = loadtxt("kplr006603043-2011145075126_slc.tab") data_new = [] for i in data: if i[0] > 1691.5 and i[0] < 1693.1: data_new.append(i) data = array(data_new) mag = data[:,3] flux = 10**((mag-median(mag))/-2.5) o = open("lc2.dat","w"...
chelseah/LCFIT
primitive_lcfit_scripts/data/formatlc.py
formatlc.py
py
467
python
en
code
0
github-code
6
35612174500
primeList=[] def countPrimes(n): prime=0 if(n>2): for i in range(2,n): count=0 end=i//2+1 for j in range(2,end): if(i%j==0): count+=1 break if(count==0): prime+=1 prime...
Anusuya-Balakrishnan/Python-Basic-Programs
leetCode/31.5.2022/prime.py
prime.py
py
423
python
en
code
0
github-code
6
36649330794
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 08 08:15:31 2020 @author: alexanderfalk """ from copy import deepcopy from itertools import permutations # from solverNN import NearestNeightbour import time import solution import sys class TabuSearchTwoRoutes: def __init__(self, instance, s...
AlexanderFalk/2020_Project01_CS_HA
src/solverTabu2.py
solverTabu2.py
py
6,084
python
en
code
0
github-code
6
18932883260
# === Úloha 25=== # Napíšte program, ktorý z intervalu <1, N> vypíše prvočísla. Na overenie toho, či číslo je prvočíslo, vytvorte funkciu s jedným parametrom. N = 20 def je_prvocislo(x): for i in range(2, x): # <2, x) if x % i == 0: return False return True # je prvocislo len ak neni delitelne nicim inym...
Plasmoxy/MaturitaInformatika2019
ulohyPL/u25.py
u25.py
py
427
python
sk
code
2
github-code
6
41509625545
import services.Color as Color import time def gradient_mode(config): color_from = (0, 255, 30) color_to = (0, 80, 20) while True: array = [] color_generator = Color.animate_color(color_from, color_to, 18) for y in range(config["matrix_height"]): current_color = next(...
memchenko/x-max-tree
modes/gradientMode.py
gradientMode.py
py
508
python
en
code
0
github-code
6
15826756401
import pandas, main from db import db from config import Style def add_item_to_list(): while True: conn = db.create_connection() cursor = conn.cursor() main.speak("What is the name of the Item?") ITEM = main.listen().capitalize() main.speak("What is the category ...
PhantomCaboose/Python-Virtual_Assistant
features/shopping_list.py
shopping_list.py
py
3,773
python
en
code
0
github-code
6
8167059453
import sys import os import numpy as np from numpy.linalg import svd from numpy.linalg import eig from skimage import io from skimage import transform face_folder = sys.argv[1] if face_folder[len(face_folder)-1] != '/': face_folder += "/" target = sys.argv[2] image_data = [] for file in os.listdir(face_folder): ...
muachilin/Machine-Learning
hw4/pca.py
pca.py
py
1,052
python
en
code
0
github-code
6
5995774734
#!/usr/bin/python from pylab import * import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from pyhdf.SD import SD,SDC import healpy as hp import os def modisfile(month,day=None,year=2016,datadir="/home/kawahara/exomap/sot/data/aux/"): import pandas as pd if day is None: dat=pd...
HajimeKawahara/sot
src/sot/dymap/analyzeMYD.py
analyzeMYD.py
py
2,825
python
en
code
4
github-code
6
9205961554
from .MS_Celeb_1M import MSCeleb from .glintasia import GlintAsia __data_factory = { # image classification models 'Ms_celeb': MSCeleb, 'GlintAsia': GlintAsia, 'default': MSCeleb, } def get_names(): return list(__data_factory.keys()) def init_database(name, *args, **kwargs): if name not in ...
heroinlin/face_recognition
datasets/__init__.py
__init__.py
py
439
python
en
code
7
github-code
6
4495959966
from Funcionarios import Funcionarios from Fornecedores import Fornecedores func = Funcionarios() forn = Fornecedores() class CateProd: def __init__(self): pass def DadosCategorias(self): arq = open('Categorias.txt','r') lin_cate = arq.readlines() lis_cate = [] for x i...
Ander20n/Codigos-Faculdade
Projeto IP/CategoriasProdutos.py
CategoriasProdutos.py
py
17,921
python
pt
code
0
github-code
6
15852362512
from . import client class Mintage: def __init__(self, URI): self.URI = URI def getMintageData( self, selfAddr : str, prevHash : str, tokenName : str, tokenSymbol : str, totalSupply : str, decimals : int, pledgeAmount : int, **kwa...
realForbis/qlc-python-SDK
pyqlc/mintage.py
mintage.py
py
7,086
python
en
code
0
github-code
6
19499771211
# -*- coding: utf-8 -*- from typing import List import math class Solution: def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int: smallest_distance = math.inf index = -1 for ix, c in enumerate(points): cx = c[0] cy = c[1] if x ...
michaeldye/mdye-python-samples
src/mdye_leetcode/solution_1779.py
solution_1779.py
py
591
python
en
code
0
github-code
6
30399091692
from socket import * serverName = 'localhost' serverPort = 12000 clientSocket = socket(AF_INET, SOCK_DGRAM) message = input('Insira sua mensagem para a civilização extraterrena:') clientSocket.sendto(message.encode(), (serverName, serverPort)) modifiedMessage, serverAdress = clientSocket.recvfrom(2048) print(modi...
AllanCFE/Redes
clientSocket.py
clientSocket.py
py
364
python
en
code
0
github-code
6
29915222521
# -*- coding: utf-8 -*- """User views.""" from flask import Blueprint, render_template, request, flash, redirect, url_for from flask_login import login_required, current_user from food_journal.user.models import User from food_journal.user.forms import EditProfileForm blueprint = Blueprint("user", __name__, url_prefi...
ariesunique/food-journal
food_journal/user/views.py
views.py
py
2,403
python
en
code
0
github-code
6
8401186293
from cards import Cards from Deck import Deck class Game: def __init__(self,deck, numhands): self.numhands = numhands self.deck = deck self.hands = [] self.gethand(self.deck,0,5) def gethand (self,deck,start,hands): allhands = [] print ("number of hands is "...
tennisha/fourcardpoker
Game.py
Game.py
py
817
python
en
code
0
github-code
6
19682806766
#!/usr/bin/env python #Splits a cif file containing multiple structures into separate cif files for each structure #call as cif_splitter.cif <cif_file> import sys to_split=sys.argv[1] with open(to_split, 'r') as ifile: for line in ifile: if '_database_code_depnum_ccdc_archive' in line: prin...
EduardoSchiavo/utilities
cif_splitter.py
cif_splitter.py
py
928
python
en
code
0
github-code
6
26336185630
from annotated_text import annotated_text import Scripts.Utilities as Utils def __show_single_announcement(st, announcement): st.markdown(f""" <div style="background-color: rgba(250, 202, 43, 0.2); color: "rgb(148, 124, 45)"; padding: 10px; border-radius: 10px; border: 1px solid rgba(250, 202, 43, 0.2)"> ...
PeaPals/docnets
Pages/announcements_page.py
announcements_page.py
py
1,745
python
en
code
0
github-code
6
22903751015
""" module with classes Player and Enemy """ import random from module2.classes.exceptions import GameOver, EnemyDown, RestartGame from module2.classes.settings import DEFAULT_LIVES_COUNT, ALLOWED_COMMANDS class Enemy(object): """ class Enemy """ def __init__(self): self.level = 1 self...
MarinaZh16/Module-2-OOP
classes/models.py
models.py
py
4,050
python
en
code
0
github-code
6
26213405914
from typing import Generator, Any import numpy as np import pandas as pd from sklearn.model_selection import GroupKFold from sklearn.preprocessing import LabelEncoder, OrdinalEncoder from hw2.datasets.base import Dataset class TrainDataset(Dataset): def reduce_by_members(self, size: int, inplace: bool = False) ...
Sushentsev/recommendation-systems
hw2/datasets/train.py
train.py
py
3,215
python
en
code
0
github-code
6
11983564091
# -*- coding: utf-8 -*- import sys from ccm import * from PyQt5.QtWidgets import QMainWindow, QApplication class CCMWindow(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_CCMTask() self.ui.setupUi(self) self.ui.retranslateUi(self) self.show() if __name__...
yyFFans/DemoPractises
CCMtask/startui.py
startui.py
py
581
python
en
code
0
github-code
6
27108312423
import math import plotly import dash_bootstrap_components as dbc from dash import html, dcc import dash from django_plotly_dash import DjangoDash from geopy.geocoders import ArcGIS import plotly.graph_objects as go import plotly.express as px import multiprocessing import re import pandas as pd class Mapa: def __...
victoralmeida428/master-edition
apps/geoloc/dash.py
dash.py
py
2,470
python
en
code
0
github-code
6
7822007724
import os def extract_from_qmake(path, variable): sources_list = [] def next_linelist(it): line = next(it) line = line.replace('\n', '').strip() return [tok for tok in line.split() if tok != ''] with open(path, 'r') as qfile: line_iter = iter(qfile) try: ...
phernst/pyctl
create_cmakelists.py
create_cmakelists.py
py
3,970
python
en
code
6
github-code
6
209689754
def list_op(): opcodes=[] with open('input_day5.txt') as f: for line in f: for op in line.strip().split(','): opcodes.append(int(op)) return opcodes def sol(imput): movs={1:4, 2:4, 3:2, 4:2, 7:4, 8:4, 5:3, 6:3} opcodes=list_op() pointer= 0 #print(opcodes) while True: #print(pointer) opcode=f...
heyheycel/advent-of-code
2019/day5.py
day5.py
py
1,336
python
en
code
0
github-code
6
7177357229
import json import os from eth_hash.auto import ( keccak, ) from eth_utils import ( encode_hex, ) from eth.tools.fixtures.fillers import ( fill_test, ) from eth.tools.fixtures.fillers.formatters import ( filler_formatter, ) from eth.tools.fixtures.helpers import ( get_test_name, ) PARENT_DIR = os...
ethereum/py-evm
tests/fillers/build_json.py
build_json.py
py
1,932
python
en
code
2,109
github-code
6
10253684387
from __future__ import division import time import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import cv2 from util import * from darknet import Darknet import pandas as pd import colorsys import random import pickle as pkl import argparse def arg_parse(): """ Parse argu...
pokotsun/pytorch-yolov3-scratch
detect_video.py
detect_video.py
py
4,780
python
en
code
0
github-code
6
13842647368
# only links are new should be crawled for additional links # looks for all links that begin with /wiki/ (don't restrict to article links) # collects the title, the 1st paragraph of content and the link to edit the page if available from urllib.request import urlopen from bs4 import BeautifulSoup import re pa...
ViolaZhou7/2016-09-python
crawlNewLinks.py
crawlNewLinks.py
py
1,111
python
en
code
0
github-code
6
24347880200
import pytest import zipfile from io import BytesIO from PIL import Image from pathlib import Path from zesje.raw_scans import create_copy, process_page from zesje.scans import _process_scan, exam_metadata from zesje.database import db, Exam, Student, Submission, Scan, Problem, ProblemWidget, ExamLayout, Copy, Page ...
zesje/zesje
tests/test_raw_scans.py
test_raw_scans.py
py
3,269
python
en
code
9
github-code
6
36294164710
import argparse import os import torch from net.models import LeNet from net.quantization import apply_weight_sharing import util parser = argparse.ArgumentParser(description='This program quantizes weight by using weight sharing') parser.add_argument('model', type=str, help='path to saved pruned model') parser.add_...
mightydeveloper/Deep-Compression-PyTorch
weight_share.py
weight_share.py
py
977
python
en
code
383
github-code
6
75316088506
import re import wx from wx import GridSizer from wx.lib.agw.supertooltip import SuperToolTip from boaui.units import area, charge, inertia, length, mass, pressure, volume, tnt, density, torque from .label import SmartLabel from . import LayoutDimensions, SmartToolTip from ..units import KEY_IMPERIAL, KEY_METRIC f...
JoenyBui/boa-gui
boaui/textbox/smart.py
smart.py
py
36,235
python
en
code
0
github-code
6
19399912919
# 位1的个数 # https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn1m0i/ class Solution: def hammingWeight(self, n: int) -> int: count = 0 while n is not 0: count += n & 1 n = n >> 1 return count r = Solution().hammingWeight(0b1111) print(r)
Yigang0622/LeetCode
hammingWeight.py
hammingWeight.py
py
317
python
en
code
1
github-code
6
70756756988
from cavefinder.support.cstruct import * # --------------------- # | Dos Header | # --------------------- # | Pe Signature | # --------------------- # | COFF Header | # ********************* # | Optional Header | # ********************* # | Section Table | # --------------------- # | Mappable s...
jacopodl/CaveFinder
cavefinder/support/mspe.py
mspe.py
py
10,962
python
en
code
15
github-code
6
30201145239
from uuid import uuid1 import click from awsscripter.stack.helpers import catch_exceptions, confirmation from awsscripter.stack.helpers import simplify_change_set_description from awsscripter.stack.helpers import write, get_stack_or_env from awsscripter.stack.stack_status import StackStatus, StackChangeSetStatus @c...
xformation/awsscripter
awsscripter/cli/stack/update.py
update.py
py
2,044
python
en
code
0
github-code
6
3231216071
# # License: See LICENSE.md file # GitHub: https://github.com/Baekalfen/PyBoy # __pdoc__ = { "GameWrapperPokemonGen1.cartridge_title": False, "GameWrapperPokemonGen1.post_tick": False, } import logging from pyboy.utils import WindowEvent from .base_plugin import PyBoyGameWrapper logger = logging.getLogger(_...
muddi900/PyBoy
pyboy/plugins/game_wrapper_pokemon_gen1.py
game_wrapper_pokemon_gen1.py
py
2,149
python
en
code
null
github-code
6
18536492857
# -*- coding: utf-8 -*- """ Created on Wed Dec 11 15:05:36 2019 @author: Ashley """ # Manuscript Malezieux, Kees, Mulle submitted to Cell Reports # Figure S3 - Complex spikes # Description: changes in complex spikes with theta and LIA, plotted separately # %% import modules import os import numpy as n...
Ashkees/Malezieux_CellRep_2020
figure_scripts/Malezieux_CellRep_FigS3.py
Malezieux_CellRep_FigS3.py
py
63,803
python
en
code
2
github-code
6
41465348149
from commands import * from pyfiglet import Figlet from datetime import timedelta fterm = f = Figlet(font="term", justify="center", width=Console.width()) # fonts = Str.nl(File.read("pyfiglet_fonts.txt").strip()) def now(): return Time.datetime() ends = [] for arg in OS.args[1:]: ends.append(arg) if not ...
egigoka/test
time_until.py
time_until.py
py
2,474
python
en
code
2
github-code
6
43242806041
from preggy import expect from tornado.testing import gen_test from tests.base import TestCase from thumbor.config import Config from thumbor.context import Context from thumbor.importer import Importer class HealthcheckHandlerTestCase(TestCase): @gen_test async def test_can_get_healthcheck(self): re...
thumbor/thumbor
tests/handlers/test_healthcheck.py
test_healthcheck.py
py
1,446
python
en
code
9,707
github-code
6
17940251781
from sklearn.linear_model import LogisticRegression import numpy as np def logistic(train_feature_dir, train_label_dir, test_feature_dir, test_label_dir): train_feature = np.load(train_feature_dir) train_label = np.load(train_label_dir) test_feature = np.load(test_feature_dir) test_label = np.load(te...
jingmouren/antifraud
antifraud/methods/LR.py
LR.py
py
1,063
python
en
code
0
github-code
6
854022654
from PyQt4 import QtCore, QtGui from dat import PipelineInformation from dat.gui.overlays import Overlay from dat.vistrail_data import VistrailManager from dat.vistrails_interface import get_plot_modules from vistrails.core.modules.module_registry import get_module_registry, \ ModuleRegistryException from vistrai...
VisTrails/DAT
dat/gui/overlays/plot_config.py
plot_config.py
py
6,358
python
en
code
3
github-code
6
7954786176
import KeyHelper import PictureHelper import DESUnit import pickle def decrypt(): decrypt_keys = KeyHelper.keySelect() print(len(decrypt_keys)) file = open("key_sequence.txt", "rb") key_sequence = pickle.load(file) file.close() image_name = "en_2.bmp" image_data = PictureHelper.read_pictur...
2014zhouyou/ImageSharing
Decrypt.py
Decrypt.py
py
918
python
en
code
5
github-code
6
71168709947
import os import subprocess from django.conf import settings from django.utils.dateparse import parse_date from rest_framework import status from rest_framework.pagination import LimitOffsetPagination from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framewor...
maxcrimea/ARSY
web/fileconverter/views.py
views.py
py
3,589
python
en
code
0
github-code
6
29325676672
import numpy as np import warnings import sys import time import random import nna from primitives import * import copy import math LIMIT = 100 warnings.filterwarnings('ignore') def opt(cycle, sw1, sw2): rev = cycle[sw1:sw2+1] rev.reverse() cycle = cycle[:sw1]+rev+cycle[sw2+1:] return cycle def simul...
ichiro-ss/algo_eng
const_algo/sa.py
sa.py
py
2,404
python
en
code
0
github-code
6
18425266806
# from flask import Flask from flask import Flask, render_template, request, redirect, url_for, session import pymysql.cursors import json import pickle from flask import jsonify import sklearn from flask_sqlalchemy import model # Loading in the training models that we will be using later bike_model = pickle.load(open...
Winnie901/Software-Engineering-Project-Git5
app.py
app.py
py
5,366
python
en
code
0
github-code
6
41681774832
import cv2 import numpy as np import time import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=['SimHei'] plt.rcParams['axes.unicode_minus']=False m=2 # 初始化隶属度矩阵U def Initial_U(sample_num, cluster_n): # sample_num为样本个数, cluster_n为分类数 U = np.random.rand(cluster_n,sample_num) # 对 U 按列求和,然后取倒数 ...
LAS1520/Image-Processing
final pj/codes/FCM.py
FCM.py
py
2,715
python
en
code
0
github-code
6
71745856507
# AC12 import time import os # Parte 1 def fib(n): if n < 2: return n return fib(n - 2) + fib(n - 1) def read_file(path): with open(path, 'rb') as file: all_size = os.path.getsize(path) process = 0 print("{0: <9d}|{1: ^9d}|{2: ^12d}|{3: >8.2f}%|{4: ^1.8f}".format( ...
isidoravs/iic2233-2016-2
Actividades/AC12/AC12.py
AC12.py
py
4,099
python
es
code
0
github-code
6
72784212027
# https://www.codewars.com/kata/558c04ecda7fb8f48b000075 def same(arr_a, arr_b): if len(arr_a) != len(arr_b): return False for a, b in zip(arr_a, arr_b): a.sort() b.sort() arr_a.sort() arr_b.sort() for a, b in zip(arr_a, arr_b): if a != b: return False ...
blzzua/codewars
6-kyu/same_array.py
same_array.py
py
420
python
en
code
0
github-code
6