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
24946374273
from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, ForeignKey, Integer, String db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(120), unique=True, nullable=False) password = db.Column(db.String(80), unique=False, nullable=...
Sergei1607/Star-Wars-API
src/models.py
models.py
py
3,048
python
en
code
0
github-code
13
19647068803
#%% Spam detection with keras import nltk nltk.download('stopwords') from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() #%% import tensorflow as tf import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn...
FarshadGVeshki/Deep_learning_classification_models
Spam_classification_keras.py
Spam_classification_keras.py
py
2,765
python
en
code
0
github-code
13
25578873972
#!/usr/bin/env python3 # coding: utf-8 import random import z3 import itertools from functools import reduce from z3.z3util import get_vars # Approach taken from: # Rafael Dutra, Kevin Laeufer, Jonathan Bachrach and Koushik Sen: # Efficient Sampling of SAT Solutions for Testing, ICSE 2018. # https://github.com...
ZJU-Automated-Reasoning-Group/arlib
arlib/sampling/finite_domain/quick_sampler.py
quick_sampler.py
py
3,889
python
en
code
6
github-code
13
18056552508
from src.circle import Circle from math import pi def test_get_area(): # Test the radius of a circle with an area of 1 c1 = Circle(radius=1) assert c1.get_area() == pi # Test the radius of a circle with an area of 100 c2 = Circle(radius=10) assert c2.get_area() > 314 # Test the radius...
pctmoraes/pytest
tests/test_circle.py
test_circle.py
py
706
python
en
code
0
github-code
13
16765325692
import setuptools with open("README.md", "r") as fh: long_description = fh.read() with open("version.txt", "r") as fh: version = fh.read().strip() setuptools.setup( name="pogona", version=version, author="Data Communications and Networking (TKN), TU Berlin", author_email="stratmann@ccs-labs....
tkn-tub/pogona
setup.py
setup.py
py
915
python
en
code
3
github-code
13
16249797865
from fcm import FCM from point import Point f = open("sample1.csv", "r") f.readline() points = [] for line in f: pointLine = line.replace("\n","").split(",") value = [] point = Point() for val in pointLine: value.append(float(val)) point.setValue(value) points.append(point) fcm = FCM(p...
mohrobati/FuzzyCMeans
main.py
main.py
py
371
python
en
code
0
github-code
13
23449434812
from solvers import Solver ''' The TestRotate solver works through the matches from front to back. At every index it tries all not yet used pairings. The score is ignored, every combination is only judged based on the individual check. ''' class TestRotate(Solver): def __init__(self, matches = 10): Solv...
cestcedric/PerfectMatch
solvers/TestRotate.py
TestRotate.py
py
2,050
python
en
code
0
github-code
13
3998604520
# SPDX-License-Identifier: GPL-2.0 "Record and report data access pattern in realtime" import argparse import os import signal import subprocess import sys import _damon import _damon_args def cleanup(): if target_type == _damon_args.target_type_cmd and cmd_pipe.poll() == None: cmd_pipe.kill() def sigh...
awslabs/damo
damo_monitor.py
damo_monitor.py
py
3,030
python
en
code
119
github-code
13
42406602061
#!/usr/bin/env python3 import os import requests import subprocess import json import re OUTPATH = os.getenv('OUTPATH') or 'json' CODECS_JSON = 'https://browser-resources.s3.yandex.net/linux/codecs.json' STRINGS_CMD = os.getenv('STRINGS') or 'strings' BROWSERS = { 'yandex-browser-stable': (os.getenv('STABLE'),...
teu5us/nix-yandex-browser
update/codecs.py
codecs.py
py
2,880
python
en
code
1
github-code
13
32058793370
''' 16 ''' from PIL import Image img = Image.open('mozart.gif') tar = 195 i = 0 ll = list(img.getdata()) for l in [list(t) for t in zip(*[iter(ll)]*img.size[0])]: pos = l.index(tar) l = l[pos:] + l[0:pos] img2 = Image.new(img.mode, (img.size[0], 1)) img2.putdata(l) img.paste(img2, (0, i, img.size[0...
aihex/pythonchallenge
level16.py
level16.py
py
374
python
en
code
0
github-code
13
22036055205
# # @lc app=leetcode.cn id=540 lang=python3 # # [540] 有序数组中的单一元素 # from typing import List # @lc code=start class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: start, end = 0, len(nums)-1 while start < end: mid = start+(end-start)//2 if nums[mid] == nums[...
revang/leetcode
540.有序数组中的单一元素.py
540.有序数组中的单一元素.py
py
955
python
en
code
0
github-code
13
1098109251
from turtle import Turtle, Screen import pandas as pd from get_name import Name turtle = Turtle() screen = Screen() image = 'blank_states_img.gif' screen.addshape(image) turtle.shape(image) data_file = pd.read_csv('50_states.csv') all_state = data_file.state.tolist() correct_count = 0 correct_list = [] game_is_on = ...
haanguyenn/python_learning
state_guessing/main.py
main.py
py
1,300
python
en
code
0
github-code
13
15087222906
import logging # Create your views here. from django.shortcuts import render,render_to_response from django.http import HttpResponse,HttpResponseRedirect from django.core.mail import EmailMessage from django.contrib.auth.decorators import login_required from django.conf import settings from django.template import Requ...
abhi3188/djangodash13
mails/views.py
views.py
py
5,808
python
en
code
1
github-code
13
27204058909
from aiogram import types import aiohttp from loader import dp, bot from models.models import UserCart from tortoise.queryset import Q from utils.misc import api from data.config import PAYMENTS_PROVIDER_TOKEN from keyboards.inline import back_keyboard RUSSIAN_POST_SHIPPING_OPTION = types.ShippingOption(id='ru_post', ...
Kyle-krn/TelegramShop
handlers/payments/payments_shipping_handlers.py
payments_shipping_handlers.py
py
6,886
python
en
code
0
github-code
13
1467884719
#%% from airflow.operators.python import PythonOperator import requests, pytz from airflow.decorators import task_group from datetime import datetime stockholm_timezone = pytz.timezone("Europe/Stockholm") theme_parks = {"liseberg": 11} #%% def _extract_queue_times(theme_park): response = requests.get(f"https:/...
kokchun/Data-engineering-AI22
Lecture-code/Lec5-Airflow_ELT/include/queue_time/extract.py
extract.py
py
1,275
python
en
code
1
github-code
13
16031827257
import numpy as np import os import torch from torch.utils.data import Dataset from hypothesis.util.data.numpy import InMemoryStorage from hypothesis.util.data.numpy import PersistentStorage class SimulationDataset(Dataset): r"""""" def __init__(self, inputs, outputs, in_memory=False): super(Simula...
montefiore-ai/hypothesis
hypothesis/util/data/numpy/simulation_dataset.py
simulation_dataset.py
py
1,064
python
en
code
47
github-code
13
1449845581
while True: num1 = input("enter num1:") num2 = input("enter num2:") try: raise Exception("主动出现异常") num1 = int(num1) num2 = int(num2) result = num1 + num2 except Exception as ex: print(ex) else: print("num1 + num2 的值为%s" %result) finally: ...
248808194/python-study
异常处理/主动出发异常.py
主动出发异常.py
py
362
python
en
code
0
github-code
13
26269507176
import os import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand BASE_PATH = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(BASE_PATH, 'README.rst')).read() __version__ = '0.1.10' __author__ = 'Masashi Shibata <contact@c-bata.link>' __auth...
kobinpy/kobin
setup.py
setup.py
py
2,242
python
en
code
67
github-code
13
2813110569
#!/usr/bin/env python3 import requests import os import re import pyfiglet from colorama import Fore, init from multiprocessing.dummy import Pool as ThreadPool # Color green = Fore.LIGHTGREEN_EX red = Fore.LIGHTRED_EX white = Fore.WHITE cyan = Fore.LIGHTCYAN_EX yellow = Fore.LIGHTYELLOW_EX init(autoreset=True) phpfi...
MrG3P5/CVE-2017-9841
main.py
main.py
py
2,254
python
en
code
4
github-code
13
26601472094
# Robot Movement https://projecteuler.net/problem=208 # Track Location https://math.stackexchange.com/questions/1384994/rotate-a-point-on-a-circle-with-known-radius-and-position import math import time class Robot: def __init__(self, movementAngle, x, y, xCenter, yCenter): """ Initialize a robot o...
Timsnky/challenges
euler_robot/robot_move.py
robot_move.py
py
5,908
python
en
code
0
github-code
13
43356255367
# 맵의 세로 크기 N, 가로 크기 M 입력 # 게임 캐릭터의 좌표, 방향 d가 공백으로 구분하여 주어짐. # 셋째 줄부터 육지(0), 바다(1)로 이루어진 맵 정보가 주어짐. (맵의 외곽은 항상 바다) n, m = map(int, input().split()) # 방문한 위치를 저장하기 위한 맵을 생성하여 0으로 초기화 d = [[0] * m for _ in range(n)] x, y, direction = map(int, input().split()) d[x][y] = 1 # 현재 좌표 방문 처리 array = [] for i in range(n): ...
tr0up2r/coding-test
implementation/008_game_development.py
008_game_development.py
py
1,172
python
ko
code
0
github-code
13
4250089850
from django.shortcuts import render, get_object_or_404,redirect from django.forms.models import model_to_dict from django.http import HttpResponse ,JsonResponse from django.utils.translation import gettext as _ # from django.views.generic import DetailView from .models import User, Designer, Skill, Project # from .for...
akshayk652/Designers-Hub
designers_hub/user_profile/views.py
views.py
py
8,170
python
en
code
0
github-code
13
13603478172
import pygame, math, random class ball: def __init__(self, screen, color, x, y, velocity = 0, accel = 1, angle = 0, decel = 100 ): self.screen = screen self.color = color self.pos = [x, y] self.velocity = velocity self.angle = angle self.accel = accel * -1 self.decel = decel self.y_comp = self.ve...
lambopancake/Gravity_Sim
vectorMath.py
vectorMath.py
py
1,004
python
en
code
0
github-code
13
23206468820
# -*- coding: utf-8 -*- """ Created on Sun Oct 20 17:40:22 2019 @author: timhe """ import os import gdal import glob import warnings import datetime import numpy as np import pandas as pd import watertools.General.raster_conversions as RC import watertools.General.data_conversions as DC def main(inputs): # Set ...
TimHessels/WaporTranslator
LEVEL_2/Run_Intermediate_Parameters.py
Run_Intermediate_Parameters.py
py
52,038
python
en
code
8
github-code
13
18950122170
# -*- coding: utf-8 -*- # weibifan 2022-10-8 # PaddleNLP,中文自然语言处理的工具,可以完成PLMs的下载,微调,及使用 # https://www.paddlepaddle.org.cn/paddle/paddlenlp ''' https://paddlenlp.readthedocs.io/zh/latest/data_prepare/dataset_list.html 使用PaddleNLP语义预训练模型ERNIE优化情感分析 https://aistudio.baidu.com/aistudio/projectdetail/1294333 ''' import pad...
weibifan/myPaddleEx
PaddleNLP_ex4.py
PaddleNLP_ex4.py
py
4,288
python
en
code
0
github-code
13
70765699218
"""SQLAlchemy models for Translation Buddy""" from flask_bcrypt import Bcrypt from flask_sqlalchemy import SQLAlchemy from sqlalchemy_utils import auto_delete_orphans bcrypt = Bcrypt() db = SQLAlchemy() class User(db.Model): """User in the system""" __tablename__ = "users" id = db.Column( db...
adamnyk/capstone-1
app/models.py
models.py
py
5,224
python
en
code
0
github-code
13
13280201959
import numpy as np import matplotlib.pyplot as plt import math from tkinter import * fields = 'xo', 'xf', 'yo', 'yf', 'Function' def func(x,y,func): return eval(func) def getVal(entries, text): a = float(entries[text].get()) return a def getFunc(entries): f = str(entries['Function'].get()) retur...
jbaig77/graphing-toolkit
main.py
main.py
py
1,395
python
en
code
1
github-code
13
5467532826
import requests from will import settings from will.mixins import StorageMixin from will.decorators import require_settings from .base import AnalysisBackend class HistoryAnalysis(AnalysisBackend, StorageMixin): def do_analyze(self, message): # Load the last few messages, add it to the context under "hi...
skoczen/will
will/backends/analysis/history.py
history.py
py
807
python
en
code
405
github-code
13
73458188819
from __future__ import print_function from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D from keras.optimizers import SGD from keras.utils import np...
akshatbjain/Object-Detection-using-Computer-Vision
Deep Learning approach/VGG16_Model_training.py
VGG16_Model_training.py
py
3,418
python
en
code
0
github-code
13
36146856306
from pkgfixtures import host_with_saved_yum_state import json # Requirements: # From --hosts parameter: # - host(A1): first XCP-ng host > 8.2. # And: # - access to XCP-ng RPM repository from hostA1 class TestUpdate: def test_check_update(self, host): host.call_plugin('updater.py', 'check_update') def...
xcp-ng/xcp-ng-tests
tests/xapi-plugins/plugin_updater/test_updater.py
test_updater.py
py
1,447
python
en
code
3
github-code
13
41992726641
from app import app from flask import render_template @app.route('/') def homepage(): fighter_stats = {"Jon Jones": {"url":"https://dmxg5wxfqgb4u.cloudfront.net/styles/athlete_bio_full_body/s3/2020-09/JONES_JON_L_12-29.png?VersionId=_V_SgUOaxjt7ja7ddhcJB4m9ALbyeMJz&itok=kMklO45v", ...
ToddGallegos/coding_temple_flask_app
app/routes.py
routes.py
py
1,645
python
en
code
0
github-code
13
40958803714
S_EXT_LOW ='.s' S_EXT_HI ='.S' C_EXT ='.c' O_EXT ='.o' PRFX_I = '-I' # Definizione directory INCLUDE #------------------------------------------------------- dir_h = './include' # All INCLUDE dir asl_h = dir_h + '/asl' handler_h = dir_h + '/handler' pcb_h = dir_h + '/p...
jjak0b/BiKayaOS
SConstruct
SConstruct
7,744
python
en
code
0
github-code
13
10391688117
from GR86.chassis.taskcenter.tushare_task import TushareTask from GR86.chassis.spider.tushare import Tushare from GR86.chassis.taskcenter.work_type import WorkType import queue import logging from threading import Thread, Event import sys import time event = Event() class Producer(Tushare, Thread): def __init__(...
JackFrankWen/nothing
GR86/chassis/taskcenter/financial_statement_task.py
financial_statement_task.py
py
6,289
python
en
code
0
github-code
13
70195365458
from PyQt4.QtCore import * from PyQt4.QtGui import * import re from cStringIO import StringIO from pyqt.utils import PyQtSignalMapper try: from ipshell import IterableIPShell except: from pshell import IterablePShell as IterableIPShell # Mapping of terminal colors to X11 names. ANSI_COLORS = {'0' : 'black',...
bennihepp/snippets
ipython/ipython_view_qt.py
ipython_view_qt.py
py
14,613
python
en
code
1
github-code
13
4693633085
word=[] number=0 first_word=input() word.append(first_word) while True: words=input() if word[number][-1]!=words[0]: print("틀린 단어를 입력하셨습니다. 게임을 종료합니다.") break if words in word: print("앞에서 사용한 단어와 동일한 단어를 입력하셨습니다. 게임을 종료합니다.") break if ((number+1)%5)==4: ...
SongMinQQ/Python-Study
ex3-5.py
ex3-5.py
py
546
python
ko
code
0
github-code
13
3980845061
#!/usr/bin/env python # encoding: utf-8 from django.template import RequestContext from django.http import HttpResponse, HttpResponseRedirect from django.utils import simplejson as json from django.core.serializers.python import Serializer from django.db.models.fields import FieldDoesNotExist from StringIO import Stri...
multmeio/django-flattenfields-form-builder
builder/views.py
views.py
py
4,915
python
en
code
5
github-code
13
74030537939
import socket import logging import threading FORMAT = "%(threadName)s %(thread)d %(message)s" logging.basicConfig(format=FORMAT, level=logging.INFO) class ChatClient: def __init__(self, ip='127.0.0.1', port=9999): self.address = ip, port self.sock = socket.socket() self.eve...
sqsxwj520/python
网络编程/服务端编程/客户端类编程.py
客户端类编程.py
py
1,417
python
en
code
1
github-code
13
28544222181
if __name__ == '__main__': a = input() alnum = False alpha = False digit = False lower = False upper = False for s in a: if s.isalnum(): alnum = True if s.isalpha(): alpha = True if s.isdigit(): digit = True...
PahulGogna/Hackerrank_python
string_validation_problem.py
string_validation_problem.py
py
523
python
en
code
0
github-code
13
74247638738
from omdbapi.movie_search import GetMovie as g m=g(api_key='d67ffdb0') print('----------Movie Details----------') mv=input('\n Enter the movie name:') det=m.get_movie(title=mv,plot='full') print(det) f=m.get_data('actors','year') print(f)
dhaneshvg/Python_tkinder
movieAPI.py
movieAPI.py
py
242
python
en
code
1
github-code
13
41974308212
from threading import Lock, Thread from typing import Any class SingletonMeta(type): __instances = {} # Create an empty dictionary _lock = Lock() # Thread Lock def __call__(cls, *args: Any, **kwds: Any) -> Any: with cls._lock: if cls not in cls.__instances: in...
hieukien503/DesignPattern
DesignPattern/Creational DP/Singleton_thread_safe.py
Singleton_thread_safe.py
py
925
python
en
code
0
github-code
13
7494399313
from selenium.common.exceptions import NoSuchElementException from GrouponScraper.Devices import Devices from GrouponScraper.CommentManager import CommentManager class TicketFactory: def __init__(self): return def isGroupon(self, driver): # Check if the main body things its a groupon ...
DavidCastillo2/GrouponScraper
TicketFactory.py
TicketFactory.py
py
5,556
python
en
code
0
github-code
13
40789624142
word=input('Enter the string to find the vowels:') vowels={'a','e','i','o','u'} d={} for ch in word: if ch in vowels: d[ch]=d.get(ch,0)+1 for k,v in sorted(d.items()): print('Vowel {} is appearing {} times'.format(k,v))
sudheemujum/Python-3
dict_vowel_count.py
dict_vowel_count.py
py
238
python
en
code
0
github-code
13
24367774101
from PIL import Image, ImageOps import numpy as np def print_info(img): print(img.format) print(img.mode) print(img.size) print(img.width) print(img.height) print(img.palette) print(img.info) def load_image(filename): img = Image.open(filename) img.load() return img def m...
hekrause/BIVE
Uebung01/work.py
work.py
py
1,454
python
en
code
0
github-code
13
6143174661
import logging import sys import pytest from stringOrderCheck.stringOrder import checkOrder, orderIndices, orderScan logger = logging.getLogger(__name__) streamHandler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") streamHandler.setFormatter(...
michael-c-hoffman/TestDrivenDevelopmentPythonPytest
stringOrderCheck/tests/unitTests/stringOrderCheckTests.py
stringOrderCheckTests.py
py
1,905
python
en
code
0
github-code
13
27788135813
import csv import json import requests from elasticsearch import Elasticsearch from elasticsearch.helpers import bulk import uuid extract_url = 'http://localhost:9200/skills_taxonomy' copy_url = 'http://enter elasticsearch_url here/' def load_csv(): filename="Categories.csv" data = [row for row...
Gayatri-Shastri7/Search-Engine
Copy_data_to_server.py
Copy_data_to_server.py
py
1,294
python
en
code
0
github-code
13
36834783539
import torch import unittest from core.embed import PositionalEmbedding class TestEmbed(unittest.TestCase): def test_positional_embedding(self): pe = PositionalEmbedding(12) x = torch.LongTensor([[1]]) y = pe(x) w,h,t = y.size() self.assertEqual(w,1) self.assert...
imeepos/imeepos
tests/test_embed.py
test_embed.py
py
370
python
en
code
0
github-code
13
39148398548
#!/bin/python3 #https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem import sys def minJumps(n, c): i = 0 count = 0 while i < len(c) - 1: if (len(c) - 1) - i == 1: i += 1 count += 1 elif c[i + 2] == 1: i = i + 1 c...
saumya-singh/CodeLab
HackerRank/Implementation/Jumping_On_The_Clouds.py
Jumping_On_The_Clouds.py
py
547
python
en
code
0
github-code
13
71455226578
# -*- coding: utf-8 -*- # @Author : ZhaoKe # @Time : 2021-08-16 16:11 import numpy as np import matplotlib.pyplot as plt import matplotlib def bar_single(): data = np.loadtxt("chaos-res-matrix/res-0.txt", delimiter=',', encoding="GB2312") print("结果的形状", data.shape) mean_list = np.mean(data, axis=1) st...
ZhaoKe1024/IntelligentAlgorithmScheduler
draw_plot.py
draw_plot.py
py
2,948
python
en
code
7
github-code
13
17042446804
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayMarketingCampaignDiscountBudgetCreateModel(object): def __init__(self): self._biz_from = None self._fund_type = None self._gmt_end = None self._name = None ...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/AlipayMarketingCampaignDiscountBudgetCreateModel.py
AlipayMarketingCampaignDiscountBudgetCreateModel.py
py
4,461
python
en
code
241
github-code
13
16748096048
import numpy as np class Dataset(): def __init__(self, data, target, n_classes=None, max_output_size=None): self.data = data self.target = target self.n_classes = n_classes self.max_output_size = max_output_size self.data_type = 'list' if isinstance(target, list) else 'num...
AndreasMadsen/bachelor-code
dataset/_shared.py
_shared.py
py
1,919
python
en
code
1
github-code
13
16879760797
""" You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achie...
melanietai/leetcode-practice
dynamic_programming/best_time_to_buy_and_sell_stock.py
best_time_to_buy_and_sell_stock.py
py
977
python
en
code
0
github-code
13
6583280263
import numpy as np import tensorflow as tf class DQN: def __init__(self, session: tf.Session, input_size: int, output_size: int, name: str="main"): self.session = session self.input_size = input_size self.output_size = output_size self.net_name = name self._build_network()...
ParkSangBeom/DQN
DQN/DQN.py
DQN.py
py
1,734
python
en
code
0
github-code
13
42834494796
from pytest import raises as assert_raises from sys import argv from threading import Thread from time import sleep from wsgiref.simple_server import make_server from rdflib import Graph, Literal, Namespace, RDF, URIRef from re import compile as RegExp from rdfrest.exceptions import CanNotProceedError from rdfrest.c...
ktbs/ktbs
utest/example1.py
example1.py
py
21,837
python
en
code
24
github-code
13
20680529038
import argparse import rlcard from rlcard.agents import RandomAgent from rlcard.utils import set_seed def run(args): # Make environment env = rlcard.make(args.env, config={'seed': 42}) num_episodes = 2 # Seed numpy, torch, random set_seed(42) # Set agents agent = RandomAge...
Derrc/UnoRL
UnoRL/uno_random.py
uno_random.py
py
886
python
en
code
1
github-code
13
6948030724
from typing import * class Solution: def sortByBits(self, arr: List[int]) -> List[int]: dic1 = {} for val in arr: dic1[val] = self.num_one(val) arr.sort(key=lambda x: (dic1[x], x)) return arr def num_one(self, val): num = 0 while val: va...
Xiaoctw/LeetCode1_python
位运算/根据数字二进制下1的数目排序_1356.py
根据数字二进制下1的数目排序_1356.py
py
516
python
en
code
0
github-code
13
2434116573
#!/usr/bin/env python3 """ --------------------------- Test :mod:`phile.tray.tmux` --------------------------- """ # Standard library. import asyncio import typing import unittest # Internal packages. import phile.asyncio import phile.tray import phile.tray.tmux from test_phile.test_tmux.test_control_mode import ( ...
BoniLindsley/phile
tests/test_phile/test_tray/test_tmux.py
test_tmux.py
py
2,607
python
en
code
0
github-code
13
4749899921
from collections import namedtuple import networkx as nx Point = namedtuple('Loc', ['r', 'c', 'elevation', 'name']) def elevation_from_letter(letter): if letter == 'S': letter = 'a' elif letter == 'E': letter = 'z' if 'a' <= letter <= 'z': return ord(letter) - ord('a') else: ...
willf/advent_of_code_2022
12/solve.py
solve.py
py
3,283
python
en
code
0
github-code
13
37290568985
# Sky Hoffert, Gabby Boehmer # main.py # Processes exoplanet data import matplotlib.pyplot as plt import sys import numpy as np db_path = 'data/kepler.csv' def main(): filein = open(db_path, 'r') # create an empty db db = [] # parse input file for line in filein.readlines(): fin...
skyhoffert/ds_exoplanets
sky.py
sky.py
py
2,374
python
en
code
1
github-code
13
7528376792
import time import numpy as np import pandas as pd from bokeh import plotting as bop, io as boi from bokeh import models as bom, events as boe, layouts as bol from bokeh.palettes import Category10_10 from itertools import cycle from . import stats, paths from contextlib import contextmanager from IPython.display import...
andyljones/megastep
rebar/plots.py
plots.py
py
7,923
python
en
code
117
github-code
13
24393423066
import controller.verification as v from model.sample import Sample from model.feature import Feature import unittest class TestVerification(unittest.TestCase): """ A class for testing functions from verification module Attributes (Object) modelvalues_for_testing: example modelvalues for test function...
ameliebrucker/KeystrokeBiometrics
keystroke_biometrics/tests/verification_test.py
verification_test.py
py
15,041
python
en
code
0
github-code
13
18761289362
# This code checks for internet connection and informs whenever the internet is connected or disconnected import socket import urllib.request import time from datetime import datetime import tkinter from tkinter import messagebox root = tkinter.Tk() root.withdraw() time_now = datetime.now() read_time = time_now.strft...
jeff9901/Network_and_Web_Analysis
Connectivity_check.py
Connectivity_check.py
py
1,711
python
en
code
0
github-code
13
16808483964
import pytest from hypothesis import given, settings, strategies as st from hypothesis.errors import InvalidArgument from hypothesis.extra.array_api import COMPLEX_NAMES, REAL_NAMES from hypothesis.internal.floats import width_smallest_normals from tests.array_api.common import ( MIN_VER_FOR_COMPLEX, dtype_na...
HypothesisWorks/hypothesis
hypothesis-python/tests/array_api/test_arrays.py
test_arrays.py
py
16,753
python
en
code
7,035
github-code
13
11199828675
import numpy as np from scipy.ndimage import convolve1d from .csf_utils import csf_dict, csf_frequency, csf_mannos_daly, csf_spat_filter from pywt import wavedec2, waverec2 def filter_pyr(pyr, csf_funct): n_levels = len(pyr) - 1 filt_pyr = [] filt_pyr.append(pyr[0]) # Do not filter approx subband. fo...
abhinaukumar/funque
funque/third_party/funque_atoms/filter_utils.py
filter_utils.py
py
2,707
python
en
code
2
github-code
13
5150072386
from glob import glob import sqlite3 import pandas as pd PATH = '/media/tiago/HDD - Tiago/pnad' for ano in range(2012, 2016): print(ano) with open(f'{PATH}/{ano}/Dicionários e input/input PES{ano}.txt', encoding='windows-1252') as myfile: input_PNADC_trimestre2 = [l...
tiago-freitas/pnad-educational-data
extrator.py
extrator.py
py
1,369
python
en
code
0
github-code
13
20974669779
#!/usr/bin/env python3 import logging import os import pyroscope l = logging.getLogger() l.setLevel(logging.DEBUG) addr = os.getenv("PYROSCOPE_SERVER_ADDRESS") or "http://pyroscope:4040" print(addr) pyroscope.configure( application_name = "simple.python.app", server_address = addr, enable_logging = True, ) def ...
grafana/pyroscope
examples/python/simple/main.py
main.py
py
617
python
en
code
8,798
github-code
13
73192583057
#Preguntas a responder #¿Cual es el % de ventas historicas de los distintos articulos? #Del item más vendido, ¿en que mes se vende más? #¿Cuantos articulos de los mas vendidos se deberian comprar en marzo del 2022? import pandas as pd import numpy as np def run(): dir_ventas = './datos/{}'.format('ventas.csv') ...
Danvalrub/ventas_pandas
ventas_pandas.py
ventas_pandas.py
py
2,077
python
es
code
0
github-code
13
32276473443
# exercise 58: Is It a Leap Year? year = int(input('enter year: ')) if year % 400 == 0: res = 'leap' elif year % 100 == 0: res = 'not leap' elif year % 4 == 0: res = 'leap' else: res = 'not leap' print('year %d: %s year' % (year, res)) """ alternative: at each if statement I might write isLeapYear ...
sara-kassani/1000_Python_example
books/Python Workbook/decision_making/ex58.py
ex58.py
py
429
python
en
code
1
github-code
13
36697722472
############# # # In this example, we look at Modules. # # Now I know what you're thinking! Every deep learning library out there has a class called Module. There's # haiku.Module, flax.linen.Module, objax.Module etc. # # And each time you have to sit down and read the documentation and understand what "Module" means f...
codeaudit/equinox
examples/build_model.py
build_model.py
py
6,034
python
en
code
null
github-code
13
17127074015
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL...
LuisBosquez/student-net-2015
src/university_dashboard/migrations/0007_auto_20150308_2309.py
0007_auto_20150308_2309.py
py
1,695
python
en
code
0
github-code
13
72172438418
from __future__ import annotations from logging import getLogger, NullHandler from typing import TYPE_CHECKING, List, Dict, Tuple from watchdog.observers import Observer from watchdog.observers.api import ObservedWatch if TYPE_CHECKING: from . import Reloadable logger = getLogger(__name__) logger.addHandler(Nu...
urushiyama/reloadrable
reloadrable/reloadable_manager.py
reloadable_manager.py
py
1,258
python
en
code
0
github-code
13
22920535185
def dictionary(l1,l2): d1 = {} for i in l1: if i in d1: d1[i] += 1 else: d1[i] = 1 d2 = {} for j in l2: if j in d2: d2[j] += 1 else: d2[j] = 1 return d1,d2 def numerator(d1,d2): tsum = 0 for i in d1: for j in d2: if i == j: tsum = tsum + d1[i] * d2[j] return(tsum) def denominator(...
uday12345678/Plagiarism-Detector
CSPP1_2017_part-1_20176043-bagOfCodes.py
CSPP1_2017_part-1_20176043-bagOfCodes.py
py
1,727
python
en
code
0
github-code
13
10396917279
from nodoBusqueda import nodoBusqueda import distancia class Problema(): def __init__(self,espacioEstados,estadoInicial): self.espacioEstados = espacioEstados self.estadoInicial = estadoInicial self.contador=1 self.tabla = {} def EstadoMeta(self,Estado): return sel...
soker90/inteligentes
Carpeta_Fuente/Problema.py
Problema.py
py
2,395
python
es
code
0
github-code
13
2435738643
import os from operator import itemgetter import re import numpy as np import mlp accuracy = np.zeros(1) nhidden = 12 with open('train_s.txt','r') as train_file: train = eval(train_file.read()) with open('traint_s.txt','r') as traint_file: traint = eval(traint_file.read()) with open('valid_s.txt','r') as valid_f...
bjornife/Uber_Secret_Project_1
get_the_data.py
get_the_data.py
py
945
python
en
code
0
github-code
13
40242416276
#Import libraries import socketserver, os #import mimetypes # Copyright 2013 Abram Hindle, Eddie Antonio Santos # # 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.or...
BAFiogbe/CMPUT404-assignment-webserver
server.py
server.py
py
3,783
python
en
code
null
github-code
13
37882169930
from collections import defaultdict readline = lambda: list(map(int, input().split())) r, c, k = readline() board = [] for _ in range(3): board.append(readline()) def do_R(): for idx, i in enumerate(board): dic = defaultdict(int) new_list = [] for j in i: if j == 0: ...
kod4284/kod-algo-note
백준/17140-이차원-배열과-연산/solution.py
solution.py
py
1,957
python
en
code
0
github-code
13
27325991310
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Patent Claim Scoring System Functionality: Provide a GUI for our tool @author: Zhipeng Yu Input: 1.previously saved machine learning model: 'model.json', 'model.h5','emb_model.json','emb_model.h5' 2.negative and positive word list for word level features:...
yuzhipeng588/Machine-Learning-NLP
GUI.py
GUI.py
py
13,080
python
en
code
0
github-code
13
9792027936
import os import shutil import rasterio import numpy as np from glob import glob from tqdm import tqdm from mpi4py import MPI from rasterio import windows from itertools import product from scipy.stats import linregress from argparse import ArgumentParser comm = MPI.COMM_WORLD # get MPI communicator object size = com...
danielz02/neon
src/nitrogen_regression_mpi.py
nitrogen_regression_mpi.py
py
5,622
python
en
code
0
github-code
13
2413710137
from __future__ import print_function import httplib, urllib, sys, json, re, os, requests #check if dev or prod mode mode = sys.argv[1] #load config from file f = open('automin_config.json', 'r') config = json.loads(f.read()) f.close() total_files = len(config['files']) files_done = 0 dev_path = { "js": config['...
werlang/automin
automin.py
automin.py
py
8,690
python
en
code
7
github-code
13
73126781138
from odoo import api, fields, models, _ class PosPaymentCommande(models.Model): _name = "pos.payment_cmd" payment_date = fields.Datetime(string='Date', required=True, readonly=True, default=lambda self: fields.Datetime.now()) pos_commande_id = fields.Many2one('pos.commande', string='Commande') mo...
hilinares1/MADEMO
tit_pos_order/models/PosPaymentCommande.py
PosPaymentCommande.py
py
899
python
en
code
0
github-code
13
33639469734
from tkinter import filedialog from tkinter import * import customtkinter import pygame import os customtkinter.set_appearance_mode("dark") # Modes: "System" (standard), "Dark", "Light" customtkinter.set_default_color_theme("dark-blue") # Themes: "blue" (standard), "green", "dark-blue" window = customtkin...
humza-uddin/MusicPlayer
main.py
main.py
py
3,061
python
en
code
1
github-code
13
73731864016
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.conf import settings from graphdb.redis.graphlayer import GraphLayerRedis from graphdb.schema.backlinks import Backl...
anujkhare/wings
angel/pipelines.py
pipelines.py
py
2,138
python
en
code
0
github-code
13
72915388498
import pathlib import ast import PyQt5 def find_enums(tree): """Find all PyQt enums in an AST tree.""" for node in ast.walk(tree): if not isinstance(node, ast.Assign): continue if node.type_comment is None: continue if '.' not in node.type_comment: ...
qutebrowser/qutebrowser
scripts/dev/rewrite_find_enums.py
rewrite_find_enums.py
py
1,187
python
en
code
9,084
github-code
13
23553059182
import numpy as np import ujson import SimpleITK as sitk from shapely import geometry import cv2 #from scipy.spatial import ConvexHull, convex_hull_plot_2d class Media: @staticmethod def write(file, obj): with open(file, "w") as filef: filef.write(ujson.dumps(obj)) @staticmeth...
ivarvb/MEDIA
sourcecode/src/vx/media/Media.py
Media.py
py
5,531
python
en
code
0
github-code
13
41767670572
class MyCalendarThree: def __init__(self): self.c_map = collections.defaultdict(int) def book(self, start: int, end: int) -> int: self.c_map[start] += 1 self.c_map[end] -= 1 s = 0 k = 0 # print(self.c_map) for key in sorted(self.c_map.keys()): ...
ritwik-deshpande/LeetCode
732-my-calendar-iii/732-my-calendar-iii.py
732-my-calendar-iii.py
py
597
python
en
code
0
github-code
13
34785476788
from rct229.rulesets.ashrae9012019.data.schema_enums import schema_enums from rct229.utils.jsonpath_utils import find_all, find_one from rct229.utils.utility_functions import ( find_exactly_one_fluid_loop, find_exactly_one_hvac_system, ) FLUID_LOOP = schema_enums["FluidLoopOptions"] def is_hvac_sys_preheat_f...
pnnl/ruleset-checking-tool
rct229/rulesets/ashrae9012019/ruleset_functions/baseline_systems/baseline_hvac_sub_functions/is_hvac_sys_preheat_fluid_loop_attached_to_boiler.py
is_hvac_sys_preheat_fluid_loop_attached_to_boiler.py
py
1,460
python
en
code
6
github-code
13
36588492436
class Solution: def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int: loc1, loc2, vec = [], [], defaultdict(int) for i in range(len(img1)): for j in range(len(img1[0])): if img1[i][j] == 1: loc1.append((i, j)) i...
ysonggit/leetcode_python
0835_ImageOverlap.py
0835_ImageOverlap.py
py
646
python
en
code
1
github-code
13
19158623985
# Sandro is a well organised person. Every day he makes a list of things which need to be done and enumerates them from 1 to n. However, some things need to be done before others. In this task you have to find out whether Sandro can solve all his duties and if so, print the correct order. # Dữ liệu nhập # In the first...
phamtamlinh/coding-challenges
basic/topological-sort/topological-sorting.py
topological-sorting.py
py
2,020
python
en
code
0
github-code
13
10023300596
#!/usr/bin/python3 '''Defines class Rectangle that inherits from Base''' from models.base import Base class Rectangle(Base): '''Defines class rectangle''' def __init__(self, width, height, x=0, y=0, id=None): '''Initializes an instance''' super().__init__(id) self.width = width ...
Jay-Kip/alx-higher_level_programming
0x0C-python-almost_a_circle/models/rectangle.py
rectangle.py
py
4,285
python
en
code
1
github-code
13
46275868384
import re import json import numpy as np import pandas as pd from promptsource.templates import DatasetTemplates, Template def add_translated_prompt_templates(): with open('csv_files/entities.json') as f: template_entities_dict = json.load(f) translated_prompts_df = pd.read_csv('csv_files/template_...
lintangsutawika/multilingual-t0
hf/translation.py
translation.py
py
6,771
python
en
code
6
github-code
13
70940496337
import os import csv import sys import subprocess ##### # def install(package): ''' Installs a given Python Package ''' subprocess.check_call([sys.executable, "-m", "pip", "install", package]) def find(m_id): ''' Finds rating, region and genre of an id ''' # we get a...
DanHutsul/imdb_popularity
imdb_popularity/main.py
main.py
py
6,278
python
en
code
0
github-code
13
29696047904
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: return self.back_tracking_method(s, wordDict) word_dict = set(wordDict) ans = [False] * len(s) for i in range(0, len(ans)): if s[:i + 1] in word_dict: ans[i] = True ...
xincheng-cao/loser_fruit
backtracking/139. Word Break.py
139. Word Break.py
py
1,246
python
en
code
0
github-code
13
3108448366
""" Create a program that determines whether or not it is possible to construct a particular total using a specific number of coins. For example: it is possible to have a total of $1.00 using four coins if they are all quarters. However, there is no way to have a total of $1.00 using 5 coins. Yet it is possible to ha...
aleattene/python-workbook
chap_08/exe_181_possible_change.py
exe_181_possible_change.py
py
2,632
python
en
code
1
github-code
13
41604954976
import sys def initial_matrix(n, m): d = [] for i in range(n+1): d.append([0]*(m+1)) d[i][0] = i for j in range(m+1): d[0][j] = j return d def print_matrix(seq, mseq, matrix, start, n, mlen, direction=1): print('\t\t{}'.format('\t'.join(list(mseq)))) for i in range(n+1): if i > 0: base = seq[star...
lmdu/pytrf
atrfinder.py
atrfinder.py
py
5,674
python
en
code
4
github-code
13
27326806194
# -*- coding: utf-8 -*- # 主函数 import sys from PyQt5 import QtGui, QtCore, QtWidgets import index, alert, bye def get_relus(): """ 获取规则库,并将结论和前提分开存储 :return:P:存储前提 Q:存储结论 """ RD = open("data\RD.txt", "r") # 打开规则库 P = [] # 存储前提 Q = [] # 存储结论 for line in RD: ...
Mr-Zhang-915/Animal-recognition-expert-system
基于PYQT5的动物识别专家系统/main.py
main.py
py
4,898
python
zh
code
1
github-code
13
1632319037
from __future__ import annotations import math import re from os.path import exists from typing import Optional, List, Set from thefuzz import fuzz from yacs.config import CfgNode import os from textdistance import levenshtein from logging import Logger import itertools import torch import pandas as pd import enlight...
ChristinaK97/KnowledgeGraphs
KnowledgeGraphsPython/DeepOnto/src/deeponto/align/bertmap/mapping_prediction.py
mapping_prediction.py
py
24,725
python
en
code
0
github-code
13
34941555974
from tkinter import * import random class window: def __init__(self, master, length): self.master = master master.title("Simon") self.length = length self.b1 = Button(master, width=12, height=6, bg="grey", relief=RIDGE, activebackground="blue", ...
Danielx2003/simon
simon Says Flashing buttons.py
simon Says Flashing buttons.py
py
5,814
python
en
code
0
github-code
13
11617749761
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @Filename :modules.py @Description : @Date :2022/02/21 16:55:34 @Author :Arctic Little Pig @version :1.0 ''' from enum import IntEnum import torch import torch.nn as nn from .resnet import ResNet from .squeeze import checkerboard_mask clas...
Master-PLC/NeuralODE
RealNVP_Density_Estimation_Using_Real_NVP/models/modules.py
modules.py
py
4,796
python
en
code
0
github-code
13
43760495016
from main import models def order_middleware(get_response): def middleware(request): if 'order_id' in request.session: order_id = request.session['order_id'] try: order = models.Order.objects.get(id=order_id) request.order = order ...
kosreharsh/Ecommerce
main/middlewares.py
middlewares.py
py
540
python
en
code
0
github-code
13
25139131519
import catboost from catboost import CatBoostClassifier, CatBoostRegressor from sklearn.model_selection import StratifiedKFold, KFold import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns class CatBoost: def __init__(self, args, data): super().__init__() #...
boostcampaitech4lv23recsys1/level2_dkt_recsys-level2-recsys-07
code/dkt/Catboost/CatBoost_model.py
CatBoost_model.py
py
3,445
python
en
code
0
github-code
13
24313231665
import datetime from magaz.models import Prises from django.conf import settings class Cart(object): def __init__(self, request): self.session = request.session cart = request.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} ...
mushroom2/laserSite
cart1/cart.py
cart.py
py
2,041
python
en
code
2
github-code
13