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
73357295548
from .MainDataToICS import MainDataToICS from .WebJWC import WebJWC import time import os from hashlib import md5 import random import json def getData(id,password): web = WebJWC(id,password) print('TOPO1') web.runDriver() time.sleep(1) print('TOPO2') web.loginIn() time.sleep(1) print('...
CQU-CSA/CQUScheduleCalendar
DjangoICS/CQUClassICS/src/MainICS.py
MainICS.py
py
1,500
python
en
code
0
github-code
6
3705027331
import bitstring def shift_check( filename ): f = open(filename, 'rb') bits = bitstring.Bits( f ) f.close() bits_array = bitstring.BitArray( bits ) skip =8*3 for k in range(8): start = k + skip stop = start+ 200*8 shifted = bits_array[start:stop] byte_data = sh...
tj-oconnor/spaceheroes_ctf
forensics/forensics-rf-math/solve/shifty.py
shifty.py
py
583
python
en
code
13
github-code
6
41509638995
import math def get_delta_color(c_from, c_to, step): d_r_col = math.ceil(c_from[0] - c_to[0]) if c_from[0] > c_to[0] else math.ceil(c_to[0] - c_from[0]) d_r_col = math.ceil(d_r_col / step) if d_r_col != 0 else 0 d_g_col = math.ceil(c_from[1] - c_to[1]) if c_from[1] > c_to[1] else math.ceil(c_to[1] - c_fro...
memchenko/x-max-tree
services/Color.py
Color.py
py
2,964
python
en
code
0
github-code
6
24199924707
class Solution: def maxAreaOfIsland(self, grid): """ Args: grid: list[list[int]] Return: int """ res = 0 self.grid = grid self.visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))] for i in ran...
AiZhanghan/Leetcode
code/695. 岛屿的最大面积.py
695. 岛屿的最大面积.py
py
1,091
python
en
code
0
github-code
6
18385696956
# Import the libraries import cv2 import os import numpy as np class Auxiliary(object): """ Class that provides some auxiliary functions. """ def __init__(self, size_x=100, size_y=100, interpolation=cv2.INTER_CUBIC): """ Set the default values for the image size and the interpolation...
kelvins/Reconhecimento-Facial
FaceRecognition/classes/auxiliary.py
auxiliary.py
py
9,896
python
en
code
20
github-code
6
2246571162
testname = 'apconfiguration_2.2.2.20' avoiderror(testname) printTimer(testname,'Start','Ac config wrong image file for ap. Ap can download image, but can not upgrade') ############################################################################### #Step 1 #操作 # 在AC1上为AP1_image_type指定错误的image文件,(其他image_type的文件) # 在AC1...
guotaosun/waffirm
autoTests/module/apconfiguration/apconfiguration_2.2.2.20_ONE.py
apconfiguration_2.2.2.20_ONE.py
py
5,667
python
en
code
0
github-code
6
35914457874
class Solution(object): # @param nestedList a list, each element in the list # can be a list or integer, for example [1,2,[1,2]] # @return {int[]} a list of integer def flatten(self, nestedList: list) -> list: import collections stack = collections.deque([nestedList]) result = [...
Super262/LintCodeSolutions
data_structures/stack/problem0022.py
problem0022.py
py
575
python
en
code
1
github-code
6
30827683895
import os import logging from novelwriter.enum import nwItemLayout, nwItemClass from novelwriter.error import formatException from novelwriter.common import isHandle, sha256sum logger = logging.getLogger(__name__) class NWDoc(): def __init__(self, theProject, theHandle): self.theProject = theProject ...
vaelue/novelWriter
novelwriter/core/document.py
document.py
py
7,928
python
en
code
null
github-code
6
37530932561
from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from curriculum.serializers.curriculum_serializers import SubjectLevelListSerializer, SubjectLevelSerializer, SubjectLevelWriteSerializer from rest_framework.exceptions import NotFound from rest...
markoco14/student-mgmt
curriculum/views/subject_level_views.py
subject_level_views.py
py
3,238
python
en
code
0
github-code
6
5503956648
# https://www.hackerrank.com/challenges/swap-case/problem def swap_case(s): result = "" for let in s: if let.isupper(): result += let.lower() else: result += let.upper() return result string = input() print(swap_case(string))
Nikit-370/HackerRank-Solution
Python/swap-case.py
swap-case.py
py
282
python
en
code
10
github-code
6
73798071227
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.http import HttpResponse, HttpResponseRedirect, QueryDict from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth import authenticate, login, logout from django.views.generic import View, TemplateView from d...
alfonsoolavarria/cm
maracay/views.py
views.py
py
34,284
python
en
code
0
github-code
6
31484686923
import torch from models.conformer.activation import GLU, Swish class DepthWiseConvolution(torch.nn.Module): def __init__(self, in_channels, kernel_size, stride, padding): super(DepthWiseConvolution, self).__init__() self.conv = torch.nn.Conv1d(in_channels, in_channels, kernel_size, stride, paddin...
m-koichi/ConformerSED
src/models/conformer/convolution.py
convolution.py
py
1,709
python
en
code
25
github-code
6
14807526088
import time import multiprocessing def work(): for i in range(10): print("工作中...") time.sleep(0.2) if __name__ == '__main__': work_process = multiprocessing.Process(target=work) work_process.daemon=True work_process.start() # 程序等待1秒 time.sleep(1) print("程序结束")
kids0cn/leetcode
Python语法/python多线程多进程/4.守护进程.py
4.守护进程.py
py
333
python
en
code
0
github-code
6
7357205248
import requests import json import nestConfig #AWS Constants url = nestConfig.get_URL() query = ''' mutation Mutation($id: String!) { checkIn(id: $id) { code message } } ''' def checkIn(nestID): #Ensure nest is connected to the backend content = json.dumps({'id':nestID}) #Assign nest name to be c...
EzequielRosario/ImperiumBinarium-Files
NestFunctions/HourlyCheckIn.py
HourlyCheckIn.py
py
642
python
en
code
0
github-code
6
16475584397
import sqlite3 from sqlite3 import Error class Data(): __error = None __result = None def __init__(self, db): try: self.con = sqlite3.connect(db, check_same_thread = False) self.cur = self.con.cursor() except Error as e: print(e) def clean_db(self):...
madePersonal/Android_forensic_tools
Data.py
Data.py
py
6,992
python
en
code
0
github-code
6
42480209825
import pandas as pd def listaProdutos(tabela_produtos, n): my_list = [] for index, rows in tabela_produtos.iterrows(): m_l = [] if n == 0: k = 0 m_l.append(rows.Produto+"-"+rows.Marca + "-" + rows.Método_Compra) for m in range(len(m_l)): for n...
jcromeck/ProjectPetShop
Funções.py
Funções.py
py
5,917
python
pt
code
0
github-code
6
9388340974
"""Functions and constants used in several modules of the gtphipsi package. This module exports the following functions: - get_name_from_badge (badge) - get_all_big_bro_choices () - create_user_and_profile (form_data) - log_page_view (request, name) This module exports the following constant definitio...
will2dye4/gtphipsi
common.py
common.py
py
5,867
python
en
code
2
github-code
6
39620320183
from Folder_de_Testes.base import Fox_HEIGHT, Fox_WIDTH import pygame import random #Parametros gerais WIDTH = 880 HEIGHT = 400 gravity = 1 def randon_sizes_for_walls(xpos): protection = 200 altura = random.randint(200, 400) wall = Wall(False, xpos, altura) inversal_wall = Wall(True, xpos,HEIGHT - ...
RodrigoAnciaes/Flying_Fox_game
Folder_de_Testes/personagens.py
personagens.py
py
7,008
python
en
code
0
github-code
6
44295661280
import numpy as np from lib import EulerUtils as eu # Problem 36 solution! def checkIfNumberIsPalindromeInBothBases(number): numberString = str(number) baseTwoString = "{0:b}".format(number) if (eu.isPalindrome(numberString) and eu.isPalindrome(baseTwoString)): return True else: return...
Renoh47/ProjectEuler
project euler python/problem36.py
problem36.py
py
426
python
en
code
0
github-code
6
71971273469
import logging from kubernetes import client from kubernetes.client.models.v1_resource_requirements import V1ResourceRequirements from kubeflow.fairing.constants import constants logger = logging.getLogger(__name__) def get_resource_mutator(cpu=None, memory=None, gpu=None, gpu_vendor='nvidia'): """The mutator for...
kubeflow/fairing
kubeflow/fairing/kubernetes/utils.py
utils.py
py
5,342
python
en
code
336
github-code
6
70007062267
from typing import Any, Dict import os import json import httpx from odt.config import PipeConfig _TEMPFILENAME = "lgbm_tmp_model.txt" class ODTManager: def __init__(self, server_host: str) -> None: self.server_host = server_host def update_config(self, config: PipeConfig): # serialization...
Tsoubry/fast-lightgbm-inference
rust-transformer/python/odt/manage.py
manage.py
py
1,506
python
en
code
0
github-code
6
3480167544
import json import boto3 from smart_open import smart_open, codecs from ConfigParser import ConfigParser import psycopg2 def publish_message(producerInstance, topic_name, key, value): "Function to send messages to the specific topic" try: producerInstance.produce(topic_name,key=key,value=value) ...
vikash4281/Corpus-Callosum
Ingestion/Streaming.py
Streaming.py
py
5,581
python
en
code
0
github-code
6
9756160768
from __future__ import print_function, absolute_import, division import numpy as np def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.): ''' Pad each sequence to the same length: the length of the longest sequence. If maxlen is provide...
trungnt13/odin_old
odin/features/text.py
text.py
py
2,108
python
en
code
2
github-code
6
17661406387
from collections import defaultdict, deque from enum import Enum def read(filename): with open(filename) as f: insts = (line.strip().split(' ') for line in f) return [(inst[0], tuple(inst[1:])) for inst in insts] def isint(exp): try: int(exp) return True except ValueError:...
pdhborges/advent-of-code
2017/18.py
18.py
py
2,447
python
en
code
0
github-code
6
36021205025
from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from sendQueries import SendQueriesHandler from ResponseHandler import ResponseHandler class HomeHandler(webapp.RequestHandler): def get(self): self.response.out.write("Hello!") appRoute = webapp.WSGIApplication( ...
stolksdorf/lifetracker
web/home.py
home.py
py
508
python
en
code
1
github-code
6
20785922085
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('reviews.views', url(r'^$', 'home', name='home'), url(r'^courses/$', 'courses', name='courses'), url(r'^courses/find/$', 'find_course', name='find_course'), url(r'^...
aldeka/ClassShare
classshare/urls.py
urls.py
py
1,746
python
en
code
3
github-code
6
37892985042
class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: col_set = [set() for j in range(9)] row_set = [set() for j in range(9)] box_set = [set() for j in range(9)] for i in range(9): for j in range(9): if board[i][j] == ".": ...
johnrhimawan/LeetCode-Solution
Medium/valid-sudoku.py
valid-sudoku.py
py
644
python
en
code
0
github-code
6
40291222328
""" Purpose - A concordance Author - Vivek T S Date - 12/12/2018 """ def find(text, target): for index in range(len(text)-len(target)+1): if text[index:index+len(target)]==target: return index return -1 def concordanceEntry(target): textFile = open('Mobydick.txt','r',encoding='utf-8') lineNumber=1 for l...
vivekworks/learning-to-code
4. Discovering Computer Science/Python/Chapter 6 - Text, Documents & DNA/concordance.py
concordance.py
py
731
python
en
code
0
github-code
6
12903245570
import faust import uuid app = faust.App( 'greetings', broker='kafka://localhost:9092', ) class Greeting(faust.Record, serializer='json', isodates=True): message: str uuid: str greetings_topic = app.topic('greetings', value_type=Greeting) @app.agent(greetings_topic) async def get_gr...
tyao117/faust-fastapi
faust_hello_world.py
faust_hello_world.py
py
747
python
en
code
0
github-code
6
25508690525
#!/usr/bin/env python3 import requests import os url = 'http://localhost/upload/' path = os.getcwd() + '/supplier-data/images/' only_jpeg = [] for file in os.listdir(path): name, ext = os.path.splitext(file) if ext == '.jpeg': only_jpeg.append(os.path.join(path,file)) for jpeg in only_jpeg: with open(jpe...
paesgus/AutomationTI_finalproject
supplier_image_upload.py
supplier_image_upload.py
py
393
python
en
code
0
github-code
6
7781848764
import imutils import cv2 import numpy as np class DistanceCalculator: def __init__(self, distance_ref, width_ref, pixels): self.distance_ref = distance_ref self.width_ref = width_ref self.focal_ref = (pixels*distance_ref)/width_ref def find_object(self, original): """ ...
tarekbrahmi/Open-cv-project
MyProjects/distance-calculator/example2/DistanceCalculator.py
DistanceCalculator.py
py
1,870
python
en
code
0
github-code
6
34183851752
# def solution(s): # q, r = divmod(len(s), 2) # if r : q -= 1 # result_list = [] # for n in range(1, q+1): # cur = 0 # result_str = '' # print(n) # while cur < len(s): # cur_str = s[cur:cur + n] # count = 1 # for i in range(cur + n, le...
study-for-interview/algorithm-study
hanjo/개인용/programmers/카카오/L2_문자열압축/solution.py
solution.py
py
2,617
python
en
code
8
github-code
6
28193366899
from datetime import datetime, time import sys from time import sleep import datefunc def choose_date(now): datefunc.clear_terminal() option = input("Choose counter:\n 1 - time to pay,\n 2 - time to vacation,\n 3 - time to end of working day \n") datefunc.clear_terminal()\ if option == '1...
NikitaTymofeiev-dev/simpleApp
main.py
main.py
py
1,046
python
en
code
0
github-code
6
40787987363
## import libraries from tkinter import * from gtts import gTTS from playsound import playsound ################### Initialized window#################### root = Tk() root.geometry('350x300') root.resizable(0,0) root.config(bg = 'light yellow') root.title('DataFlair - TEXT_TO_SPEECH') ##heading ...
program444/HELIGA-TEKST-
Text-to-Speech.py
Text-to-Speech.py
py
1,453
python
en
code
0
github-code
6
71168432827
''' This project is a GUI calculator for a high yield savings account. The GUI will display 4 input boxes. An intial deposit, monthly deposit, APY yield, and years to calculate The result will be a number at the end of the year, as well as a graph that displays the growth of the account. Possible extras could incl...
MaxC1880/HYSAcalculator
HYSAcalculator.py
HYSAcalculator.py
py
6,918
python
en
code
0
github-code
6
71601372029
class Greeter: def __init__(self, meno): self._meno = meno self._vek = 30 def pozdrav(self): for i in range(0, 10): if i % 2 == 0: print("Ahoj {0}, mas {1} rokov. Vitaj na PSA v 2023".format(self._meno, self._vek+i)) print("Ah...
Merlinkooo/CviceniePondelok
cv1Triedy.py
cv1Triedy.py
py
466
python
hr
code
0
github-code
6
38486654704
from datetime import datetime, timezone, timedelta def stem(label: str, blacklist: list): ''' This function stems a given event label. Inputs: - label: single label to stem - blacklist: list of terms, that should be excluded from the label Return: stemmed label ''' parts = label.split...
bptlab/bpi-challenge-2020
src/util.py
util.py
py
2,829
python
en
code
4
github-code
6
23917961666
from langchain.document_loaders import WebBaseLoader from langchain.document_loaders import PyPDFLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.embeddings import HuggingFaceEmbeddings from langchain.vectorstores import Chroma import os from langchain.chat_models import JinaChat...
luongthang0105/rag-cla
create_bot.py
create_bot.py
py
2,864
python
en
code
0
github-code
6
74977721787
import logging import psycopg2 from dipper.sources.Source import Source LOG = logging.getLogger(__name__) class PostgreSQLSource(Source): """ Class for interfacing with remote Postgres databases """ files = {} def __init__( self, graph_type, are_bnodes_skole...
monarch-initiative/dipper
dipper/sources/PostgreSQLSource.py
PostgreSQLSource.py
py
6,689
python
en
code
53
github-code
6
70416777467
from multiprocessing import Value, Queue, Process from config import config from spider.HtmlCrawl import IpCrawl from usable.usable import usable from db.db_select import save_data def startProxyCrawl(queue,db_proxy_num): crawl = IpCrawl(queue,db_proxy_num) crawl.run() def validator(queue1,queue2): pass ...
queenswang/IpProxyPool
proxyspider.py
proxyspider.py
py
703
python
en
code
0
github-code
6
27161606711
# Written by RF while True: s1=float(input("What is the length of side one in cm?")) s2=float(input("What is the length of side two in cm?")) A=(s1*s2) print("The area is", A, "cm^2") while True: answer = str(input('Anything else? (y/n): ')) if answer in ('y', 'n'): brea...
GustavMH29/Python
Code/Math/Surface Area/Area Square.py
Area Square.py
py
443
python
en
code
0
github-code
6
5962399898
from aoc_helpers.perf_helpers import * from aoc_helpers.input_helpers import * from aoc_helpers.collection_helpers import * from aoc_helpers.test_helpers import * from collections import defaultdict from collections import Counter import string import time from pprint import pprint from itertools import cycle class...
colejd/AdventOfCode2018
day_09/day09part2.py
day09part2.py
py
2,316
python
en
code
0
github-code
6
19362201808
def ternary_search(list1,item): #the list must be sorted to implement ternary search low=0 # O(log3(n))---->Time Complexity high=len(list1)-1 # Divide the array in 3 parts and check for the item. ...
AnkitM18-tech/Data-Structures-And-Algorithms
Algorithms/Searching Algorithms/Ternary Search.py
Ternary Search.py
py
1,130
python
en
code
1
github-code
6
43190945536
from .object_tracking_visualizer_name import ObjectTrackingVisualizerName class ObjectTrackingVisualizerFactory(): def create(visualizer_name="TrackingVisualizer"): if visualizer_name == ObjectTrackingVisualizerName.tracking_visualizer.value: from .visualization.tracking_visualizer import Trac...
hampen2929/inferencia
inferencia/task/object_tracking/object_tracking/visualization/object_tracking_visualizer_factory.py
object_tracking_visualizer_factory.py
py
531
python
en
code
0
github-code
6
29041072051
from flask import Flask, jsonify from datetime import datetime import requests from flask import request app = Flask(__name__) logs = [] @app.route("/list", methods=["POST"]) def list(): r = request.data.decode("utf-8") logs.append(r) return jsonify(success=True) @app.route("/usage.log") def home(): ...
maciejgrosz/containers_network_communication
loggerservice/loggerservice.py
loggerservice.py
py
390
python
en
code
0
github-code
6
18158243961
def findRoot(f,a,b,epsilon) : m = (a + b) / 2 # Stopping criterion if abs(b - a) <= epsilon or f(m) == 0 : return m # Check if this is already a root if f(a) == 0 : return a if f(b) == 0 : return b # Go into recursion if (f(a) < 0 and f(m) > 0) or (f(a) > 0...
Saquith/WISB256
Opdracht4/bisection.py
bisection.py
py
1,119
python
en
code
0
github-code
6
7368325823
#! /usr/bin/env python def geokar_Ax(n, x, y): Ax = 0.0 for i in range(n): Ax = Ax + (x[i+1] + x[i]) * (y[i+1] - y[i]) return 0.5 * Ax def main(): # Vnos podatkov print("Vnos podatkov ...") n = int(input("Podaj število točk: ")) x = [] y = [] for i in range(n): #...
matevzdolenc/matevzdolenc.github.io
python/src/015/geokar.py
geokar.py
py
1,002
python
sl
code
4
github-code
6
27215126875
import pytest from hbutils.system import telnet, wait_for_port_online @pytest.mark.unittest class TestSystemNetworkTelnet: def test_telnet(self): assert telnet('127.0.0.1', 35127) assert telnet('127.0.0.1', 35128) assert not telnet('127.0.0.1', 35129, timeout=1.0) def test_wait_for_p...
HansBug/hbutils
test/system/network/test_telnet.py
test_telnet.py
py
559
python
en
code
7
github-code
6
3232593391
import logging class LogDB: def __init__(self,fileName): self.fileName = fileName self.loglist = [] self.files = None self.final = {} def log(self, message=None ): FORMAT = '%(asctime)s %(message)s' logging.basicConfig(format=FORMAT, filename=self.fileName) ...
reza2002801/Torrent
logDB.py
logDB.py
py
1,524
python
en
code
0
github-code
6
43279150633
from django.contrib import admin from django.urls import path from . import views app_name = 'task' urlpatterns=[ # path('', views.index, name='index') path('', views.TasksView.as_view(), name='index'), path('addtask/', views.add_task, name='addtask'), path('remover/', views.remove_all_task, name='...
eh97979/Task-manager
task_project/task/urls.py
urls.py
py
456
python
en
code
0
github-code
6
71924390587
from setuptools import setup, find_packages from os.path import join name = 'menhir.simple.livesearch' version = '0.1' readme = open("README.txt").read() history = open(join("docs", "HISTORY.txt")).read() setup(name = name, version = version, description = 'Dolmen simple extension : livesearch', lon...
trollfot/menhir.simple.livesearch
setup.py
setup.py
py
1,479
python
en
code
0
github-code
6
20538458179
# https://leetcode.com/problems/last-stone-weight/ """ Time complexity:- O(N logN) Space Complexity:- O(N) """ import heapq from typing import List class Solution: def lastStoneWeight(self, stones: List[int]) -> int: # Create a max heap (negate each element to simulate a min heap) h = [-x for x...
Amit258012/100daysofcode
Day60/last_stone_weight.py
last_stone_weight.py
py
844
python
en
code
0
github-code
6
5449618648
def longestCommonPrefix(self, strs: list[str]) -> str: res = min(strs, key = len) for i in strs: while res != i[:len(res)]: res = res[:-1] return res # A function to find the longest common prefix string amongst an array of strings. # If there is no common prefix, ...
jvm-coder/Hacktoberfest2022_aakash
Python/longest_common_prefix.py
longest_common_prefix.py
py
523
python
en
code
47
github-code
6
5469847519
import os import numpy as np from datetime import datetime import time from Utils import _add_loss_summaries from model import * #from augmentation import pre_process_image NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 367 NUM_EXAMPLES_PER_EPOCH_FOR_TEST = 101 NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 1 TEST_ITER = 200 # ceil(NUM_EXAM...
mohbattharani/Segmentation_
SegNet/train.py
train.py
py
7,704
python
en
code
0
github-code
6
28339877749
from itertools import product k,m = list(map(int,input().split())) arr = [] cart_prod = [] maxS=0 for _ in range(k): lstN = list(map(int,input().split()[1:])) arr.append(lstN) cart_prod = list(product(*arr)) for elem in cart_prod: sum1=0 for i in elem: sum1+=i**2 if sum1%m>maxS:...
t3chcrazy/Hackerrank
maximize-it.py
maximize-it.py
py
358
python
en
code
0
github-code
6
4785885470
from collections import defaultdict, deque n = int(input()) d = defaultdict(list) for i in range(1, n): l = list(map(int, input().split())) now = 1 for j in range(i+1, n+1): d[i].append((j, l[now-1])) d[j].append((i, l[now-1])) now += 1 print(d) s = set() max = 0 def dfs(now, flg...
K5h1n0/compe_prog_new
abc318/d/main.py
main.py
py
570
python
en
code
0
github-code
6
30172144350
import pandas as pd from models import DataPoint, db INDENTATION = 4 DB_NAME = "data_point" class DBHandler: __instance = None @staticmethod def get_instance(weather_app): """ Static access method. """ if DBHandler.__instance is None: DBHandler(weather_app) return DBH...
MayDruyan/weather-service
db_handler.py
db_handler.py
py
1,935
python
en
code
0
github-code
6
71992464828
import json # Đọc dữ liệu từ file input1.json và input2.json with open('input1.json', 'r', encoding='utf-8') as file1, open('input2.json', 'r', encoding='utf-8') as file2: data1 = json.load(file1) data2 = json.load(file2) # Tìm các cặp key có cùng giá trị trong cả hai file common_key_value_pairs = [] for key...
mminhlequang/python_tools
key_have_same_value/main.py
main.py
py
1,139
python
vi
code
0
github-code
6
8743120221
import pandas as pd #pandas是强大的分析结构化数据的工具集 as是赋予pandas别名 from matplotlib import pyplot as plt #2D绘图库,通过这个库将数据绘制成各种2D图形(直方图,散点图,条形图等) #全国哪一个城市地铁线最多 def subline_count(): df1 = df.iloc[:, :-1] #筛选前三列 df是下面main读取的 df2 = df1.drop_duplicates(subset=['city', 'subwayline']) # 去重 # ...
rlxy/python
爬虫/数据分析/城市地铁数量排行榜/analysis.py
analysis.py
py
1,315
python
zh
code
0
github-code
6
19580309816
import pytest from torch.optim import RMSprop as _RMSprop from neuralpy.optimizer import RMSprop @pytest.mark.parametrize( "learning_rate, alpha, eps, weight_decay, momentum, centered", [ (-6, 0.001, 0.001, 0.001, 0.001, False), (False, 0.001, 0.001, 0.001, 0.001, False), ("invalid", 0...
imdeepmind/NeuralPy
tests/neuralpy/optimizer/test_rmsprop.py
test_rmsprop.py
py
3,352
python
en
code
78
github-code
6
25273022270
x, y = map(int, input().split()) N = int(input()) # 가로, 세로 절단면을 저장할 리스트를 생성하고 처음과 끝 값을 저장 x_cut = [0, x] y_cut = [0, y] # 가로, 세로 절단면을 입력받고 해당 리스트에 저장 for _ in range(N): d, cut = map(int, input().split()) if d: x_cut.append(cut) else: y_cut.append(cut) x_max = 1 y_max = 1 # 연산을 용이하게 하기 위해서 내림...
powerticket/algorithm
Baekjoon/event/2628_com.py
2628_com.py
py
895
python
ko
code
0
github-code
6
42565773392
import time class AutoMail(): def __init__(self, mail_provider, mail_from, mail_to, timeout): self.mail_provider = mail_provider self.mail_from = mail_from self.mail_to = mail_to self.timeout = timeout self.images_bank = [] self.start_time = None def add_image(s...
Malik-Fleury/RaspPi_SuperVision
Program/Mail/AutoMail.py
AutoMail.py
py
920
python
en
code
0
github-code
6
43348614388
from scrabzl import Word, Dictionary import unicodedata def strip_accents(text): try: text = unicode(text, 'utf-8') except NameError: # unicode is a default on python 3 pass text = unicodedata.normalize('NFD', text)\ .encode('ascii', 'ignore')\ .decode("utf-8") ...
charleswilmot/scrabzl
src/create_dictionary.py
create_dictionary.py
py
1,733
python
en
code
0
github-code
6
5309109260
def search_matrix(matrix, target): # 예외 처리 if not matrix: return False # 첫행의 맨뒤 row = 0 col = len(matrix[0]) - 1 # 작으면 왼쪽, 크면 아래로 이동 while row <= len(matrix) - 1 and col >= 0: if target == matrix[row][col]: return True elif target < matrix[row][col]: ...
louisuss/Algorithms-Code-Upload
Python/Tips/BinarySearch/2d_matrix.py
2d_matrix.py
py
518
python
ko
code
0
github-code
6
34320404112
import urllib.request def get_url(digikeyID): with urllib.request.urlopen('https://www.digikey.com/products/en?keywords=' + digikeyID) as url: s = url.read() s = str(s) s = s.split('\\n') for line in s: if "lnkDatasheet" in line: line = line.strip(' ').split(' ') ...
aschwarz22/work_arr
prac/url.py
url.py
py
1,181
python
en
code
0
github-code
6
35945080718
import json import csv filename = 'data/predictions/test_prediction_RD_15_0.00003_4_finnum_5_bertuncase.csv' j = 0 predictions = [] with open(filename, 'r') as csvfile: datareader = csv.reader(csvfile) for row in datareader: j += 1 if j == 1: continue new_row = [] new_...
MikeDoes/ETH_NLP_Project
predictions_to_json.py
predictions_to_json.py
py
1,144
python
en
code
0
github-code
6
74055844987
import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from collections import namedtuple from .set2set import Set2Vec ReadoutConfig = namedtuple( 'ReadoutConfig', [ 'hidden_dim', 'readout_hidden_dim', 'mode', 'target_dim', ...
isaachenrion/gcn
models/mpnn/readout/readout.py
readout.py
py
3,763
python
en
code
0
github-code
6
38470272604
import collections def flatten_path(nested, parent_key=()): items = [] for k, v in nested.items(): new_key = parent_key + (k,) if isinstance(v, collections.abc.MutableMapping): items.extend(flatten_path(v, new_key).items()) else: items.append((new_key, v)) r...
BRGM/inept
inept/utils.py
utils.py
py
439
python
en
code
1
github-code
6
27773482180
import threading from sqlalchemy import Column, UnicodeText, Integer from telepyrobot.db import BASE, SESSION from telepyrobot.utils.msg_types import Types class Notes(BASE): __tablename__ = "self_notes" user_id = Column(Integer, primary_key=True) name = Column(UnicodeText, primary_key=True) value = C...
Divkix/TelePyroBot
telepyrobot/db/notes_db.py
notes_db.py
py
3,140
python
en
code
40
github-code
6
9633991773
import os import pandas FILES = [ "../.data/accidents_2005_to_2007.csv", "../.data/accidents_2009_to_2011.csv", "../.data/accidents_2012_to_2014.csv", ] def preprocess_accident_data(): for csv_file in FILES: df = pandas.read_csv(csv_file) data = df[[ 'Date', 'Day_of_Week'...
mustafa-cosar/ceng562
src/preprocess.py
preprocess.py
py
1,057
python
en
code
0
github-code
6
21296048306
# -*- coding: utf-8 -*- """ Created on Sat Oct 31 22:15:47 2020 @author: Sinki """ class Event: ''' 活动 ''' def __init__(self,event): ''' 根据event生成新的对象 { "name": "初心纪念活动", "start": "201101", "end": "201121", "gacha": [1,...
NingChenhui/Mirror
event.py
event.py
py
1,093
python
en
code
0
github-code
6
10887625874
from Korisnik import * class Sluzbenik(Korisnik): def __init__(self, korisnicko_ime, lozinka, id, sektor): super().__init__(korisnicko_ime, lozinka) self.id = id self.sektor = sektor @staticmethod def prijava(niz): #posto je staticka metoda, ne mora da ima self za paramet...
marko-smiljanic/vezbanje-strukture-podataka
vezbanje-strukture-podataka/V1_z2_korisnici/Sluzbenik.py
Sluzbenik.py
py
867
python
sl
code
0
github-code
6
36942726510
from PIL import Image myImg = Image.open('Image1.jpg') newImg = myImg.convert('L') print("Do you want your ", myImg, "converted to GRY?") print("Type: y or n") answer = str(input("y or n?: ")) if answer == "y": newImg.show() newImg.save('Image1_Grayscale.jpg') if answer == "n": myImg.show()
Sir-Lance/CS1400
EX7-3.py
EX7-3.py
py
304
python
en
code
0
github-code
6
7169957044
def solve_maze(n, instructions): dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] x = y = dir = 0 grid = [[0] * 100 for i in range(100)] for i in range(n): if instructions[i] == 'F': x += dx[dir] y += dy[dir] grid[x][y] = 1 elif instructions[i] == 'L': ...
Competitions-And-Hackathons/Cos-Pro-1tier-python
BOJ/구현/c미로만들기.py
c미로만들기.py
py
1,033
python
en
code
0
github-code
6
32644474997
import mgear.core.pyqt as gqt from mgear.vendor.Qt import QtCore, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(200, 133) self.verticalLayout_2 = QtWidgets.QVBoxLayout(Dialog) self.verticalLayout_2.setObjectName("verticalL...
mgear-dev/mgear4
release/scripts/mgear/shifter/component/chain_guide_initializer_ui.py
chain_guide_initializer_ui.py
py
4,345
python
en
code
209
github-code
6
26416473947
# -*- coding: UTF-8 -*- from flask import Flask from flask import request from flask import json import requests app = Flask(__name__) # http://blog.luisrei.com/articles/flaskrest.html @app.route('/oslh2b', methods=['POST']) def oslh2b(): if request.method == 'POST': json_headers = request.headers ...
elmanytas/osl-computer
ansible-flask/roles/flaskapp/files/flaskapp/flaskapp/__init__.py
__init__.py
py
12,045
python
en
code
2
github-code
6
73016495228
from tkinter import * from tkinter import ttk import sqlite3 import time #-------------------------------------- # DEFININDO MODULO HORA E DATA #-------------------------------------- time = time.localtime() hour = ('{}:{}'.format(time[3], time[4])) date = ('{}/{}/{}'.format(time[0], time[1], time[2])) #---------...
S4UDeveloper/MDI
DB/Database.py
Database.py
py
5,792
python
en
code
1
github-code
6
36339047472
import csv from datetime import datetime import random Header=["Time","Sample number","Temperature","Humidity","Sensor response", "PM response", "Temperature MFC"] dataLine=["","","","","","",""] with open('main.csv','w') as main: csv_writer=csv.writer(main, delimiter=",") csv_writer.writerow(Header) #csv_writer.wr...
Virgile-Colrat/YFA-Project_python_interface
Sources/testcs.py
testcs.py
py
723
python
en
code
0
github-code
6
22755470032
from collections import namedtuple import time from .utils import ( client_array_operation, make_valid_data, create_host_urn, create_resource_arn, create_hash, set_required_access_v2, transformation, ipaddress_to_urn ) from .registry import RegisteredResourceCollector from schematics imp...
StackVista/stackstate-agent-integrations
aws_topology/stackstate_checks/aws_topology/resources/ec2.py
ec2.py
py
14,997
python
en
code
1
github-code
6
34714688235
import argparse import torch import torch.utils.data import src.utils as utils from src.utils import alphabet from src.utils import strLabelConverterForAttention as converter import src.dataset as dataset import model parser = argparse.ArgumentParser() parser.add_argument('--testList', default='label/test_label.txt')...
WANGPeisheng1997/HandwrittenTextRecognition
cnn+lstm+attention/test.py
test.py
py
5,492
python
en
code
0
github-code
6
24423662765
#! /usr/bin/env python3 from typing import Any, Dict import rospy import dynamic_reconfigure.server from example_package_with_dynamic_reconfig.cfg import ExampleDynamicParametersConfig def dynamic_reconfigure_callback(config: Dict[str, Any], level: Any) -> Dict[str, Any]: return config if __name__ == "__main__"...
keivanzavari/dynamic-reconfigure-editor
example/example_package_with_dynamic_reconfig/src/example_package_with_dynamic_reconfig/node.py
node.py
py
710
python
en
code
0
github-code
6
35362077083
import random def hello(): print("------------------------------") print(" X and O ") print("------------------------------") print(" начнем игру ") print(" люди против машин ") print("------------------------------") print(" ...
SanSvin/X-and-0
Xand0 1.py
Xand0 1.py
py
5,446
python
en
code
0
github-code
6
72059016508
from random import randint play = True ronde = 1 bomb = randint(1,1) score = 0 while play == True: geuss = input("Ronde "+str(ronde)+": Op welk getal denkt U dat de bom ligt ") ronde = ronde + 1 nextRound = input("Wilt nu naar ronde "+str(ronde)+" (Y/N)? ").lower() if nextRound == "n": play...
Th0mas05/leren-programmeren
Klassikale opdrachten/sweeper.py
sweeper.py
py
352
python
nl
code
0
github-code
6
27391300473
# flake8: NOQA; import os import sys from collections.abc import Generator import pytest from fastapi import FastAPI from fastapi.testclient import TestClient current: str = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(os.path.join(current, "src")) from database import Database from ...
ebysofyan/dcentric-health-hometest
chatroom-backend/tests/conftest.py
conftest.py
py
868
python
en
code
0
github-code
6
21903304999
from tkinter import * import math class Calculator: '''Class to define the calculator and its layout''' def get_and_replace(self): ''' Replaces printable operators with machine readable ones''' self.expression = self.e.get() TRANS = self.expression.maketrans({ '÷':'/','x':'*'...
RahulKeluskar/Calculator
interface.py
interface.py
py
1,876
python
en
code
0
github-code
6
38746906775
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: #loop through the linked list and store the node in an array. Store the node and not Just the val of #node as the val can be repeated but node cannot be because ...
HiteshKhandelwal901/120DaysOfLeetCode
day4_question141.py
day4_question141.py
py
674
python
en
code
0
github-code
6
73111312187
from langchain.document_loaders import TextLoader from langchain.text_splitter import CharacterTextSplitter, NLTKTextSplitter import glob import os from transformers import AutoModel, AutoTokenizer from dotenv import load_dotenv from langchain.embeddings import HuggingFaceEmbeddings from langchain.vectorstores import C...
shaunxu/try-langchain
injest.py
injest.py
py
1,703
python
en
code
0
github-code
6
17657067303
from tkinter import * import pygame from tkinter import filedialog import time from mutagen.mp3 import MP3 import random from AudioFile import AudioFile, Song, Podcast from Exceptions import * from Playlist import Playlist from Artist import Artist from User import User from LastFmConnection import LastFmC...
ydamirkol/music-player
play mode3.py
play mode3.py
py
13,889
python
en
code
0
github-code
6
6713641650
""" Utilities for dictionaries of xy tuple values. """ from __future__ import print_function, division import random from collections import defaultdict def center(pos, dimensions): x = [p[0] for p in pos.values()] y = [p[1] for p in pos.values()] minx, maxx = min(x), max(x) miny, maxy = min(y), max(y...
joel-simon/evo_floorplans
floor_plans/pos_utils.py
pos_utils.py
py
1,635
python
en
code
84
github-code
6
34508602000
def merge(left, right): a= [] #[None]*(len(left)+len(right)) i=j=k =0 while i <= len(left)-1 and j <= len(right)-1: if left[i] <= right[j]: # a[k] = left[i] a.append(left[i]) k += 1 i += 1 else : # a[k] = right[j] ...
ved93/deliberate-practice-challenges
code-everyday-challenge/n136_repeat_program.py
n136_repeat_program.py
py
839
python
en
code
0
github-code
6
28194386524
from __future__ import print_function, division import os import time import random import numpy as np from base import BaseModel from replay_memory import ReplayMemory from utils import save_pkl, load_pkl import tensorflow as tf import matplotlib.pyplot as plt class Agent(BaseModel): def __init__(self, config, e...
BandaidZ/OptimizationofSEandEEBasedonDRL
agent.py
agent.py
py
18,757
python
en
code
13
github-code
6
12657115952
# level:medium # 思路:广度遍历,计算二叉树每层最大宽度,取最大值 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from Queue import Queue class Solution(object): def widthOfBinaryTree(self, root): """ ...
PouringRain/leetcode
662.py
662.py
py
1,534
python
en
code
1
github-code
6
20910138172
from constants import * from game.scripting.action import Action class DrawBricksAction(Action): def __init__(self, video_service): self._video_service = video_service def execute(self, cast, script, callback): bricks = cast.get_actors(BRICK_GROUP) for brick in brick...
Abstact/CSE210-projects
Group_Work/Pong/batter/game/scripting/draw_bricks_action.py
draw_bricks_action.py
py
720
python
en
code
2
github-code
6
18256028081
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- t=int(input()) for i in range(t): n=int(input()) l=[int(i) for i in input().split()] f=1 a=0 b=n-1 ans=[] for i in range(n): if f: ans.append(l[a]) a+=1 else: ans.append(l[b]) b-=1...
clarinet758/codeforces
round/round0676-700/round0690/a1.py
a1.py
py
356
python
en
code
0
github-code
6
1586622740
import tkinter as tk from tkinter import END, ttk, messagebox from tkinter.font import BOLD import util.generic as utl import mysql.connector class MasterPanel: def conectar_bd(self): # Conectar a la base de datos conexion = mysql.connector.connect( host='192.168.100.9', user=...
Guuuuussss/Proyecto-Acceso-y-Pase-de-Lista
Interfaz/forms/form_master.py
form_master.py
py
13,497
python
es
code
0
github-code
6
23706350056
#!/usr/bin/env python """Plot sky positions onto an Aitoff map of the sky. Usage: %s <filename>... [--racol=<racol>] [--deccol=<deccol>] [--mjdcol=<mjdcol>] [--filtercol=<filtercol>] [--expnamecol=<expnamecol>] [--commentcol=<commentcol>] [--usepatches] [--alpha=<alpha>] [--outfile=<outfile>] [--tight] [--delimiter=...
genghisken/gkplot
gkplot/scripts/skyplot.py
skyplot.py
py
15,360
python
en
code
0
github-code
6
7711698828
from PyPDF2 import PdfReader def get_pdf_text(pdfs): """ Get the pdf and extract the text content Parameters: pdf_docs (pdf) : all the pdfs Returns: string : returns text from the pdfs """ text = "" for pdf in pdfs: pdf_reader = PdfReader(pdf) for page in pdf...
arunavabasu-03/PDFAssist
src/helpers/getPdf.py
getPdf.py
py
399
python
en
code
0
github-code
6
23844088819
log_file = open("um-server-01.txt") #the variable log-file opens the parameter of um-server01.txt as readable, because the default is to read the text you do not have to declare the the file modes def sales_reports(log_file): #define function sales_reports from the argument log_file for line in log_file: #loops t...
heimdalalr/assessment-data
process.py
process.py
py
1,410
python
en
code
0
github-code
6
25687922492
import astroid from hypothesis import assume, given, settings, HealthCheck from .. import custom_hypothesis_support as cs from typing import Any, Dict, List, Set, Tuple settings.load_profile("pyta") @given(cs.subscript_node()) @settings(suppress_health_check=[HealthCheck.too_slow]) def test_index(node): module, ...
ihasan98/pyta
tests/test_type_inference/test_literals.py
test_literals.py
py
772
python
en
code
null
github-code
6
27712887237
class Solution: def canPartition(self, nums: List[int]) -> bool: sum_array = sum(nums) n = len(nums) if sum_array % 2 != 0: return False dp = set() dp.add(0) target = sum_array//2 for i in range(len(nums)): ...
jemis140/DSA_Practice
Dynamic Programming/Partiton_equal_sum.py
Partiton_equal_sum.py
py
506
python
en
code
0
github-code
6