seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
8224649664 | import json, requests, io
import pandas as pd
import numpy as np
import sys, argparse
#Managing input
parser = argparse.ArgumentParser(description='Script to download data of lung cancer from TCGA')
parser.add_argument('-t', '--type',
help='Sample type. Ej: NAD',
required='True',
choices=['NAD'... | josemaz/lung-mirnas | py/casemirna.py | casemirna.py | py | 1,900 | python | en | code | 1 | github-code | 6 |
27655143629 | from db.run_sql import run_sql
from models.slot import Slot
# CREATE TABLE slots (
# id SERIAL PRIMARY KEY,
# slot_num INT,
# time_stamp VARCHAR(255),
# turbo_slot BOOLEAN
# );
# CREATE
def save(slot):
sql = "INSERT INTO slots (slot_num, time_stamp, turbo_slot) VALUES (%s, %s, %s) RETURNING id"... | MistaRae/TurboGym | turbo_gym/repositories/slot_repository.py | slot_repository.py | py | 1,401 | python | en | code | 1 | github-code | 6 |
25070333505 | from django.db import models
from django.contrib import admin
from django import forms
import purplship.server.providers.models as carriers
def model_admin(model):
class _Admin(admin.ModelAdmin):
list_display = ("__str__", "test", "active")
exclude = ["active_users", "metadata"]
formfield... | danh91/purplship | server/modules/core/purplship/server/providers/admin.py | admin.py | py | 1,114 | python | en | code | null | github-code | 6 |
30281915177 | def near_ten(n):
# nearten = 10, 11, 12, 18, 19, 20, 21, 22, etc
satuan = n % 10
# if satuan == 0 or satuan == 1 or satuan == 2 or satuan == 8 or satuan == 9:
if satuan in [0, 1, 2, 8, 9]:
print(True)
else:
print(False)
bilangan = int(input('Masukkan sebuah bilangan: '))
print(n... | TIxKostan/latihan_Python | near_ten.py | near_ten.py | py | 338 | python | en | code | 0 | github-code | 6 |
39005103669 | #!/usr/local/bin/python
# The previous line (which must be the first one to work) makes the script self-executing,
# assuming that the system has the Python interpreter at path /usr/local/bin/python.
# This wants to be run in Python 3.
# Reference Pre-Processor
# Given: A string reference
# An integer horizon... | Moyaccercchi/bio-info-graph | python/2_reference_preprocessor/e2.py | e2.py | py | 4,348 | python | en | code | 1 | github-code | 6 |
71455781947 | from flask import Flask,flash, render_template, url_for, request, redirect
import googleapiclient.discovery
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from gtts import gTTS
import heapq
import nltk
import string
from nltk.corpus import stopwords
from nltk... | Anmol567/Youtube_Comment_Reviewer | my_new_flask_app.py | my_new_flask_app.py | py | 6,600 | python | en | code | 1 | github-code | 6 |
41207274862 | """Environment using Gymnasium API for Franka robot.
The code is inspired by the D4RL repository hosted on GitHub (https://github.com/Farama-Foundation/D4RL), published in the paper
'D4RL: Datasets for Deep Data-Driven Reinforcement Learning' by Justin Fu, Aviral Kumar, Ofir Nachum, George Tucker, Sergey Levine.
This... | Skeli9989/Gymnasium-Robotics | gymnasium_robotics/envs/franka_kitchen/franka_env.py | franka_env.py | py | 6,370 | python | en | code | null | github-code | 6 |
6193285358 | #! /usr/bin/env python
"""
Clean a text file containing tabular data.
Leon Hostetler, June 9, 2018
USAGE: python clean.py
"""
from __future__ import division, print_function
import numpy as np
import sys
# Filenames
inputfile = 'inputdata.txt'
outputfile = 'outputdata.txt'
# Import the data from the file. Comme... | leonhostetler/sample-programs | python/data_cleaning/clean.py | clean.py | py | 1,127 | python | en | code | 0 | github-code | 6 |
25010873745 | """
В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами.
Сами минимальный и максимальный элементы в сумму не включать.
"""
from random import randint
arr_spread = 10
arr_size = 10
arr = [randint(1, arr_spread) for _ in range(arr_size)]
print(arr)
lim1, lim2 = 0, arr_sprea... | the-nans/py2-repo_gb | lesson3_hw/l3_task6.py | l3_task6.py | py | 1,028 | python | ru | code | 0 | github-code | 6 |
5556252937 | from data.legacy_datagen import eddy_forcing,spatial_filter_dataset
from data.high_res_dataset import HighResCm2p6
from constants.paths import FINE_CM2P6_PATH,TEMPORARY_DATA
from utils.xarray_oper import plot_ds,fromtorchdict
from data.load import load_grid,load_xr_dataset
import xarray as xr
import os
import numpy as... | CemGultekin1/cm2p6 | temp/data_comparison.py | data_comparison.py | py | 2,408 | python | en | code | 0 | github-code | 6 |
13383663470 | # Alex Zaremba
# October 11th, 2022
file_name = input('Please enter name of the file: ') # Ask user for file name
out_file = file_name + ".html" # Convert file to html
body_h1 = input('Please enter character\'s name: ') # Request name of character
body_h1 = "<h1>" + body_h1 + "</h1>\n"
body_h2 = input('Please ent... | abzaremba97/Character-Generator | create-webpage.py | create-webpage.py | py | 1,355 | python | en | code | 0 | github-code | 6 |
22895124073 | import serial
import getch
serialport = serial.Serial("/dev/ttyS0")
serialport.baudrate = 115200
while True:
x = getch.getch()
if "W" == x.upper():
# Forwards
command = "+100+10015+00"
elif "S" == x.upper():
# Backwards
command = "-250-25015+00"
elif x == "A" or x == "a... | SinaRabiee/Digital_LAB_SSH | ssh-raspberry.py | ssh-raspberry.py | py | 597 | python | en | code | 0 | github-code | 6 |
2839743102 | '''
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2... | sgmzhou4/leetcode_problems | Array/18_4Sum.py | 18_4Sum.py | py | 1,549 | python | en | code | 0 | github-code | 6 |
36065549678 | from dotenv import load_dotenv
import os
import requests
from pprint import pprint
from datetime import datetime, timedelta
from flight_data import FlightData
load_dotenv()
API_KEY = os.getenv("flight_search_api")
KIWI_ENDPOINT = "https://api.tequila.kiwi.com"
class FlightSearch:
#This class is responsible for ta... | Shivam29k/Python_Projects | flight_deals_alert/flight_search.py | flight_search.py | py | 3,453 | python | en | code | 1 | github-code | 6 |
12712406140 | import tensorflow_hub as hub
import matplotlib.pyplot as plt
import numpy as np
import scipy.cluster.hierarchy as scp
module_url = "https://tfhub.dev/google/universal-sentence-encoder/4"
text_model = hub.load(module_url)
def embed_compare(sentence):
text_embedding = text_model(sentence)
sim_mat = np.inner(tex... | mgkumar138/determiners-objdet | submodels/universal_sentence_encoder_analysis.py | universal_sentence_encoder_analysis.py | py | 2,035 | python | en | code | 0 | github-code | 6 |
11454255593 | import torch
import os
import chartmodel
from torch.utils.data import Dataset
import albumentations
from albumentations.pytorch import ToTensorV2 as AT
from charttype import dataset
batch_size = 32
num_workers = 4
if __name__ == '__main__':
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
... | ksvyatov/chart-recognizer | charttype/test.py | test.py | py | 1,473 | python | en | code | 0 | github-code | 6 |
16502029718 | #! /usr/bin/python3
import logging
import os
from urllib3 import make_headers
from telegram import (InlineKeyboardButton, InlineKeyboardMarkup, InputTextMessageContent,
ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, CallbackQueryHandle... | oleges1/meet_bot | bot/add_location.py | add_location.py | py | 2,998 | python | en | code | 0 | github-code | 6 |
11899942747 | import requests
import json
import datetime
# On importe la liste des jours pou lesquels on a déjà les données
with open("days.txt", "r") as days:
completed_days = days.read()
days.close()
# On importe la date d'aujourd'hui et on la formatte
today = datetime.datetime.now()
today = str(today).split(" ")
to... | Aarrn33/auto-wind-importer | get_today.py | get_today.py | py | 1,312 | python | en | code | 0 | github-code | 6 |
71239238267 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import OrderedDict
import numpy
import json
import sys
import os.path
def readXYZ(filename):
# read molecular coordinates from .xyz file
# return list of symbols and list of coordinate
geom = []
with open(filename, "r") as f:
for ... | humeniuka/chem-queue | scripts/bagel_template.py | bagel_template.py | py | 3,245 | python | en | code | 0 | github-code | 6 |
8412882304 | from psiturk.psiturk_config import PsiturkConfig
import subprocess
CONFIG = PsiturkConfig()
CONFIG.load_config()
sections = ['psiTurk Access','AWS Access']
for section in sections:
for item in CONFIG.items(section):
#print 'heroku config:set ' + '='.join(item)
subprocess.call('heroku config:set ' ... | markkho/value-guided-construal | experiment.psiturkapp/set-heroku-settings.py | set-heroku-settings.py | py | 423 | python | en | code | 20 | github-code | 6 |
31684540429 | # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class DouluoSpider(CrawlSpider):
name = 'douluo'
allowed_domains = ['tycqxs.com']
start_urls = ['http://www.tycqxs.com/54_54196/']
custom_settings = {'ITEM_PIPELINES': {'s... | zhangcq1/MyCrawler | 爬虫基础梳理/shop/shop/spiders/douluo.py | douluo.py | py | 1,034 | python | en | code | 0 | github-code | 6 |
42663404209 | import copy
import math #needed for calculation of weight and bias initialization
import numpy as np
import pandas as pd
from torch.utils.data import Dataset, DataLoader
import torch, torch.nn as nn, torch.nn.functional as F
import torchvision
from torchvision import transforms, models, utils
#Set seeds
np.random.see... | rachellea/explainable-ct-ai | src/models/custom_models_diseasereps.py | custom_models_diseasereps.py | py | 21,347 | python | en | code | 3 | github-code | 6 |
29017166061 | from django.forms import model_to_dict
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from api.models.facility import Facility
from api.serializers.facility_serializer import FacilitySerializer
@api_view(['GET'])
def facility(request, ... | jazzhammer/jitgurup | api/views/facilitys_view.py | facilitys_view.py | py | 2,880 | python | en | code | 0 | github-code | 6 |
74358331067 | TITLE = 2
NAME = 0
PID = 1
SALARY = 3
with open('hr_system.txt', 'r') as f:
lines = f.readlines()
persons = [line.split() for line in lines]
for person in persons:
print(f'Name: {person[NAME].strip()}, Title: {person[TITLE].strip()}')
for person in persons:
salary = float(person[SALARY])
salary =... | gabrielchboff/CSE110 | src/Week06/team_activity.py | team_activity.py | py | 482 | python | en | code | 0 | github-code | 6 |
14699326224 | # -*- coding: utf-8 -*-
import sys
from os import listdir
from os.path import isfile, join
import io
def extract_files(path):
onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
return onlyfiles
def get_text(onlyfiles,path):
text = ''
for file in onlyfiles:
f = io.open(joi... | SerPablo/redib_extractor | src/text_extractor.py | text_extractor.py | py | 683 | python | en | code | 0 | github-code | 6 |
2140571757 | from tkinter import ttk, constants, messagebox, font
from services.study_app_service import study_app_service
from ui.navigation import Navigation
class CourseView:
"""Kurssinäkymästä vastaava luokka. Näyttää yksittäisen kurssin tehtävät."""
def __init__(self, root, previous_view, create_task, show_task, log... | erjavaskivuori/ot-harjoitustyo | study-app/src/ui/course_view.py | course_view.py | py | 3,973 | python | fi | code | 0 | github-code | 6 |
24994085411 | """
constants definition
"""
# definition for resourcetype
COLLECTION=1
OBJECT=None
DAV_PROPS=['creationdate', 'displayname', 'getcontentlanguage', 'getcontentlength', 'getcontenttype', 'getetag', 'getlastmodified', 'lockdiscovery', 'resourcetype', 'source', 'supportedlock']
# Request classes in propfind
RT_ALLP... | factorlibre/openerp-extra-6.1 | document_webdav_old/webdav/DAV/constants.py | constants.py | py | 350 | python | en | code | 9 | github-code | 6 |
15764585120 | """
Anisha Kadri 2017
ak4114@ic.ac.uk
A Module containing methods to create networks from different models.
1) For pure preferential attachement:-
pref_att(N, m)
2) For random attachment:-
rand_att(N,m)
3) For a mixture of the two, attachment via random walk:-
walk_att(N,m,L)
References
----------
[1]... | anishakadri/barabasialbert | model.py | model.py | py | 5,291 | python | en | code | 0 | github-code | 6 |
312775884 | from .models import Cart
from django.contrib.auth.models import User
def cart_count(request):
if request.user.isauthencated:
accountuser = request.user
products = Cart.get_all_by_user(accountuser)
count = products.count()
return {'cart_count': count}
else:
return {'cart_... | Yashraj098/ShopIt | ecom/context_processors.py | context_processors.py | py | 330 | python | en | code | 0 | github-code | 6 |
3225854902 | #!/usr/bin/python2.7
from functools import wraps
from flask import Flask, request, jsonify, Response, abort, json
import MySQLdb, collections
app = Flask(__name__)
MYSQL_DATABASE_HOST = "127.0.0.1"
MYSQL_DATABASE_USER = "twitter"
MYSQL_DATABASE_PASSWORD = "DF7U7q2yy6pUPSn3"
MYSQL_DATABASE_DB = "twitter"
db = MySQ... | brianfife/twitterapi | twitter.py | twitter.py | py | 8,268 | python | en | code | 0 | github-code | 6 |
28514991368 | """
This module transforms the corpus into the format require by each benchmarked tool
"""
import json
def liwc(senders, data):
ds = dict()
for hashed_addr in senders:
try:
emails = '. '.join(data[hashed_addr])
ds[hashed_addr] = emails
except KeyError:
cont... | collab-uniba/tosem2021-personality-rep-package | src/data_preparation.py | data_preparation.py | py | 1,782 | python | en | code | 1 | github-code | 6 |
7935100756 | # -*- coding: utf-8 -*-
#import sys
#reload(sys)
#sys.setdefaultencoding('utf-8') #gb2312
import codecs
import random
import numpy as np
from tflearn.data_utils import pad_sequences
from collections import Counter
import os
import pickle
import json
import jieba
from predictor.data_util_test import pad_truncate_list
P... | 201520815029009/Text-classification-augmented-with-label-definitions | cnn_classification/data_util.py | data_util.py | py | 11,736 | python | en | code | 0 | github-code | 6 |
38705340896 | ## Script (Python) "getPautasPanoramaIpea"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Retorna a lista de pautas do Panorama IPEA
pautas = context.portal_catalog.searchResults(portal_type='Pauta', \
... | lflrocha/ebc.pauta | ebc/pauta/skins/ebc_pauta_custom_templates/getPautasPanoramaIpea.py | getPautasPanoramaIpea.py | py | 468 | python | fi | code | 0 | github-code | 6 |
30366634041 | """ Simple polygon plot.
The UI allows you to change some of the attributes of the plot.
"""
import numpy as np
from traits.api import HasTraits, Instance, Range
from traitsui.api import View, UItem, Item, Group, HGroup, VGroup, spring
from chaco.api import Plot, ArrayPlotData, PolygonPlot
from enable.api import Co... | enthought/chaco | chaco/examples/demo/basic/polygon_plot_demo.py | polygon_plot_demo.py | py | 3,167 | python | en | code | 286 | github-code | 6 |
38760601495 | import sys
import netCDF4
import math
import itertools
from functools import reduce
def array_pieces(ndarray, max_bytes=None, overlap=0):
'''
Generator to return a series of numpy arrays less than max_bytes in size and the offset within the complete data from a NetCDF variable
Parameters:
ndarray: ... | GeoscienceAustralia/geophys_utils | geophys_utils/_array_pieces.py | _array_pieces.py | py | 4,493 | python | en | code | 22 | github-code | 6 |
75234645628 | from odoo import models, fields, api, exceptions, _
from odoo.exceptions import Warning, ValidationError
import datetime
from dateutil.relativedelta import relativedelta
class ExtraContractInherit(models.Model):
_inherit = 'hr.contract'
date_of_birth = fields.Date(string='تاريخ ميلاد الموظف', compute='cal_co... | emadraafatgad/visoneer | hr_insurance/models/employee_contract.py | employee_contract.py | py | 14,406 | python | en | code | 0 | github-code | 6 |
6836039340 | from fastapi import APIRouter, Depends, Response
from queries.games import GamesQueries
from typing import Union
router = APIRouter()
@router.get("/api/games/{game_id}")
def get_game(
game_id: int,
response: Response,
queries: GamesQueries = Depends(),
):
data = queries.get_game_by_id(game_id)
if... | tinatran079/netstix | games/routers/games.py | games.py | py | 1,682 | python | en | code | 0 | github-code | 6 |
9136295998 | #1.创建一个文件夹
import os
from multiprocessing import Pool,Manager
def copyFileTask(name,oldFolderName,newFolderName,queue):
fr=open(oldFolderName+'/'+name)
fw=open(newFolderName+'/'+name,'w')
content=fr.read()
fw.write(content)
fr.close()
fw.close()
queue.put(name)
def main():
# 0.获取用户要输入... | pgg-pgg/pythonTest | 19-多进程文件copy.py | 19-多进程文件copy.py | py | 1,051 | python | en | code | 0 | github-code | 6 |
70097864829 | import pygame as pg
import sys
from pygame.sprite import Group
from constants import *
from settings import Settings
from ship import Ship
import functions as funcs
from stats import Stats
from button import Button
from score import Score
from sound import Sound
def main():
sound = Sound()
pg.init()
... | hoangdesu/Alien-Invasion-Pygame | main.py | main.py | py | 2,009 | python | en | code | 1 | github-code | 6 |
37553859431 | # Cleans peers.txt of duplicates and nodes on same first network octet
# thus improving geographic spread of peers
import re
global netlist #so it can be accessed in multiple places
netlist = []
def clean_tuples(sent_tuples): # sent_tuples is the peer tuple list from local or remote
cleaned = [] # holder for the a... | Stoner19/stuff | peer_clean.py | peer_clean.py | py | 1,377 | python | en | code | 0 | github-code | 6 |
20629891320 | import argparse
import json
from collections import OrderedDict
import kernel_tuner as kt
import common
# Parse command line arguments
def parse_command_line():
parser = argparse.ArgumentParser(description='Tuning script for add_fluxes_kernel kernel')
parser.add_argument('--tune', default=False, action='store... | earth-system-radiation/rte-rrtmgp-cpp | tuning_kernels_cuda/add_fluxes_kernel.py | add_fluxes_kernel.py | py | 3,673 | python | en | code | 3 | github-code | 6 |
30461892433 | import csv
import base64
import pprint
import mysql.connector
from time import sleep as s
from functions import files, getLinesFromFile, getIPs, nmapScan, toLogFile
#fromLogs
#+---------------+--------------+------+-----+-------------------+-------------------+
#| Field | Type | Null | Key | Default ... | sschatz1997/Sams_website | py_MySQL/IPcount.py | IPcount.py | py | 2,677 | python | en | code | 1 | github-code | 6 |
8522443313 | import requests
from io import BytesIO
import time
from PIL import UnidentifiedImageError
import warnings
class PlateClient:
def __init__(self, url: str):
self.url = url
def readNumber(self, im) -> str:
res = requests.post(
f'{self.url}/readNumber',
headers={'Conte... | alexej-anosov/aaa_backend_hw | src/plate_client.py | plate_client.py | py | 1,142 | python | en | code | 0 | github-code | 6 |
29010586279 | import logging
import dposutils
def _get_url():
"""
"""
if __pillar__.get('app_port'):
url = 'http://localhost:{}'.format(__pillar__.get('app_port'))
else:
return None
return url
def _get_api():
"""
"""
url = _get_url()
if not url:
return None
retu... | treverson/salty-dpos | salt/_modules/salty_dpos_post.py | salty_dpos_post.py | py | 1,262 | python | en | code | 1 | github-code | 6 |
20800563712 | import math
tris = [int(i) for i in input().split()]
def angle(a, b, c): return math.degrees(math.acos((a**2 + b**2 - c**2)/(2.0 * a * b)))
def equal(a,b,c, a1, b1, c1):
aa = angle(a,b,c)
bb = angle(b,a,c)
cc = 180 - aa - bb
aa1 = angle(a1, b1, c1)
bb1 = angle(b1, a1, c1)
cc1 = 180 - aa1 - b... | michbogos/olymp | 50/17_simmilar_tris.py | 17_simmilar_tris.py | py | 458 | python | en | code | 0 | github-code | 6 |
6358696084 | #!/usr/bin/env python3
import json
from statistics import median
from datetime import datetime, timedelta
SENT_MESSAGE = "Sent message"
RECEIVED_MESSAGE = "Received message"
TRANSACTION_INIT = "Initialising transaction"
TRANSACTION_COMMIT = "Delivered transaction"
WITNESS_SET_SELECTED = "Witness set selected"
WITNESS_... | interestIngc/simulation-analyzer | logs_analyzer.py | logs_analyzer.py | py | 12,715 | python | en | code | 0 | github-code | 6 |
34670400006 | import json
from app_logic_extractor import app_logic_extractor
from lib.entity import App, Device, Net
from lib.util import convert_to_prolog_symbol, convert_to_prolog_var
from vul_analyzer import vul_analyzer
from vul_scanner import vul_scanner
def translate_vul_exists(prolog_dev_name, cve_id):
"""
Given a... | pmlab-ucd/IOTA | python/translator.py | translator.py | py | 8,669 | python | en | code | 1 | github-code | 6 |
70101306109 | """Control api connections and information gathering."""
import os
import requests
from constants.endpoints import endpoints
from typing import Tuple, Optional
class Binance:
"""Class to manage connection with Binance and data retrieving and inputting."""
def __init__(self, api_type: str = 'prod', endpoints = ... | cthadeufaria/redesigned-pas-trading | src/utils/api.py | api.py | py | 2,165 | python | en | code | 0 | github-code | 6 |
26626842826 | from django.shortcuts import render_to_response
from django.template import RequestContext
from product.models import Product
from satchmo_store.shop import signals
from signals_ahoy.signals import application_search
def search_view(request, template="shop/search.html"):
"""Perform a search based on keywords and c... | dokterbob/satchmo | satchmo/apps/satchmo_store/shop/views/search.py | search.py | py | 1,013 | python | en | code | 30 | github-code | 6 |
31609185391 | def notas(*resp, sit=False):
"""
-> Função para analisar notas e situações de alunos.
:param resp: uma ou mais notas de alunos
:param sit: valor opcional, indicando se deve ou não aparecer a situação de cada aluno
:return: dicionário com várias informações sobre a situação do aluno
"""
dict ... | pedrobarauna8/CursoPython | ex105.py | ex105.py | py | 720 | python | pt | code | 0 | github-code | 6 |
10438441538 | import cluster
import graph_builder
import pandas as pd
def main():
# The data files should be stored in these given locations.
country_codes_filename = "./data/COW-country-codes.csv"
dyadic_mid_filename = "./data/dyadic_mid_4.01.csv"
graphs_directory = "./graphs"
graph_builder.override_data_locat... | pmacg/mid-clustering | main.py | main.py | py | 587 | python | en | code | 0 | github-code | 6 |
71362243707 | import networkx as nx
import config.config as config
def graph_kernel_map_to_nodetypes(_graph):
"""
NOT SUPPORTED AFTER GRAPH ENCODING CHANGE.
A pre-processing step to collapse nodes to their model types.
:param _graph:
:return:
"""
graph_relabelled = nx.relabel_nodes(_graph, {no... | benjimaclellan/aesop | algorithms/assets/graph_edit_distance.py | graph_edit_distance.py | py | 2,807 | python | en | code | 2 | github-code | 6 |
42339560418 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def majuscule(mot):
for lettre in mot:
x= " "
if ord(lettre)>=65 and ord(lettre)<=90:
x=ord(lettre) + 32
return "Cette lettre en minuscule est " + chr(x)
def minuscule(mot):
for lettre in mot:
x= " "
if ord(lettre)>=9... | INF1007-2022H/ch2-RTorrella | exercice.py | exercice.py | py | 687 | python | fr | code | 0 | github-code | 6 |
19330268889 | class Solution(object):
def uniqueOccurrences(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
counter = dict()
for num in arr:
if num not in counter.keys():
counter[num] = 1
else:
counter[num]+=1
... | clarkeand/MoCodeMoProblems | my-folder/problems/unique_number_of_occurrences/solution.py | solution.py | py | 565 | python | en | code | 0 | github-code | 6 |
19416857297 | """Visualises the range of potentials relative to demand in each municipality."""
from itertools import chain, repeat
import click
import pandas as pd
import geopandas as gpd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import pycountry
from src.vis import RED, GREEN, BLUE
SORT_QUANTILE =... | timtroendle/possibility-for-electricity-autarky | src/vis/potentials_normed_boxplot.py | potentials_normed_boxplot.py | py | 3,114 | python | en | code | 10 | github-code | 6 |
74187907709 | #Richard Janssen <richardnjanssen@gmail.com>
#28/07/2023
#CS50 Introduction to Programming with Python
#File Input/Output
#This program expect for two command-line arguments, the first one is a image file input and the second
#is the output file name or path. This program overlay a "shirt image" on the given input file... | richardnj14/CS50_python | file_input_output/shirt/shirt.py | shirt.py | py | 1,411 | python | en | code | 0 | github-code | 6 |
10417120713 | from __future__ import annotations
import argparse
from argparse import ArgumentParser
def render_region_graph_logic(args):
import hashlib
import re
import graphviz
from randovania.game_description import default_database
from randovania.game_description.db.dock_node import DockNode
from ra... | randovania/randovania | randovania/cli/commands/render_regions.py | render_regions.py | py | 6,961 | python | en | code | 165 | github-code | 6 |
19528086110 | # -*- coding: utf-8 -*-
__author__='zhaicao'
from PyQt5 import QtCore, QtGui, QtWidgets
from frameUI.CreateControls import TraceControlsUI
from frameUI.CreateTextUI import TraceCreateTextUI
from frameUI.MainData import TraceObjItems
from eventAction.DefinedActions import TraceActions
from eventAction.DefinedSolot imp... | zhaicao/pythonWorkspace | DeployTool/frameUI/mainUI.py | mainUI.py | py | 15,888 | python | en | code | 0 | github-code | 6 |
1008816122 | '''Euler problem 527
https://projecteuler.net/problem=527'''
from random import randint
def binSearch(n):
'''number of guesses needed to find a
number in range n'''
t = randint(1,n)
lower = 1
upper = n
guesses = 0
while True:
#print("t=",t)
#print("lower = ",l... | hackingmath/Project-Euler | euler527.py | euler527.py | py | 1,421 | python | en | code | 0 | github-code | 6 |
24526237848 | import pandas as pd
import sys
def parse_osteometric_data(df):
try:
clavicle_df = df.loc[df['Element'] == 'Clavicle'][['Id', 'Side', 'Element',
'Cla_01', 'Cla_04', 'Cla_05']]
clavicle_l = clavicle_df.loc[clavicle_df['Side'] == 'Lef... | jwarsom/osteometrics | osteometrics/utils/util.py | util.py | py | 13,345 | python | it | code | 0 | github-code | 6 |
2780102996 | ################################################################################################
#Busca de erro
################################################################################################
@n1_web_tools.route('/buscador-de-erros/', methods=['GET', 'POST'])
def erros():
form = SearchForm(request.... | quesmues/example-form-onsubmit-script | view.py | view.py | py | 1,519 | python | de | code | 0 | github-code | 6 |
10754618870 | from nltk.corpus import stopwords
import pandas as pd
from nltk.stem.snowball import SnowballStemmer
import re
import nltk
class ngrams:
def __init__(self, df,column,n=10):
texto = " ".join(str(x) for x in df[column].values)
tokens = texto.split()
tokens=[x.lower() for x in tokens]
stopset = set(stop... | omedranoc/ThesisPreprocessing | model/ngrams.py | ngrams.py | py | 1,850 | python | en | code | 0 | github-code | 6 |
39870180773 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import imageio
import scipy.misc
import numpy as np
import videostyletransfer as vst
video_id = 'temple_2'
content_path = os.getcwd() + '/input/' + video_id + '/'
style_path = os.getcwd() + '/style-images/starry_night.jpg'
flow_path = os.getcwd() + '/flow/' +... | tomstrident/Video-Style-Transfer | video_style_transfer_demo.py | video_style_transfer_demo.py | py | 986 | python | en | code | 0 | github-code | 6 |
42673179666 | import graphene
from graphene_django.types import DjangoObjectType
from graphql import GraphQLError
from .models import *
from django.contrib.auth.models import User
class user(DjangoObjectType):
class Meta:
model = User
class task(DjangoObjectType):
class Meta:
model = Task
class Query(o... | neelansh/Todo_app_graphql | todo/app/schema.py | schema.py | py | 879 | python | en | code | 0 | github-code | 6 |
73203288508 | from konlpy.tag import Kkma
from konlpy.tag import Twitter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import normalize
import numpy as np
import pymongo
from pymongo import MongoClient
import pymysql
class SentenceT... | hanseul1/Text-summarize-with-TextRank | main.py | main.py | py | 4,729 | python | en | code | 0 | github-code | 6 |
75224158908 | from asyncio import run
import discord
from discord import app_commands
from discord import Interaction
from discord import Intents
from discord.ext import commands, tasks
import os
import asqlite
# Import the Guild ID
from misc.load import TEST_SERVER_ID
# Import the bot token
from Secure import BOT_TOKEN
# Bot... | Alexici/discordpybot | main.py | main.py | py | 12,874 | python | en | code | 0 | github-code | 6 |
9087413248 | import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import os
import json
import math
import random, os
import shutil
# Extract and save MFCCs from audiofiles
def save_mfcc(dataset_path, json_path, n_mfcc=20, n_fft=2048, hop_length=1024, num_segments=1):
data = ... | NOR2R/ML_miniproject | pythonScripts/MFCCExtraction_SaveJson.py | MFCCExtraction_SaveJson.py | py | 2,349 | python | en | code | 0 | github-code | 6 |
12010103629 | import time
from appium import webdriver
# 设备连接前置配置
descried_caps = dict()
descried_caps["platformName"] = "android"
descried_caps["platformVersion"] = "5.1.1"
descried_caps["deviceName"] = "emulator-5554"
descried_caps["appPackage"] = "com.bjcsxq.chat.carfriend"
descried_caps["appActivity"] = ".MainActivity"
# 实例化... | 1chott/appAutoStudy | code_D_04/code_03_常见api启动关闭app.py | code_03_常见api启动关闭app.py | py | 747 | python | en | code | 0 | github-code | 6 |
39912096462 | import jwt
from django.contrib.auth import authenticate
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework import status
from smtplib import SMTPException
from .serializers import SignupSerializer, VerifyAccoun... | TEAM-ILSAN/yourpool-backend | users/views.py | views.py | py | 3,630 | python | en | code | 0 | github-code | 6 |
16782914255 | import torch
import random
import gc
import optuna
import pandas as pd
import numpy as np
from utils import map3, compute_metrics, set_seed
from config3 import CFG
from config import CFG1
from datasets import Dataset
from torch.optim import AdamW
from pathlib import Path
from transformers import AutoModelForMultipleCho... | zdhdream/LLM-Science-Exam | Hyperparameter-Search.py | Hyperparameter-Search.py | py | 11,550 | python | en | code | 1 | github-code | 6 |
22124073233 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#todo: stop words and symbols are mucking things up
import os
import os.path
import nltk
import operator
from nltk import word_tokenize
import collections
import math
import sklearn
import sklearn.cluster
import numpy as np
import pandas as pd
from sklearn.cluster import KM... | mcwatera/WWTBHT | wwtbht/pages/scripts/ppmi/mcwatera_fp.py | mcwatera_fp.py | py | 6,495 | python | en | code | 0 | github-code | 6 |
74413560828 | class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if k == 0:
return
k = k % len(nums)
def reverse(arr, i, j):
while i < j:
arr[i], arr[j] = arr[j], a... | garimaarora1/LeetCode-2023 | rotate-array/rotate-array.py | rotate-array.py | py | 494 | python | en | code | 0 | github-code | 6 |
12567993602 | '''Create big blob of data
'''
import os
import pandas as pd
from dataset_creators import bikerawdata
TPE_FILE_ROOT = '../bike_raw_data/taipei'
HEL_FILE_ROOT = '../bike_raw_data/helsinki'
LON_FILE_ROOT = '../bike_raw_data/london'
TOR_FILE_ROOT = '../bike_raw_data/toronto'
TPE_FILES = ['{}/{}'.format(TPE_FILE_ROOT, f... | anderzzz/viral-bikers | dataset_creators/make_blob.py | make_blob.py | py | 1,444 | python | en | code | 1 | github-code | 6 |
72532766909 | """
Functions and models to query scicrunch service REST API (https://scicrunch.org/api/)
- http client for API requests
- Error handling:
- translates network errors
- translates request error codes
Free functions with raw request scicrunch.org API
- client request context
- ra... | ITISFoundation/osparc-simcore | services/web/server/src/simcore_service_webserver/scicrunch/_rest.py | _rest.py | py | 3,706 | python | en | code | 35 | github-code | 6 |
39081271022 | import pandas as pd
def getAirline(row: pd.Series) -> str:
"""Run through the potential columns and return the one that matches
Parameters
----------
row:pd.Series : row series of dataframe with Airline run through get
dummies
Returns
-------
string of the airline
"""
ret = '... | SL477/Predicting_future_trends_in_airline_profitability | data/notebookhelp/getAirlineFromDummies.py | getAirlineFromDummies.py | py | 1,013 | python | en | code | 0 | github-code | 6 |
34381391905 | """
Compile QEMU Version 5.1.0 or newer. 5.1.0 is when AVR support was introduced.
.. code-block:: console
$ wget https://download.qemu.org/qemu-6.1.0.tar.xz
$ tar xvJf qemu-6.1.0.tar.xz
$ cd qemu-6.1.0
$ ./configure --target-list="avr-softmmu"
$ make -j $(($(nproc)*4))
Change directory to this... | sedihglow/braccio_robot_arm | python/archive/QEMU_arduino_serial_testing/test_cmd_msg.py | test_cmd_msg.py | py | 3,529 | python | en | code | 0 | github-code | 6 |
12449590446 | from distutils.errors import LibError
from tabnanny import verbose
from time import timezone
from django.db import models
from django.forms import CharField
from django.contrib.auth.models import User
from datetime import datetime,date, time
from django.utils import timezone
# Create your models here.
class TipoVeh... | xpilasi/segundo_liquidadora | web_base/models.py | models.py | py | 8,166 | python | es | code | 0 | github-code | 6 |
69860227068 | from igraph import *
import csv
from concurrent import futures
f_input_ncol='/tmp/socgraph/cnn_comment_yearweek.ncol'
f_output_graphml='/tmp/socgraph/output/week%d.graphml'
'''
This snippet:
+reads in a "big-graph" in which edges are created at different time (different weeks).
+Partitions "big-graph" into smaller ... | pdphuong/soclust | bigobject/socgraph_clustering.py | socgraph_clustering.py | py | 1,766 | python | en | code | 0 | github-code | 6 |
23982957449 | """
[Week 1 - Session 1]
Problem #1 Reverse a String
"""
"""
UNDERSTAND:
-Is the user input always going to be string?
-> First assume that it is
-empty string should just print out empty string
MATCH:
-indexing string from the back and concatenating
PLAN:
-Create a new empty string
-Using a simple for loop that in... | ryder0705/codepath | week1/StringReverse.py | StringReverse.py | py | 990 | python | en | code | 0 | github-code | 6 |
31841821973 | from rest_framework.views import APIView
from app.super_admin.controller import SuperAdminController
from common.django_utility import send_response
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import IsAuthenticated
from dateutil.parser import parse
superAdmin... | ayush431/m_56studios | m56studios_be/app/super_admin/views.py | views.py | py | 1,194 | python | en | code | 0 | github-code | 6 |
41661344170 |
def parse_args(args, opts):
values = [ [] for opt in opts ]
flat_opts = []
for opt in opts:
if isinstance(opt,list):
flat_opts.extend(opt)
else:
flat_opts.append(opt)
for arg_number, arg in enumerate(args):
for opt_number, opt in enumerat... | nmaxwell/pyTexNotes | tools.py | tools.py | py | 512 | python | en | code | 1 | github-code | 6 |
7171062634 | #Answer to Set .add()
n = int(input())
a = set()
for i in range(n):
a.add(input())
print(len(a))
"""
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
None
>>> print s
set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R'])
""" | CompetitiveCode/hackerrank-python | Practice/Sets/Set .add().py | Set .add().py | py | 316 | python | en | code | 1 | github-code | 6 |
44344352975 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from heapq import heappush, heappop
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
heap = []
for i i... | nayeonkinn/algorithm | leetcode/[Hard] 23. Merge k Sorted Lists.py | [Hard] 23. Merge k Sorted Lists.py | py | 622 | python | en | code | 0 | github-code | 6 |
23055518013 | """
Creation:
Author: Martin Grunnill
Date: 2023-01-25
Description: Derivation of Basic Reproductive Number (R0) and beta given R0 for model described in manuscript.
For methods see:
Diekmann, O., Heesterbeek, J. A. P., & Roberts, M. G. (2010). The construction of next-generation matri... | LIAM-COVID-19-Forecasting/Modelling-Disease-Mitigation-at-Mass-Gatherings-A-Case-Study-of-COVID-19-at-the-2022-FIFA-World-Cup | meta_population_models/reproductive_numbers/MGE_single_population_derivation.py | MGE_single_population_derivation.py | py | 3,417 | python | en | code | 0 | github-code | 6 |
5584993015 | import asyncio
import httpx
from .._utils import chunk_file, format_locations
from .._exceptions import UploadException, LocationRetrieveException
class ConcatenateUploader:
default_concatenate_headers = {
"Tus-Resumable": "1.0.0",
"Upload-Concat": "partial",
}
default_chunk_size = 4 * 1... | LesPrimus/aiotusx | aiotusx/_uploaders/concatenate.py | concatenate.py | py | 3,146 | python | en | code | 0 | github-code | 6 |
29834597841 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 28 16:16:07 2021
@author: chomi
"""
from detecto import core, utils, visualize
import os
model = core.Model.load('new_model.pth', ['0_','1_', '2_','3_','4_'])
directory = 'C:/Users/chomi/Desktop/test/'
for filename in os.listdir(directory):
if(filename.endswith(".p... | Mcful123/auto_training | example.py | example.py | py | 557 | python | en | code | 0 | github-code | 6 |
37319818 | from IPython import get_ipython
from IPython.core.magic import Magics, magics_class, cell_magic
from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring
import mamo
@magics_class
class MamoMagics(Magics):
@cell_magic
@magic_arguments()
@argument("name", type=str, default=None, h... | BlackHC/mamo | mamo/support/ipython.py | ipython.py | py | 678 | python | en | code | 0 | github-code | 6 |
10876951886 | import yaml
import json
import os
import subprocess
class MLOps(object):
spool_dir = "/tmp/ta"
agent_dir = "/opt/mlops-agent"
mlops_dir_name = "datarobot_mlops_package-8.1.2"
total_dir_path = agent_dir + "/" + mlops_dir_name
def __init__(self, api_token, path):
self.token = api_token
... | algorithmiaio/algorithmia-adk-python | adk/mlops.py | mlops.py | py | 2,766 | python | en | code | 6 | github-code | 6 |
39441351801 | import re
import spacy
from bpemb import BPEmb
from mlearn import base
from string import punctuation
from ekphrasis.classes.tokenizer import SocialTokenizer
from ekphrasis.classes.preprocessor import TextPreProcessor
class Preprocessors(object):
"""A class to contain preprocessors and wrap preprocessing function... | zeeraktalat/mlearn | mlearn/data/clean.py | clean.py | py | 12,772 | python | en | code | 2 | github-code | 6 |
19637216652 | import pickle
import lasagne
import numpy as np
import theano as th
import theano.tensor as T
import lasagne.layers as ll
from data_reader import load
from settings import DATA_DIR
from inception_v3 import build_network, preprocess
def extract(data, layer, batch_size):
nr_batches_train = int(data.shape[0]/batch... | maciejzieba/svmCIFAR10 | extract_inception.py | extract_inception.py | py | 1,602 | python | en | code | 2 | github-code | 6 |
23007800095 | import numpy as np
from keras.utils import to_categorical
def create_labels(train_positives, train_negatives=None, flag=False):
''' This function creates labels for model training '''
if flag == False :
# only positive data in trainings
labels = np.zeros(train_positives.shape[0])
la... | nikitamalviya/user-authentication-using-siamese | features_and_labels.py | features_and_labels.py | py | 1,281 | python | en | code | 0 | github-code | 6 |
35239523373 | print("hello")
string = "MALAYALAM"
temp = []
for i in string:
if i not in temp:
temp.append(i)
print(i, "->",string.count(i))
class Node:
def __init__(self, name, age):
self.name = name
self.age = age
def print1(self):
print("Name ->", self.name)
print("Ag... | cadetgoutham/master | Practice/Python/sample.py | sample.py | py | 3,130 | python | en | code | 0 | github-code | 6 |
18674675586 | import os
import shutil
import random as rand
from constants.constants import EXTRACTED_IMAGES, VALIDATION_IMAGES
def split_data():
"""
Splits data into training and validation sections for training.
:return:
"""
# check if validation folder exists, create if not
if not os.path.exists(VALIDATI... | prsn670/Handwritten-Equation-Solver | prep_data/split_data.py | split_data.py | py | 1,091 | python | en | code | 0 | github-code | 6 |
11890317934 | n = int(input())
array = list(map(int,input().split()))
even_pos = [elem for elem in array[::2]]
even_pos.sort()
i = 0
for elem in even_pos:
array[i] = elem
i += 2
print(' '.join([str(n) for n in array]))
| syedjaveed18/codekata-problems | Arrays/Q23.py | Q23.py | py | 215 | python | en | code | 0 | github-code | 6 |
35176426735 | '''
Organisation Model.py file
'''
import uuid
from django.db import models
class Organisation(models.Model):
'''
Organisation Table
id - Organisations ID
name - Organisations Name (Max length of 255 characters)
'''
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4... | Code-Institute-Submissions/Support-Software-Inc | organisations/models.py | models.py | py | 590 | python | en | code | 0 | github-code | 6 |
18515188174 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 21 16:49:53 2017
@author: mducoffe
appendix : expansion operator for convolutional KFAC
"""
from keras.models import Model, Sequential
from keras.layers import Dense
import keras.backend as K
from keras.layers.merge import Concatenate
from keras.e... | mducoffe/Active_Learning_Variational_Inference_Deep_Networks | appendix.py | appendix.py | py | 1,264 | python | en | code | 4 | github-code | 6 |
39583332735 | # -*- coding:utf-8 -*-
from flask import json
from DataSet import db
from DataSet.fastdfs.view import fun
from DataSet.models import Image, Label
def storage(up_file, collection, file_name):
try:
image_status = fun.upload(up_file, file_ext_name='jpg')
image = Image()
image.name = file_nam... | limingzhang513/lmzrepository | data_module/src/Data_Processing/DataSet/utils/change_json_file.py | change_json_file.py | py | 4,014 | python | en | code | 0 | github-code | 6 |
72013269309 | import numpy as np
from collections import deque
from segment_tree import SumSegmentTree,MinSegmentTree
class ReplayBuff(object):
def __init__(self,max_size,observation_shape):
self.max_size=max_size
self.observations=np.zeros([max_size,observation_shape],dtype=np.float32)
self.actions=np.... | linnaeushuang/RL-pytorch | value-based/rainbow/memory.py | memory.py | py | 6,851 | python | en | code | 8 | github-code | 6 |
1008840332 | '''Problem 62 cubic permutations'''
import time
from itertools import permutations
t1 = time.time()
cubes = [x**3 for x in range(1001,10000)]
def make_list(cube):
cubestring = str(cube)
#print(cubestring)
cubelist = [int(x) for x in cubestring]
cubelist.sort()
return cubelist#.so... | hackingmath/Project-Euler | euler62.py | euler62.py | py | 1,623 | python | en | code | 0 | github-code | 6 |
22075010385 | from flask import Flask, request, jsonify
from flask_cors import CORS
import sqlite3
import base64
app = Flask(__name__)
CORS(app)
@app.route('/')
def index():
return 'Index Page'
@app.route('/deleteUser', methods=['DELETE'])
def delete_user():
print("Petición DELETE")
try:
data = request.get... | DevEliezerMartinez/PosMABG | Back-end/server.py | server.py | py | 5,235 | python | en | code | 1 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.