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
24722163523
#!/usr/bin/env python3 # wykys 2020 # databáze konverzací pro generování korpusu from sqlalchemy import create_engine, text, func from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import as_declarative, declared_attr, declarative_base from sqlalche...
wykys/chateen
src/chateen/database/database.py
database.py
py
1,911
python
en
code
0
github-code
36
43823710793
import json from collections import Counter from template import * relation_ground_truth_count = json.load(open("../../data/relation_count.json")) for relation in relation_list[:1]: result_data = [] with open(f"./data/alias/query_result/{relation}.json", "r") as f: for line in f: json_obj ...
bigdante/nell162
backup/verification/chatgpt_gen_yes_no/check_gen.py
check_gen.py
py
2,169
python
en
code
0
github-code
36
3381408882
from rest_framework import serializers from .models import PetModel, FA from datetime import date,datetime,timedelta from django.utils import timezone class PetSerial(serializers.ModelSerializer): class Meta: model=PetModel fields=( "Category", "Name", "Sex", "BirthDt", "City", "Departement", ...
tapaloeil/PetAdmin
Pet/serializers.py
serializers.py
py
1,218
python
en
code
0
github-code
36
3458590367
import numpy as np from typing import List #本质:元素的左上角元素都相同 class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: if not matrix or not matrix[0]: return True m, n = len(matrix), len(matrix[0]) for i in range(m): for j in range(n): ...
pi408637535/Algorithm
com/study/algorithm/daily/766. Toeplitz Matrix.py
766. Toeplitz Matrix.py
py
728
python
en
code
1
github-code
36
31065339378
### Shuffle Cog ### ### Imports ### # General import json # Library import nextcord from nextcord.ext import commands from tinydb import TinyDB, Query from utils import embeds # Internal from utils.content import ShuffleContent from utils.embeds import embed_shuffle, embed_invalid_shuffle, embed_shuffle_records, em...
dbchristenson/meji
cogs/shuffle.py
shuffle.py
py
11,298
python
en
code
0
github-code
36
42090960900
from pathlib import Path import mmcv from mmcls.apis import inference_model from mmdet.apis import inference_detector from mmseg.apis import inference_segmentor from mmrazor.apis import init_mmcls_model, init_mmdet_model, init_mmseg_model def _sync_bn2bn(config: mmcv.Config) -> None: def dfs(cfg_dict) -> None:...
Gumpest/AvatarKD
tests/test_apis/test_inference.py
test_inference.py
py
3,065
python
en
code
6
github-code
36
29557419686
import pytest from brownie import chain, RewardsManager, reverts from math import floor from utils.config import network_name from os.path import exists import json rewards_period = 3600 * 24 * 7 rewards_amount = 5_000 * 10**18 def test_acceptance( ldo_token, stranger, rewards_contract, helpers, ...
lidofinance/curve-rewards-manager
tests/test_acceptance.py
test_acceptance.py
py
4,186
python
en
code
0
github-code
36
73973980585
import numpy as np import transforms3d as t3d from scipy.linalg import expm, sinm, cosm class SE3(object): """ 3d rigid transform. """ def __init__(self, R, t): self.R = R self.t = t def matrix(self): m = np.eye(4) m[:3, :3] = self.R m[:3, 3] = self.t ...
shanmo/OrcVIO
python_scripts/object_map_eval/se3.py
se3.py
py
9,254
python
en
code
20
github-code
36
34477179356
# -*- coding: utf-8 -*- """ Created on Sun Jul 23 15:48:44 2023 @author: shikh """ import streamlit as st import main_gp as gp st.set_option('deprecation.showPyplotGlobalUse', False) #gp.GaussianEngine(1,0.014,230,1,"C") #gp.plot() st.title("Air dispersion simulation") st.text("Using Gaussian plume model") def main...
shikhar58/Air-dispersion-model
run_file.py
run_file.py
py
1,280
python
en
code
0
github-code
36
4394054103
# 여행경로 # https://programmers.co.kr/learn/courses/30/lessons/43164 # r1 x def solution(tickets): tickets.sort(reverse=True) routes = dict() for t1, t2 in tickets: if t1 in routes: routes[t1].append(t2) else: routes[t1] = [t2] stack = ['ICN'] answer = [] wh...
sjjam/Algorithm-Python
programmers/type/DFS&BFS/43164.py
43164.py
py
641
python
en
code
0
github-code
36
14822411979
# # @lc app=leetcode.cn id=434 lang=python3 # # [434] 字符串中的单词数 # # https://leetcode-cn.com/problems/number-of-segments-in-a-string/description/ # # algorithms # Easy (28.91%) # Total Accepted: 3.9K # Total Submissions: 13.4K # Testcase Example: '"Hello, my name is John"' # # 统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。 # # 请注意,...
ZodiacSyndicate/leet-code-solutions
easy/434.字符串中的单词数/434.字符串中的单词数.py
434.字符串中的单词数.py
py
897
python
en
code
45
github-code
36
40967086967
from django import forms from django.forms import extras from .models import * class registered_user_form(forms.ModelForm): username = forms.CharField(max_length=30) password = forms.CharField(max_length=30) date_of_birth = forms.DateField(widget=extras.SelectDateWidget(years=range(1900,2017))) class ...
dsunchu/431W
congo/database/forms.py
forms.py
py
5,910
python
en
code
0
github-code
36
28861454822
#!/usr/local/bin/python # -*- coding: utf-8 -*- from techism.models import Event, EventTag, Location, Organization, OrganizationTag, Setting, TweetedEvent from django.contrib import admin import reversion class EventInline(admin.TabularInline): model = Event fields = ['title', 'date_time_begin', 'date_time_en...
techism/techism
techism/admin.py
admin.py
py
2,057
python
en
code
7
github-code
36
41396486126
"""A module for implementing communication tasks.""" from typing import Optional, Tuple import numpy as np from communication_tasks import monotones from utils.utils import matrix_is_rowstochastic, sample_random_row_stochastic_matrix class CommunicationMatrix: """A class which defines all relevant features of c...
oskarikerppo/communication-tasks
communication_tasks/communication_matrices.py
communication_matrices.py
py
2,247
python
en
code
0
github-code
36
73880579625
# # This file is part of Pytricia. # Joel Sommers <jsommers@colgate.edu> # # Pytricia is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later v...
jsommers/pytricia
testload.py
testload.py
py
2,625
python
en
code
203
github-code
36
73130978664
from tempfile import mkdtemp import multiprocessing import environ # ENVIRON # ============================================================================== env = environ.Env() DEBUG = env.bool("DEBUG") FORWARDED_ALLOW_IPS = env.str("GUNICORN_FORWARDED_ALLOW_IPS") PROXY_ALLOW_IPS = env.str("GUNICORN_PROXY_ALLOW_IP...
by-Exist/django-skeleton
backend/gunicorn.conf.py
gunicorn.conf.py
py
8,837
python
ko
code
0
github-code
36
73137395944
# simulate_one_group.py # Benjamin Crestel, 2020-12-22 import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm from simulations import simulate_normal def simulate_one_group(number_samples: int, mean: float = 100.0, std: float = 15.0): """ Generate samples of IQ tests and plot :...
bcrestel/coursera_statisticalinferences
src/simulate_one_group.py
simulate_one_group.py
py
1,114
python
en
code
0
github-code
36
27649483225
from django.shortcuts import render from .models import ProductInBasket from django.http import JsonResponse from ordering.views import is_user_registered def show_basket(request): session_key = request.session.session_key if is_user_registered(session_key): # Перевірка, чи є користувач зареєстрованим ...
akarumeis/CoffeMania
basket/views.py
views.py
py
3,932
python
uk
code
1
github-code
36
39869456678
import os import registry import end_to_end_tests.test_utils as utils def TestBuild(registry, out_dir): foobar_filepath = os.path.join(out_dir, 'foobar.txt') foo = registry.SubRespireExternal('generate_foo.respire.py', 'GenerateFoo', out_dir=out_dir) bar = registry.SubRespir...
aabtop/respire
src/python/end_to_end_tests/test_subrespire_external/simple_test_entry_point.respire.py
simple_test_entry_point.respire.py
py
711
python
en
code
0
github-code
36
28612470946
from PySide import QtCore, QtGui import configdialog_rc class ConfigurationPage(QtGui.QWidget): def __init__(self, parent=None): super(ConfigurationPage, self).__init__(parent) configGroup = QtGui.QGroupBox("Server configuration") serverLabel = QtGui.QLabel("Server:") serverComb...
pyside/Examples
examples/dialogs/configdialog/configdialog.py
configdialog.py
py
6,814
python
en
code
357
github-code
36
4822466026
class Cambio: IOF = 0.6 dolar = 5.10 @staticmethod def paraDolar(valor: float): return Cambio.dolar * valor * (1 + Cambio.IOF) @staticmethod def variacaoDolar(variacao: float): Cambio.dolar += variacao a = Cambio print(a.paraDolar(7)) # 5.10 * 7 * 1.6 == 57.12 b = Cambio.par...
amadeusantos/softexrecife
classeEstatica.py
classeEstatica.py
py
428
python
it
code
0
github-code
36
25569236359
# From Sololearn, Android App # Teaching a computer to predict the output of a mathematical expression without # "knowing" the exact formula, using neural networks and back propagation # one single neuron with two inputs and one outputs # The actual expression is (a+b)*2 from numpy import exp, array, random, dot clas...
tank-t-bird/100-days-ML
code/day006/teachMath.py
teachMath.py
py
1,060
python
en
code
0
github-code
36
8393586286
import json import re from collections import Counter import matplotlib.pyplot as plt import pandas as pd import requests from nltk.corpus import stopwords df = pd.read_csv("./misc/chanlog.csv") def fetch_emotes(url: str, id: str) -> str: try: resp = requests.get(f"{url}{id}") json = resp.json()...
smehlhoff/twitch-chat-election
top_words.py
top_words.py
py
1,876
python
en
code
0
github-code
36
23127977963
import struct from hashlib import sha512 from shutil import copyfile from time import time_ns def loadSaveFile(path): saveFileData = None with open(path, 'rb') as file: saveFileData = readSaveFile(file) return saveFileData def readSaveFile(file): file.read(4) #File length in bytes, without SH...
SixPraxis/ValheimMapCombiner
vmcUtils.py
vmcUtils.py
py
4,169
python
en
code
1
github-code
36
25546086148
def parse_time(time_str): # here I convert my data in time (seconds) h, m, s = map(int, time_str.split('|')) return h * 3600 + m * 60 + s def format_time(seconds): h, rem = divmod(seconds, 3600) # h = hours after divison by 3600, rem = remainder of this calculation m, s = divmod(rem, 60) # m = minu...
LeaBani/algo-training
python/statisticsAtheltic.py
statisticsAtheltic.py
py
1,376
python
en
code
0
github-code
36
1016610993
class Solution: def bitwiseComplement(self, n: int) -> int: def setBit(n): set = 0 n //= 2 while n > 0: n //=2 set += 1 return 1 << set return n^((setBit(n)<<1)-1)
khubaibalam2000/Leetcode-Submissions
1009. Complement of Base 10 Integer.py
1009. Complement of Base 10 Integer.py
py
266
python
en
code
0
github-code
36
74962694182
import datetime import qrcode from django.core.mail import send_mail from django.utils.crypto import get_random_string from rest_framework import status from rest_framework.generics import get_object_or_404 from rest_framework.response import Response from rest_framework.views import APIView from rest_framework impo...
theshag1/Instagram
user/views.py
views.py
py
14,038
python
en
code
0
github-code
36
42388719525
from peewee import * from datetime import datetime from flaskblog import db, login_manager from flask_login import UserMixin from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from flask import current_app @login_manager.user_loader def load_user(user_id): return User.get_by_id(int(user_id)) ...
Braindead3/vladislav_blog
flaskblog/models.py
models.py
py
1,778
python
en
code
0
github-code
36
73970127144
from twilio import twiml from twilio.rest import TwilioRestClient f = open('.key.txt', "r") key = f.readlines() f.close() MSG_HELP = "Valid commands:\n/find - find random partner\n/leave - leave current chat\n/share - share your phone number with partner\n/fun - more fun commands!" MSG_FUN = "Fun fun! :D\n/count - s...
imondrag/project-kitten
server_files/twiliocomms.py
twiliocomms.py
py
2,867
python
en
code
0
github-code
36
28912360217
""" """ # Entrada do user - Entrada de datas dia = int(input("Dia: ")) mes = int(input("Mês: ")) ano = int(input("Ano: ")) data_valida = False ano_atual = 2022 #Meses de 31 dias if mes == 1 or mes == 3 or mes == 5 or mes == 7 or mes == 8 or mes == 10 or mes == 12: if dia <= 31: data_valida = True #Mese...
BrunoDias312/CursoPython
Curso/Atividade Curso/Secao 05/Questao38.py
Questao38.py
py
735
python
pt
code
0
github-code
36
9738142506
from django.urls import path from . import views app_name = 'todolist' urlpatterns = [ path('home/', views.home, name="主页"), path('about/', views.about, name="关于"), path('edit/<每一件事_id>', views.edit, name="编辑"), path('delete/<每一件事_id>', views.delete, name="删除"), path('cross/<每一件事_id>', views.cross,...
AIM-1993/To_Do_List
Django_Projects/to_do_list/todolist/urls.py
urls.py
py
379
python
en
code
1
github-code
36
23165828885
import csv from flask import render_template,request,redirect from app import app from app.forms import SubmitForm @app.route('/') @app.route('/index',methods=['GET','POST']) def index(): form=SubmitForm() if request.method == "POST": abc=request.form['query'] print(abc) csv_file=o...
jain-abhi007/Fake-news-detection
app/routes.py
routes.py
py
478
python
en
code
1
github-code
36
31062259395
from ..utils import Object class ToggleMessageSenderIsBlocked(Object): """ Changes the block state of a message sender. Currently, only users and supergroup chats can be blocked Attributes: ID (:obj:`str`): ``ToggleMessageSenderIsBlocked`` Args: sender_id (:class:`telegram.api.typ...
iTeam-co/pytglib
pytglib/api/functions/toggle_message_sender_is_blocked.py
toggle_message_sender_is_blocked.py
py
1,026
python
en
code
20
github-code
36
18246284421
#!/usr/bin/python3 import sys import os from rooms import rooms from monster_manual import monsters from time import sleep import time from newplayer import newPlayer # Replace RPG starter project with this code when new instructions are live def clear(): os.system('clear') def type_delay(char, delay=0.1): ...
Dr3adnought/RPG_game
GoD.py
GoD.py
py
5,518
python
en
code
0
github-code
36
72811988585
from dotenv import load_dotenv load_dotenv(override=True) import os appOAuthServer=os.getenv('OAUTH_SERVER') appOAuthCredential=os.getenv('OAUTH_CRED') appOAuthRedirectUrl=os.getenv('OAUTH_REDIRECT_URL') import hvac vault=hvac.Client( url=os.getenv('VAULT_ADDR'), token=os.getenv('VAULT_TOKEN') ) import u...
CiscoDevNet/webex-vault-samples
people_me_flask.py
people_me_flask.py
py
1,736
python
en
code
0
github-code
36
15973885303
#!/usr/bin/python3 #endereço do compilador para usar o executável #import dos módulos: import tkinter as tk from tkinter import ttk import serial import numpy as np Polynomial = np.polynomial.Polynomial import math import matplotlib.pyplot as plt #--------------------- #Variáveis globais: global portaUSB portaUSB = ""...
abbarreto/Beer-Lambert
GuiLambertv1.py
GuiLambertv1.py
py
23,636
python
en
code
0
github-code
36
12149713993
from asyncio import current_task from typing import AsyncGenerator, Any from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, async_scoped_session, AsyncSession from core.config import settings class DataBaseHelper: def __init__(self, url: str, echo: bool) -> None: self.engine = cr...
Norgius/microshop
core/models/db_helper.py
db_helper.py
py
1,060
python
en
code
0
github-code
36
42232863780
# -*- coding:utf-8 -*- import mysql.connector from mysql.connector import Error from ConfigParser import ConfigParser from Errors import Errors from datetime import datetime class DbConnector(): def __init__(self): pass def getConnection(self): conn=None dbconfig=self._...
FelixMailwriter/VendService
DAL/DBConnector.py
DBConnector.py
py
9,921
python
en
code
0
github-code
36
24288468105
# -*- coding: utf-8 -*- """ Created on Sat Oct 16 17:56:41 2021 @author: s2073467 """ import os import scipy.io import matplotlib.pyplot as plt import scipy.signal import voltron_ROI as ROI import pandas as pd import numpy as np from airPLS import airPLS #%% Load triggered mode data '''triggered: lo...
MattNolanLab/SPAD_in_vivo
SPAD_ex_vivo_analysis/Spike_trigger.py
Spike_trigger.py
py
6,758
python
en
code
0
github-code
36
24299518692
import numpy as np, math, os alldata = [] for file in os.listdir('1.clean'): f = open('./1.clean/' + file).read().splitlines() temp = [] for i in f[1:]: a, b = i.split(' | ') temp.append(b) alldata.append(temp) scores = [] for file in os.listdir('3.scored'): f = open('...
deyanarajib/DM_Summarization-of-News-Articles-Using-Fuzzy-Logic-Scoring
LSA.py
LSA.py
py
1,655
python
en
code
1
github-code
36
38386069628
# Write your code here import random import string print("H A N G M A N") command = input('Type "play" to play the game, "exit" to quit:') words = ("python", "java", "kotlin", "javascript") word = random.choice(words) word_arr = list("-" * len(word)) guess_word = ''.join(word_arr) typed = set() while command == "play...
vitaly-m/hangman
Hangman/task/hangman/hangman.py
hangman.py
py
1,380
python
en
code
0
github-code
36
72692973223
from csv import DictReader import sys import csv from csv import DictWriter from afinn import Afinn class PredictSentiment: # making sure really long csv fields could be read and processed maxInt = sys.maxsize while True: # decrease the maxInt value by factor 10 # as long as the Overflo...
madeleinemvis/original_gdp
BackEnd/functions/article_sentiments.py
article_sentiments.py
py
2,099
python
en
code
0
github-code
36
72607798505
#!/usr/bin/env python3 import rospy import datetime import sys, os from rosgraph_msgs.msg import Log rospy.init_node('NECST_logger') ###config save_to = '/home/amigos/log' try: file_name = sys.argv[1] except: file_name = '' ### def save_file_conf(): today = datetime.date.today() year = today.year ...
nanten2/necst-ros
scripts/record/ROS_save_logger.py
ROS_save_logger.py
py
1,525
python
en
code
0
github-code
36
32144128910
''' 4. Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações. ''' nome = input("Digite um Nome: ") senha = input("Digite uma senha: ") while nome == senha: senha = input("senha digita ...
grazielags/cp12
Reginei/Módulo 3/Aula 8 Python/Aula 3 estrutura de repeticão exercicios/exercicio4.py
exercicio4.py
py
402
python
pt
code
0
github-code
36
18336730125
import json from functions import get_access_token, get_animal_types, get_animals_by_type, \ get_animals_dataset, print_babies_adults, print_animal_types, \ digit_check, string_check, string_check_1, add_animal, info_about_pet with open('data.json') as infile: dataset = j...
evnng/Animal-Project
main_programm.py
main_programm.py
py
3,472
python
en
code
0
github-code
36
5096598714
from FastExpression import * from backtesting import Backtest, Strategy from backtesting.lib import crossover from backtesting.test import SMA import math import pandas as pd class SmaCross(Strategy): n1 = 10 n2 = 20 def init(self): close = self.data.Close self.sma1 = self.I(SMA, close, sel...
quangtiennnn/cryptoprediction
QuantAnalysis.py
QuantAnalysis.py
py
2,022
python
en
code
1
github-code
36
74470173222
import struct import re from print_out import print_out_str from bitops import is_set # name from tz dump, corresponding T32 register, whether or not to # print_out_str (the function name) sysdbg_cpu64_register_names_default = [ ('x0', 'x0', False), ('x1', 'x1', False), ('x2', 'x2', False), ('x3', 'x3'...
emonti/qualcomm-opensource-tools
linux-ramdump-parser-v2/watchdog_v2.py
watchdog_v2.py
py
23,636
python
en
code
26
github-code
36
8754718855
# -*- coding: utf-8 -*- # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models, api, tools, _ class OfInvoicedRevenueAnalysis(models.Model): """Analyse CA facturé""" _name = 'of.invoiced.revenue.analysis' _auto = False _description = "Analyse CA facturé" ...
odof/openfire
of_crm/reports/of_invoiced_revenue_analysis.py
of_invoiced_revenue_analysis.py
py
27,307
python
en
code
3
github-code
36
35225497072
import logging import pathlib import sys from helloworld.errors import OutputFileExists _logger = logging.getLogger(__name__) def write_message(message, output_file, clobber=False): if output_file != '-': # only overwrite output_file if --clobber specified. if pathlib.Path(output_file).exists() ...
KeithMnemonic/python-helloworld
helloworld/scripts/cli_utils.py
cli_utils.py
py
1,155
python
en
code
0
github-code
36
37319866519
import pickle import json import numpy as np import pygame import cv2 import copy from overcooked_ai_py.env import OverCookedEnv from overcooked_ai_py.mdp.overcooked_mdp import OvercookedState from overcooked_ai_py.visualization.state_visualizer import StateVisualizer from overcooked_ai_py.mdp.overcooked_mdp import Re...
bic4907/Overcooked-AI
test/visualize_dataframe.py
visualize_dataframe.py
py
2,684
python
en
code
19
github-code
36
37402699617
from regression_tests import * class Test(Test): settings=TestSettings( tool='fileinfo', args='--json --verbose', input=[ '564FAF0B9F25C0A8F156E9C82A36D2B854E5110820C9400374EB26EC631C19E5.dat', 'F70FA1DCD6C54E95D4F5FE69F62AD5AED813FB6F9ECB27D8637E34F517ACE97E.dat' ...
avast/retdec-regression-tests
tools/fileinfo/bugs/yaragen-assert-ElementType-BoxedObject-found/test.py
test.py
py
537
python
en
code
11
github-code
36
32195239070
def myAtoi(s): if len(s)==0: return 0 sign='positive' sign_found=False isfloat=False for i in range(len(s)): if s[i]=='.': isfloat=True if isfloat==True: s=float(s) s=int(s) s=str(s) i=0 while not s[i].isdigit():...
JimNtantakas/Leetcode-problems
8.py
8.py
py
1,300
python
en
code
0
github-code
36
11693199631
from allauth.account.forms import SignupForm from django import forms as d_forms from django.contrib.auth import forms, get_user_model from django.contrib.auth.forms import UserChangeForm, UserCreationForm from django.contrib.auth.models import Group from django.core.exceptions import ObjectDoesNotExist, ValidationErro...
decorouz/elearningforfarmers
users/forms.py
forms.py
py
2,176
python
en
code
0
github-code
36
8943599832
#!/usr/bin/env python3 import math import ausmash_api def get_player_matches_in_multiple_events(player_id, event_ids): all_matches = ausmash_api.get_player_matches(player_id) matches = {} for event_id in event_ids: event_matches = [match for match in all_matches if match['Event']['ID'] == event_id] matches[e...
Miss-Inputs/ausmash-labs
ausmash_lib.py
ausmash_lib.py
py
6,474
python
en
code
0
github-code
36
154683882
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @return a ListNode def addTwoNumbers(self, l1, l2): sum0 = (l1.val + l2.val) % 10 carry = (l1.val + l2.val) / 10 # root root ...
zhiyelee/leetcode
python/add_two_numbers.py
add_two_numbers.py
py
1,447
python
en
code
14
github-code
36
6432501039
import json,time from collections import Iterable from django.utils.timezone import datetime from django.conf import settings from django.core.paginator import Paginator from django.http import JsonResponse from django.views.generic import View from Hellocial_0_1.settings import logger from apps.products.models import ...
eashme/Django-backend
Hello_Server/apps/scripts/views.py
views.py
py
16,481
python
en
code
1
github-code
36
12584775918
# 2. Get the number of occurrences of var b in array a. # Example: # a = [1, 1, 2, 2, 2, 2, 3, 3, 3] # b = 2 # Result: # 4 # Global variables my_list and var_to_find used for the list introduced from the keyboard and the item to be counted my_list = [i for i in input("Please enter the list items : ").split()] var_to_...
marinabobesi/session1
Homework_Course2.2.py
Homework_Course2.2.py
py
547
python
en
code
0
github-code
36
14410680508
# A Variable is a container for a value, which can be of various types ''' This is a multiline comment or docstring (used to define a function purpose) can be single or double quotes ''' """ VARIABLE RULES - Variable names are case sensitive (name and NAME are different variables) - Must start with a letter o...
kas-pre/python-scientific_computing_projects
first_hands_on/variables.py
variables.py
py
749
python
en
code
0
github-code
36
1990226900
from collections import deque, OrderedDict import numpy as np import dm_env from dm_control.mujoco.engine import Camera def xyz2pixels(xyz, cam_mat): """ Project 3D locations to pixel locations using the camera matrix """ xyzs = np.ones((xyz.shape[0], xyz.shape[1]+1)) xyzs[:, :xyz.shape[1]] = xyz xs...
rinuboney/FPAC
dm_wrappers.py
dm_wrappers.py
py
8,725
python
en
code
0
github-code
36
8361752991
import os import requests from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) # variables loaded in from .env file COC_TOKEN = os.environ.get("COC_TOKEN") headers = { 'Accept': 'application/json', 'authorization': 'Bearer ' ...
dougscohen/ClashStash
clash.py
clash.py
py
5,842
python
en
code
0
github-code
36
32015272591
from PPlay.gameimage import * def abertura_producao(janela): cont = 0 fundo = GameImage("imagens/abertura/abertura100.jpg") while(cont <= 300): cont += 1 fundo.draw() janela.update() def abertura_jogo(janela): cont = 0 fundo = GameImage("imagens/abertura/wallpaper100.jpg...
jsimonassi/Cross-Bike
abertura.py
abertura.py
py
427
python
pt
code
0
github-code
36
13149514360
import random def numero_aleatorio(): lista=[] while len(lista)!=5: num=random.randrange(0,9) if num not in lista: lista.append(str(random.randrange(1,9))) numero="".join(lista) return numero def comprueba(secreto,numero): #Creamos diccionario para guardar los valores ...
jmarrieta98/Programacion
Python/Examenes/Prueba Diciembre/prueba1.py
prueba1.py
py
1,972
python
es
code
0
github-code
36
22602819959
import numpy as np import matplotlib.pyplot as plt import os from glob import glob import json def plot_item(key='train_loss'): sub_dirs = glob("./logs/*/", recursive=False) plt.figure(figsize=(6, 4)) plt.xticks(range(21)) for sub_dir in sub_dirs: _ = sub_dir[sub_dir.index('_')+1:] net...
Gariscat/HouseX
plot.py
plot.py
py
935
python
en
code
18
github-code
36
27022438847
"""JSON loaders.""" from flask import request from .errors import MarshmallowErrors def marshmallow_loader(schema_class): """Marshmallow loader for JSON requests.""" def json_loader(): request_json = request.get_json() context = {} pid_data = request.view_args.get('pid_value') ...
slint/cookiecutter-invenio-datamodel
{{cookiecutter.project_shortname}}/{{cookiecutter.package_name}}/loaders/json.py
json.py
py
714
python
en
code
null
github-code
36
24398908749
from flask import Flask, jsonify from flask_restful import Api from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_cors import CORS from sqlalchemy import or_ , cast from sqlalchemy.dialects.postgresql import TEXT url = open("databaseuri.txt", "r").read().rstrip() app = Flas...
CarsenKennedy/EU4-flask-api
app.py
app.py
py
4,707
python
en
code
0
github-code
36
6760048820
"""supervisor controller.""" # You may need to import some classes of the controller module. Ex: # from controller import Robot, Motor, DistanceSensor import copy from controller import Supervisor import numpy as np import math supervisor = None robot_node = None target_node = None def init_supervisor(): globa...
artem690/robotics_final_project
controllers/controller_base/supervisor.py
supervisor.py
py
3,808
python
en
code
0
github-code
36
39560364761
import subprocess f = open("m1.txt", "r") scale = f.readline() data = scale.split() x = int(data[0]) f.close() f = open("m2.txt", "r") scale = f.readline() data = scale.split() y = int(data[1]) f.close() arr = ["static", "dynamic", "guided"] for k in range(0, 8): # static 8 threads 1 chunk # j = x * y // (k ...
powercoderlol/threads_ifmo
lab1/run_test.py
run_test.py
py
970
python
en
code
1
github-code
36
40451994919
import os from configparser import ConfigParser from .database import Database from create_databases import GuildSettings class GuildSettingsModel(Database): def __init__(self): super().__init__() async def add(self, guild_id: int, server_name: str, region: str, owner_id: int): new = GuildSet...
jcsumlin/secret-santa-discord-bot
cogs/utils/GuildSettings.py
GuildSettings.py
py
741
python
en
code
0
github-code
36
35836541266
# @Date : 22:38 05/01/2020 # @Author : ClassicalPi # @FileName: Data_Analysis.py # @Software: PyCharm import numpy as np from pyecharts.charts import Map,Geo from pyecharts import options import pandas as pd import nltk import re import os import matplotlib.pyplot as plt import string import json import openpyxl ...
QiaoLin-MA/Sentiment_Analysis
Sentiment_Analysis/Code/Data_Analysis.py
Data_Analysis.py
py
12,007
python
en
code
0
github-code
36
40264531439
starting_points = 301 current_points = starting_points total_success_shots = 0 total_fail_shots = 0 name = input() command = input() is_winning = False is_retired = False while command != "Retire": section = command points = int(input()) if section == "Single": points = points elif section == "...
ivoivanov0830006/1.1.Python_BASIC
0.Exams_Basics/4.Darts.py
4.Darts.py
py
958
python
en
code
1
github-code
36
26104880010
from spheres.magic import * from functools import * class OperatorExpression: def __init__(self, ops): self.ops = ops def __mul__(self, other): if type(other) == OperatorExpression: return OperatorExpression(self.ops+other.ops) elif type(other) == qObj and other.type == "oper": return OperatorExpressio...
heyredhat/spheres-old
old/art.py
art.py
py
2,596
python
en
code
0
github-code
36
5149623989
import tensorflow as tf import numpy as np # binary logic functions that support per-element operations between numpy # nd arrays. xor_fn = np.vectorize(lambda x, y: x != y) nand_fn = np.vectorize(lambda x, y: not (x and y)) and_fn = np.vectorize(lambda x, y: x and y) or_fn = np.vectorize(lambda x, y: x or y) def sam...
benkamphaus/tf-examples
logic_nets.py
logic_nets.py
py
5,349
python
en
code
0
github-code
36
27574117500
import libpysal as lps import geopandas as gpd import csv state = "ok" file = ("./ok_boundary.json") shp = gpd.read_file(file) rW = lps.weights.Rook.from_dataframe(shp, idVariable="GEOID") outputName = state + "_neighbors.csv" header = ['id','NEIGHBORS'] with open(outputName, 'w', newline='') as csv_out: write...
kenchin3/CSE416_Warriors
client/preprocessing/neighbors.py
neighbors.py
py
682
python
en
code
0
github-code
36
14352296820
import unittest import mock import networkx from kiva.testing import KivaTestAssistant from graphcanvas.graph_container import GraphContainer from graphcanvas.graph_node_component import GraphNodeComponent from graphcanvas.graph_view import graph_from_dict class TestGraphContainer(KivaTestAssistant, unittest.TestC...
enthought/graphcanvas
graphcanvas/tests/test_graph_container.py
test_graph_container.py
py
8,263
python
en
code
25
github-code
36
25798612752
# 과목의 수강생 번호 1~ N번 # 제출하지 않은 사람의 번호를 오름차순으로 출력하는 프로그램을 작성하라. # set? # 첫 번째 줄에는 수강생의 수를 나타내는 정수와 과제를 제출한 사람의수 # 두 번째는 과제를 제출한 사람의 번호 import sys sys.stdin = open('input.txt', 'r') T = int(input()) for t in range(1, T+1): student_num, submit = list(map(int, input().split())) # 5 2 submit_num = list(map(int, in...
00purplecandy00/Algorithm-Test-03
2200040/5431.py
5431.py
py
780
python
ko
code
null
github-code
36
32144801473
from typing import List, Any from sqlalchemy.orm import Session from api import schemas, models, crud from api.votes import schemas as votes_schemas def get_votes_from_game_id(db: Session, game_id: int) -> List[Any]: return db.query(models.Vote).filter(models.Vote.game_id == game_id).all() def add_vote(db: Sess...
cyborggeneraal/weerwolven
api/votes/crud.py
crud.py
py
722
python
en
code
4
github-code
36
15628419363
from spack import * from spack.pkg.builtin.amr_wind import AmrWind class AmrWind(AmrWind): git = "https://github.com/Alpine-DAV/amr-wind.git" version('ascent', branch='ascent', submodules=True) # draft of changes needed to build amr-wind+ascent variant('ascent', default=False, des...
cinemascienceworkflows/2021-05_ExaWind-AMRWind
inputs/spack/pantheon/packages/amr-wind/package.py
package.py
py
760
python
en
code
0
github-code
36
17981884227
#!/usr/bin/python3 """ Module: 4-print_square Contain function print_square that print a square with # char Testing: use tests/4-print_square.txt with doctest() """ def print_square(size): """Prints the square with # char Arg: size (int): size of the square """ if isinstance(size, int): ...
david-develop/holbertonschool-higher_level_programming
0x07-python-test_driven_development/4-print_square.py
4-print_square.py
py
567
python
en
code
0
github-code
36
36760483704
num=input("enter multiple with space number:") spli=num.split() '''ans=",".join(spli) print(ans) ''' tab=" " count=0 for word in spli: count=count+1 tab=tab+word if(count<len(spli)): tab=tab+"-" print(tab)
narendra1100/python_projects
cama.py
cama.py
py
238
python
en
code
0
github-code
36
37087106292
from torch.utils import data from get_data import get_data import torch BATCH_SIZE = 4 [items, attributes, df] = get_data() NUM_ITEMS = len(items) NUM_ATTRIBUTES = len(attributes) features = torch.tensor(to_categorical(range(NUM_ITEMS)), dtype=torch.float32) targets = torch.tensor(df.values, dtype=torch.float32) ...
Pocket-titan/rogers_mcclelland_pytorch
dataset.py
dataset.py
py
966
python
en
code
1
github-code
36
26677018639
import tkinter as tk from tkinter import ttk, messagebox from constants import BACKGROUND, DATA_BASE, LABEL_FONT, PHOTO_DEFAULT, TITLE_FONT from global_functions import add_image, run_sql, transform_image class MaterialView(tk.Frame): def __init__(self, window): tk.Frame.__init__(self, window, bg=BACKGROU...
Masailama/muntanya
material.py
material.py
py
10,659
python
en
code
0
github-code
36
7689618737
def method1(): a = [1, 2, 3, 4, 5] for _ in range(1): f = a[0] for j in range(0, len(a) - 1): a[j] = a[j + 1] a[len(a) - 1] = f return a if __name__ == "__main__": """ from timeit import timeit print(timeit(lambda: method1(), number=10000)) 0.008410404003370...
thisisshub/DSA
D_arrays/problems/left_rotate_the_elements_of_an_array.py
left_rotate_the_elements_of_an_array.py
py
332
python
en
code
71
github-code
36
15627650024
import numpy as np import time def encode(str, row): start = 0 end = int(len(str) / row) arr = [] while int(len(str) - row*end) != 0: str = str + "+" end = int(len(str) / row) for i in range(row): if end > len(str): arr.append(list(str[start...
diduk228/Simple_encoding
main.py
main.py
py
1,241
python
en
code
0
github-code
36
28555405451
import time import sys import math from dronekit import connect, VehicleMode, LocationGlobalRelative, Command from vehicle_additional import get_bearing, get_distance_metres, get_location_metres from pymavlink import mavutil from pid import PID from wingman import Wingman import argparse parser = argparse.ArgumentPar...
liangz678/arduplane_formation_flying
mission_follow.py
mission_follow.py
py
1,486
python
en
code
0
github-code
36
74352223463
# -*- coding: utf-8 -*- """ Created on Fri Feb 18 13:40:36 2022 maybe needed: %load_ext autoreload %autoreload 2 @author: fabian_balzer """ # %% import argparse import input_scripts.availability_plots as av import input_scripts.filter_coverage_plot as fc import input_scripts.separation_plots as sep import output_...
Fabian-Balzer/sel-4hi-q
old/master_plots.py
master_plots.py
py
4,507
python
en
code
0
github-code
36
13995656554
#!/usr/bin/env python3 import socket socket_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) socket_server.bind(('127.0.0.1', 9876)) print('Bind UDP on 9876...') while True: data, addr = socket_server.recvfrom(1024) print(data.decode('utf-8')) #print('Received %s from %s:%s.' % (data.decode('ut...
JiangEndian/grace_20190205
apps/someapp/sompy3app/server_udp.py
server_udp.py
py
397
python
en
code
0
github-code
36
33203889383
import folium from geopy.geocoders import Nominatim film_studio_cities = ['Los Angeles', 'Rome', 'Wellington', 'Saint-Denis', 'Mumbai', 'Ouarzazate', 'Berlin'] film_studio = ['Hollywood', 'Cinecitta', 'Weta', 'La Cité du Cinéma', 'Bollywood', ' Atlas', 'Filmpark Babelsberg'] locations = list() lst = list() titl...
lurak/web-map
map.py
map.py
py
2,246
python
en
code
0
github-code
36
11761210802
#!/bin/python3 import math import os import random import re import sys # Complete the plusMinus function below. def plusMinus(arr): zeros = 0 pos = 0 neg = 0 for num in arr: if num is 0: zeros +=1 elif num > 0: pos +=1 else: ...
g2des/taco4ways
hackerrank/algorithm/plusMinus.py
plusMinus.py
py
607
python
en
code
0
github-code
36
22565786888
import itertools import json import zipfile from typing import BinaryIO, List, Tuple import numpy as np from PIL import Image from shap_e.rendering.view_data import Camera, ProjectiveCamera, ViewData class BlenderViewData(ViewData): """ Interact with a dataset zipfile exported by view_data.py. """ ...
openai/shap-e
shap_e/rendering/blender/view_data.py
view_data.py
py
3,109
python
en
code
10,619
github-code
36
11128560558
from urllib.request import urlopen html = urlopen("https://stepik.org/media/attachments/lesson/209717/1.html").read().decode('utf-8') s = str(html) a = s.count('Python') b = s.count('C++') print(a, b) if a > b : print('Python') else: print('C++')
Stran1ck/python_mini
download.py
download.py
py
254
python
en
code
0
github-code
36
37968323293
from django.conf.urls.defaults import * from contact.views import * from contact.models import * urlpatterns = patterns ('django.views.generic.simple', url( r'^info/$', ContactController.info, name="info" ), url( r'^$', ContactController.default, name="def...
hsk81/swmm-cms
swmm-cms/contact/urls.py
urls.py
py
336
python
en
code
0
github-code
36
7194793169
from collections import defaultdict from typing import List, TypeVar, Generic, Dict, Optional from mapfmclient import Problem from src.data.agent import Agent from src.data.vertex import Vertex A = TypeVar("A", bound=Agent) class Grid(Generic[A]): def __init__(self, problem: Problem): self.width: int =...
RobbinBaauw/CBMxSOC
src/grid.py
grid.py
py
950
python
en
code
0
github-code
36
71930968745
#!/usr/bin/python2.7 import json import time import socket import glob from websocket import create_connection import rippled import monitoring2_7 apiKey = "APIKEY" core_dir = "/data/rippled/var/cores" SLEEP = 20 hostname = socket.gethostname() host_type = rippled.ServerType.lookup(hostname) if not host_type: prin...
afrank/ripple-python
check_rippled.py
check_rippled.py
py
3,957
python
en
code
0
github-code
36
32160839259
""" Multiple WAD Injector checks for a settings file and: - Clones OOTR repo if not already present - Then prints a link to it if gz gui is not already present - Then requests a settings string if not present - Then Requests the number of seeds to generate, if not present Then loops and generates the roms, follow...
castlez/MultiWadOOTR
main.py
main.py
py
4,857
python
en
code
0
github-code
36
11469135915
""" sample hyperparameters sample maximum values by gumble, random features all in python optimization the criterion 1 hyperparameter feed: Xsamples, ysamples, l, sigma, sigma0, initialxs multiple hyperparameters feed: Xsamples, ysamples, ls, sigmas, sigma0s, initialxs return train...
ZhaoxuanWu/Trusted-Maximizers-Entropy-Search-BO
optfunc.py
optfunc.py
py
25,020
python
en
code
3
github-code
36
40364787807
import os import tempfile import requests from testbot.configs import worker_config, server_url from testbot.util import md5sum class APIError(Exception): pass def get_auth_param(): return worker_config['name'], worker_config['password'] def report_started(submission_id: int, work_id: str, hostname: str...
tjumyk/submit-testbot
testbot/api.py
api.py
py
3,017
python
en
code
0
github-code
36
29266081838
import cv2 from model import FacialExpressionModel import numpy as np import threading, time import queue import logging import sys from memory_profiler import profile logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',) BUFFER_SIZE = 700 qbuffer = queue....
nuralabuga/facial-expression-recognition--with--multithreads
camera_multithread_ram.py
camera_multithread_ram.py
py
3,226
python
en
code
0
github-code
36
9221143434
import requests, os from flask import Flask, jsonify, render_template, request app = Flask(__name__) apikey = os.getenv("API_KEY") @app.route("/") def index(): return render_template("index.html") @app.route("/convert", methods=["POST"]) def convert(): # Query for currency exchange rate symbol = requ...
Yoimer/cs50-lecture-folders
lecture5/convert/application.py
application.py
py
876
python
en
code
3
github-code
36
36579110550
#!/usr/bin/env python3 # coding: utf-8 import re from PIL import Image, ImageDraw import yaml, sys, subprocess def draw_arc(draw: ImageDraw.ImageDraw, target, offset=(0,0), scale=1.0): # check # calc x0 = (target['center']['x'] - target['radius']) * scale + offset[0] x1 = (target['center']['x'] + target['radius']...
takumi4424/takumi4424
generate_icon.py
generate_icon.py
py
1,441
python
en
code
0
github-code
36
439277880
"""Used to call an external NLP API for a given text input """ # Library imports import cProfile import pstats import logging import os import PyPDF2 as pypdf import nltk from nltk.sentiment import SentimentIntensityAnalyzer import src.Internal_API.db_connector as db_connector # Setup logging for text analysis module ...
CMander02/SmartNewsAnalyzer
src/ExternalAPI/text_analysis.py
text_analysis.py
py
3,192
python
en
code
0
github-code
36