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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
8404513140 | """
En una lengua alienígena también utilizan las letras del español,
pero posiblemente en un orden diferente.
Es una permutación de nuestro alfabeto.
Tu desafío es, dada una secuencia de palabras escritas en el
idioma extranjero y el orden del alfabeto alienígena,
devolver verdadero si y solo si las palabras dadas es... | javieramayapat/advanced-algorithms-and-data-structures-platzi | arrays-strings/two-pointer-pattern/verifiying-alien-dictionary.py | verifiying-alien-dictionary.py | py | 2,321 | python | es | code | 0 | github-code | 36 |
11927778388 | # Returns a list of the factors of a number
import math
def divisors(n):
divisorList = []
for divisor in range(1, round(math.sqrt(n)) + 1):
if n % divisor == 0:
divisorList.append(divisor)
if divisor == n//divisor:
continue
else:
divi... | aniruddhamurali/python-algorithms | src/math/number-theory/factors/divisors.py | divisors.py | py | 370 | python | en | code | 1 | github-code | 36 |
74062136745 | import re
with open('../data/input_201810.txt') as f:
lines = [l.rstrip('\n') for l in f]
lines = [[int(i) for i in re.findall(r'-?\d+', l)] for l in lines]
# print(lines)
#
# for i in range(20000):
# minx = min(x + i * vx for (x, y, vx, vy) in lines)
# maxx = max(x + i * vx for (x, y,... | eignatenkov/aoc2020 | solutions/day_201810.py | day_201810.py | py | 669 | python | en | code | 0 | github-code | 36 |
30832116443 | """
5. Elaborar un algoritmo casa de cambio, que reciba una cantidad de dinero en pesos colombianos y
realice su equivalente en dolares, yenes y euros, tenga en cuenta que el cambio deberá realizarse a la
tasa representativa de cada moneda (actual) y que la casa de cambio, incluye un 2% de ganancia a ese
valor.
""... | 1205-Sebas/TALLERCV-GOMEZ-DIAZ | Ejercicio5.py | Ejercicio5.py | py | 757 | python | es | code | 0 | github-code | 36 |
28632705196 | import time
import traceback
import functools
from functools import update_wrapper
from flask import request, make_response, current_app
from datetime import timedelta
from densefog import config
from densefog import logger
from densefog.common import jsonable
from densefog.common import local
from densefog.error_code... | hashipod/densefog | densefog/web/grand.py | grand.py | py | 5,280 | python | en | code | 0 | github-code | 36 |
32846353410 | # This program downloads a list of files from an NCBI FTP site that are delineated in a csv file.
# Assumes that the CSV file has a header, and skips the first row.
# ARGUMENT1 - CSV file that contains the URLs of the files to download.
# ARGUMENT2 - The suffix of the files to download. i.e. "_genomic.fna", "_protei... | platipenguin/metaproteomics-database-optimization | jupyter_notebooks/DownloadFromNCBIFTPtxt.py | DownloadFromNCBIFTPtxt.py | py | 2,950 | python | en | code | 0 | github-code | 36 |
33314270996 | def search_in_file(fname, search1, search2):
file_1 = open(fname, "r")
string_s = file_1.read()
file_1.close()
search1_count = 0
search2_count = 0
for letter in string_s:
if letter == search1:
search1_count = search1_count + 1
elif letter == search2:
searc... | YNaglenko/Python_lvl_1 | Hw11/Practice/Hw11_practice_2.py | Hw11_practice_2.py | py | 445 | python | en | code | 0 | github-code | 36 |
71513937705 | from src.capture import Capture
from src.config import Config
from src.detect import Detect
from src.display import Display
from src.label import Label
from src.local_camera import LocalCamera
from src.save import Save
from src.transform import Transform
from sys imp... | ColinShaw/yet-another-face-tracker | capture.py | capture.py | py | 1,346 | python | en | code | 3 | github-code | 36 |
19842328575 | import os
import re
from io import open
import torch
class Dictionary(object):
def __init__(self):
self.word2idx = {}
self.idx2word = []
def add_word(self, word):
if word not in self.word2idx:
self.idx2word.append(word)
self.word2idx[word] = len(self.idx2word) -... | TheMarvelousWhale/NTU-CE4045-NLP | Assignment2/part_1/data_fnn.py | data_fnn.py | py | 1,860 | python | en | code | 3 | github-code | 36 |
19123385662 | #!/usr/bin/env Python3
# Web scraping script for fun
import requests
from bs4 import BeautifulSoup
def scrape_website(url):
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, "html.parser")
links = soup.find_all("a")
for link in links:... | Caedesium/PythonPractice | Scripts1.0/webscraper1.py | webscraper1.py | py | 561 | python | en | code | 1 | github-code | 36 |
38069332889 | import re
def isvalid(expression):
stack = []
for ch in expression:
if ch == '(':
stack.append(ch)
elif ch == ')':
if not stack:
return False
stack.pop()
return not stack
def calculate(expression):
try:
expression = re.sub(... | Jay1105/Jay-GDSC-ML_Task | calc.py | calc.py | py | 792 | python | en | code | 0 | github-code | 36 |
8758398775 | # -*- coding: utf-8 -*-
from odoo import api, fields, models
import base64
from cStringIO import StringIO
import xlsxwriter
from xlsxwriter.utility import xl_range, xl_rowcol_to_cell
class OFRapportGestionStockWizard(models.TransientModel):
_name = "of.rapport.gestion.stock.wizard"
product_ids = fields.Many2... | odof/openfire | of_sale_stock/wizard/of_report_tableur_wizard.py | of_report_tableur_wizard.py | py | 10,613 | python | en | code | 3 | github-code | 36 |
18499754885 | import tkinter as tk
root = tk.Tk()
root.title("Hello")
root.geometry("200x300")
root["background"] = 'pink'
box1 = tk.Label(
root,
text="Hello tkinter",
bg="green",
fg="purple"
)
box1.pack(
ipadx=50,
ipady=100,
expand=True,
)
root.mainloop() | LaraMol/tkinter | hello.py | hello.py | py | 296 | python | en | code | 0 | github-code | 36 |
6418714782 | # defining main function
def main():
choice = 0
rep_dict = {}
# cause it to quit if user chooses 7
while choice != 7:
choice = menu()
print('\n')
# show list
if choice == 2:
print("Recipient list:" + '\n')
print('-------------------' + '\n')
... | alberto-guzman/CS-08-Python | project3FINAL.py | project3FINAL.py | py | 4,229 | python | en | code | 1 | github-code | 36 |
20803043179 | from django.contrib import messages
def info(request, msg):
"""
Log the message to the current page template if request is not None. Log msg
to stdout also.
"""
assert len(msg) > 0
if request is not None:
messages.info(request, msg, extra_tags="alert alert-secondary", fail_silently=True... | Robinqiuau/asxtrade | src/viewer/app/messages.py | messages.py | py | 999 | python | en | code | 0 | github-code | 36 |
4451991317 | import os
import sys
import tensorflow as tf
from tensorflow.keras import backend as K
# requirement : tensorflow 1.15
assert tf.__version__ == '1.15.2', 'Tensorflow version Error. You need 1.15.2 version'
assert len(sys.argv) == 2, 'Usage: python get_pretrained_model.py [output pb file path]'
output_path = sys.argv... | munema/tensorflow_helper | get_frozen_model.py | get_frozen_model.py | py | 1,459 | python | en | code | 0 | github-code | 36 |
14715992978 | from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Numeric, text
engine = create_engine('postgresql://postgres:1@localhost/news_db', echo = True)
meta = MetaData() # box
students = Table(
'students' , meta ,
Column('id' , Integer , primary_key=True),
Column('first_name' , S... | devabsaitov/self_study | sqlalchemy_lesson/Basic/3_insert _expression.py | 3_insert _expression.py | py | 912 | python | en | code | 0 | github-code | 36 |
23403038536 | #1
import mysql.connector
connection = mysql.connector.connect(
host = '127.0.0.1',
port = 3306,
database = 'flight_game',
user = 'dbuser',
password = 'pass_word'
)
def showairport(icao):
sql = "select ident, name, iso_country from airport"
sql += " WHERE ident='" + icao + "'"
print(sql)... | nguyenhis/MODULE8 | main.py | main.py | py | 3,024 | python | en | code | 0 | github-code | 36 |
1297708081 | import operator
from shared.configs import *
from services.visualizer import Visualizer
from services.world import World
from services.population import Population
class Controller:
"""
Controller, the central processing hub,
Responsible for handling the visualizer and other services
"""
def __i... | sujay-ee/genetic-rockets-simulation | services/controller.py | controller.py | py | 2,448 | python | en | code | 5 | github-code | 36 |
8933108827 | # Loops
list_data = [1, 2, 3, 4, 5]
embedded_list = [[1, 2, 3], [4, 5, 6]]
dict_data = {
1: {"name": "Reis",
"money": "£0.05"},
2: {"name": "Luke",
"money": "£3.66"},
3: {"name": "James",
"money": "£1.14"}
}
# Basic Loop
# for num in list_data:
# print(num * 2)
# Nested loops
"... | ReisCodes/control_flow | loops.py | loops.py | py | 1,205 | python | en | code | 0 | github-code | 36 |
23412397140 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('compras', '0018_auto_20151108_1208'),
]
operations = [
migrations.Alte... | pmmrpy/SIGB | compras/migrations_1/0019_auto_20151108_1747.py | 0019_auto_20151108_1747.py | py | 2,202 | python | es | code | 0 | github-code | 36 |
19141473384 | import matplotlib.pyplot as plt
import sys
from numpy import *
def _poly(a, x):
"""Returns the function value of a polynomial with coefficients a and variable x.
Parameters
----------
a : list
a list of coefficients
x : number
the variable of the polynomial
Returns
-------... | wiLLSE23/DAT455 | Labs/Labb3/numpy_regression.py | numpy_regression.py | py | 2,675 | python | en | code | 0 | github-code | 36 |
26822270635 | import requests
import json
import openpyxl
import pandas as pd
from dotenv import load_dotenv
load_dotenv()
import os
import time
import asyncio
import aiohttp
api_key_binance = os.environ.get('API_B')
api_secret_binance = os.environ.get('SECRET_B')
async def get_binance_futures_tickers():
url = 'https://fapi.bin... | BobbyAxer/Binance_funding_calc | main.py | main.py | py | 3,519 | python | en | code | 0 | github-code | 36 |
26077331720 | import grid_ops, random
#Abstract search tree class
class Node():
# this is the constructor of the node class it takes the state of the node (a
# 2D grid), the operator from the parent that lead to the current node, the
# parent node itself, depth of the current node, path cost from root and
# whether it is ro... | m0hamed/2048-solver | adt.py | adt.py | py | 1,858 | python | en | code | 0 | github-code | 36 |
32823335080 | # **41.** Дан массив, состоящий из целых чисел.
# Напишите программу, которая в данном массиве
# определит количество элементов, у которых два
# соседних и, при этом, оба соседних элемента меньше данного.
# Массив чисел вводится в одну строку через пробел.
# Массив состоит из целых чисел.
# Пример:
# 5 1 3 7 9 6 -> 1
#... | NaumovM/GeekBrains | Python/sem6/task41.py | task41.py | py | 764 | python | ru | code | 0 | github-code | 36 |
11863065064 | # Orbit propagator class to encapsulate solve
import numpy as np
import matplotlib.pyplot as plt
## for newer scipy.integrate
# import scipy.integrate as ode
## for older scipy.integrate (in the videos)
from scipy.integrate import ode
from mpl_toolkits.mplot3d import Axes3D
import planetary_data as pd
class OrbitPro... | stevespreiz/orbit-solver | src/OrbitPropagator.py | OrbitPropagator.py | py | 3,754 | python | en | code | 0 | github-code | 36 |
74791822182 | import os
import csv
import logging
from collections import defaultdict
logger = logging.getLogger(__name__)
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO
)
# ROOT_PATH = "/Midgard/home/martinig/thesis-src"
ROOT_PATH ... | martinigoyanes/LexiconGST | src/postprocessing/collect_results.py | collect_results.py | py | 5,189 | python | en | code | 0 | github-code | 36 |
15534559885 | '''Setup script for GridCells.'''
from __future__ import absolute_import, print_function, division
from os.path import join
try:
from setuptools import setup, Extension
except ImportError:
from distutils.core import setup, Extension
all_packages = [
'gridcells',
'gridcells.analysis',
'gridcells.co... | MattNolanLab/gridcells | setup.py | setup.py | py | 4,136 | python | en | code | 6 | github-code | 36 |
11326856436 | import math
import numpy as np
def total_demand(customers):
return sum((c.demand for c in customers))
def total_cost(allocations, customers, facilities):
m = 1
try:
validate(allocations, customers, facilities)
except AssertionError:
diag = diagnose(allocations, customers, facilities)... | pooyad359/discrete-optim | 5 facility/calc.py | calc.py | py | 3,071 | python | en | code | 0 | github-code | 36 |
28890469001 | """Public interface to top-level pytype functions."""
import contextlib
import dataclasses
import logging
import os
import sys
import traceback
from typing import Optional
import libcst
from pytype import __version__
from pytype import analyze
from pytype import config
from pytype import constant_folding
from pytyp... | google/pytype | pytype/io.py | io.py | py | 11,659 | python | en | code | 4,405 | github-code | 36 |
36635815592 | #Caching Mode
from config import api_id, api_key, account_id, site_ip, get_site_status
import requests
url_cache_mode = 'https://my.imperva.com/api/prov/v1/sites/performance/cache-mode'
def modify_cache_mode():
with open('./domain.txt', 'r', encoding="utf-8") as file:
domain_site = get_site_status... | coeus-lei/python | imperva/ModifyCacheMode.py | ModifyCacheMode.py | py | 851 | python | en | code | 0 | github-code | 36 |
43229153536 | import requests
def buscar_avatar(usuario):
"""
Buscar o avatar de um usuario no GitHub
:param usuario: str com o nome de usuario do github
:return: str com o link do avatar
"""
url = f'https://api.github.com/users/{usuario}'
resp = requests.get(url)
return resp.json()['avatar_url']
... | wartrax13/libpythonpro | libpythonpro/github_api.py | github_api.py | py | 386 | python | pt | code | 1 | github-code | 36 |
5535781560 |
"""
Whether or not city links should be enabled.
This is used to check if moves are valid.
If True, player moves are checked for validity. This is done using `drac_links.py`
If False, any player can move from any location to any other location.
"""
links = True
"""
The mode to run drac in.
Valid settings are:
... | nickrobson/drac | drac_config.py | drac_config.py | py | 1,591 | python | en | code | 1 | github-code | 36 |
17928875089 | # -*- coding: utf-8 -*-
import datetime
from django.utils.decorators import method_decorator
from django.conf import settings
from django.contrib.auth.decorators import permission_required
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
from django.db.models import Count
from dja... | jgesim/kiwitcms | tcms/testplans/views.py | views.py | py | 28,207 | python | en | code | 1 | github-code | 36 |
22292426243 | '''
큰 수 만들기
문제 설명
어떤 숫자에서 k개의 수를 제거했을 때 얻을 수 있는 가장 큰 숫자를 구하려 합니다.
예를 들어, 숫자 1924에서 수 두 개를 제거하면 [19, 12, 14, 92, 94, 24] 를 만들 수 있습니다. 이 중 가장 큰 숫자는 94 입니다.
문자열 형식으로 숫자 number와 제거할 수의 개수 k가 solution 함수의 매개변수로 주어집니다. number에서 k 개의 수를 제거했을 때 만들 수 있는 수 중 가장 큰 숫자를 문자열 형태로 return 하도록 solution 함수를 완성하세요.
제한 조건
number는 1자리 이상... | 98hyun/algorithm | greedy/p_41.py | p_41.py | py | 1,397 | python | ko | code | 0 | github-code | 36 |
12117482478 | if self.last == None:
new_client = Client(name, pin)
self.last = ClientList.Node(new_client, None)
else:
current = self.last
while current is not None:
if current.data.userName == name:
node.data.setPin(pin)
found = True
break
current = curre... | HOIg3r/LINFO1101-Intro-a-la-progra | Exercices INGI/Examen Blanc/ClientList.updtate.py | ClientList.updtate.py | py | 441 | python | en | code | 4 | github-code | 36 |
34574985230 | m, n = map(int, input().split())
big_set = set(range(1, n + 1))
items = list(map(int, input().split()[:m]))
friends = {i + 1: set(range(1, items[i] + 1)) for i in range(m)}
for k, v in friends.items():
tmp = big_set.difference(v)
if len(tmp) == 0:
print(-1)
exit(0)
value = next(iter(tmp))
... | Squarx/Route256-Contest | E-Cards.py | E-Cards.py | py | 418 | python | en | code | 0 | github-code | 36 |
24854285401 | import requests
STOCK_NAME = "TSLA"
COMPANY_NAME = "Tesla Inc"
STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"
api_key = "6KPNON1CEDUUZNPO"
news_api_key = "9738bfb7f9b648b197ca544a5d4da261"
stock_parameters = {
"function": "TIME_SERIES_DAILY",
"symbol... | rkhidesh/100-Days-Of-Code | 100 Days/day36/main.py | main.py | py | 1,035 | python | en | code | 0 | github-code | 36 |
14497607923 | import unittest
from reverse_string import reverse
class ReverseStringTests(unittest.TestCase):
def test_reverse(self):
my_string = "testing"
my_reversed_string = "gnitset"
returned_string = reverse(my_string)
assert my_reversed_string == returned_string
if __name__ =... | mjhea0/python-devtest | part1/reverse-string/reverse_reisch/test_reverse.py | test_reverse.py | py | 356 | python | en | code | 14 | github-code | 36 |
29296183032 | from django.views import generic # 2nd
from other.models import Ramadan, Feature
#==========================================================
class RamadanListView(generic.ListView):
model = Ramadan
paginate_by = 4
class RamadanDetailView(generic.DetailView):
model = Ramadan
#======================... | anowar143/django-news-frontend | src/other/views.py | views.py | py | 509 | python | en | code | 1 | github-code | 36 |
39946543852 | import json
import pathlib
from function import handler
from testing.mock import LambdaContext
current_dir = pathlib.Path(__file__).parent.resolve()
def test_message_ept_good_request() -> None:
"""Test /message endpoint with good request"""
with open(
f"{current_dir}/data/test_message_ept_good_reques... | AlgoWolf-com/aw2-api-backend | api-gateway/user-api/tests/function_test.py | function_test.py | py | 984 | python | en | code | 0 | github-code | 36 |
74050346024 | import os
import random
from collections import defaultdict
from parlai.tasks.md_gender.build import build
"""
Gender utilities for the multiclass gender classification tasks.
"""
MASK_TOKEN = '[MASK]'
MASC = 'male'
FEM = 'female'
NEUTRAL = 'gender-neutral'
NONBINARY = 'non-binary'
UNKNOWN = 'unknown'
SELF_UNKNOWN... | facebookresearch/ParlAI | parlai/tasks/md_gender/utils.py | utils.py | py | 8,435 | python | en | code | 10,365 | github-code | 36 |
28295707377 | #!/bin/env python3
import nltk
# load the grammar and sentences
grammar = nltk.data.load("grammars/atis-grammar-original.cfg")
sents = nltk.data.load("grammars/atis-test-sentences.txt")
sents = nltk.parse.util.extract_test_sentences(sents)
parser = nltk.parse.BottomUpChartParser(grammar)
for sent, _ in sents:
tr... | zouharvi/uds-student | computational_linguistics/hw3/generate_gold_counts.py | generate_gold_counts.py | py | 464 | python | en | code | 0 | github-code | 36 |
36223801735 | import tkinter as tk
from Interface import Interface
from Converter import Converter
from Online import Online
# Objective: Show Interface with two buttons to open Calculator or Converter
class Main_Window(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
... | mileesingh/pythoncalculator | Main_Window.py | Main_Window.py | py | 1,443 | python | en | code | 0 | github-code | 36 |
25822096454 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
class Star:
def __init__(self, name, x = 0, y = 0):
self.name = name
self.x = x
self.y = y
def rotate(self, angle):
rad = angle * (math.pi / 180)
self.x = self.x * math.cos(rad) - self.y * math.sin(rad)
... | LiudaShevliuk/python | lab12_2/lab12_2.py | lab12_2.py | py | 1,065 | python | en | code | 0 | github-code | 36 |
13651355448 | # В данном упражнении мы развернем ситуацию из предыдущей задачи. На этот раз вам предстоит
# написать программу, в которой пользователь будет вводить временной промежуток
# в виде общего количества секунд,после чего на экране должна быть показана та же длительность
# в формате D:HH:MM:SS, где D, HH, MM и SS – это коли... | Wladislavich/Wlad_study | Python excercises/chapter 1 - variables/ex025 Units of time2.py | ex025 Units of time2.py | py | 2,115 | python | ru | code | 0 | github-code | 36 |
43509231022 | import socket
import threading
from ConnectionHandler import ConnectionHandler
from enum import Enum
class Role(Enum):
SERVER = 1
CLIENT = 2
class NetworkInterface:
def __init__(self):
self.listeners = []
self.connectionHandler = ConnectionHandler()
self.running = True
def s... | ChrisWindmill/NWS | 01 Network Examples/18 Wait for server to be available/NetworkInterface.py | NetworkInterface.py | py | 2,518 | python | en | code | 2 | github-code | 36 |
42147496534 | from pydantic import BaseModel
class ServiceInfo(BaseModel):
name: str
service_type: str
namespace: str
classification: str = "None"
deleted: bool = False
def get_service_key(self) -> str:
return f"{self.namespace}/{self.service_type}/{self.name}"
def __eq__(self, other):
... | m8e/robusta | src/robusta/core/model/services.py | services.py | py | 670 | python | en | code | null | github-code | 36 |
36168261306 | # Do not modify these lines
__winc_id__ = '49bce82ef9cc475ca3146ee15b0259d0'
__human_name__ = 'functions'
# Add your code after this line
def greet(name):
greetings = 'Hello, '
return f'{greetings}{name}!'
greetints = greet('Fred')
print(greetints)
def add(a,b,c):
calc1 = a + b + c
return calc1
s... | BJanssen78/Winc | functions/main.py | main.py | py | 614 | python | en | code | 0 | github-code | 36 |
12598914400 | # Write a program where only the process with number zero reports on how many processes there are in total.
from mpi4py import MPI
comm = (
MPI.COMM_WORLD
) # Default communicator in MPI. Groups processes together all are connected.
proc_nom = comm.Get_rank() # Current process number.
nom_procs = comm.Get_size(... | GMW99/mpi-examples | exercises/2.5.py | 2.5.py | py | 423 | python | en | code | 0 | github-code | 36 |
11005944981 | # The variables which are intialized or declared with the help of self keyword are called as instancevariables.
class Student:
def __init__(self,name,age,rollno,dob):
self.name = name
self.age = age
self.rollno = rollno
self.dob = dob
def getInfo(self):
print('Name... | srimani-programmer/OOPS-WITH-PYTHON | Variables/InstanceVariables.py | InstanceVariables.py | py | 582 | python | en | code | 1 | github-code | 36 |
9817005327 | import os,torch,warnings,sys
import numpy as np
from Schrobine import *
import matplotlib.pyplot as plt
global args
warnings.filterwarnings('ignore')
SetSeed()
args = Parse()
labelupdateindex=100
TureLabel = torch.from_numpy(np.load('Label1024.npy')).long()
ActuralLabel = torch.from_numpy(np.load('Label1024.npy')).long... | suzuqiang/TMECH-09-2022-14281 | 函数测试.py | 函数测试.py | py | 1,194 | python | en | code | 0 | github-code | 36 |
25873666341 | from flask import Flask,render_template,request,redirect,url_for
import tweepy
import textblob
import pandas as pd
import numpy as np
app= Flask(__name__)
@app.route('/', methods = ['POST', 'GET'])
def data():
consumer_key= "*********"
consumer_secret= "**********"
access_token= "**********"
access_to... | harman4498/Tweet_Sentiment_Analysis | sentiment.py | sentiment.py | py | 1,694 | python | en | code | 1 | github-code | 36 |
10589524750 | from pathlib import Path
from enum import Enum
DEFAULT_FILE_CONTENT_VALUE = ""
DEFAULT_CURRENT_LINE_CONTENT_VALUE = []
PARAMETER_OPEN = "<"
PARAMETER_CLOSE = ">"
START_KEYWORD = "$"
KEYWORDS_TABLE = \
(
"$CREATE_FILE",
"$LINK",
"$FILE",
"$TEXT",
"$TARGET"
)
class KEYW... | Cijei03/TextFilesMerger | Parser.py | Parser.py | py | 5,126 | python | en | code | 0 | github-code | 36 |
27942071843 | import argparse
from src.screen import Screen
def check_difficulty():
difficulty = input("What difficulty do you want to play?\n 1-)easy 2-)medium\n 3-)hard\n")
if difficulty == '1' or difficulty=='easy':
main('easy')
elif difficulty == '2' or difficulty=='medium':
main('medium')
eli... | DantasEduardo/minefield | main.py | main.py | py | 1,421 | python | en | code | 1 | github-code | 36 |
25430599066 |
import requests
class Github:
def __init__(self):
self.name = "Github"
self.base_url = 'https://api.github.com'
self.description = "This service is all about Github."
self.actions = ["detect_new_repository", "detect_new_follower", "detect_new_following"]
self.reactions = ... | arkea-tech/DEV_area_2019 | server/Components/github_service.py | github_service.py | py | 855 | python | en | code | 0 | github-code | 36 |
6994313010 | from lib.cuckoo.common.abstracts import Signature
class MemoryAvailable(Signature):
name = "antivm_memory_available"
description = "Checks amount of memory in system, this can be used to detect virtual machines that have a low amount of memory available"
severity = 1
categories = ["anti-vm"]
author... | cuckoosandbox/community | modules/signatures/windows/antivm_memory_available.py | antivm_memory_available.py | py | 954 | python | en | code | 312 | github-code | 36 |
42689797779 | import time
from itchat.content import *
from master_robot import Robot
FENQUN_HELP = '''回复【我要进群】进行下一步操作'''
FENQUN_AUTOREPLY = '''这是由名片全能王筹建的商务合作社群,是人脉共享,资源对接的免费共享平台,名片全能王app有2亿优质商务用户,目前社群人数30,000+,群数量100+。
【1023】机械机电自动化交流群
【1024】金融行业交流群
【1025】IT互联网行业交流群
【1026】房产建筑行业交流群
【1027】快消零售交流群
【1028】广告媒体交流群
【1029】教育行业交流群
【103... | Dkner/weixin_robot | fenqun_robot.py | fenqun_robot.py | py | 5,228 | python | zh | code | 0 | github-code | 36 |
71050502825 | def decodeString(s):
stack = []
for char in s:
if char != ']':
stack.append(char)
else:
decoded_str = ''
while stack[-1] != '[':
decoded_str += stack.pop()
stack.pop() # Pop the opening bracket '['
k = ''
... | Shreyanshraj12/practice8 | question7.py | question7.py | py | 722 | python | en | code | 0 | github-code | 36 |
19566926375 | import machine
import utime
from stepper import STEPPER
from LCD import CharLCD
from rotary_irq_rp2 import RotaryIRQ
from config import *
lcd.clear()
lcd.message("Photogrammetry", 2)
lcd.set_line(1)
lcd.message("Set deg: 00",2)
val_old = r.value()
while True:
val_new = r.value()
if val_old != val_new:
... | WhackyPanos/legendary-rotary-photographer | software/old/main (copy).py | main (copy).py | py | 868 | python | en | code | 0 | github-code | 36 |
38033762926 | import asyncio
import inspect
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import List
import pytest
from typing_extensions import Annotated, TypedDict
from pydantic import BaseModel, Extra, Field, ValidationError, validate_arguments
from pydantic.decorator import ValidatedF... | merlinepedra25/PYDANTIC | tests/test_decorator.py | test_decorator.py | py | 13,616 | python | en | code | 1 | github-code | 36 |
8555906265 | import torch
import torch.nn as nn
import torch.autograd as autograd
import torch.nn.functional as F
import numpy as np
torch.set_num_threads(8)
class Model(nn.Module):
def __init__(self,
hidden_dim = 512,
representation_len=300,
dropout = .5,
... | mrwangyou/IDSD | repLearning/cnn.py | cnn.py | py | 2,495 | python | en | code | 4 | github-code | 36 |
11737234773 | from copy import deepcopy
from zope.interface import implements
from Globals import InitializeClass
from AccessControl import ClassSecurityInfo
from Acquisition import aq_base, aq_inner, aq_parent, aq_chain
from OFS.PropertyManager import PropertyManager
from Products.CMFCore.utils import getToolByName
from Products.... | nuxeo-cps/products--CPSSchemas | widgets/indirect.py | indirect.py | py | 7,146 | python | en | code | 0 | github-code | 36 |
19931655401 | import typing
from .datatype import Datatype
def parse_int(v: typing.Any) -> int:
"""Parse the value `v` to an int.
This function fixes parsing values like "100.1" to int by rounding.
Raises
------
ValueError
When the value `v` could not be parsed
Parameters
----------
v... | miile7/pylo-project | pylo/default_datatypes.py | default_datatypes.py | py | 3,582 | python | en | code | 1 | github-code | 36 |
73360095144 | # django imports
from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
from django.db.models.signals import post_save
from django.db.models.signals import pre_save
from django.db.models.signals import pre_delete
# lfs imports
from lfs.caching.utils import clear_cache
from lfs.c... | django-lfs/lfs | caching/listeners.py | listeners.py | py | 7,661 | python | en | code | 23 | github-code | 36 |
16937190382 | import re
import pandas as pd
import requests
from bs4 import BeautifulSoup as bs
base = "https://www.dictionary.com/browse/"
csv = pd.read_csv("words.csv")
meaning = []
pronounce = []
password = []
words = csv["Word"]
for word in words:
url = base + word
try:
read = requests.get(url,... | priyakaur/portifolio | fetch_meaning.py | fetch_meaning.py | py | 1,586 | python | en | code | 0 | github-code | 36 |
16434367671 | #!/usr/bin env python 3.4
import subprocess
import os,re,sys
import enums
import androiddevicebt
from subprocess import Popen,PIPE,STDOUT,check_output, CalledProcessError
#to perform adb root on the windows machine
def adbroot(device):
try:
t=subprocess.call(["adb","-s",device,"root"],shell=True)
except CalledPr... | supermannba/Workspace | lib/adbmodule.py | adbmodule.py | py | 2,804 | python | en | code | 0 | github-code | 36 |
42335487280 | # Дано натуральное число A > 1. Определите, каким по
# счету числом Фибоначчи оно является, то есть
# выведите такое число n, что φ(n)=A. Если А не
# является числом Фибоначчи, выведите число -1.
# Input: 5
# Output: 6.
number = int(input('Введите натуральное число больше 1 : '))
if number < 0:
print('Перечитай ус... | Britani/Acquaintance_wich_Pyhton | seminar_2_11.py | seminar_2_11.py | py | 1,105 | python | ru | code | 0 | github-code | 36 |
26373220797 | import pandas as pd
import numpy as np
import math
def export_to_excel_powiaty(path_to_excel, dochod_na_jst_2019, dochod_na_jst_2020, ludnosc_w_jst_2020, sredni_dochod_opodatkowany_20, wariancja_dochodu, srednia_wazona):
powiaty = {}
for wk, pk, gk, gt in ludnosc_w_jst_2020[['WK','PK','GK','GT']].val... | czarobxm/NYPD | projekt_zaliczeniowy_NYPD/pit_module/pit/export/export_to_excel_powiaty.py | export_to_excel_powiaty.py | py | 4,838 | python | pl | code | 0 | github-code | 36 |
29403941645 | """Handlers tests."""
from django.conf import settings
from django.db.models.signals import post_save
from django.test import override_settings
from test_plus.test import TestCase
import responses
import rovercode_web
@override_settings(SUBSCRIPTION_SERVICE_HOST='http://test.test')
class TestHandlers(TestCase):
... | rovercode/rovercode-web | rovercode_web/users/tests/test_handlers.py | test_handlers.py | py | 1,401 | python | en | code | 14 | github-code | 36 |
12485364280 | budget = float(input())
people = int(input())
price_dress = float(input())
decoration = budget * 0.1
total_dress = people * price_dress
if people > 150:
total_dress = total_dress - (total_dress * 0.1)
expenses = decoration + total_dress
if expenses > budget:
print(f"Not enough money!")
pri... | SimeonTsvetanov/Coding-Lessons | SoftUni Lessons/Python Development/Python Basics April 2019/Lessons and Problems/05 - Conditional Statements Exercise/06. Godzilla vs. Kong .py | 06. Godzilla vs. Kong .py | py | 494 | python | en | code | 9 | github-code | 36 |
40965965237 | from django.urls import path
from django.views.decorators.cache import cache_page, never_cache
from catalog.apps import CatalogConfig
from catalog.views import HomeView, ContactsView, ProductDetailView, ProductListView, ProductDeleteView, \
ProductCreateView, \
ProductUpdateView, BlogRecordListView, \
Blog... | DSulzhits/06_2_3 | catalog/urls.py | urls.py | py | 2,135 | python | en | code | 0 | github-code | 36 |
16537362389 | import json
import pickle
import math
import os
import torch
import numpy as np
from pycocoevalcap.eval import COCOEvalCap
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence
from torch.utils.data import DataLoader
from torchvision.transforms import transforms
from build_vocab import Vocabulary
... | b-feldmann/ImcaptionNet | train.py | train.py | py | 5,421 | python | en | code | 1 | github-code | 36 |
38900063978 | import numpy as np
import adcpreader
mounted_pitch=11*np.pi/180
# first transform
t0 = adcpreader.rdi_transforms.TransformENU_SFU()
t1 = adcpreader.rdi_transforms.TransformSFU_XYZ(0, mounted_pitch, 0)
t2 = adcpreader.rdi_transforms.TransformXYZ_BEAM()
transform_enu_to_beam = t2 * t1 * t0
# second transform
t3 = adc... | smerckel/adcpreader | examples/pipeline.py | pipeline.py | py | 1,606 | python | en | code | 0 | github-code | 36 |
72529053224 | from django.shortcuts import render_to_response, render
from django.contrib.auth.decorators import login_required
from models import Court
from notification.models import Notification
# Create your views here.
@login_required
def all(request):
'''
To list all the court
:param request:
:return:
''... | Championzb/TenniSoda | court/views.py | views.py | py | 662 | python | en | code | 0 | github-code | 36 |
8123580390 | '''The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.'''
#true is prime and false is not prime
def sieve(n):
is_prime=[True]*(n-1)
current_prime=2
total_sum=0
#takes the current prime and does 2p, 3p, 4p, 5p etc
#repeats for every prime checking
whi... | amoghkapalli/ProjectEuler | Problem10.py | Problem10.py | py | 1,010 | python | en | code | 0 | github-code | 36 |
7405420240 | import numpy as np
import operator
import matplotlib.pyplot as plt
import os
def createDataSet():
group = np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group, labels
def classify0(inX, dataSet, labels, k): #k-近邻算法
dataSetSize = dataSet.shape[0] #shape代表读取矩阵第一维度的长度
... | GuoBayern/MachineLearning | kNN.py | kNN.py | py | 6,576 | python | en | code | 0 | github-code | 36 |
36168242476 | # Do not modify these lines
__winc_id__ = '63ce21059cf34d3d8ffef497ede7e317'
__human_name__ = 'comments'
# Add your code after this line
# Here's a single-line comment.
answer = 42
question = "How many roads?" # Here's an end-of-line comment.
""" Here's a multiline comment.
It uses multiple lines and is the only comm... | BJanssen78/Winc | comments/main.py | main.py | py | 559 | python | en | code | 0 | github-code | 36 |
6939711390 | from bokeh.plotting import figure, show
x = [1, 2, 3, 4, 5]
y1 = [6, 7, 2, 4, 5]
y2 = [2, 3, 4, 5, 6]
y3 = [4, 5, 5, 7, 2]
p = figure(title="Multiple bars example")
# top defines the single y-coord for each bar; stated more clearly, height
# bottom defines y-intercept, i.e. the 0 value where the lowest data pt starts... | marnatgon/Senior-Design | software/example/bokeh/2-custom-render/bar.py | bar.py | py | 525 | python | en | code | 0 | github-code | 36 |
70806732583 | from bs4 import BeautifulSoup
import requests
import time
import json
import wikipedia
import html2text
API_URL = "https://{}.fandom.com/api.php"
def timeit(fn):
def wrapper(*args, **kwargs):
av_list = []
for i in range(10):
start = time.time()
fn(*args, **kwargs)
... | Unic-X/Kala-Bot | commands/Fandom/fandom.py | fandom.py | py | 4,901 | python | en | code | 2 | github-code | 36 |
41865321011 | import sys
import copy
import tempfile
import os.path
import filecmp
import shutil
import functools
from album import Album, ParseError, SaveError
TEST_CASE_DIR = "test_cases/DyphalGenerator_Album_save"
def create_file(name, dir_name):
with open(os.path.join(dir_name, name), "w") as f:
pass
def create_f... | rdegraaf/dyphal | test/test_DyphalGenerator_Album_save.py | test_DyphalGenerator_Album_save.py | py | 7,238 | python | en | code | 2 | github-code | 36 |
7838997057 | from django.conf.urls import url
from django.contrib.auth.views import LoginView, LogoutView
from .views import *
urlpatterns = [
url(r'^login/',
LoginView.as_view(template_name='management/login.html'), name='login'),
url(r'^logout/',
LogoutView.as_view(template_name='management/logout.html',
... | robbydrive/RestaurantsAPI | management/urls.py | urls.py | py | 1,143 | python | en | code | 0 | github-code | 36 |
29142750716 | # Assignment Collector/Grader - a Django app for collecting and grading code
# Copyright (C) 2010,2011,2012 Anthony Rossi <anro@acm.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free ... | rossica/assignmentcollectorgrader | collector/admin.py | admin.py | py | 7,481 | python | en | code | 0 | github-code | 36 |
4108346507 | for q in range(5):
grid = []
for _ in range(8):
line = input()
a = []
for i in line:
if i in "123456789":
a.append(int(i))
elif i == ".":
a.append(0)
else:
a.append(-1)
grid.append(a)
dp = [[0... | AAZZAZRON/DMOJ-Solutions | dwite10c2p3.py | dwite10c2p3.py | py | 615 | python | en | code | 1 | github-code | 36 |
12340279038 | # treatment of routes for search
from pathlib import Path
from flask import Blueprint, \
make_response, \
render_template, \
request, \
session
from backend.collect import container_images_cache, \
update_status
from backend.config import config
from frontend.misc import is_htmx
SORTABLE_BY = [... | HenriWahl/gitlab-container-registry-hub | frontend/search.py | search.py | py | 6,841 | python | en | code | 1 | github-code | 36 |
4108142067 | n = int(input())
arr = [int(x) for x in input().split()]
duke, alice = 0, 0
for i in arr:
if i % 2 == 0:
duke += i // 2
else:
alice += i // 2 + 1
if duke > alice:
print("Duke")
else:
print("Alice")
| AAZZAZRON/DMOJ-Solutions | dmopc21c1p1.py | dmopc21c1p1.py | py | 230 | python | en | code | 1 | github-code | 36 |
74957408425 | #! /usr/bin/env python
from __future__ import print_function
import os
import sys
import argparse
from subprocess import CalledProcessError
from scripting.conda import install_python
from scripting.contexts import cd, cdtemp, homebrew_hidden, setenv
from scripting.unix import system, which, check_output
from scriptin... | csdms/csdms-stack | build-stack.py | build-stack.py | py | 7,372 | python | en | code | 0 | github-code | 36 |
14566840458 | from datetime import date
from django.apps import apps
from django.db import models
from lxml import etree
import requests
from .product_forms import FORMS
class IsbnPool(models.Model):
PURPOSE_GENERAL = 'GENERAL'
PURPOSE_WL = 'WL'
PURPOSE_CHOICES = (
(PURPOSE_WL, 'Wolne Lektury'),
(PURPOS... | fnp/redakcja | src/isbn/models.py | models.py | py | 6,085 | python | en | code | 4 | github-code | 36 |
34836324109 | # _*_ coding: utf-8 _*_
import ta
import os
import sys
import warnings
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
warnings.filterwarnings("ignore")
import pandas as pd
class TechnicalAnalysis(object):
def __init__(self, data, window_size):
self.data = data
... | dxcv/InvestmentTestbed | CODE/COMM/TechnicalAnalysis_Util.py | TechnicalAnalysis_Util.py | py | 1,631 | python | en | code | 0 | github-code | 36 |
21158916889 | from colorsys import rgb_to_yiq
import speedtest
s = speedtest.Speedtest()
bytes_num = 1000000
dws = round(s.download()/bytes_num, 2)
ups = round(s.upload()/bytes_num, 2)
print(f' download {dws}')
print(f' download {ups}') | jesus-sanchez5/Kali_pruebas | Programas_prueba/python/pruebaVelocidad.py | pruebaVelocidad.py | py | 227 | python | en | code | 0 | github-code | 36 |
42022013353 | import pandas as pd
from docx import Document
def get_lst():
df = pd.read_excel('Sample_Questions_Compliance.xls')
lst = []
for index, row in df.iterrows():
lst.append((row['Model Question'], row['Additional Tags / Synonyms for questions (from QnA Chatbot)'],row['Model Answer']))
wordDoc ... | silasalberti/gpt3-comprehendum | backend/intelligent_parse.py | intelligent_parse.py | py | 1,145 | python | en | code | 17 | github-code | 36 |
34405116951 | import time
import re
import codecs
import io
#import urllib2 as ul
import requests
import xml.etree.ElementTree as ET
from konlpy.tag import Kkma
from konlpy.utils import pprint
import zipfile
def LoadDB_2020(src='oro'):
dat = []
z = zipfile.ZipFile('../scraped/{}/{}.zip'.format(src,src))
for j in z.filel... | nborggren/BadukNews | src/BadukCorpus.py | BadukCorpus.py | py | 4,965 | python | en | code | 1 | github-code | 36 |
43157704514 | #!/usr/bin/python3
#-*- coding:utf-8 -*-
import sys
import pygame
from pygame.locals import *
SCREEN_WIDTH, SCREEN_HEIGHT = 480, 700
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Plane Flight")
bk_img = pygame.image.load("resources/image/background.png")... | minskeyguo/mylib | python-edu/plane/02-plane.py | 02-plane.py | py | 1,311 | python | en | code | 0 | github-code | 36 |
14147429202 | import argparse
import re
PLATOON_PRESETS= {
# scenario 1: 4 AVs with human cars inbetween, some of which are sensing cars used to collect metrics on
'scenario1': 'human#sensor human*5 (human#sensor human*5 av human*5)*4 human#sensor human*5 human#sensor',
}
def parse_args():
parser = argparse.ArgumentPar... | sarahbhaskaran/cosim | scripts/args.py | args.py | py | 2,504 | python | en | code | 1 | github-code | 36 |
34173082997 | #!/usr/bin/env python
__author__ = 'xinya'
from bleu.bleu import Bleu
from meteor.meteor import Meteor
from rouge.rouge import Rouge
from cider.cider import Cider
from collections import defaultdict
from argparse import ArgumentParser
import codecs
from pdb import set_trace
import sys
import numpy as np
reload(sys)
... | zpeide/transfer_qg | metric/qgevalcap/eval.py | eval.py | py | 3,487 | python | en | code | 2 | github-code | 36 |
71485638184 | import json
from .lock import f_lock
from .config import read_config
config = read_config()
def update_dict(key=None, target=4, goal=4, flag=1):
pwd = config["pwd"]
with f_lock(f"{pwd}/bin3D_list.json") as json_file:
json_dict = json.load(json_file)
if key is None:
for key in js... | lorenghoh/bin3D2zarr | src/lib/handler.py | handler.py | py | 887 | python | en | code | 0 | github-code | 36 |
43302752004 | import py
import sys
from rpython.rtyper.lltypesystem import lltype
from rpython.rlib import rawstorage
from rpython.rlib.rawstorage import alloc_raw_storage, free_raw_storage,\
raw_storage_setitem, raw_storage_getitem, AlignmentError,\
raw_storage_setitem_unaligned, raw_storage_getitem_unaligned
from rpython... | mozillazg/pypy | rpython/rlib/test/test_rawstorage.py | test_rawstorage.py | py | 3,046 | python | en | code | 430 | github-code | 36 |
21052645591 | import csv
import datetime as dt
import os
import numpy as np
from matplotlib import pyplot
from pandas import datetime
from pandas import read_csv
from sklearn.metrics import mean_squared_error
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.tsa.statespace.sarimax import SARIMAX
from prepare_historica... | chaitanyacsss/github_repository_growth_forecast | arima_predictions.py | arima_predictions.py | py | 4,334 | python | en | code | 1 | github-code | 36 |
24788463789 | from collections import defaultdict
class TrieNode:
def __init__(self):
self.word = -1
self.children = defaultdict(TrieNode)
self.palindrome_word = []
class Trie:
def __init__(self):
self.root = TrieNode()
@staticmethod
def is_palindrome(word: str) -> bool:
r... | inhyeokJeon/AALGGO | Python/LeetCode/trie/336_palindrome_pair.py | 336_palindrome_pair.py | py | 2,814 | python | en | code | 0 | github-code | 36 |
17890104045 | from inspect import stack, getmodule
from os.path import exists
def inline_snippet(
example_path: str,
write_mode: str = 'w+',
error_message: str = "# Attempted inline snippet failed."
) -> None:
"""Writes the content in `example_path` to the calling file.
Args:
example_path (str): Path ... | pyn-sol/blueprinter | blueprinter/inline.py | inline.py | py | 1,094 | python | en | code | 0 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.