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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
70397498577 | '''
File contains functions for cleaning the raw data from Beer Advocate
'''
def cleanDigits(unformatted_score):
'''
remove unwanted formatting from scores
'''
import re
scsplit = re.split('/',unformatted_score)
## If there was character to split on, normalize it
if len(scsplit) > 1:
... | ericsdata/colinsbeer | src/BeerBrush.py | BeerBrush.py | py | 1,119 | python | en | code | 0 | github-code | 13 |
17080007274 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.EcConsumeInfo import EcConsumeInfo
from alipay.aop.api.domain.EcOrderInfo import EcOrderInfo
from alipay.aop.api.domain.EcConsumeInfo import EcConsumeInfo
from alipay.a... | alipay/alipay-sdk-python-all | alipay/aop/api/response/AlipayCommerceEcConsumeDetailQueryResponse.py | AlipayCommerceEcConsumeDetailQueryResponse.py | py | 2,948 | python | en | code | 241 | github-code | 13 |
71617248018 | #!/bin/python3 -u
import discord
import os
from dotenv import load_dotenv
from discord.ext import commands
from discord.utils import get
import re
load_dotenv()
intents = discord.Intents.all()
client = commands.Bot(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print('ccbot_commands star... | DrewCording/TenTalkBot | ccbot_commands.py | ccbot_commands.py | py | 3,343 | python | en | code | 3 | github-code | 13 |
38399276593 | import network as net
from PIL import Image, ImageDraw, ImageFont
from vector import Vector
WIDTH = 800
HEIGHT = 600
BG = ( 0, 0, 0 )
FG = ( 255, 255, 255 )
def draw( network: net.NeuralNetwork ) -> Image:
im = Image.new( "RGB", ( WIDTH, HEIGHT ), BG )
dr = ImageDraw.Draw( im )
layers = network.get_lay... | ejdam87/neural-network | old/draw_network.py | draw_network.py | py | 1,873 | python | en | code | 0 | github-code | 13 |
18855966708 | from typing import List
def checker(n, idx, arr):
if n == 0:
return 0
fwd_dist = None
for i in range(idx + 1, len(arr)):
if arr[i] != 0:
continue
fwd_dist = i - idx
break
bwd_dist = None
for i in range(idx - 1, -1, -1):
if arr[i] != 0:
... | vaydich/algorithms | introduction_to_algorithms/final_part/a.py | a.py | py | 802 | python | en | code | 0 | github-code | 13 |
23125168760 | from __future__ import print_function
import gdown
from googleapiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
import io
from googleapiclient.http import MediaIoBaseDownload
SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'
store = file.Storage('storage... | Vassar-Miniscope/miniursi | drive/drive_list.py | drive_list.py | py | 2,226 | python | en | code | 0 | github-code | 13 |
15817151609 | """Dataset and DataModule for the MultiNLI dataset."""
# Imports Python builtins.
import os
import os.path as osp
import sys
# Imports Python packages.
import numpy as np
import pandas as pd
import wget
# Imports PyTorch packages.
import torch
from torchvision.datasets.utils import (
extract_archive,
)
# Import... | tmlabonte/last-layer-retraining | milkshake/datamodules/multinli.py | multinli.py | py | 4,191 | python | en | code | 7 | github-code | 13 |
10895057054 | ### this .py is for generating model performance, MAE, NRMSE, and CR
import numpy as np
import matplotlib.pyplot as plt
def tripLengthFrequency(OD,distance):
distanceRange=np.arange(0, np.floor(distance.max())+1,0.5)
tlf=np.zeros(len(distanceRange)-1)
n=len(OD)
for k in range(len(distanceRa... | nicholasadam/PKDD2018-dynamic-zone-correlation | ODMOE.py | ODMOE.py | py | 1,162 | python | en | code | 1 | github-code | 13 |
70014292818 | import random
import asyncio
from aiotasks import build_manager
manager = build_manager("redis://")
@manager.task()
async def task_01(num):
wait_time = random.randint(0, 4)
print("Task 01 starting: {}".format(num))
await asyncio.sleep(wait_time, loop=manager.loop)
print("Task 01 stopping")
... | cr0hn/aiotasks | examples/standalone_tasks_and_wait_standalone.py | standalone_tasks_and_wait_standalone.py | py | 822 | python | en | code | 431 | github-code | 13 |
39298646006 | # These 4 list store data for users, meetups, questions & rsvps respectively
users, meetups, questions, rsvps = [], [], [], []
class BaseModels(object):
"""
This class contains methods that are common to all other
models
"""
def __init__(self):
self.users = users
self.meetups = ... | ansarisan/vigilant-spoon | app/api/v1/models/base_model.py | base_model.py | py | 2,598 | python | en | code | 0 | github-code | 13 |
18462384632 | def solution(left, right):
answer = 0
num_list = [i for i in range(left, right+1)]
for num in num_list:
divisor_list = []
for i in range(1,num+1):
if num % i == 0:
divisor_list.append(i)
if len(divisor_list) % 2 == 0:
answer += num
else... | zzuckerfrei/yesjam | programmers/약수의_개수와_덧셈.py | 약수의_개수와_덧셈.py | py | 366 | python | en | code | 0 | github-code | 13 |
28990531035 | class Triangle:
number_of_sides=3
def __init__(self,angle1,angle2,angle3):
self.angle1=angle1
self.angle2=angle2
self.angle3=angle3
def checkangles(self):
if((self.angle1+self.angle2+self.angle3)==180):
print("True")
return True
els... | SumanthPai/Python-CodeVerse | triangle.py | triangle.py | py | 543 | python | en | code | 0 | github-code | 13 |
18501370907 | from aws_cdk import core
from replication.s3stack import S3Stack
class replicationStack:
def __init__(self):
self.app = core.App()
def build(self) -> core.App:
setup_stack = S3Stack(
self.app,
"setup-stack",
env={'region':'us-east-1'}
)
r... | fossouo/S3ReplicationCDK | app/replication/replicationstack.py | replicationstack.py | py | 477 | python | en | code | 0 | github-code | 13 |
28169093614 | import pygame, sys, time
from pygame.locals import *
from random import randint
class TankMain(object):
"""坦克大战的主窗口"""
width = 800
height = 600
my_tank_missile_list = []
my_tank = None
# enemy_list = []
enemy_list = pygame.sprite.Group() # 敌方坦克的族群
explode_list = []
enemy_missile_l... | mengfangpo123/pythoncode | tank.py | tank.py | py | 15,153 | python | en | code | 0 | github-code | 13 |
6527712738 | import csv
import os
import json
import numpy
import numpy as np
import onnx
from collections import defaultdict
from onnx import numpy_helper
from onnx import shape_inference
from onnx_explorer import logo_str
from onnx_explorer.utils import get_file_size, byte_to_mb, get_file_size_mb, get_model_size_mb
class ONNXM... | isLinXu/onnx-explorer | onnx_explorer/OnnxAlyzer.py | OnnxAlyzer.py | py | 17,893 | python | en | code | 4 | github-code | 13 |
17625380375 | import sys
from PyQt5.QtWidgets import *
from math import *
class Main(QDialog):
def __init__(self):
super().__init__()
self.init_ui()
self.equation = "" #계산식을 저장할 변수 생성
self.numeric = "" #두 자리 수 이상을 표시하기 위해 변수 생성
self.operation =[] #연산자 저장
d... | Yuren03/pyqt_calculator_practice | calculator_main.py | calculator_main.py | py | 7,728 | python | en | code | 0 | github-code | 13 |
17723307322 | import numpy as np
import pandas as pd
import seaborn as sns
import statsmodels.api as sm
import sys
from matplotlib import pyplot as plt
from mne_bids.tsv_handler import _from_tsv
from pathlib import Path
from ptitprince import PtitPrince as pt
from sklearn.utils import check_random_state
if not str(Path(__file__).pa... | adam2392/motor-decoding | mtsmorf/move_exp/functions/time_window_selection_functions.py | time_window_selection_functions.py | py | 13,810 | python | en | code | 0 | github-code | 13 |
12269716908 | import sys
sys.stdin = open("글자수_input.txt", "r")
T = int(input())
for test_case in range(1, T + 1):
inx = list(input())
inx = list(set(inx))
table = input()
out = 0
for c in inx:
temp=0
for text in table:
if text==c:
temp+=1
if temp>out:
... | ksinuk/python_open | my_pychram/6 string course/글자수.py | 글자수.py | py | 379 | python | en | code | 0 | github-code | 13 |
6364104441 | """
Ce programme est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL diffusée sur le site "http://www.cecill.info".
"""
import discord
from disc... | Curiosity-org/Gipsy | plugins/welcome/welcome.py | welcome.py | py | 2,690 | python | en | code | 13 | github-code | 13 |
30765949865 | import os
import albumentations as A
import hydra
import pytorch_lightning as pl
from albumentations.pytorch.transforms import ToTensorV2
from torch.utils.data import DataLoader, random_split
from datasets import UNETDataset
from utils import get_data
class UNETDataModule(pl.LightningDataModule):
def __init__(s... | mrdvince/dltb_hpu | src/datamodules.py | datamodules.py | py | 2,250 | python | en | code | 0 | github-code | 13 |
42173365530 | from django.shortcuts import render, redirect, HttpResponse
from django.core.files.storage import FileSystemStorage
from django.http import JsonResponse
from django.views.generic.base import View
from rest_framework.views import APIView
from main.models import Product, Photo_product
from django.core import serializers
... | YannGotti/kyrsovaya-mironov-django | project/main/views.py | views.py | py | 5,206 | python | en | code | 0 | github-code | 13 |
21253897266 |
# Bottom up
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
n = len(s1)
m = len(s2)
if n + m != len(s3):
return False
dp = [[False for _ in range(m+1)] for _ in range(n+1)]
dp[n][m] = True
for i in range(n, -1, -1):
... | sundar91/dsa | DP/interleaving-strings.py | interleaving-strings.py | py | 1,308 | python | en | code | 0 | github-code | 13 |
71136359379 | from django.urls import path
from chats.views import *
urlpatterns = [
path('chats_list/<int:user_id>/', ChatList.as_view(), name='chats_list'),
path('chats_detail/<int:id>/', ChatEditDeleteUpdate.as_view(), name='chat_detail'),
path('create_chat/', ChatListCreate.as_view(), name = 'create_chat'),
... | Klorestz/Backend-dev-VK | project/messenger/chats/urls.py | urls.py | py | 688 | python | en | code | 0 | github-code | 13 |
19965782785 | """foreign key
Revision ID: c5d41f501eae
Revises: 37cf6cf9e9e1
Create Date: 2020-08-22 17:05:46.585115
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c5d41f501eae'
down_revision = '37cf6cf9e9e1'
branch_labels = None
depends_on = None
def upgrade():
# ##... | R0YLUO/Semester-Calendar | migrations/versions/c5d41f501eae_foreign_key.py | c5d41f501eae_foreign_key.py | py | 2,011 | python | en | code | 0 | github-code | 13 |
2082665470 |
from solver import *
def solve_system(m, input_i, output_i, state_i, nstate_i, input_n, output_n, state_n):
"""
Solve a system with data gathered in the matrix m, and the input / output
/ state names / indicies in that matrix specified.
The _n name arrays are contain the names of the given col indicies into
t... | Mobius5150/C115_Logic_Analyzer | solve.py | solve.py | py | 4,810 | python | en | code | 0 | github-code | 13 |
27216045548 | '''
这个文件主要封装了一些常用的函数
'''
import nltk
from nltk import word_tokenize
from textblob import TextBlob
import textblob
from nltk.stem import WordNetLemmatizer
from bs4 import BeautifulSoup
from textblob.tokenizers import SentenceTokenizer as sent_tok
from textblob.tokenizers import WordTokenizer as word_tok
from .read_conf... | lavizhao/insummer | code/insummer/util.py | util.py | py | 4,831 | python | en | code | 7 | github-code | 13 |
9400355778 | import click
from sqlalchemy import select
from rich.console import Console
# ------------
# Custom Modules
from .models import (
Vehicle,
FuelRecord,
select_vehicle_by_id,
select_vehicle_by_name,
)
from .common import is_int
# -------------
console = Console()
date_format_strings = [
"%Y-%m-... | TroyWilliams3687/fuel_tracker | src/fuel_tracker/command_fuel.py | command_fuel.py | py | 7,165 | python | en | code | 0 | github-code | 13 |
22224201874 | import json
import os
import pprint
import sys
from core.content import get_Data
from concurrent.futures import ThreadPoolExecutor
from core import login_hodj
threa = ThreadPoolExecutor(max_workers=32)
sys.path.append(os.getcwd())
def get_list(data):
# param = {"no": "dy0002", "data": {"days": 1, "rankType": 5,... | qifiqi/codebase | python_codebase/爬虫/红人点集/main.py | main.py | py | 1,367 | python | en | code | 3 | github-code | 13 |
10590941797 | import socket
SOCKET = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# First param: Family - Address family - assign type of address the socket can communicate with
# AF_INET - IPV4
# AF_INET6 - IPV6
# AF_UNIX - used for unix domian socket
# Second param : Type
# SOCK_DGRAM - specifies user datagram protocol (UD... | shalvinpshaji/socket-programming | socket1.py | socket1.py | py | 821 | python | en | code | 1 | github-code | 13 |
8865758711 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 10:15:05 2018
@author: james
"""
#%% Preamble
import os
import yaml
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
from scipy import optimize
#%% Functions
def load_yaml_configfile(fname):
"""
load yam... | jamesmhbarry/PVRAD | aeronetmystic/aeronetmystic/pvcal_aerosol_input.py | pvcal_aerosol_input.py | py | 40,278 | python | en | code | 1 | github-code | 13 |
17046159004 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipaySecurityRiskContentSyncDetectModel(object):
def __init__(self):
self._channel = None
self._content_type = None
self._data_list = None
self._open_id = None
... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AlipaySecurityRiskContentSyncDetectModel.py | AlipaySecurityRiskContentSyncDetectModel.py | py | 4,627 | python | en | code | 241 | github-code | 13 |
39357252944 | import pandas as pd
import os
import pickle
import geopandas as gpd
from pathlib import Path
from nextbike.constants import CONSTANTS
from nextbike.constants import __FILE__
from nextbike import utils
def __read_geojson(geojson):
"""
Method is private. It reads geojson-files located in the external folder
... | ey96/DataScienceBikesharing | nextbike/io/input.py | input.py | py | 2,177 | python | en | code | 0 | github-code | 13 |
8062497619 | import os
import sys
import requests
import argparse
# pip install "qrcode[pil]"
from PIL import Image
import qrcode
from pathlib import Path
from urllib.parse import urlparse
from io import BytesIO
ALL_DUCKS_ENDPOINT = "/admin/many-ducks"
OUTPUT_DIR = "./qrcodes"
def ducks_endpoint(frontend, id_of_duck):
url = ... | Congyuwang/cyberduck-backend | python-utils/gen_duck_qr_codes.py | gen_duck_qr_codes.py | py | 2,505 | python | en | code | 2 | github-code | 13 |
1398254155 | # Uses python3
import sys
def fibonacci_partial_sum_naive(from_, to):
sum = 0
current = 0
next = 1
for i in range(to + 1):
if i >= from_:
sum += current
current, next = next, current + next
return sum % 10
def pisano10():
fibs = [0, 1] + [-1 for i in range(2, 61... | AlexEngelhardt-old/courses | Data Structures and Algorithms/01 Algorithmic Toolbox/Week 2 - Algorithmic Warm-up/assignment/7_fibonacci_partial_sum.py | 7_fibonacci_partial_sum.py | py | 913 | python | en | code | 2 | github-code | 13 |
9735564748 | from operator import itemgetter
#input arr
arr = [2,1,2,2]
#Parse the arr for freq
parsed_arry = [[0 for x in range(2)] for y in range(len(arr))]
for x in arr:
parsed_arry[x][1] += 1
parsed_arry[x][0] = x
#Sort the array by 2nd column from desc order.
sorted_arr = sorted(parsed_arry, key=itemgetter(1), rever... | ScorpiosCrux/coding-challenges | hackerrank/amazon-practice/amazon_summary.py | amazon_summary.py | py | 737 | python | en | code | 0 | github-code | 13 |
35517934308 | import numpy as np
from .. import tools
from ..HomTra import HomTra
def mean_distance_between(focal_point, facet_centers):
"""
Returns the average distance between the focal_point position and all
the individual mirror facet center positions.
Parameter
---------
focal_point 3D position
... | cherenkov-plenoscope/cable_robo_mount | cable_robo_mount/mirror_alignment/mirror_alignment.py | mirror_alignment.py | py | 6,973 | python | en | code | 0 | github-code | 13 |
24471430476 | #!/usr/bin/python3
import os
def HammingDistance(firstBinary, secondBinary):
assert len(firstBinary) == len(secondBinary)
result = 0
for i in range(len(firstBinary)):
if (firstBinary[i] != secondBinary[i]):
result += 1
return result
def hexCharToBin(hexChar):
if (hexChar == '0... | Pelcz97/HW-Sicherheit | Task1-PUF/source_files/analyze_puf_data.py | analyze_puf_data.py | py | 3,926 | python | en | code | 0 | github-code | 13 |
15642702528 | import cv2
import easy_tf_log
import numpy as np
from gym import spaces
from gym.core import ObservationWrapper, Wrapper
"""
Wrappers for gym environments to help with debugging.
"""
class NumberFrames(ObservationWrapper):
"""
Draw number of frames since reset.
"""
def __init__(self, env):
O... | mrahtz/ocd-a3c | debug_wrappers.py | debug_wrappers.py | py | 3,966 | python | en | code | 38 | github-code | 13 |
26377419112 | import pandas as pd
import numpy as np
from constants import *
def getData():
df = pd.read_csv(TRAIN_DATA_FILEPATH, encoding = DATASET_ENCODING, header = None, names = DATASET_COLUMNS)
df = df.fillna("")
usefulColumns = ['target','text']
df = df[usefulColumns]
df['target'] = df['target'].astype(np.... | neha-singh09/sentiment_analysis | data_loading.py | data_loading.py | py | 395 | python | en | code | 0 | github-code | 13 |
8596874382 | from sklearn.feature_selection import mutual_info_regression
from carotid import carotid_data_util as cdu
from scipy.stats import pearsonr
dataset = 'ko'
target = 'Stenosis_code'
seed = 7
if dataset == 'ko':
id_all, x_data_all, y_data_all = cdu.get_ko(target)
fName = 'svm_ko.csv'
elif dataset == 'jim':
id... | chingheng113/ml_farm | carotid/bk/independence_test.py | independence_test.py | py | 791 | python | en | code | 0 | github-code | 13 |
41180728714 | import cv2
import numpy as np
img = cv2.imread('tapu.jpg')
img_cpy = img.copy()
img_cpy2 = img.copy()
img_cpy3 = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, img_thres = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY)
img_cont, contours, hierarchy = cv2.findContours(img_thres, cv2.RETR_EXTERNAL, cv2.... | knzkhuka/4e_experiment | 8_computer_graphics/prog/mask.py | mask.py | py | 2,035 | python | en | code | 0 | github-code | 13 |
70583484178 | import peers
from core.nodes import Miner, Node, Wallet
from core.base import indieChain, Block
import tkinter as tk
from tkinter import *
from tkinter import Canvas, Entry, Label
import logging
from time import sleep
import _thread
from threading import Thread
from core.base import UTXO, Transaction
import random
# ... | asutoshpalai/indiechain | gui_test.py | gui_test.py | py | 4,625 | python | en | code | 13 | github-code | 13 |
26993571685 | class vertex:
def __init__(self, value, visited):
self.value = value
self.visited = visited
self.adj_vertices = []
self.in_vertices = []
class graph:
g = []
def __init__(self, g):
self.g = g
# This method creates a graph from a list of words. A node of
# the graph c... | myers-dev/Data_Structures | graphs/circular_words/main-working.py | main-working.py | py | 4,193 | python | en | code | 1 | github-code | 13 |
42434930366 | #!/usr/bin/python3
import argparse
import subprocess
DB_PATH = '/lustre7/software/experimental/biocontainers_image/command.db'
def main():
args = parse_args()
if args.command:
search_by_command(args.command)
elif args.image:
search_by_image(args.image)
elif args.filepath:
sear... | yookuda/biocontainers_image | search_command_db.py | search_command_db.py | py | 2,211 | python | en | code | 0 | github-code | 13 |
72915318418 | import dataclasses
from typing import List, Iterator
from qutebrowser.commands import cmdexc, command
from qutebrowser.misc import split, objects
from qutebrowser.config import config
@dataclasses.dataclass
class ParseResult:
"""The result of parsing a commandline."""
cmd: command.Command
args: List[st... | qutebrowser/qutebrowser | qutebrowser/commands/parser.py | parser.py | py | 6,430 | python | en | code | 9,084 | github-code | 13 |
41884230960 | from django.db import transaction
from rest_framework import serializers
from rest_framework.exceptions import NotFound, PermissionDenied
from core.models import User
from core.serializers import ProfileSerializer
from goals.choices import Role, Status
from goals.models import Board, BoardParticipant, Goal, GoalCatego... | Danilu2537/ToDo-web-app | goals/serializers.py | serializers.py | py | 7,619 | python | en | code | 1 | github-code | 13 |
17061241834 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.OrganizationContractDTO import OrganizationContractDTO
class UserSubOrganizationDTO(object):
def __init__(self):
self._id = None
self._org_contract_list = Non... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/UserSubOrganizationDTO.py | UserSubOrganizationDTO.py | py | 3,472 | python | en | code | 241 | github-code | 13 |
74528073936 | # This file includes the algorithm for two-dimensional optimisation of the channels of a soft touchpad.
import cv2
import numpy as np
# Hyperparameters
height = 50 # height of the touchpad
width = 50 # width of the touchpad
maxt_iterations = 100000 # maximum number of iterations
max_individuals = 100 # number of i... | gaborsoter/phd_codes | optimisation/genetic_algorithm.py | genetic_algorithm.py | py | 2,067 | python | en | code | 0 | github-code | 13 |
19594869253 | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
import json
from .models import UserProfileModel
from .serializers import UserProfileSerializer, UserProfileSerializerModificate
def custom_response(ms... | alanggdev/devconnect-back | userprofile/views.py | views.py | py | 3,153 | python | en | code | 0 | github-code | 13 |
7590233259 | from collections import Counter
def word_count(fname):
with open(fname) as f:
return Counter(f.read().split())
print("Number of words in the file :",word_count("test.txt"))
##S = [x**2 for x in range(10)] # read elements to list
#M = [x for x in S if x % 2 == 0]
#M.reverse()
def Max(list)... | prgit21/Scripting-Lab | 1a.py | 1a.py | py | 683 | python | en | code | 0 | github-code | 13 |
285320455 | class Rearrange(object):
def get_len_of_ones(self, val):
count = 0
while val > 0:
count += 1
val = val & (val - 1)
return count
def count(self, list):
map = {}
for item in list:
b = self.get_len_of_ones(item)
data = map.g... | soniaarora/Algorithms-Practice | Solved in Python/LeetCode/arrays/Rearrange.py | Rearrange.py | py | 683 | python | en | code | 0 | github-code | 13 |
34447120712 | '''NOTE: added Pi > 0.05 threshold at the end'''
'''Changes made:
- Added split function to make training and test set
- Added 'fixed' boolean input to determine fixed point or not in bhat
- Changed variable names from X1 X2 to X_train and X_test etc
'''
import numpy as np
def MMalgVAL(X, y):
... | CarlmYang/The-KLIMAX-method | MMalgVAL.py | MMalgVAL.py | py | 3,885 | python | en | code | 0 | github-code | 13 |
72260994899 | # initial setup of stations in the subway map
stations = []
harvard_square = ("Harvard Square", 'red', None)
stations.append(harvard_square)
central_square = ("Central Square", 'red', None)
stations.append(central_square)
kendall_square = ("Kendall Square", 'red', None)
stations.append(kendall_square)
south_sta... | KaylaRuby/bps | SubwaySolution.py | SubwaySolution.py | py | 2,867 | python | en | code | 0 | github-code | 13 |
37979036913 | from encode import text_encoder
from decode import text_decoder
def main():
user_choice = str(input(
"- Enter 1 for encoding text into an image file\n- Enter 2 for decoding text from an image file\n- Enter 3 to exit\nEnter your choice: "))
if int(user_choice) == 1:
text_encoder()
mai... | AkshayBenny/lsb-python | app.py | app.py | py | 557 | python | en | code | 0 | github-code | 13 |
70601954259 | import json
import logging
import os
from utility.dynamo_utility import get_item
from utility.decimal_encoder import DecimalEncoder
def handler(event, context):
try:
if 'identifier' not in event['queryStringParameters']:
logging.error('Bad query param')
return {'statusCode': 400,
... | fatihaydilek/async-url-processor | url/get.py | get.py | py | 1,032 | python | en | code | 0 | github-code | 13 |
71800302737 | from common.graph.node import Node
from common.graph.edge import Edge
from common.container.uri import Uri
from common.container.linkeditem import LinkedItem
from common.utility.mylist import MyList
import itertools
import logging
from tqdm import tqdm
class Graph:
def __init__(self, kb, logger=None):
sel... | AskNowQA/SQG | common/graph/graph.py | graph.py | py | 9,318 | python | en | code | 47 | github-code | 13 |
19596222320 | #!/usr/bin/env python
from datetime import datetime
class Settings:
user = None
orm = None
settings = Settings()
def set_default_user(user):
settings.user = user
def set_default_orm(orm):
settings.orm = orm
def auth_user(username, password, email, active=True, staff=False, superuser=False, ... | google-code-export/yabi | yabiadmin/yabiadmin/yabi/migrationutils/__init__.py | __init__.py | py | 9,959 | python | en | code | 0 | github-code | 13 |
26157611138 | from lmpc import *
class Relax(LMPC):
def __init__(self, T, dt, N, J, R):
super().__init__(T, dt, N, J, R)
self.name = 'relax'
self.W = 0.5*self.w_L + 0.5*self.w_C # lateral safety distance for FCC and RCC
self.const1, self.const2 = 10000, 10000 # costs on slack variables
def e... | ivarben/SF280X | source code/relax.py | relax.py | py | 8,481 | python | en | code | 0 | github-code | 13 |
15734853943 | import torch.nn as nn
from Layers.resnet import ResNetLayer
import numpy as np
class ResNet(nn.Module):
''' A encoder models with self attention mechanism. '''
def __init__(
self, position_encoding_layer, n_layers, n_head, d_features, max_seq_length, d_meta, d_k=None, d_v=None, dropout=0.1, use_bo... | Jincheng-Sun/Kylearn-pytorch | Modules/ResNet.py | ResNet.py | py | 2,479 | python | en | code | 0 | github-code | 13 |
17911085377 | import numpy
import image_processor
from puzzle_model import PuzzleModel
import copy
import sys
def policy_action(model, policy):
max_reward = None
best_action = None
# for action in range(environment.nA): # [0, 1, 2, 3, 4, 5]
options = model.get_options()
for action in options:
reward = p... | tkim338/ball-sorter | q_learner_solver.py | q_learner_solver.py | py | 2,764 | python | en | code | 0 | github-code | 13 |
7957983049 | import matplotlib.pyplot as plt
import numpy as np
with open('result.txt') as f:
array = [float(line) for line in f]
x = np.arange(len(array))
plt.bar(x , array, align='center', alpha=0.5, color='purple' )
plt.plot( array )
plt.title("Reachability Plot")
plt.xlabel("Data Point")
plt.ylabel("Reachability Distanc... | shashank-yadav/OPTICS-dataMining | plot.py | plot.py | py | 362 | python | en | code | 0 | github-code | 13 |
24909569607 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import UserChangeForm
from search_admin_autocomplete.admin import SearchAutoCompleteAdmin
from import_export.admin import ImportExportModelAdmin
from import_export import resources
from imp... | MakerSpaceLeiden/makerspaceleiden-crm | members/admin.py | admin.py | py | 3,389 | python | en | code | 6 | github-code | 13 |
33821644519 | from urllib import request, error
import socket
try:
response = request.urlopen("http://www.jd123.com/test.html")
except error.HTTPError as e: # 成功捕获Bad Request 异常
print(type(e.reason))
print(e.reason, e.code, e.headers)
try:
response = request.urlopen("https://jd.com", timeout=0.00002)
except error.H... | lzxin96/python_spider | src/urllib/HTTPErrorDemo.py | HTTPErrorDemo.py | py | 733 | python | en | code | 0 | github-code | 13 |
12135561123 | '''
文本文件的读取
'''
import os
import tensorflow as tf
def read_csv(filelist):
# 构建文件队列
file_queue = tf.train.string_input_producer(filelist)
# 定义读取器
reader = tf.TextLineReader()
# 使用读取器在文件队列中读取数据
k, v = reader.read(file_queue)
# 解码
records = [['None'], ['None']]
example, label = tf.de... | 15149295552/Code | Month08/day16/02_read_csv.py | 02_read_csv.py | py | 1,320 | python | en | code | 1 | github-code | 13 |
74330556177 | import math
def isPrime(x):
if x < 3:
return x == 2
n = int(math.sqrt(x) + 1)
for i in range(2, n+1):
if x % i == 0:
return False
return True
def primeFactors(x):
if x == 1:
return []
divisors = set()
d = 2
n = x
while n > 1:
if n %... | spegesilden/projecteuler | e47/DistinctPrimeFactors.py | DistinctPrimeFactors.py | py | 833 | python | en | code | 0 | github-code | 13 |
38329387702 | # -*- coding:utf-8 -*-
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.geometry("200x200")
# this will create style object
style = Style()
# this will create a style and we'll name it W.TButton (ttk.Button)
style.configure('W.TButton', font=('calibri', 10, 'bold', 'underline'),
foregr... | ZCyborgs/Test | GUI_test.py | GUI_test.py | py | 621 | python | en | code | 0 | github-code | 13 |
38047473008 | ########################
# Framework
########################
import AthenaCommon.AtlasUnixGeneratorJob
from AthenaCommon.AlgSequence import AlgSequence
topSequence = AlgSequence()
from AthenaCommon.AppMgr import theApp
theApp.EvtMax = 10
########################
# Generate config XML files
########################... | rushioda/PIXELVALID_athena | athena/Trigger/TrigAnalysis/TrigDecisionMaker/share/trigDec_pureSteeringL2_WritePOOL.py | trigDec_pureSteeringL2_WritePOOL.py | py | 2,675 | python | en | code | 1 | github-code | 13 |
73875539537 | from architectures.mnist import Encoder as MnistEncoder, Decoder as MnistDecoder
from architectures.cifar10 import Encoder as Cifar10Encoder, Decoder as Cifar10Decoder
from architectures.celeba import Encoder as CelebaEncoder, Decoder as CelebaDecoder
def get_architecture(identifier: str, z_dim: int):
if id... | gmum/cwae-pytorch | src/factories/architecture_factory.py | architecture_factory.py | py | 662 | python | en | code | 6 | github-code | 13 |
39286497774 | from django.urls import path, include
from Profiles_API import views
from rest_framework.routers import DefaultRouter
# URL = http://127.0.0.1:8000/api/profile/
# For a specific user http://127.0.0.1:8000/api/profile/[id_name]
router = DefaultRouter()
# Since in views.py 'queryset' property is set so 'basenam... | neet1313/DRF-Project1-Profile | Profiles_API/urls.py | urls.py | py | 730 | python | en | code | 0 | github-code | 13 |
37961360728 | OutputLevel = INFO
doJiveXML = False
doVP1 = False
doWriteESD = False
doWriteAOD = False
doReadBS = True
doAuditors = True
import os
if os.environ['CMTCONFIG'].endswith('-dbg'):
doEdmMonitor = True
doNameAuditor = True
else:
doEdmMonitor = False
doNameAuditor ... | rushioda/PIXELVALID_athena | athena/InnerDetector/InDetMonitoring/TRT_Monitoring/share/jobOptions_artest.py | jobOptions_artest.py | py | 3,931 | python | en | code | 1 | github-code | 13 |
20571896082 | import pymongo
client = pymongo.MongoClient("mongodb://127.0.0.1:27017/") #client is important
newDB = client["firsttest"] #if it doesnt exist it will create new db#can use .<name>
newCollection = newDB.testing #creating collection .<name> inside db
#newUpdate = newCollection.update_one({"id": 5},{"$set":{"name":"... | ritheasen/project-test | 54 python mongodb updating record.py | 54 python mongodb updating record.py | py | 409 | python | en | code | 0 | github-code | 13 |
16450116681 | from general_functions import get_image, save_json, definePageRowCollumn
from formating_functions import format_name
def retrieve_perks(table, icons_path, json_path, project_url):
perks_list = []
for table_row in table.findAll('tr')[1:]:
perk = {}
row_headers = table_row.findAll('th')
... | GregorioFornetti/Projeto-dbd-roleta | scraping/perks.py | perks.py | py | 1,223 | python | en | code | 0 | github-code | 13 |
35775246254 | #coding=utf-8
#!/usr/bin/env python
from aip import AipOcr
import Translate
import numpy as np
from PIL import Image, ImageDraw, ImageFont
#读取本地图片测试
def Get_Image():
with open('./HTML/0.jpg', 'rb') as fp:
return fp.read()
#创建客户端
def Create_Client():
APP_ID = '17517601'
API_KEY = 'FL... | Toiler-haitao/2019-HMI-ISP-01 | Project (final)/Info.py | Info.py | py | 2,956 | python | en | code | 6 | github-code | 13 |
21579204345 | from Gurobi_direct.OptModel_m import OptModel_gurobi
#from column.ColumnAlgorithm import column_generating
import matplotlib.pyplot as plt
import re
from Data.Data import Data
class Solution:
'''
1.OptModel输出的最优解 → routes
2.可视化
'''
def __init__(self):
self.model = OptModel_gurobi()
... | LiuZunzeng/Code_VRPTW | Visualizition/Solution_origin.py | Solution_origin.py | py | 3,756 | python | en | code | 0 | github-code | 13 |
42071613589 | from itertools import *
def multiples(n):
a=sum(x for x in range(n) if ((x % 3) ==0 or (x % 5)==0))
return a
if __name__ =="__main__":
print(multiples(1000))
| prizmaweb/practice | multiples.py | multiples.py | py | 176 | python | en | code | 0 | github-code | 13 |
31611957552 | import pytest
import os
import requests
from dotenv import load_dotenv
from weather_app import get_weather_data
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
def raise... | ranms25/Python-Weather-App | tests/test_get_weather_data.py | test_get_weather_data.py | py | 1,623 | python | en | code | 0 | github-code | 13 |
8934399359 | ################ While Loop with Else #############################
a = 1
while (a<=20):
print(a)
a+=1
else:
print("Code Successfully Executed ")
b = 10
while (b<=100):
print(b)
b+=10
print("While Lopp Code Sucessfull Executed ")
else:
print("Else Part Executed NOW Emjoy :)") ... | haresh22/learn_python | 5.1.py | 5.1.py | py | 323 | python | en | code | 0 | github-code | 13 |
10053011737 | # -*- coding: UTF-8 -*-
from django.contrib import admin
from stocks.models import (Stock, StockPair, PairTransaction, BoughtSoldTransaction, Account, SubAccount,
AccountStock, Snapshot, SnapshotStock, Transaction, AccountStocksRange, AccountStockGroup,
AccountStoc... | fruitschen/fruits_learning | stocks/admin.py | admin.py | py | 4,679 | python | en | code | 1 | github-code | 13 |
36245364003 | import pandas as pd
import glob
import seaborn as sns
import matplotlib as mpl
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.legend_handler import HandlerBase
import copy
from networkx.algorithms.connectivity.connectivity import average_node_connectivity
from matplot... | tan0101/Commercial_WGS2023 | Scripts/network_ML_features.py | network_ML_features.py | py | 9,371 | python | en | code | 0 | github-code | 13 |
6921526157 | from heat.common import exception
from heat.common.i18n import _
from heat.engine import properties
from heat.engine import resource
from common.mixins import f5_bigip
from common.mixins import F5BigIPMixin
class F5CmSync(resource.Resource, F5BigIPMixin):
'''Sync the device configuration to the device group.'''
... | F5Networks/f5-openstack-heat-plugins | f5_heat/resources/f5_cm_sync.py | f5_cm_sync.py | py | 2,570 | python | en | code | 7 | github-code | 13 |
27629837484 | import matplotlib.pyplot as plt
import numpy as np
from numpy.fft import fft,fftfreq
def myctft(T,T1,fs):
f = 10;
time_x = np.arange(-T,T + 1/(fs*f), 1/(fs*f))
x = np.sin(2 * np.pi * f * time_x)
time_y = np.arange(-T1, T1 + 1 / (fs * f), 1 / (fs * f))
if T1 <= T:
y = np.sin(2 * np.pi * f * ... | shantanutyagi67/CT303_Labs | Lab 1/py files/q2.py | q2.py | py | 1,319 | python | en | code | 1 | github-code | 13 |
5772944665 | #!/usr/bin/python3
""" Lockboxes """
def canUnlockAll(boxes):
"""
- boxes is a list of lists
- A key with the same number as the box will open that box
- assuming all keys to be positive integers
- The first box boxes[0] is unlocked
- Return True if all boxes can be opened, else return False
... | HenryKenDephil/alx-interview | 0x01-lockboxes/0-lockboxes.py | 0-lockboxes.py | py | 794 | python | en | code | 0 | github-code | 13 |
36628629925 | #zad1
A=[1-x for x in range(1,11,1)]
print(A)
B=[4**x for x in range(0,8,1)]
print(B)
C=[x for x in B if x%2==0]
print(C)
#zad2
import random
lista1=[int(random.random()*100) for x in range(10)]
print(lista1)
lista2=[x for x in lista1 if x%2==0]
print(lista2)
#zad5
def pole_trapezu(a,b,h):
pole=((a+b)*h)/2
if... | SnowKid99/WD_zad_lab3 | main.py | main.py | py | 765 | python | en | code | 0 | github-code | 13 |
14917653379 | import csv
def print_matrix(matrix):
longest_len = 1
for row in matrix:
for n in row:
if len(str(n)) > longest_len:
longest_len = len(str(n))
longest_len += 1
for row in matrix:
for n in row:
n_len = len(str(n))
n_spaces = longe... | RenataRomero/LinearRegression | matrix.py | matrix.py | py | 2,303 | python | en | code | 0 | github-code | 13 |
36689093055 | import sys
import cx_Freeze
build_exe_options = {"packages": ["os","pygame","codecs"], "excludes": ["tkinter"],"include_files" : ["zeroTurn.png","ThunderboltTurns.png","water.png"]}
cx_Freeze.setup( name = "TailGunner",
version = "0.1",
description = "GameProject",
options = {"build_exe":... | AlexanderLuasan/Tailgunner | setup.py | setup.py | py | 400 | python | en | code | 0 | github-code | 13 |
24365786102 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
class fang_list_item(Item):
# 实体类型
item_type = Field()
# 房源编号
newcode = Field()
# 唯一标识 [url]
item_url = Field(... | chensource/BeginningPython | spider/fang_scrapy/fang_link/fang_link/items.py | items.py | py | 4,493 | python | en | code | 0 | github-code | 13 |
12393564398 | import torch
import torch.optim as optim
from torch.autograd import Variable
import torch.nn as nn
from torch.utils.data import DataLoader
class AutoEncoder:
def __init__(self, encoder, decoder, use_cuda=True):
self.enc = encoder
self.dec = decoder
self.use_cuda = use_cuda
# Dimens... | cheng-xie/motionEncode | autoencoder/autoencoder.py | autoencoder.py | py | 3,720 | python | en | code | 0 | github-code | 13 |
21860634730 | import json
from urllib.parse import urlparse, urlunsplit
from urllib.request import Request, urlopen
TIKTOK_VM = "https://vm.tiktok.com"
def follow_url(url):
request = Request(url)
response = urlopen(request)
ugly = response.geturl()
return ugly
def resolve_tiktok(url):
html_url = follow_url(ur... | jjdelc/verbose-happiness | lambda.py | lambda.py | py | 1,000 | python | en | code | 0 | github-code | 13 |
45740039214 | # Ciholas, Inc. - www.ciholas.com
# Licensed under: creativecommons.org/licenses/by/4.0
# System libraries
import pyqtgraph as pg
from pyqtgraph.Qt import QtWidgets, QtCore
from functools import partial
# Local libraries
from cdp import BootloadProgress
from network_objects import *
from settings import *
from generi... | ciholas/cuwb-monitor | libs/plots/public/individual_plots/plot_bootload_progress.py | plot_bootload_progress.py | py | 12,458 | python | en | code | 0 | github-code | 13 |
73175247378 | import subprocess
out = "/home/user/out"
def checkout(cmd, text):
result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, encoding='utf-8')
if text in result.stdout and result.returncode == 0:
return True
else:
return False
def checkout_negative(cmd, text):
re... | ludmila0704/pythonProject_AUTO_LINUXX | checker.py | checker.py | py | 814 | python | en | code | 0 | github-code | 13 |
35216342264 | from django.forms import ModelForm
from rakes.models import Rake, Module
class RakeForm(ModelForm):
class Meta:
model = Rake
fields = ['RakeName', 'Module1', 'Module2',
'Module3', 'Module4', 'Module5', 'Module6', 'Module7', 'Module8', 'Module9', ]
class ModuleForm(ModelForm):
... | vinaykumar1908/082021i | rakes/forms.py | forms.py | py | 493 | python | en | code | 0 | github-code | 13 |
17041680154 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayInsSceneCouponSendModel(object):
def __init__(self):
self._channel_user_id = None
self._channel_user_source = None
self._dimension_id = None
self._dimension_... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/AlipayInsSceneCouponSendModel.py | AlipayInsSceneCouponSendModel.py | py | 4,314 | python | en | code | 241 | github-code | 13 |
40281442883 | #take an input
a = input("Enter a number")
b = input("Enter a operator ")
c = input("Enter num2")
# convert input into integer
a = int(a)
c = int(c)
#checking b
if b == '/':
print( a / c)
elif b == '*':
print(a * c)
elif b == '+':
print(a + c)
elif b == '-':
print(a - c)
else:
print("Invali... | sohamthalpati/python | calculator.py | calculator.py | py | 389 | python | en | code | 2 | github-code | 13 |
71223538897 | #!/usr/bin/env python3
import sys, re, collections, pprint
with open(sys.argv[1]) as f:
data = [ list(map(int,re.findall(r'-?\d+', l))) for l in f ]
dist = lambda p,q: (abs(p[0]-q[0]) + abs(p[1]-q[1]))
grid = collections.defaultdict(lambda: [])
for sx,sy,bx,by in data:
d = dist((sx,sy),(bx,by))
for ... | ivanpesin/aoc | 2022/2022.15/sol.py | sol.py | py | 1,088 | python | en | code | 0 | github-code | 13 |
43070090563 | # coding:utf-8
import tensorflow as tf
# input and weight using placeholder
x = tf.placeholder(tf.float32, [1, 2])
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
with tf.Session() as sess:
init_o... | caoshen/ai-practice-tf-notes | tf/tf3_4.py | tf3_4.py | py | 486 | python | en | code | 0 | github-code | 13 |
73333818898 | from unittest import result
from django.shortcuts import render
from flask import Flask, request, render_template, url_for, flash, redirect
from flask_login import LoginManager, UserMixin, login_required, login_user, logout_user, current_user
import datetime
import sqlite3
import pandas as pd
import pandas.io.sql as ps... | taylananas/limonchan | sitefund.py | sitefund.py | py | 2,356 | python | en | code | 0 | github-code | 13 |
73050117459 | import socket
import threading
def receive_messages(client_socket):
while True:
try:
message = client_socket.recv(1024).decode('utf-8')
if message:
print('Message reçu :', message)
except:
break
client_socket.close()
def start_... | tgbhy/python | onlinechat/client.py | client.py | py | 855 | python | en | code | 0 | github-code | 13 |
19455764072 | from FileOperations import *
from Find_Domain import *
from Crawling import crawling
#Taking input from user
url = str(input("Please enter the url here: "))
directoryName = getDomainName(url)
domainName = directoryName
makeFolder(directoryName)
toCrawlPath,crawledPath,backup_crawledPath = makeFiles(directoryName,url)... | VaibhavDN/Crawler | CrawlerMain.py | CrawlerMain.py | py | 1,640 | python | en | code | 0 | github-code | 13 |
6337508322 | '''
User Story 10:
Marriage after 14
'''
from datetime import datetime, timedelta
monthWordToInt = {
"JAN": "01",
"FEB": "02",
"MAR": "03",
"APR": "04",
"MAY": "05",
"JUN": "06",
"JUL": "07",
"AUG": "08",
"SEP": "09",
"OCT": "10",
"NOV": "11",
"DEC":... | chloequinto/SSW_555_Project | package/userStories/us10.py | us10.py | py | 1,908 | python | en | code | 0 | github-code | 13 |
6089901987 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : test.salary_process.py
@Time : 2020/08/24 13:21:52
@Author : Tong tan
@Version : 1.0
@Contact : raogx.vip@hotmail.com
'''
from salary.process import Process
from salary.operators import GzOperator
from salary.operators impo... | versnoon/mg_hr_salary_support_pro | tests/test_salary_process.py | test_salary_process.py | py | 1,141 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.