uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
050326e7ca972562b7127406 | train | class | class LandType(models.Model):
classify_land = models.CharField(
"Land Classification", help_text="Rural, Urban, Peri-Urban",
max_length=100, blank=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
... | class LandType(models.Model):
| classify_land = models.CharField(
"Land Classification", help_text="Rural, Urban, Peri-Urban",
max_length=100, blank=True)
create_date = models.DateTimeField(null=True, blank=True)
edit_date = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('classify_land',)
... | *args, **kwargs):
if self.create_date is None:
self.create_date = datetime.now()
self.edit_date = datetime.now()
super(ProfileType, self).save()
# displayed in admin templates
def __str__(self):
return self.profile
class LandType(models.Model):
| 64 | 64 | 160 | 6 | 57 | michaelbukachi/Activity | workflow/models.py | Python | LandType | LandType | 635 | 654 | 635 | 635 | 6b1a042c83eb607af5f1f1d0fc8a1fc27db1f4a6 | bigcode/the-stack | train |
52b0b2c2d806e436ff950c32 | train | function | def follow():
api.create_friendship(Follow_Entry.get())
Follow_Feedback.delete("1.0","end-1c")
Follow_Feedback.insert("1.0","Followed Successfully")
| def follow():
| api.create_friendship(Follow_Entry.get())
Follow_Feedback.delete("1.0","end-1c")
Follow_Feedback.insert("1.0","Followed Successfully")
| Results.insert("end","Location: "+S_location+"\n")
Search_Results.insert("end","The last 20 followers include: \n")
for follower in get_user.followers():
Search_Results.insert("end",follower.name+"\n")
#Code for followers
def follow():
| 64 | 64 | 43 | 3 | 60 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | follow | follow | 69 | 72 | 69 | 69 | 556229fd7e1b4e2bbc2a8e36d8e98afe6e70a8a1 | bigcode/the-stack | train |
5fa256d122dd55c328ca7de9 | train | function | def update_account_location():
api.update_profile(location=Location_Entry.get())
Update_Feedback.delete("1.0","end-1c")
Update_Feedback.insert("1.0","Location Updated Successfully!")
| def update_account_location():
| api.update_profile(location=Location_Entry.get())
Update_Feedback.delete("1.0","end-1c")
Update_Feedback.insert("1.0","Location Updated Successfully!")
| 0","Unfollowed Successfully")
#Code for my account
def update_account_name():
api.update_profile(name=Name_Entry.get())
Update_Feedback.delete("1.0","end-1c")
Update_Feedback.insert("1.0","Name Updated Successfully!")
def update_account_location():
| 63 | 64 | 45 | 5 | 58 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | update_account_location | update_account_location | 86 | 89 | 86 | 86 | 2fe1f8289d4f323b4f4bb8bbb4d94da9efba245f | bigcode/the-stack | train |
ec643b42077110fecf9cd7df | train | function | def block_user():
api.create_block(Block_Entry.get())
BlockText.delete("1.0", "end-1c")
BlockText.insert("1.0","Blocked Successfully!")
| def block_user():
| api.create_block(Block_Entry.get())
BlockText.delete("1.0", "end-1c")
BlockText.insert("1.0","Blocked Successfully!")
| api.destroy_favorite(tweet.id)
Like_Feedback.delete("1.0","end-1c")
Like_Feedback.insert("1.0",f"Disliking tweet with Id:{tweet.id} of {tweet.author.name}")
#Code for blocking and viewing blocked users
def block_user():
| 64 | 64 | 40 | 4 | 59 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | block_user | block_user | 112 | 115 | 112 | 112 | ec0d68cd757c9d4c8e6a3ebd1d6ac89968f59b7f | bigcode/the-stack | train |
d7f362f59390cbbca03198d0 | train | function | def blocked_user():
for block in api.blocks():
BlockText.delete("1.0","end-1c")
BlockText.insert("1.0",block.name)
| def blocked_user():
| for block in api.blocks():
BlockText.delete("1.0","end-1c")
BlockText.insert("1.0",block.name)
| end-1c")
BlockText.insert("1.0","Blocked Successfully!")
def unblock_user():
api.destroy_block(Block_Entry.get())
BlockText.delete("1.0", "end-1c")
BlockText.insert("1.0","Unblocked Successfully!")
def blocked_user():
| 63 | 64 | 37 | 4 | 59 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | blocked_user | blocked_user | 124 | 127 | 124 | 124 | 4f97a75403edf618b2b520de4fb5643dfe42eec3 | bigcode/the-stack | train |
40c8dcd9df9ff2a864933b23 | train | function | def update_status():
status=Tweet_Entry.get("1.0", "end-1c")
api.update_status(status)
| def update_status():
| status=Tweet_Entry.get("1.0", "end-1c")
api.update_status(status)
| -1c")
public_tweets=api.home_timeline()
for tweet in public_tweets:
text1.insert("1.0",f"ID:{tweet.id}, {tweet.user.name} said {tweet.text}\n \n")
#Code for updating the timeline status
def update_status():
| 64 | 64 | 28 | 4 | 59 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | update_status | update_status | 45 | 47 | 45 | 45 | 8e1ae5c7a93a4c98f8d6d9e67d697c431e859c63 | bigcode/the-stack | train |
266b7bf04121b02ae532dfaf | train | function | def like():
tweets=api.get_status(Like_Entry.get())
tweet=tweets
api.create_favorite(tweet.id)
Like_Feedback.delete("1.0","end-1c")
Like_Feedback.insert("1.0",f"Liking tweet with Id:{tweet.id} of {tweet.author.name}")
| def like():
| tweets=api.get_status(Like_Entry.get())
tweet=tweets
api.create_favorite(tweet.id)
Like_Feedback.delete("1.0","end-1c")
Like_Feedback.insert("1.0",f"Liking tweet with Id:{tweet.id} of {tweet.author.name}")
| 1.0","Location Updated Successfully!")
def update_account_description():
api.update_profile(description=Description_Entry.get())
Update_Feedback.delete("1.0","end-1c")
Update_Feedback.insert("1.0","Description Updated Successfully!")
#Code for Like and Dislike
def like():
| 64 | 64 | 69 | 3 | 60 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | like | like | 97 | 102 | 97 | 97 | 30371ff5a9da4ce7f648e5eeafd17ced0a06ebf5 | bigcode/the-stack | train |
d3a3188b98875c82d41b6fdc | train | function | def get_user():
Search_Results.delete("1.0","end-1c")
user_name=Search_Entry.get()
get_user=api.get_user(user_name)
S_name=get_user.name
S_description=get_user.description
S_location=get_user.location
Search_Results.insert("1.0","The user details inlcude: \n")
Search_Results.insert("en... | def get_user():
| Search_Results.delete("1.0","end-1c")
user_name=Search_Entry.get()
get_user=api.get_user(user_name)
S_name=get_user.name
S_description=get_user.description
S_location=get_user.location
Search_Results.insert("1.0","The user details inlcude: \n")
Search_Results.insert("end","Username: "+... | tweet.user.name} said {tweet.text}\n \n")
#Code for updating the timeline status
def update_status():
status=Tweet_Entry.get("1.0", "end-1c")
api.update_status(status)
#Code for searching users and get information using code
def get_user():
| 64 | 64 | 169 | 4 | 59 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | get_user | get_user | 50 | 66 | 50 | 50 | 21ee89ff4b7fb2aef1c6f41f3f7259e6928de57e | bigcode/the-stack | train |
9183bfe764b06c98cb173a07 | train | function | def retweet():
api.retweet(Retweet_Entry.get())
Retweet_Feedback.delete("1.0","end-1c")
Retweet_Feedback.insert("1.0","Retweeted Successfully")
| def retweet():
| api.retweet(Retweet_Entry.get())
Retweet_Feedback.delete("1.0","end-1c")
Retweet_Feedback.insert("1.0","Retweeted Successfully")
| Topics
def trending_topics():
trending = api.trends_place(1)
for trend in trending[0]["trends"]:
Trending_Text.delete("1.0","end-1c")
Trending_Text.insert("1.0", trend["name"])
#Code for Retweets
def retweet():
| 64 | 64 | 46 | 4 | 59 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | retweet | retweet | 137 | 140 | 137 | 137 | 9503cd8690ad832188906e153cf7f388990ec2fc | bigcode/the-stack | train |
68d28d6d29745687671a9e68 | train | function | def unblock_user():
api.destroy_block(Block_Entry.get())
BlockText.delete("1.0", "end-1c")
BlockText.insert("1.0","Unblocked Successfully!")
| def unblock_user():
| api.destroy_block(Block_Entry.get())
BlockText.delete("1.0", "end-1c")
BlockText.insert("1.0","Unblocked Successfully!")
| :{tweet.id} of {tweet.author.name}")
#Code for blocking and viewing blocked users
def block_user():
api.create_block(Block_Entry.get())
BlockText.delete("1.0", "end-1c")
BlockText.insert("1.0","Blocked Successfully!")
def unblock_user():
| 63 | 64 | 41 | 4 | 59 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | unblock_user | unblock_user | 118 | 121 | 118 | 118 | c12de2c5a86286ecdc4890edce82f88760198fc1 | bigcode/the-stack | train |
515fe808490cf044eba15180 | train | function | def public_tweets():
text1.delete("1.0","end-1c")
public_tweets=api.home_timeline()
for tweet in public_tweets:
text1.insert("1.0",f"ID:{tweet.id}, {tweet.user.name} said {tweet.text}\n \n")
| def public_tweets():
| text1.delete("1.0","end-1c")
public_tweets=api.home_timeline()
for tweet in public_tweets:
text1.insert("1.0",f"ID:{tweet.id}, {tweet.user.name} said {tweet.text}\n \n")
| consumer_secret_key = ''
access_token = ''
access_token_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret_key)
auth.set_access_token(access_token, access_token_secret)
api= tweepy.API(auth,wait_on_rate_limit=True)
#Code for timeline review
def public_tweets():
| 64 | 64 | 67 | 5 | 58 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | public_tweets | public_tweets | 38 | 42 | 38 | 38 | d5e11d679a05cbf9080b57a366269fffe4af9eb0 | bigcode/the-stack | train |
80b07b99b848161d90bb1228 | train | function | def unfollow():
api.destroy_friendship(Follow_Entry.get())
Follow_Feedback.delete("1.0","end-1c")
Follow_Feedback.insert("1.0","Unfollowed Successfully")
| def unfollow():
| api.destroy_friendship(Follow_Entry.get())
Follow_Feedback.delete("1.0","end-1c")
Follow_Feedback.insert("1.0","Unfollowed Successfully")
| ollower.name+"\n")
#Code for followers
def follow():
api.create_friendship(Follow_Entry.get())
Follow_Feedback.delete("1.0","end-1c")
Follow_Feedback.insert("1.0","Followed Successfully")
#Code for Unfollowers
def unfollow():
| 64 | 64 | 45 | 4 | 59 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | unfollow | unfollow | 75 | 78 | 75 | 75 | ae2352f17ed19ba59aa2331e2a0e71de2a08ce20 | bigcode/the-stack | train |
1c73567faff3b264eb948ce1 | train | function | def dislike():
tweets=api.get_status(Like_Entry.get())
tweet=tweets
api.destroy_favorite(tweet.id)
Like_Feedback.delete("1.0","end-1c")
Like_Feedback.insert("1.0",f"Disliking tweet with Id:{tweet.id} of {tweet.author.name}")
| def dislike():
| tweets=api.get_status(Like_Entry.get())
tweet=tweets
api.destroy_favorite(tweet.id)
Like_Feedback.delete("1.0","end-1c")
Like_Feedback.insert("1.0",f"Disliking tweet with Id:{tweet.id} of {tweet.author.name}")
| _status(Like_Entry.get())
tweet=tweets
api.create_favorite(tweet.id)
Like_Feedback.delete("1.0","end-1c")
Like_Feedback.insert("1.0",f"Liking tweet with Id:{tweet.id} of {tweet.author.name}")
def dislike():
| 64 | 64 | 71 | 3 | 61 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | dislike | dislike | 104 | 109 | 104 | 104 | 6117895c821f43aac9d219adf248d6ff865188b2 | bigcode/the-stack | train |
0591ebc63d0b67e6c64622fe | train | function | def exit_program():
root.destroy()
exit()
| def exit_program():
| root.destroy()
exit()
| "])
#Code for Retweets
def retweet():
api.retweet(Retweet_Entry.get())
Retweet_Feedback.delete("1.0","end-1c")
Retweet_Feedback.insert("1.0","Retweeted Successfully")
#Code for exiting the program
def exit_program():
| 64 | 64 | 11 | 4 | 59 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | exit_program | exit_program | 143 | 145 | 143 | 143 | 2aea1929e50dfb9c84300ea054ad98b9fb8cda51 | bigcode/the-stack | train |
1d29688e850a253fdd5cce6c | train | function | def update_account_description():
api.update_profile(description=Description_Entry.get())
Update_Feedback.delete("1.0","end-1c")
Update_Feedback.insert("1.0","Description Updated Successfully!")
| def update_account_description():
| api.update_profile(description=Description_Entry.get())
Update_Feedback.delete("1.0","end-1c")
Update_Feedback.insert("1.0","Description Updated Successfully!")
| Update_Feedback.insert("1.0","Name Updated Successfully!")
def update_account_location():
api.update_profile(location=Location_Entry.get())
Update_Feedback.delete("1.0","end-1c")
Update_Feedback.insert("1.0","Location Updated Successfully!")
def update_account_description():
| 64 | 64 | 45 | 5 | 59 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | update_account_description | update_account_description | 91 | 94 | 91 | 91 | 8424ff8568da6968dbc272f3665ecb67c467ec74 | bigcode/the-stack | train |
c9a97fe09ea466bd77c2d0c0 | train | function | def update_account_name():
api.update_profile(name=Name_Entry.get())
Update_Feedback.delete("1.0","end-1c")
Update_Feedback.insert("1.0","Name Updated Successfully!")
| def update_account_name():
| api.update_profile(name=Name_Entry.get())
Update_Feedback.delete("1.0","end-1c")
Update_Feedback.insert("1.0","Name Updated Successfully!")
| Successfully")
#Code for Unfollowers
def unfollow():
api.destroy_friendship(Follow_Entry.get())
Follow_Feedback.delete("1.0","end-1c")
Follow_Feedback.insert("1.0","Unfollowed Successfully")
#Code for my account
def update_account_name():
| 64 | 64 | 45 | 5 | 58 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | update_account_name | update_account_name | 81 | 84 | 81 | 81 | c9f83f4fb726b291d1cc454de8ce39ba41df021c | bigcode/the-stack | train |
f96f14ef3d0cc947921b3d66 | train | function | def trending_topics():
trending = api.trends_place(1)
for trend in trending[0]["trends"]:
Trending_Text.delete("1.0","end-1c")
Trending_Text.insert("1.0", trend["name"])
| def trending_topics():
| trending = api.trends_place(1)
for trend in trending[0]["trends"]:
Trending_Text.delete("1.0","end-1c")
Trending_Text.insert("1.0", trend["name"])
| 1c")
BlockText.insert("1.0","Unblocked Successfully!")
def blocked_user():
for block in api.blocks():
BlockText.delete("1.0","end-1c")
BlockText.insert("1.0",block.name)
#Code for Trending Topics
def trending_topics():
| 64 | 64 | 52 | 4 | 59 | JoseMbilwa/Python-Twitter-Bot | Python-Twitter-Bot.py | Python | trending_topics | trending_topics | 130 | 134 | 130 | 130 | 245d9c9844bea721802c0844aabb37927688736e | bigcode/the-stack | train |
211b8376bb8868bea79aca6a | train | class | class Migration(migrations.Migration):
dependencies = [("users", "0004_alter_user_username")]
operations = [
migrations.AlterField(
model_name="user",
name="username",
field=models.CharField(
blank=True, max_length=150, verbose_name="Phone number"
... | class Migration(migrations.Migration):
| dependencies = [("users", "0004_alter_user_username")]
operations = [
migrations.AlterField(
model_name="user",
name="username",
field=models.CharField(
blank=True, max_length=150, verbose_name="Phone number"
),
)
]
| # Generated by Django 3.2.4 on 2021-08-05 12:37
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 70 | 7 | 30 | Rey092/SwipeApp | src/users/migrations/0005_alter_user_username.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | 7e1883aa679bdcf69fb20ac79fbee12652788a32 | bigcode/the-stack | train |
4d82798b9218e0f4cbf08831 | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('session_id', models.CharField(max_leng... | # Generated by Django 3.2.8 on 2022-03-03 04:09
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 148 | 7 | 30 | jaysridhar/ca_eye | djangoapp/eye/migrations/0001_initial.py | Python | Migration | Migration | 6 | 29 | 6 | 7 | 159210a3be2fa52a8c7fa44450d0e145a87957f0 | bigcode/the-stack | train |
8b295f102dc210ac1c515503 | train | class | class TestClusterNodeExtended(unittest.TestCase):
"""ClusterNodeExtended unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testClusterNodeExtended(self):
"""Test ClusterNodeExtended"""
# FIXME: construct object with mandatory attributes with example... | class TestClusterNodeExtended(unittest.TestCase):
| """ClusterNodeExtended unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testClusterNodeExtended(self):
"""Test ClusterNodeExtended"""
# FIXME: construct object with mandatory attributes with example values
# model = isi_sdk_8_1_0.models.clu... | import absolute_import
import unittest
import isi_sdk_8_1_0
from isi_sdk_8_1_0.models.cluster_node_extended import ClusterNodeExtended # noqa: E501
from isi_sdk_8_1_0.rest import ApiException
class TestClusterNodeExtended(unittest.TestCase):
| 64 | 64 | 95 | 9 | 54 | mohitjain97/isilon_sdk_python | isi_sdk_8_1_0/test/test_cluster_node_extended.py | Python | TestClusterNodeExtended | TestClusterNodeExtended | 23 | 36 | 23 | 23 | 446ed365d537b3d5a55d6e14ba729b7b75dd05e8 | bigcode/the-stack | train |
f09f9d8e28e41dee7cf47ca3 | train | class | class DatabaseParser:
""" Parses SQLite databases in data/db
"""
def __init__(self, database, bot):
self.database = database
self.bot = bot
async def retrieve(self, ctx, category, option):
""" Retrieve a specific option from a category of options
"""
# Create query to retrie... | class DatabaseParser:
| """ Parses SQLite databases in data/db
"""
def __init__(self, database, bot):
self.database = database
self.bot = bot
async def retrieve(self, ctx, category, option):
""" Retrieve a specific option from a category of options
"""
# Create query to retrieve data from database
... | )
async def theskeld_browse(self, ctx, category):
""" Allows member to browse data stored in The Skeld database
"""
await self.the_skeld_parser.browse(ctx, category)
@the_skeld.group(
name="listopts", case_insensitive=True, pass_context=True,
aliases=["ls"]
)
async d... | 256 | 256 | 1,756 | 4 | 252 | JLpython-py/Among-Us-Bot | lib/cogs/mapdatabase.py | Python | DatabaseParser | DatabaseParser | 232 | 438 | 232 | 232 | c0875d95a01f81df7caac86d02ac6a47fcb187c6 | bigcode/the-stack | train |
cff0cd448c5748955adf5d05 | train | function | async def send_with_reactions(ctx, embed, image):
""" Sends message with reactions for member to browse data with
"""
# Send embed and image
message = await ctx.channel.send(
embed=embed, file=image
)
# Add scroll control reactions
reactions = [
u'\u23ee', u'\u23ea', u'\u25c0', u... | async def send_with_reactions(ctx, embed, image):
| """ Sends message with reactions for member to browse data with
"""
# Send embed and image
message = await ctx.channel.send(
embed=embed, file=image
)
# Add scroll control reactions
reactions = [
u'\u23ee', u'\u23ea', u'\u25c0', u'\u25b6', u'\u23e9', u'\u23ed',
u'\u2714',... | "
image_path = os.path.join('data', image_name)
image = discord.File(image_path, image_name)
embed.set_image(url=f"attachment://{image_name}")
# Return constructed embed and image
return embed, image
async def send_with_reactions(ctx, embed, image):
| 64 | 64 | 145 | 12 | 51 | JLpython-py/Among-Us-Bot | lib/cogs/mapdatabase.py | Python | send_with_reactions | send_with_reactions | 470 | 485 | 470 | 470 | 7cbe01d671b173b3e8bcefaf8324f90ed1df8ee1 | bigcode/the-stack | train |
5ed803ccd595577bc0882448 | train | class | class MapDatabase(commands.Cog):
""" Allows member to explore available information in Among Us
"""
def __init__(self, bot):
self.bot = bot
self.arship_parser = DatabaseParser(self.bot.airship, self.bot)
self.mira_hq_parser = DatabaseParser(self.bot.mirahq, self.bot)
self.polus_p... | class MapDatabase(commands.Cog):
| """ Allows member to explore available information in Among Us
"""
def __init__(self, bot):
self.bot = bot
self.arship_parser = DatabaseParser(self.bot.airship, self.bot)
self.mira_hq_parser = DatabaseParser(self.bot.mirahq, self.bot)
self.polus_parser = DatabaseParser(self.bot.p... | """
==============================================================================
MIT License
Copyright (c) 2020 Jacob Lee
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, in... | 256 | 256 | 1,481 | 7 | 248 | JLpython-py/Among-Us-Bot | lib/cogs/mapdatabase.py | Python | MapDatabase | MapDatabase | 39 | 229 | 39 | 39 | 5d6a37fd466f09f7b89122239b3180f639989139 | bigcode/the-stack | train |
ca7f43313dff99feb56977dc | train | function | def scrolling_embed(mapname, category, data, *, index=0):
""" Creates an embed to allow member to browser data with
"""
# Get current option data
option_data = list(data.values())[index]
# Construct embed to send data
embed = discord.Embed(
title=f"{category.title()}: {option_data['name']}",... | def scrolling_embed(mapname, category, data, *, index=0):
| """ Creates an embed to allow member to browser data with
"""
# Get current option data
option_data = list(data.values())[index]
# Construct embed to send data
embed = discord.Embed(
title=f"{category.title()}: {option_data['name']}",
color=0xff0000
)
# Set embed footer to na... | delete_search(self, payload):
""" Delete embed from search command
"""
# Process information in payload
channel = self.bot.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
# Delete message
await message.delete()
def scrolling_embe... | 69 | 69 | 233 | 15 | 54 | JLpython-py/Among-Us-Bot | lib/cogs/mapdatabase.py | Python | scrolling_embed | scrolling_embed | 441 | 467 | 441 | 441 | 22308e00f50cff1b87ca376ae47356a51026dba8 | bigcode/the-stack | train |
248b1704bb14a10fcdfc8387 | train | function | def setup(bot):
""" Adds MapDatabase cog
"""
bot.add_cog(MapDatabase(bot))
| def setup(bot):
| """ Adds MapDatabase cog
"""
bot.add_cog(MapDatabase(bot))
| 25b6', u'\u23e9', u'\u23ed',
u'\u2714', u'\u274c'
]
for rxn in reactions:
await message.add_reaction(rxn)
# Return message for future reference
return message
def setup(bot):
| 64 | 64 | 21 | 4 | 59 | JLpython-py/Among-Us-Bot | lib/cogs/mapdatabase.py | Python | setup | setup | 488 | 491 | 488 | 488 | 1bbef4f590f1455dbfa41aea22743f32b669a095 | bigcode/the-stack | train |
99947f97d41e491b7c0fa04e | train | class | class Requirement(object):
@property
def name(self):
# type: () -> str
raise NotImplementedError("Subclass should override")
def find_matches(self):
# type: () -> Sequence[Candidate]
raise NotImplementedError("Subclass should override")
def is_satisfied_by(self, candida... | class Requirement(object):
@property
| def name(self):
# type: () -> str
raise NotImplementedError("Subclass should override")
def find_matches(self):
# type: () -> Sequence[Candidate]
raise NotImplementedError("Subclass should override")
def is_satisfied_by(self, candidate):
# type: (Candidate) -> bool
... | # type: (str, Set[str]) -> str
if not extras:
return project
canonical_extras = sorted(canonicalize_name(e) for e in extras)
return "{}[{}]".format(project, ",".join(canonical_extras))
class Requirement(object):
@property
| 64 | 64 | 81 | 8 | 56 | MichaelSaah/pip | src/pip/_internal/resolution/resolvelib/base.py | Python | Requirement | Requirement | 20 | 32 | 20 | 21 | 784c2ffd64af100d323d852bad724990898138e5 | bigcode/the-stack | train |
128765683993be8a704fb8e7 | train | function | def format_name(project, extras):
# type: (str, Set[str]) -> str
if not extras:
return project
canonical_extras = sorted(canonicalize_name(e) for e in extras)
return "{}[{}]".format(project, ",".join(canonical_extras))
| def format_name(project, extras):
# type: (str, Set[str]) -> str
| if not extras:
return project
canonical_extras = sorted(canonicalize_name(e) for e in extras)
return "{}[{}]".format(project, ",".join(canonical_extras))
| _RUNNING
if MYPY_CHECK_RUNNING:
from typing import Optional, Sequence, Set
from pip._internal.req.req_install import InstallRequirement
from pip._vendor.packaging.version import _BaseVersion
def format_name(project, extras):
# type: (str, Set[str]) -> str
| 64 | 64 | 64 | 20 | 43 | MichaelSaah/pip | src/pip/_internal/resolution/resolvelib/base.py | Python | format_name | format_name | 12 | 17 | 12 | 13 | 317404564d764f3045c4cd5894723b96b4038f16 | bigcode/the-stack | train |
51035b97bbbcd1b809848278 | train | class | class Candidate(object):
@property
def name(self):
# type: () -> str
raise NotImplementedError("Override in subclass")
@property
def version(self):
# type: () -> _BaseVersion
raise NotImplementedError("Override in subclass")
def get_dependencies(self):
# typ... | class Candidate(object):
@property
| def name(self):
# type: () -> str
raise NotImplementedError("Override in subclass")
@property
def version(self):
# type: () -> _BaseVersion
raise NotImplementedError("Override in subclass")
def get_dependencies(self):
# type: () -> Sequence[InstallRequirement]
... | Error("Subclass should override")
def find_matches(self):
# type: () -> Sequence[Candidate]
raise NotImplementedError("Subclass should override")
def is_satisfied_by(self, candidate):
# type: (Candidate) -> bool
return False
class Candidate(object):
@property
| 64 | 64 | 115 | 8 | 55 | MichaelSaah/pip | src/pip/_internal/resolution/resolvelib/base.py | Python | Candidate | Candidate | 35 | 52 | 35 | 36 | 8f6cfd3088681aee5746f11ecda9685644066970 | bigcode/the-stack | train |
8895aa435e6ac2bc185beec7 | train | function | def get_version():
return check_output("git describe --tags --abbrev=0").decode().strip()
| def get_version():
| return check_output("git describe --tags --abbrev=0").decode().strip()
| "flags": ("-s", "--silent"),
"action": "store_true",
"help": "only print errors to console",
},
}
LOG_VERBOSE = True
def log_print(*args, **kwargs):
if LOG_VERBOSE:
print(*args, **kwargs)
def get_version():
| 64 | 64 | 23 | 4 | 60 | lornat00/search-deflector | build.py | Python | get_version | get_version | 73 | 74 | 73 | 73 | a2cd92f96a8608a1c333838ad8d276a5e0c84cbb | bigcode/the-stack | train |
47c11c7093fa1115b2c72977 | train | function | def copy_files(version):
copy_file(path_join(LIBS_PATH, "libcurl.dll"), path_join(BIN_PATH, "libcurl.dll"))
copy_file(path_join(LIBS_PATH, "engines.txt"), path_join(BIN_PATH, "engines.txt"))
copy_file(path_join(LIBS_PATH, "issue.md"), path_join(VARS_PATH, "issue.md"))
copy_dir(LANG_PATH, path_join(BIN... | def copy_files(version):
| copy_file(path_join(LIBS_PATH, "libcurl.dll"), path_join(BIN_PATH, "libcurl.dll"))
copy_file(path_join(LIBS_PATH, "engines.txt"), path_join(BIN_PATH, "engines.txt"))
copy_file(path_join(LIBS_PATH, "issue.md"), path_join(VARS_PATH, "issue.md"))
copy_dir(LANG_PATH, path_join(BIN_PATH, "lang"))
vers... | mainCRTStartup"])
if args:
command.extend(args)
log_print(">", *command)
call(command)
def add_icon(binary):
log_print("Adding icon: " + binary)
call(["rcedit", "--set-icon", path_join(ASSETS_PATH, "logo.ico"), binary])
def copy_files(version):
| 70 | 70 | 234 | 5 | 65 | lornat00/search-deflector | build.py | Python | copy_files | copy_files | 135 | 159 | 135 | 135 | 78fe7f2282e2fe2a14fe176d5c1e6ba6a0337776 | bigcode/the-stack | train |
fd732afb76b8c30ec05e70e1 | train | function | def assemble_args(parser, arguments):
for dest, kwargs in arguments.items():
flags = kwargs.pop("flags")
if isinstance(flags, str):
parser.add_argument(flags, dest=dest, **kwargs)
else:
parser.add_argument(*flags, dest=dest, **kwargs)
| def assemble_args(parser, arguments):
| for dest, kwargs in arguments.items():
flags = kwargs.pop("flags")
if isinstance(flags, str):
parser.add_argument(flags, dest=dest, **kwargs)
else:
parser.add_argument(*flags, dest=dest, **kwargs)
| errors to console",
},
}
LOG_VERBOSE = True
def log_print(*args, **kwargs):
if LOG_VERBOSE:
print(*args, **kwargs)
def get_version():
return check_output("git describe --tags --abbrev=0").decode().strip()
def assemble_args(parser, arguments):
| 64 | 64 | 61 | 7 | 57 | lornat00/search-deflector | build.py | Python | assemble_args | assemble_args | 77 | 84 | 77 | 77 | 123b2078cdaa9d4abaeb98a82294a92e5115bb2a | bigcode/the-stack | train |
9d20a3f041abcbee24557b6e | train | function | def add_icon(binary):
log_print("Adding icon: " + binary)
call(["rcedit", "--set-icon", path_join(ASSETS_PATH, "logo.ico"), binary])
| def add_icon(binary):
| log_print("Adding icon: " + binary)
call(["rcedit", "--set-icon", path_join(ASSETS_PATH, "logo.ico"), binary])
| -O3", "-ffast-math", "-release"])
if not console:
command.extend(["-L/subsystem:windows", "-L/entry:wmainCRTStartup"])
if args:
command.extend(args)
log_print(">", *command)
call(command)
def add_icon(binary):
| 63 | 64 | 40 | 5 | 58 | lornat00/search-deflector | build.py | Python | add_icon | add_icon | 129 | 132 | 129 | 129 | 6786203fd437b8eaa1a5de65f097be058afd8be3 | bigcode/the-stack | train |
dd8d0a04da136021f9f1d99a | train | function | def log_print(*args, **kwargs):
if LOG_VERBOSE:
print(*args, **kwargs)
| def log_print(*args, **kwargs):
| if LOG_VERBOSE:
print(*args, **kwargs)
| "), "help": "version string to use in build"},
"silent": {
"flags": ("-s", "--silent"),
"action": "store_true",
"help": "only print errors to console",
},
}
LOG_VERBOSE = True
def log_print(*args, **kwargs):
| 64 | 64 | 22 | 9 | 54 | lornat00/search-deflector | build.py | Python | log_print | log_print | 68 | 70 | 68 | 68 | 0f174608332b429b05a34add09b3b4256f35e4c9 | bigcode/the-stack | train |
88a776b8b447b7b1236fe570 | train | function | def compile_file(source, binary, debug=True, console=False, args=None):
log_print("Compiling binary: " + binary)
command = ["ldc2", source, "-i", "-I", dirname(source), "-J", VARS_PATH, "-of", binary, "-m32"]
if debug:
command.extend(["-gc", "-d-debug", "-L/subsystem:console"])
else:
c... | def compile_file(source, binary, debug=True, console=False, args=None):
| log_print("Compiling binary: " + binary)
command = ["ldc2", source, "-i", "-I", dirname(source), "-J", VARS_PATH, "-of", binary, "-m32"]
if debug:
command.extend(["-gc", "-d-debug", "-L/subsystem:console"])
else:
command.extend(["-O3", "-ffast-math", "-release"])
if not consol... | ("Creating directory: " + directory)
makedirs(directory, exist_ok=True)
def delete_directory(directory):
if exists(directory):
log_print("Deleting directory: " + directory)
rmtree(directory, ignore_errors=True)
def compile_file(source, binary, debug=True, console=False, args=None):
| 64 | 64 | 151 | 16 | 48 | lornat00/search-deflector | build.py | Python | compile_file | compile_file | 109 | 126 | 109 | 109 | 69f6f022573e7e95cc689b585b906bca8c9a9a71 | bigcode/the-stack | train |
53b646570b28c300e3b561d1 | train | function | def create_directory(directory):
if not exists(directory):
log_print("Creating directory: " + directory)
makedirs(directory, exist_ok=True)
| def create_directory(directory):
| if not exists(directory):
log_print("Creating directory: " + directory)
makedirs(directory, exist_ok=True)
| log_print("Copying file: " + to_file)
copyfile(from_file, to_file)
def copy_dir(from_dir, to_dir):
for file in glob(path_join(from_dir, "*.*")):
copy_file(file, path_join(to_dir, basename(file)))
def create_directory(directory):
| 63 | 64 | 32 | 5 | 58 | lornat00/search-deflector | build.py | Python | create_directory | create_directory | 97 | 100 | 97 | 97 | aad7ec826970dcf354988a79eecaa92c9a90c075 | bigcode/the-stack | train |
f5461c69549212640b09237f | train | function | def copy_file(from_file, to_file):
log_print("Copying file: " + to_file)
copyfile(from_file, to_file)
| def copy_file(from_file, to_file):
| log_print("Copying file: " + to_file)
copyfile(from_file, to_file)
| ):
for dest, kwargs in arguments.items():
flags = kwargs.pop("flags")
if isinstance(flags, str):
parser.add_argument(flags, dest=dest, **kwargs)
else:
parser.add_argument(*flags, dest=dest, **kwargs)
def copy_file(from_file, to_file):
| 64 | 64 | 31 | 9 | 55 | lornat00/search-deflector | build.py | Python | copy_file | copy_file | 87 | 89 | 87 | 87 | 836723a9f8ef9f94958b71ac3b8e577af7aa9192 | bigcode/the-stack | train |
a9fccf8c8153cd421f9536ae | train | function | def delete_directory(directory):
if exists(directory):
log_print("Deleting directory: " + directory)
rmtree(directory, ignore_errors=True)
| def delete_directory(directory):
| if exists(directory):
log_print("Deleting directory: " + directory)
rmtree(directory, ignore_errors=True)
| for file in glob(path_join(from_dir, "*.*")):
copy_file(file, path_join(to_dir, basename(file)))
def create_directory(directory):
if not exists(directory):
log_print("Creating directory: " + directory)
makedirs(directory, exist_ok=True)
def delete_directory(directory):
| 64 | 64 | 30 | 5 | 59 | lornat00/search-deflector | build.py | Python | delete_directory | delete_directory | 103 | 106 | 103 | 103 | dcec58d9bd6bd10a5e8694b1fbd4cd3c8d6ad88c | bigcode/the-stack | train |
d6d37c8dbb51d7b9d6612a5f | train | function | def copy_dir(from_dir, to_dir):
for file in glob(path_join(from_dir, "*.*")):
copy_file(file, path_join(to_dir, basename(file)))
| def copy_dir(from_dir, to_dir):
| for file in glob(path_join(from_dir, "*.*")):
copy_file(file, path_join(to_dir, basename(file)))
| dest=dest, **kwargs)
else:
parser.add_argument(*flags, dest=dest, **kwargs)
def copy_file(from_file, to_file):
log_print("Copying file: " + to_file)
copyfile(from_file, to_file)
def copy_dir(from_dir, to_dir):
| 64 | 64 | 36 | 9 | 55 | lornat00/search-deflector | build.py | Python | copy_dir | copy_dir | 92 | 94 | 92 | 92 | 27d22217f94fdd89caf78d23fea2df3334fb70c2 | bigcode/the-stack | train |
b4e0ef3d15369b007676dd6e | train | class | class TempData(models.Model):
key = models.CharField(max_length=50, default="", blank=True, help_text='Приложение/объект', db_index=True)
holter_protocol_date = models.DateTimeField(null=True, blank=True, db_index=True, help_text='Последний обработанный протокол')
| class TempData(models.Model):
| key = models.CharField(max_length=50, default="", blank=True, help_text='Приложение/объект', db_index=True)
holter_protocol_date = models.DateTimeField(null=True, blank=True, db_index=True, help_text='Последний обработанный протокол')
| crie', 'CRIE'),
('L2L2', 'L2L2'),
)
type_integration = models.CharField(max_length=4, choices=TYPES, db_index=True)
research = models.ForeignKey(Researches, on_delete=models.CASCADE)
class TempData(models.Model):
| 64 | 64 | 68 | 6 | 58 | VoprosiKira/l2 | integration_framework/models.py | Python | TempData | TempData | 42 | 44 | 42 | 42 | ff25e893fda9b9bb62ddc3091a3700dbfb3a6dbf | bigcode/the-stack | train |
7cbfd8a3501fc576398a2319 | train | class | class IntegrationNamespace(models.Model):
key = models.CharField(max_length=128, primary_key=True)
active = models.BooleanField()
| class IntegrationNamespace(models.Model):
| key = models.CharField(max_length=128, primary_key=True)
active = models.BooleanField()
| from directions.models import Napravleniya
import uuid
from django.db import models
from directory.models import Researches
from utils.models import ChoiceArrayField
class IntegrationNamespace(models.Model):
| 39 | 64 | 28 | 6 | 32 | VoprosiKira/l2 | integration_framework/models.py | Python | IntegrationNamespace | IntegrationNamespace | 10 | 12 | 10 | 10 | f975bece397647b0fb37558916bef58e45b7a640 | bigcode/the-stack | train |
17b8f930ad147aa0c7ada794 | train | class | class IntegrationJournal(models.Model):
TYPE_DIRECTION = 0
TYPE_RESULT = 1
TYPES = ((TYPE_DIRECTION, 'DIRECTION'), (TYPE_RESULT, 'RESULT'))
STATUS_NONE = 0
STATUS_PENDING = 1
STATUS_UPLOADED = 2
STATUSES = ((STATUS_NONE, 'NONE'), (STATUS_PENDING, 'PENDING'), (STATUS_UPLOADED, 'UPLOADED'))
... | class IntegrationJournal(models.Model):
| TYPE_DIRECTION = 0
TYPE_RESULT = 1
TYPES = ((TYPE_DIRECTION, 'DIRECTION'), (TYPE_RESULT, 'RESULT'))
STATUS_NONE = 0
STATUS_PENDING = 1
STATUS_UPLOADED = 2
STATUSES = ((STATUS_NONE, 'NONE'), (STATUS_PENDING, 'PENDING'), (STATUS_UPLOADED, 'UPLOADED'))
namespace = models.ForeignKey(Integr... | import Napravleniya
import uuid
from django.db import models
from directory.models import Researches
from utils.models import ChoiceArrayField
class IntegrationNamespace(models.Model):
key = models.CharField(max_length=128, primary_key=True)
active = models.BooleanField()
class IntegrationJournal(models.Mo... | 64 | 64 | 136 | 6 | 58 | VoprosiKira/l2 | integration_framework/models.py | Python | IntegrationJournal | IntegrationJournal | 15 | 27 | 15 | 15 | bbe3924a8e8594da9dddbfd3588ce72de6c6eb4a | bigcode/the-stack | train |
6a3d45dfa42809f8f20ebde5 | train | class | class ExternalServiceRights(models.Model):
title = models.CharField(max_length=300, default="", blank=True, help_text='Название права', db_index=True)
def __str__(self):
return self.title
class Meta:
verbose_name = 'Роли для внешнего сервиса'
verbose_name_plural = 'Роли для внешних... | class ExternalServiceRights(models.Model):
| title = models.CharField(max_length=300, default="", blank=True, help_text='Название права', db_index=True)
def __str__(self):
return self.title
class Meta:
verbose_name = 'Роли для внешнего сервиса'
verbose_name_plural = 'Роли для внешних сервисы'
| Field(max_length=50, default="", blank=True, help_text='Приложение/объект', db_index=True)
holter_protocol_date = models.DateTimeField(null=True, blank=True, db_index=True, help_text='Последний обработанный протокол')
class ExternalServiceRights(models.Model):
| 64 | 64 | 76 | 7 | 57 | VoprosiKira/l2 | integration_framework/models.py | Python | ExternalServiceRights | ExternalServiceRights | 47 | 55 | 47 | 47 | 35fd5e8e2334695fcbe1f1de504b2009c05ce817 | bigcode/the-stack | train |
df9eb6e784cc356d6cf1dc06 | train | class | class ExternalService(models.Model):
ACCESS_RIGHT_QR_CHECK_RESULT = 'qr_check_result'
ACCESS_RIGHTS = (
(ACCESS_RIGHT_QR_CHECK_RESULT, 'QR check result'),
)
title = models.CharField(max_length=127, help_text="Название")
token = models.UUIDField(default=uuid.uuid4, editable=False, help_text... | class ExternalService(models.Model):
| ACCESS_RIGHT_QR_CHECK_RESULT = 'qr_check_result'
ACCESS_RIGHTS = (
(ACCESS_RIGHT_QR_CHECK_RESULT, 'QR check result'),
)
title = models.CharField(max_length=127, help_text="Название")
token = models.UUIDField(default=uuid.uuid4, editable=False, help_text="Токен, генерируется автоматически",... | .CharField(max_length=300, default="", blank=True, help_text='Название права', db_index=True)
def __str__(self):
return self.title
class Meta:
verbose_name = 'Роли для внешнего сервиса'
verbose_name_plural = 'Роли для внешних сервисы'
class ExternalService(models.Model):
| 71 | 71 | 238 | 6 | 65 | VoprosiKira/l2 | integration_framework/models.py | Python | ExternalService | ExternalService | 58 | 80 | 58 | 58 | 599baad83bdeab9eb12425af33004939262a85aa | bigcode/the-stack | train |
764b84a0294e285302bde103 | train | class | class CrieOrder(models.Model):
local_direction = models.ForeignKey(Napravleniya, db_index=True, on_delete=models.CASCADE)
system_id = models.IntegerField(db_index=True, null=True, blank=True)
status = models.CharField(max_length=12, blank=True, default='null', db_index=True)
error = models.TextField(bla... | class CrieOrder(models.Model):
| local_direction = models.ForeignKey(Napravleniya, db_index=True, on_delete=models.CASCADE)
system_id = models.IntegerField(db_index=True, null=True, blank=True)
status = models.CharField(max_length=12, blank=True, default='null', db_index=True)
error = models.TextField(blank=True, default='')
| null=True, blank=True, help_text='роль в базе', on_delete=models.SET_NULL)
def __str__(self):
return self.title
class Meta:
verbose_name = 'Внешний сервис'
verbose_name_plural = 'Внешние сервисы'
class CrieOrder(models.Model):
| 64 | 64 | 79 | 7 | 57 | VoprosiKira/l2 | integration_framework/models.py | Python | CrieOrder | CrieOrder | 83 | 87 | 83 | 83 | f73dba61a1d08e0267cd4cdcf391bf208867abda | bigcode/the-stack | train |
303495aec967773e06b05714 | train | class | class IntegrationResearches(models.Model):
TYPES = (
('mbu', 'MBU'),
('amd', 'AMD'),
('crie', 'CRIE'),
('L2L2', 'L2L2'),
)
type_integration = models.CharField(max_length=4, choices=TYPES, db_index=True)
research = models.ForeignKey(Researches, on_delete=models.CASCADE)
| class IntegrationResearches(models.Model):
| TYPES = (
('mbu', 'MBU'),
('amd', 'AMD'),
('crie', 'CRIE'),
('L2L2', 'L2L2'),
)
type_integration = models.CharField(max_length=4, choices=TYPES, db_index=True)
research = models.ForeignKey(Researches, on_delete=models.CASCADE)
| '), (STATUS_UPLOADED, 'UPLOADED'))
namespace = models.ForeignKey(IntegrationNamespace, db_index=True, on_delete=models.CASCADE)
type = models.SmallIntegerField(choices=TYPES, db_index=True)
key = models.IntegerField(db_index=True)
class IntegrationResearches(models.Model):
| 64 | 64 | 87 | 7 | 57 | VoprosiKira/l2 | integration_framework/models.py | Python | IntegrationResearches | IntegrationResearches | 30 | 39 | 30 | 30 | 456737965f8c7c9f3527c68d94413cdc190e061c | bigcode/the-stack | train |
d8bf367ecd677a027608a3bb | train | class | class BaseTest(reference_data.BaseTest):
"""Tests for core ResNet layers."""
def setUp(self):
super(BaseTest, self).setUp()
if keras_utils.is_v2_0:
tf.compat.v1.disable_eager_execution()
@property
def test_name(self):
return "resnet"
def _batch_norm_ops(self, test=False):
name = "batc... | class BaseTest(reference_data.BaseTest):
| """Tests for core ResNet layers."""
def setUp(self):
super(BaseTest, self).setUp()
if keras_utils.is_v2_0:
tf.compat.v1.disable_eager_execution()
@property
def test_name(self):
return "resnet"
def _batch_norm_ops(self, test=False):
name = "batch_norm"
g = tf.Graph()
with g.as... | resnet_model
from utils.misc import keras_utils
from utils.testing import reference_data
DATA_FORMAT = "channels_last" # CPU instructions often preclude channels_first
BATCH_SIZE = 32
BLOCK_TESTS = [
dict(bottleneck=True, projection=True, resnet_version=1, width=8,
channels=4),
dict(bottleneck=True... | 256 | 256 | 1,449 | 8 | 248 | CQUlearningsystemgroup/BitwiseBottlneck | layer_test.py | Python | BaseTest | BaseTest | 52 | 215 | 52 | 52 | 6e06f6572681b019e40e87cc3c1db404408d6019 | bigcode/the-stack | train |
3b3c4e20813a5b86dd00b7ec | train | class | class Solution:
"""
@param root: a binary tree
@param sum: the sum
@return: the scheme
"""
def pathSum(self, root, sum):
# Write your code here.
result = []
path = []
def dfs(root, sum):
if root is None:
return
path.append(r... | class Solution:
| """
@param root: a binary tree
@param sum: the sum
@return: the scheme
"""
def pathSum(self, root, sum):
# Write your code here.
result = []
path = []
def dfs(root, sum):
if root is None:
return
path.append(root.val)
... | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
| 40 | 64 | 139 | 3 | 37 | jiadaizhao/LintCode | 1301-1400/1357-Path Sum II/1357-Path Sum II.py | Python | Solution | Solution | 9 | 32 | 9 | 9 | d0a5ebbe15aade5ab997b63f04eb4f2657a2d57e | bigcode/the-stack | train |
17937eeff97f47cc2797ce18 | train | class | class HudsonPoller():
def __init__(self, notifier):
self.job_results = dict()
self.notifier = notifier
def poll(self, urls):
for url in urls:
job_results = self.__get_job_results(url)
for job_result in job_results:
if self._is_old_build(job_result):
continue
self.notifier.notify(job_result)... | class HudsonPoller():
| def __init__(self, notifier):
self.job_results = dict()
self.notifier = notifier
def poll(self, urls):
for url in urls:
job_results = self.__get_job_results(url)
for job_result in job_results:
if self._is_old_build(job_result):
continue
self.notifier.notify(job_result).show()
self.__add... | #!/usr/bin/env python
import feedparser
from rss_parser import RssParser
class HudsonPoller():
| 23 | 74 | 247 | 5 | 17 | alberto/hudson-notifier | src/hudson_poller.py | Python | HudsonPoller | HudsonPoller | 5 | 40 | 5 | 5 | 53db2b96da9b97ed666f3282b4054b2f841c7a43 | bigcode/the-stack | train |
18d5e92f1cb2cb6eb63bef5c | train | class | class Publisher(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def send(self, state):
try:
self.socket.sendto(repr(state), (self.host, self.port))
except socket.error:... | class Publisher(object):
| def __init__(self, host, port):
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def send(self, state):
try:
self.socket.sendto(repr(state), (self.host, self.port))
except socket.error:
pass
| import socket
class Publisher(object):
| 7 | 64 | 77 | 4 | 2 | initialed85/pi-rc-car | phase_3/publisher.py | Python | Publisher | Publisher | 4 | 15 | 4 | 4 | 1a7c0efd4ee7d6ddff090522255180ea70c82ab5 | bigcode/the-stack | train |
86d813498b18e1366feecadc | train | function | def _weight_variable(name, shape):
return tf.get_variable(name, shape, DTYPE, tf.truncated_normal_initializer(stddev=0.1))
| def _weight_variable(name, shape):
| return tf.get_variable(name, shape, DTYPE, tf.truncated_normal_initializer(stddev=0.1))
|
import tensorflow as tf
import numpy as np
FC_SIZE = 1024
DTYPE = tf.float32
def _weight_variable(name, shape):
| 33 | 64 | 32 | 8 | 24 | jjhenkel/dockerizeme | hard-gists/52bba57f724e38229da9d85fbc85b673/snippet.py | Python | _weight_variable | _weight_variable | 9 | 10 | 9 | 9 | 1fb4bcb38ae94cce82812ba476bc958cebc406e6 | bigcode/the-stack | train |
f8e12c08d9a1e5d1b1280204 | train | function | def _bias_variable(name, shape):
return tf.get_variable(name, shape, DTYPE, tf.constant_initializer(0.1, dtype=DTYPE))
| def _bias_variable(name, shape):
| return tf.get_variable(name, shape, DTYPE, tf.constant_initializer(0.1, dtype=DTYPE))
| import tensorflow as tf
import numpy as np
FC_SIZE = 1024
DTYPE = tf.float32
def _weight_variable(name, shape):
return tf.get_variable(name, shape, DTYPE, tf.truncated_normal_initializer(stddev=0.1))
def _bias_variable(name, shape):
| 64 | 64 | 33 | 8 | 56 | jjhenkel/dockerizeme | hard-gists/52bba57f724e38229da9d85fbc85b673/snippet.py | Python | _bias_variable | _bias_variable | 13 | 14 | 13 | 13 | b7c2e6c3b23146ed92dc02af5528e825548ac66c | bigcode/the-stack | train |
db7681505e11e387632c76cc | train | function | def inference(boxes, dataconfig):
prev_layer = boxes
in_filters = dataconfig.num_props
with tf.variable_scope('conv1') as scope:
out_filters = 16
kernel = _weight_variable('weights', [5, 5, 5, in_filters, out_filters])
conv = tf.nn.conv3d(prev_layer, kernel, [1, 1, 1, 1, 1], padding... | def inference(boxes, dataconfig):
| prev_layer = boxes
in_filters = dataconfig.num_props
with tf.variable_scope('conv1') as scope:
out_filters = 16
kernel = _weight_variable('weights', [5, 5, 5, in_filters, out_filters])
conv = tf.nn.conv3d(prev_layer, kernel, [1, 1, 1, 1, 1], padding='SAME')
biases = _bias_va... |
import tensorflow as tf
import numpy as np
FC_SIZE = 1024
DTYPE = tf.float32
def _weight_variable(name, shape):
return tf.get_variable(name, shape, DTYPE, tf.truncated_normal_initializer(stddev=0.1))
def _bias_variable(name, shape):
return tf.get_variable(name, shape, DTYPE, tf.constant_initializer(0.1, d... | 99 | 256 | 1,173 | 9 | 90 | jjhenkel/dockerizeme | hard-gists/52bba57f724e38229da9d85fbc85b673/snippet.py | Python | inference | inference | 17 | 106 | 17 | 17 | 59607aedbe5c1243e06d37abad3ef601c8da6d51 | bigcode/the-stack | train |
5de74b1f8ee1612c231e8db5 | train | function | def loss(logits, labels):
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits, labels, name='cross_entropy_per_example')
return tf.reduce_mean(cross_entropy, name='xentropy_mean') | def loss(logits, labels):
| cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits, labels, name='cross_entropy_per_example')
return tf.reduce_mean(cross_entropy, name='xentropy_mean') | _variable('weights', [dim, dataconfig.num_classes])
biases = _bias_variable('biases', [dataconfig.num_classes])
softmax_linear = tf.add(tf.matmul(prev_layer, weights), biases, name=scope.name)
return softmax_linear
def loss(logits, labels):
| 64 | 64 | 46 | 7 | 56 | jjhenkel/dockerizeme | hard-gists/52bba57f724e38229da9d85fbc85b673/snippet.py | Python | loss | loss | 109 | 113 | 109 | 109 | 3a4f8ce5fd14b092733abe9c9518292871f1eaf8 | bigcode/the-stack | train |
b7549d2fb069bc9ac02a67e9 | train | function | def main():
config_workers, count_workers = [], int(float(os.getenv("COUNT_WORKERS", 2)))
print(f"COUNT_WORKERS = {count_workers}")
session = create_sql_session()
advertisements = session.query(Advertisements).filter(Advertisements.title == None).all()
for advertisement in advertisements:
c... | def main():
| config_workers, count_workers = [], int(float(os.getenv("COUNT_WORKERS", 2)))
print(f"COUNT_WORKERS = {count_workers}")
session = create_sql_session()
advertisements = session.query(Advertisements).filter(Advertisements.title == None).all()
for advertisement in advertisements:
config_worker... | renew,
"text": url
})
session.commit()
except Exception as error:
print(f"ERROR: {error}")
else:
print(f"ERROR: http status code: {response.status_code}")
except Exception as error:
print(error)
return N... | 64 | 64 | 114 | 3 | 60 | Enrialonso/pasion-scraper | get_ads_data.py | Python | main | main | 69 | 82 | 69 | 69 | 4169a738a973d17fd055f09eeb95a7fc59ed3613 | bigcode/the-stack | train |
5f7dfcd9e7f82bba84d07a49 | train | function | def worker(config):
try:
response = requests.get(
f"https://www.pasion.com/stats/stats-ampliadas.php?id={config['id_ad'].replace('r', '')}")
if response.ok:
try:
html = BeautifulSoup(response.text, "html.parser")
no_ad = html.find('div', {'cla... | def worker(config):
| try:
response = requests.get(
f"https://www.pasion.com/stats/stats-ampliadas.php?id={config['id_ad'].replace('r', '')}")
if response.ok:
try:
html = BeautifulSoup(response.text, "html.parser")
no_ad = html.find('div', {'class': 'titanu'}).getT... | import os
from concurrent.futures import ThreadPoolExecutor as PoolExecutor
from datetime import datetime as dt
import requests
from bs4 import BeautifulSoup
from models.models import Advertisements
from utils.utils import create_sql_session
scraping_date = dt.now()
def worker(config):
| 58 | 150 | 503 | 4 | 54 | Enrialonso/pasion-scraper | get_ads_data.py | Python | worker | worker | 14 | 66 | 14 | 14 | 38bc8e02053a511f77485896d35d32020f2584a4 | bigcode/the-stack | train |
b8fa8d56c4e172c38236bdb2 | train | function | def astrous_conv_bn_relu(inputs,filters,kernel_size,rate=1,pad='SAME',w_summary=True,is_training = False,bias = False,name='astrous_conv_bn'):
with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape... | def astrous_conv_bn_relu(inputs,filters,kernel_size,rate=1,pad='SAME',w_summary=True,is_training = False,bias = False,name='astrous_conv_bn'):
| with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
tf.contrib.layers.xavier_initializer(uniform=False),trainable=is_train... | (0.0),shape=[filters])
return tf.nn.relu(tf.nn.bias_add(conv, bia))
else:
return tf.nn.relu(conv)
def astrous_conv_bn_relu(inputs,filters,kernel_size,rate=1,pad='SAME',w_summary=True,is_training = False,bias = False,name='astrous_conv_bn'):
| 72 | 72 | 242 | 40 | 32 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | astrous_conv_bn_relu | astrous_conv_bn_relu | 199 | 215 | 199 | 199 | c5641a0de4008ff948e89b0d7d619714aca1b400 | bigcode/the-stack | train |
4e1c19649bba99c98e1e1e9d | train | function | def _norm(x, norm_type, is_train, G=32, esp=1e-5):
with tf.variable_scope('{}_norm'.format(norm_type)):
if norm_type == 'none':
output = x
elif norm_type == 'batch':
output = tf.layers.batch_normalization(conv, training=is_train)
elif norm_type == 'group':
... | def _norm(x, norm_type, is_train, G=32, esp=1e-5):
| with tf.variable_scope('{}_norm'.format(norm_type)):
if norm_type == 'none':
output = x
elif norm_type == 'batch':
output = tf.layers.batch_normalization(conv, training=is_train)
elif norm_type == 'group':
# normalize
# tranpose: [bs, h, w, c]... | = mean_weight[0] * batch_mean + mean_weight[1] * ins_mean + mean_weight[2] * layer_mean
var = var_wegiht[0] * batch_var + var_wegiht[1] * ins_var + var_wegiht[2] * layer_var
x = (x - mean) / (tf.sqrt(var + eps))
x = x * gamma + beta
return x
def _norm(x, norm_type, is_train, G=32, esp... | 115 | 115 | 385 | 22 | 92 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | _norm | _norm | 33 | 62 | 33 | 33 | 0796477e6abf8edea6cbaf8bf63ed0c72ae43452 | bigcode/the-stack | train |
5a6116a17492b91769727b7e | train | function | def fc(inputs,filters,bias=True,name='fc'):
with tf.variable_scope(name):
shape = inputs.get_shape().as_list()
if len(shape)>2:
inputs = tf.reshape(inputs, [-1, shape[1] * shape[2] * shape[3]])
weights = tf.get_variable('weights',shape=[shape[1] * shape[2] * shape[3], filters... | def fc(inputs,filters,bias=True,name='fc'):
| with tf.variable_scope(name):
shape = inputs.get_shape().as_list()
if len(shape)>2:
inputs = tf.reshape(inputs, [-1, shape[1] * shape[2] * shape[3]])
weights = tf.get_variable('weights',shape=[shape[1] * shape[2] * shape[3], filters], dtype=tf.float32,
... | ),up_slice[j - 1])
out = tf.concat([out,sum],dim)
if w_summary:
with tf.device('/cpu:0'):
tf.summary.histogram('weights_summary', kernel, collections=['weights'])
return out
def fc(inputs,filters,bias=True,name='fc'):
| 64 | 64 | 204 | 12 | 51 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | fc | fc | 300 | 315 | 300 | 300 | d6fa68d246271bc0027c64388a7b9aead31d2807 | bigcode/the-stack | train |
d4c54854c8ef0a10b18a0373 | train | function | def deconv2d(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training = False,w_summary=True, bias = True,name='deconv'):
with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size, kernel_size, filters, inputs.get_shape().... | def deconv2d(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training = False,w_summary=True, bias = True,name='deconv'):
| with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size, kernel_size, filters, inputs.get_shape().as_list()[3]]),initializer=
tf.contrib.layers.xavier_initializer(uniform=False), trainable=is_training)
# x_shape =... | data_format='NHWC')
if w_summary:
with tf.device('/cpu:0'):
tf.summary.histogram('weights_summary', kernel, collections=['weights'])
return conv
def deconv2d(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training = False,w_summary=True, bias = True,name='deconv'):... | 78 | 78 | 263 | 39 | 38 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | deconv2d | deconv2d | 106 | 121 | 106 | 106 | 5c809dc75ae245bed03d4f24ac1b3025d2914dad | bigcode/the-stack | train |
ffdbd4a45d424300ca2e11aa | train | function | def switch_norm(x, scope='switch_norm'):
with tf.variable_scope(scope):
ch = x.shape[-1]
eps = 1e-5
batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], keep_dims=True)
ins_mean, ins_var = tf.nn.moments(x, [1, 2], keep_dims=True)
layer_mean, layer_var = tf.nn.moments(x, [1, 2... | def switch_norm(x, scope='switch_norm'):
| with tf.variable_scope(scope):
ch = x.shape[-1]
eps = 1e-5
batch_mean, batch_var = tf.nn.moments(x, [0, 1, 2], keep_dims=True)
ins_mean, ins_var = tf.nn.moments(x, [1, 2], keep_dims=True)
layer_mean, layer_var = tf.nn.moments(x, [1, 2, 3], keep_dims=True)
gamma = tf... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'xie wei'
import tensorflow as tf
from model.candidate_box_process import *
import numpy as np
import os, sys
def switch_norm(x, scope='switch_norm'):
| 56 | 90 | 303 | 10 | 45 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | switch_norm | switch_norm | 10 | 31 | 10 | 10 | 1567dde317863e437c5f5312d3a4fb0065afefba | bigcode/the-stack | train |
128ab2804aecf3285e3cd329 | train | function | def astrous_conv_relu(inputs,filters,kernel_size,rate=1,pad='SAME',w_summary=True,is_training = False,bias = True,name='astrous_conv'):
with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_l... | def astrous_conv_relu(inputs,filters,kernel_size,rate=1,pad='SAME',w_summary=True,is_training = False,bias = True,name='astrous_conv'):
| with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
tf.contrib.layers.xavier_initializer(uniform=False),trainable=is_train... | tf.zeros_initializer(filters),shape=[filters])
return tf.nn.bias_add(conv, bia)
else:
return conv
def astrous_conv_relu(inputs,filters,kernel_size,rate=1,pad='SAME',w_summary=True,is_training = False,bias = True,name='astrous_conv'):
| 64 | 64 | 201 | 38 | 25 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | astrous_conv_relu | astrous_conv_relu | 184 | 197 | 184 | 184 | f7500dfa48b083d5bda510fe4bce9de59697fc1c | bigcode/the-stack | train |
55fd71d44936ff307a90166f | train | function | def l2norm(x, scale, trainable=True, scope="L2Normalization"):
n_channels = x.get_shape().as_list()[-1]
l2_norm = tf.nn.l2_normalize(x, [3], epsilon=1e-12)
with tf.variable_scope(scope):
gamma = tf.get_variable("gamma", shape=[n_channels, ], dtype=tf.float32,
initiali... | def l2norm(x, scale, trainable=True, scope="L2Normalization"):
| n_channels = x.get_shape().as_list()[-1]
l2_norm = tf.nn.l2_normalize(x, [3], epsilon=1e-12)
with tf.variable_scope(scope):
gamma = tf.get_variable("gamma", shape=[n_channels, ], dtype=tf.float32,
initializer=tf.constant_initializer(scale),
... | .get_variable(shape=[filters], dtype=tf.float32,
initializer=tf.constant_initializer(0.0), name=name+'_biases')
return tf.nn.sigmoid(tf.nn.bias_add(tf.matmul(inputs, weights),biases))
def l2norm(x, scale, trainable=True, scope="L2Normalization"):
| 64 | 64 | 103 | 18 | 46 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | l2norm | l2norm | 346 | 353 | 346 | 346 | 043a0954cdd04c33e938a22926fdd659f70e4ac2 | bigcode/the-stack | train |
bc29dd446060a424673a5f7a | train | function | def separable_conv_bn_relu(inputs,filters,kernel_size,strides=1,pad='same',w_summary=True,is_training = False,bias = False,rate=None,name='separable_conv_bn'):
with tf.variable_scope(name):
if not rate is None:
rates=(rate,rate)
else:
rates=(1,1)
conv = tf.layers.sepa... | def separable_conv_bn_relu(inputs,filters,kernel_size,strides=1,pad='same',w_summary=True,is_training = False,bias = False,rate=None,name='separable_conv_bn'):
| with tf.variable_scope(name):
if not rate is None:
rates=(rate,rate)
else:
rates=(1,1)
conv = tf.layers.separable_conv2d(inputs, filters, (kernel_size, kernel_size),
strides=(strides, strides), padding=pad,
... | return tf.nn.relu(tf.nn.bias_add(norm, bia))
else:
return tf.nn.relu(norm)
def separable_conv_bn_relu(inputs,filters,kernel_size,strides=1,pad='same',w_summary=True,is_training = False,bias = False,rate=None,name='separable_conv_bn'):
| 64 | 64 | 215 | 42 | 22 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | separable_conv_bn_relu | separable_conv_bn_relu | 217 | 234 | 217 | 217 | 86aab13f789fa75dea485bde05afcc48e5b1c925 | bigcode/the-stack | train |
dcdb60bfc7998ad8d6178cad | train | function | def get_bias(shape,name):
bias_wights = tf.constant(0.0, shape)
init = tf.constant_initializer(value=bias_wights,dtype=tf.float32)
var = tf.get_variable(name="biases", initializer=init, shape=shape)
return var
| def get_bias(shape,name):
| bias_wights = tf.constant(0.0, shape)
init = tf.constant_initializer(value=bias_wights,dtype=tf.float32)
var = tf.get_variable(name="biases", initializer=init, shape=shape)
return var
| else:
raise NotImplementedError
return output
def get_conv_filter(shape,name):
init = tf.truncated_normal(shape, stddev=0.01)
var = tf.get_variable(name="filter", initializer=init, shape=shape)
return var
def get_bias(shape,name):
| 64 | 64 | 60 | 6 | 57 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | get_bias | get_bias | 69 | 73 | 69 | 69 | b316105ae063940d010904512f62530eae84f5f8 | bigcode/the-stack | train |
a5b14438912edc2299b416ec | train | function | def fc_relu(inputs,filters,bias=True,name='fc_relu'):
with tf.variable_scope(name):
shape = inputs.get_shape().as_list()
if len(shape)>2:
inputs = tf.reshape(inputs, [-1, shape[1] * shape[2] * shape[3]])
weights = tf.get_variable(shape=[shape[1] * shape[2] * shape[3], filters... | def fc_relu(inputs,filters,bias=True,name='fc_relu'):
| with tf.variable_scope(name):
shape = inputs.get_shape().as_list()
if len(shape)>2:
inputs = tf.reshape(inputs, [-1, shape[1] * shape[2] * shape[3]])
weights = tf.get_variable(shape=[shape[1] * shape[2] * shape[3], filters], dtype=tf.float32,
... | _variable('biases',shape=[filters], dtype=tf.float32,
initializer=tf.constant_initializer(0.0))
return tf.nn.bias_add(tf.matmul(inputs, weights),biases)
else:
return tf.matmul(inputs, weights)
def fc_relu(inputs,filters,bias=True,name='fc_relu'):
| 64 | 64 | 191 | 14 | 50 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | fc_relu | fc_relu | 317 | 329 | 317 | 317 | 8ac2c4968b2a48a8bdd85cde108ded30eac7b865 | bigcode/the-stack | train |
630b4883f17ce0e3e0076bd0 | train | function | def pool(inputs,kernel_size,stride,pooltpype='max',padding='SAME',name='pool'):
with tf.variable_scope(name):
if pooltpype=='max':
return tf.contrib.layers.max_pool2d(inputs,[kernel_size,kernel_size],[stride,stride],padding=padding)
else:
return tf.contrib.layers.avg_pool2d(i... | def pool(inputs,kernel_size,stride,pooltpype='max',padding='SAME',name='pool'):
| with tf.variable_scope(name):
if pooltpype=='max':
return tf.contrib.layers.max_pool2d(inputs,[kernel_size,kernel_size],[stride,stride],padding=padding)
else:
return tf.contrib.layers.avg_pool2d(inputs,[kernel_size,kernel_size],[stride,stride],padding=padding)
| name[3:]):
# norm = _norm(conv, 'group', is_training)
norm = tf.layers.batch_normalization(conv,training=is_training)
return tf.nn.relu(norm)
def pool(inputs,kernel_size,stride,pooltpype='max',padding='SAME',name='pool'):
| 64 | 64 | 92 | 24 | 40 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | pool | pool | 236 | 241 | 236 | 236 | f235f72259aeebc66e398e882bf19e42fd81955d | bigcode/the-stack | train |
71ca28a3d14a39b9569f9b03 | train | function | def Unsampling_bilinear(inputs,filters,kernel_size,outshape=[None,800,288,5],stride=1,padding='SAME',is_training =False,name='pool'):
with tf.variable_scope(name):
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
... | def Unsampling_bilinear(inputs,filters,kernel_size,outshape=[None,800,288,5],stride=1,padding='SAME',is_training =False,name='pool'):
| with tf.variable_scope(name):
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
tf.contrib.layers.xavier_initializer(uniform=False),trainable=is_training)
conv = tf.nn.conv2d_transpose(inputs, kerne... | return tf.contrib.layers.avg_pool2d(inputs,[kernel_size,kernel_size],[stride,stride],padding=padding)
def Unsampling_bilinear(inputs,filters,kernel_size,outshape=[None,800,288,5],stride=1,padding='SAME',is_training =False,name='pool'):
| 64 | 64 | 128 | 40 | 24 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | Unsampling_bilinear | Unsampling_bilinear | 243 | 248 | 243 | 243 | 7f9139f544e3723ca258279d1474b55db53edea2 | bigcode/the-stack | train |
6f3f81ff6502086803e4f59c | train | function | def fc_sigmoid(inputs,filters,bias=True,name='fc_sigmoid'):
with tf.variable_scope(name):
shape = inputs.get_shape().as_list()
if len(shape) > 2:
inputs = tf.reshape(inputs, [-1, shape[1] * shape[2] * shape[3]])
weights = tf.get_variable(shape=[shape[1] * shape[2] * shape[3],... | def fc_sigmoid(inputs,filters,bias=True,name='fc_sigmoid'):
| with tf.variable_scope(name):
shape = inputs.get_shape().as_list()
if len(shape) > 2:
inputs = tf.reshape(inputs, [-1, shape[1] * shape[2] * shape[3]])
weights = tf.get_variable(shape=[shape[1] * shape[2] * shape[3], filters], dtype=tf.float32,
... | .1), name=name+'_weights')
biases = tf.get_variable('biases',([filters]),initializer=tf.constant_initializer(0.0))
return tf.nn.relu(tf.nn.bias_add(tf.matmul(inputs, weights),biases))
def fc_sigmoid(inputs,filters,bias=True,name='fc_sigmoid'):
| 64 | 64 | 205 | 16 | 48 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | fc_sigmoid | fc_sigmoid | 331 | 344 | 331 | 331 | 8ec75a2bf15b308cd1a9a183d3201456e78c71fc | bigcode/the-stack | train |
784f72c6a23512e366650fa8 | train | function | def conv_(inputs, filters, kernel_size=[9,1], strides=1, pad='SAME',w_summary=True, name='conv'):
with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size[0], kernel_size[1], inputs.get_shape().as_list()[3], filters]),initializer=... | def conv_(inputs, filters, kernel_size=[9,1], strides=1, pad='SAME',w_summary=True, name='conv'):
| with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size[0], kernel_size[1], inputs.get_shape().as_list()[3], filters]),initializer=
tf.contrib.layers.xavier_initializer(uniform=False),trainable=is... | (tf.constant(0.0, shape=[filters]),name='biases')
return tf.nn.bias_add(conv, bia)
else:
return conv
def conv_(inputs, filters, kernel_size=[9,1], strides=1, pad='SAME',w_summary=True, name='conv'):
| 64 | 64 | 162 | 31 | 32 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | conv_ | conv_ | 96 | 105 | 96 | 96 | 82389a4d1f4c6439acc160db38ae2baf3f34a50b | bigcode/the-stack | train |
6b88f0307d189ebf1dc101d3 | train | function | def spatial_conv(inputs,filters,kernel_size,strides,padding,spatial='up',w_summary=True,is_training= False,name='spatial_conv'):
# feature,NHWC
# filters,W H C_in C_out
N, H, W, C = inputs.get_shape().as_list()
R=0
dim = 0
if spatial=='up':
bottom_slice = tf.split(inputs, H, 1)
R... | def spatial_conv(inputs,filters,kernel_size,strides,padding,spatial='up',w_summary=True,is_training= False,name='spatial_conv'):
# feature,NHWC
# filters,W H C_in C_out
| N, H, W, C = inputs.get_shape().as_list()
R=0
dim = 0
if spatial=='up':
bottom_slice = tf.split(inputs, H, 1)
R = H
dim = 1
elif spatial=='left':
bottom_slice = tf.split(inputs, W, 2)
R = W
dim = 2
for i in range(R-1):
with tf.variable_scop... | stride,stride],padding=padding)
def Unsampling_bilinear(inputs,filters,kernel_size,outshape=[None,800,288,5],stride=1,padding='SAME',is_training =False,name='pool'):
with tf.variable_scope(name):
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initi... | 185 | 185 | 617 | 49 | 135 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | spatial_conv | spatial_conv | 250 | 297 | 250 | 252 | 2edb21ad490c6d2440f20e393893267b3f10e6ed | bigcode/the-stack | train |
3076ad315c5da43abfdf3281 | train | function | def get_conv_filter(shape,name):
init = tf.truncated_normal(shape, stddev=0.01)
var = tf.get_variable(name="filter", initializer=init, shape=shape)
return var
| def get_conv_filter(shape,name):
| init = tf.truncated_normal(shape, stddev=0.01)
var = tf.get_variable(name="filter", initializer=init, shape=shape)
return var
| [bs, c, h, w, c] to [bs, h, w, c] following the paper
output = tf.transpose(output, [0, 2, 3, 1])
else:
raise NotImplementedError
return output
def get_conv_filter(shape,name):
| 64 | 64 | 45 | 7 | 56 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | get_conv_filter | get_conv_filter | 64 | 67 | 64 | 64 | 7d5120a7a49cd1927476902d24a270b80b1816e8 | bigcode/the-stack | train |
d2266516dbd6fe3a66088c56 | train | function | def conv_bn(inputs, filters, kernel_size=1, strides=1, pad='SAME', is_training=False, w_summary=True,name='conv_bn'):
with tf.variable_scope(name):
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
tf.contr... | def conv_bn(inputs, filters, kernel_size=1, strides=1, pad='SAME', is_training=False, w_summary=True,name='conv_bn'):
| with tf.variable_scope(name):
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
tf.contrib.layers.xavier_initializer(uniform=False),trainable=is_training)
conv = tf.nn.conv2d(inputs, kernel, [1, str... | with tf.device('/cpu:0'):
tf.summary.histogram('weights_summary', kernel, collections=['weights'])
return tf.nn.relu(norm)
def conv_bn(inputs, filters, kernel_size=1, strides=1, pad='SAME', is_training=False, w_summary=True,name='conv_bn'):
| 64 | 64 | 188 | 33 | 31 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | conv_bn | conv_bn | 140 | 151 | 140 | 140 | c29381701d375d8c2e4be9f03b12a2fd7378ac11 | bigcode/the-stack | train |
d9b5f9638b3950939e038b3c | train | function | def astrous_conv(inputs,filters,kernel_size,rate=1,pad='SAME',is_training = False,bias = True,w_summary=True,name='astrous_conv'):
with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()... | def astrous_conv(inputs,filters,kernel_size,rate=1,pad='SAME',is_training = False,bias = True,w_summary=True,name='astrous_conv'):
| with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
tf.contrib.layers.xavier_initializer(uniform=False),trainable=is_train... | 0.0))
return tf.nn.relu(tf.nn.bias_add(conv, bia))
else:
return tf.nn.relu(conv)
def astrous_conv(inputs,filters,kernel_size,rate=1,pad='SAME',is_training = False,bias = True,w_summary=True,name='astrous_conv'):
| 64 | 64 | 192 | 37 | 27 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | astrous_conv | astrous_conv | 168 | 181 | 168 | 168 | 6f1328ac4353e86d0d9d712d8a45e40591f9a3a8 | bigcode/the-stack | train |
8b3c3381e631992a52bca792 | train | function | def add_relu(input1,input2,name='add_relu'):
with tf.variable_scope(name):
add = tf.add(input1,input2,name=name)
return tf.nn.relu(add)
| def add_relu(input1,input2,name='add_relu'):
| with tf.variable_scope(name):
add = tf.add(input1,input2,name=name)
return tf.nn.relu(add)
| _wights = tf.constant(0.0, shape)
init = tf.constant_initializer(value=bias_wights,dtype=tf.float32)
var = tf.get_variable(name="biases", initializer=init, shape=shape)
return var
def add_relu(input1,input2,name='add_relu'):
| 64 | 64 | 38 | 12 | 51 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | add_relu | add_relu | 75 | 78 | 75 | 75 | 84c22faa8bdab43b22b97a3ef347cc0ca4fb6c98 | bigcode/the-stack | train |
2689e65136d5d3d7e2679561 | train | function | def conv(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training = False,w_summary=True, bias = True,name='conv'):
with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], f... | def conv(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training = False,w_summary=True, bias = True,name='conv'):
| with tf.variable_scope(name):
# Kernel for convolution, Xavier Initialisation
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
tf.contrib.layers.xavier_initializer(uniform=False), trainable=is_training)
conv = tf.... | add_relu'):
with tf.variable_scope(name):
add = tf.add(input1,input2,name=name)
return tf.nn.relu(add)
def conv(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training = False,w_summary=True, bias = True,name='conv'):
| 64 | 64 | 200 | 35 | 29 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | conv | conv | 80 | 94 | 80 | 80 | e7e71ec241943fb8ecb179fee1925e5dad2c8466 | bigcode/the-stack | train |
bf57e8faf08003e03f51c48f | train | function | def conv_bn_relu(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training=False,w_summary=True, name='conv_bn_relu'):
with tf.variable_scope(name):
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
... | def conv_bn_relu(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training=False,w_summary=True, name='conv_bn_relu'):
| with tf.variable_scope(name):
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
tf.contrib.layers.xavier_initializer(uniform=False),trainable=is_training)
conv = tf.nn.conv2d(inputs, kernel, [1, str... | = tf.Variable(tf.constant(0.0, shape=[filters]),name='biases')
return tf.nn.bias_add(deconv, bia)
else:
return deconv
def conv_bn_relu(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training=False,w_summary=True, name='conv_bn_relu'):
| 73 | 73 | 246 | 35 | 37 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | conv_bn_relu | conv_bn_relu | 122 | 138 | 122 | 122 | 8717756f6b969bfa63e55aa1c64a5b88ab4bfbbc | bigcode/the-stack | train |
b4768b36ce45ba9148fe682f | train | function | def conv_relu(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training=False,w_summary=True, bias=True,name='conv_bn_relu'):
with tf.variable_scope(name):
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
... | def conv_relu(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training=False,w_summary=True, bias=True,name='conv_bn_relu'):
| with tf.variable_scope(name):
kernel = tf.get_variable('weights',([kernel_size, kernel_size, inputs.get_shape().as_list()[3], filters]),initializer=
tf.contrib.layers.xavier_initializer(uniform=False),trainable=is_training)
conv = tf.nn.conv2d(inputs, kernel, [1, str... | with tf.device('/cpu:0'):
tf.summary.histogram('weights_summary', kernel, collections=['weights'])
return norm
def conv_relu(inputs, filters, kernel_size=1, strides=1, pad='SAME',is_training=False,w_summary=True, bias=True,name='conv_bn_relu'):
| 64 | 64 | 198 | 36 | 27 | donghaiwang/VisualTracking_DRL | car/TF_RefineDet_CIDI3/model/layers_group.py | Python | conv_relu | conv_relu | 154 | 166 | 154 | 154 | d6d12def0c9d039366c9420246323490ec06e7e7 | bigcode/the-stack | train |
6d78e1618373fabd7986363f | train | function | def gbrt_minimize(func, dimensions, base_estimator=None,
n_calls=100, n_random_starts=None,
n_initial_points=10,
initial_point_generator="random",
acq_func="EI", acq_optimizer="auto",
x0=None, y0=None, random_state=None, verbose=F... | def gbrt_minimize(func, dimensions, base_estimator=None,
n_calls=100, n_random_starts=None,
n_initial_points=10,
initial_point_generator="random",
acq_func="EI", acq_optimizer="auto",
x0=None, y0=None, random_state=None, verbose=F... | """Sequential optimization using gradient boosted trees.
Gradient boosted regression trees are used to model the (very)
expensive to evaluate function `func`. The model is improved
by sequentially evaluating the expensive function at the next
best point. Thereby finding the minimum of `func` with a... |
from sklearn.utils import check_random_state
from .base import base_minimize
from ..utils import cook_estimator
def gbrt_minimize(func, dimensions, base_estimator=None,
n_calls=100, n_random_starts=None,
n_initial_points=10,
initial_point_generator="random",
... | 129 | 256 | 1,776 | 104 | 24 | samueljamesbell/scikit-optimize | skopt/optimizer/gbrt.py | Python | gbrt_minimize | gbrt_minimize | 8 | 187 | 8 | 15 | 1fc5324a85f1ee141322de2518771a6bf4482bd2 | bigcode/the-stack | train |
fd1c1af8d75184d00bac2db8 | train | class | class ArxivParser(object):
'''
This parser can speficially handle entries for arXiv search v0.5.6.
Args: None
'''
def __init__(self):
self._abstract_class = 'abstract-full has-text-grey-dark mathjax'
self._authors_class = 'authors'
self._title_class = 'title is-5 mathjax'
@staticmethod
d... | class ArxivParser(object):
| '''
This parser can speficially handle entries for arXiv search v0.5.6.
Args: None
'''
def __init__(self):
self._abstract_class = 'abstract-full has-text-grey-dark mathjax'
self._authors_class = 'authors'
self._title_class = 'title is-5 mathjax'
@staticmethod
def __less_tag_mask(idx, con... | from bs4 import element
class ArxivParser(object):
| 12 | 197 | 658 | 6 | 5 | whymauri/ArxivParser | parser.py | Python | ArxivParser | ArxivParser | 3 | 89 | 3 | 3 | ba96ec1880cda7c2a623d455352abaa100ce8cb4 | bigcode/the-stack | train |
255744ed94ed072702d33eea | train | class | class TestLedArray:
def __init__(_self):
# Set board numbering scheme and warnings
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
def activityOn(_self):
GPIO.output(11, GPIO.HIGH)
def activityOff(_self):
... | class TestLedArray:
| def __init__(_self):
# Set board numbering scheme and warnings
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
def activityOn(_self):
GPIO.output(11, GPIO.HIGH)
def activityOff(_self):
GPIO.out... | import RPi.GPIO as GPIO
import time
#from w1temperaturesensorarray import W1TemperatureSensorArray
# Class to verify LED operation.
class TestLedArray:
| 36 | 64 | 160 | 5 | 31 | paul-maher/creeknet | utils/testled.py | Python | TestLedArray | TestLedArray | 6 | 34 | 6 | 7 | 2f31791fa55e6c144d7f87d4920f5d3a03e5dafb | bigcode/the-stack | train |
a099716ec8597850a476fc0e | train | function | def get_available_languages():
return oslo_i18n.get_available_languages(DOMAIN)
| def get_available_languages():
| return oslo_i18n.get_available_languages(DOMAIN)
| "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
def get_available_languages():
| 64 | 64 | 18 | 5 | 58 | bdrich/neutron-lbaas | neutron_lbaas/_i18n.py | Python | get_available_languages | get_available_languages | 41 | 42 | 41 | 41 | c5f3e48c34eff787a57aad5dc81d983fbe39f003 | bigcode/the-stack | train |
06393c00588387868dd7427e | train | class | class Regressor(Layer):
def __init__(
self,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
**kwargs
):
... | class Regressor(Layer):
| def __init__(
self,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
**kwargs
):
super().__init__()
... | the License.
# ==============================================================================
import logging
from functools import partial
import tensorflow as tf
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Layer
from ludwig.constants i... | 64 | 64 | 164 | 7 | 57 | mbzhu1/ludwig | ludwig/decoders/generic_decoders.py | Python | Regressor | Regressor | 30 | 57 | 30 | 31 | 05bcead79f6b4c22c55014c6b557621de2addcac | bigcode/the-stack | train |
da6d53a9fd60b4b92b99e9da | train | class | class Classifier(Layer):
def __init__(
self,
num_classes,
use_bias=True,
weights_initializer='glorot_uniform',
bias_initializer='zeros',
weights_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
... | class Classifier(Layer):
| def __init__(
self,
num_classes,
use_bias=True,
weights_initializer='glorot_uniform',
bias_initializer='zeros',
weights_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
**kwargs
):
... | =clip[1]
)
else:
raise ValueError(
'The clip parameter of {} is {}. '
'It must be a list or a tuple of length 2.'.format(
self.feature_name,
self.clip
)
... | 107 | 107 | 359 | 6 | 100 | mbzhu1/ludwig | ludwig/decoders/generic_decoders.py | Python | Classifier | Classifier | 116 | 162 | 116 | 117 | 48eac0735e049c900dfa4c45ec232ced4f90c31b | bigcode/the-stack | train |
f44c2b04a74f750db6a70873 | train | class | class Projector(Layer):
def __init__(
self,
vector_size,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
... | class Projector(Layer):
| def __init__(
self,
vector_size,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
activation=None,
... | Dense')
self.dense = Dense(
1,
use_bias=use_bias,
kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer,
kernel_regularizer=kernel_regularizer,
bias_regularizer=bias_regularizer,
activity_regularizer=activit... | 93 | 93 | 313 | 6 | 87 | mbzhu1/ludwig | ludwig/decoders/generic_decoders.py | Python | Projector | Projector | 60 | 113 | 60 | 61 | f7bc01c06ace020173a49a318672c81050099af7 | bigcode/the-stack | train |
d4de439c683bdbdc450b04b5 | train | function | def check_names(names):
"""
Check that the names are allowed
:param names:
:return:
"""
allowed_data_sheets = get_allowed_sheets()
for name in names:
if name not in allowed_data_sheets.keys():
raise Exception('The file sheet ' + name + ' is not allowed.\n'
... | def check_names(names):
| """
Check that the names are allowed
:param names:
:return:
"""
allowed_data_sheets = get_allowed_sheets()
for name in names:
if name not in allowed_data_sheets.keys():
raise Exception('The file sheet ' + name + ' is not allowed.\n'
'Did you c... | from GridCal.Engine.basic_structures import Logger
from GridCal.Engine.Core.multi_circuit import MultiCircuit
from GridCal.Engine.Devices import *
from GridCal.Engine.IO.pack_unpack import create_data_frames, get_objects_dictionary
from GridCal.Engine.IO.generic_io_functions import parse_config_df
def check_names(names... | 64 | 64 | 86 | 5 | 58 | vineetjnair9/GridCal | src/GridCal/Engine/IO/excel_interface.py | Python | check_names | check_names | 23 | 34 | 23 | 23 | b24a9b695fbbe90b878fd0ea5985962fbe6070f4 | bigcode/the-stack | train |
b9d2423d5a9a47fe7ec17217 | train | function | def interprete_excel_v2(circuit: MultiCircuit, data):
"""
Interpret the file version 2
:param circuit:
:param data: Dictionary with the excel file sheet labels and the corresponding DataFrame
:return: Nothing, just applies the loaded data to this MultiCircuit instance
"""
# print('Interpret... | def interprete_excel_v2(circuit: MultiCircuit, data):
| """
Interpret the file version 2
:param circuit:
:param data: Dictionary with the excel file sheet labels and the corresponding DataFrame
:return: Nothing, just applies the loaded data to this MultiCircuit instance
"""
# print('Interpreting V2 data...')
# clear all the data
circuit... | '].index
if len(idx) > 0:
data["version"] = np.double(df.values[idx, 1])
idx = df['Property'][df['Property'] == 'Name'].index
if len(idx) > 0:
data["name"] = df.values[idx[0], 1]
else:
data["name... | 256 | 256 | 3,792 | 14 | 241 | vineetjnair9/GridCal | src/GridCal/Engine/IO/excel_interface.py | Python | interprete_excel_v2 | interprete_excel_v2 | 230 | 665 | 230 | 230 | e373de799930aa40b3b3d753ad5aa5ee2ef83f50 | bigcode/the-stack | train |
9c0e5236f20752c25bee621c | train | function | def interpret_excel_v3(circuit: MultiCircuit, data):
"""
Interpret the file version 3
In this file version there are no complex numbers saved
:param circuit:
:param data: Dictionary with the excel file sheet labels and the corresponding DataFrame
:return: Nothing, just applies the loaded data to... | def interpret_excel_v3(circuit: MultiCircuit, data):
| """
Interpret the file version 3
In this file version there are no complex numbers saved
:param circuit:
:param data: Dictionary with the excel file sheet labels and the corresponding DataFrame
:return: Nothing, just applies the loaded data to this MultiCircuit instance
"""
# print('Int... | values
bus_to = lst['bus_to'].values
hdr = lst.columns.values
hdr = np.delete(hdr, np.argwhere(hdr == 'bus_from'))
hdr = np.delete(hdr, np.argwhere(hdr == 'bus_to'))
vals = lst[hdr].values
for i in range(len(lst)):
try:
obj = Branch(bus_from=bu... | 256 | 256 | 4,199 | 13 | 243 | vineetjnair9/GridCal | src/GridCal/Engine/IO/excel_interface.py | Python | interpret_excel_v3 | interpret_excel_v3 | 668 | 1,134 | 668 | 668 | e099314992c1cf2dcbe91be91e4301ab2256bcc7 | bigcode/the-stack | train |
71253252fa88726b047b3d06 | train | function | def get_allowed_sheets(circuit=MultiCircuit()):
"""
:param circuit:
:return:
"""
########################################################################################################
# declare objects to iterate name: [sample object, list of objects, headers]
###########################... | def get_allowed_sheets(circuit=MultiCircuit()):
| """
:param circuit:
:return:
"""
########################################################################################################
# declare objects to iterate name: [sample object, list of objects, headers]
###########################################################################... | (None, None),
# circuit.get_branches()],
# 'load': [Load(),
# circuit.get_loads()],
# 'static_generator': [StaticGenerator(),
# circuit.get_static_generators()],
# ... | 113 | 113 | 379 | 11 | 101 | vineetjnair9/GridCal | src/GridCal/Engine/IO/excel_interface.py | Python | get_allowed_sheets | get_allowed_sheets | 62 | 114 | 62 | 62 | f3d55d50dfe59a2eb7a456af1b58f47b9f640355 | bigcode/the-stack | train |
1af2e02df7a48f55a8d15bdd | train | function | def load_from_xls(filename):
"""
Loads the excel file content to a dictionary for parsing the data
"""
data = dict()
xl = pd.ExcelFile(filename)
names = xl.sheet_names
# check the validity of this excel file
check_names(names=names)
# parse the file
if 'Conf' in names: # versi... | def load_from_xls(filename):
| """
Loads the excel file content to a dictionary for parsing the data
"""
data = dict()
xl = pd.ExcelFile(filename)
names = xl.sheet_names
# check the validity of this excel file
check_names(names=names)
# parse the file
if 'Conf' in names: # version 1
data["version"]... | transformer_types': None,
'time': None,
'load_Sprof': complex,
'load_Iprof': complex,
'load_Zprof': complex,
'static_generator': None,
'static_generator_Sprof... | 256 | 256 | 905 | 7 | 248 | vineetjnair9/GridCal | src/GridCal/Engine/IO/excel_interface.py | Python | load_from_xls | load_from_xls | 117 | 227 | 117 | 117 | 8fe934dc470fef5d27fcdccd451a34c4cad4fbba | bigcode/the-stack | train |
3677c6845ec66dfb676fb186 | train | function | def save_excel(circuit: MultiCircuit, file_path):
"""
Save the circuit information in excel format
:param circuit: MultiCircuit instance
:param file_path: path to the excel file
:return: logger with information
"""
logger = Logger()
dfs = create_data_frames(circuit=circuit)
# flush... | def save_excel(circuit: MultiCircuit, file_path):
| """
Save the circuit information in excel format
:param circuit: MultiCircuit instance
:param file_path: path to the excel file
:return: logger with information
"""
logger = Logger()
dfs = create_data_frames(circuit=circuit)
# flush-save ############################################... | obj.template = branch_types[template_name]
print(template_name, 'updtaed!')
else:
circuit.logger.append('No branches in the file!')
# Other actions ################################################################################################
circuit.logger += circuit.apply_all_... | 64 | 64 | 111 | 12 | 52 | vineetjnair9/GridCal | src/GridCal/Engine/IO/excel_interface.py | Python | save_excel | save_excel | 1,137 | 1,155 | 1,137 | 1,137 | c7a150f42b00c43bdef190801a450f3692eb5817 | bigcode/the-stack | train |
976d90efad0b7224b77f6214 | train | class | class AMRParser(object):
"""
AMR Parser class
"""
def __init__(self, opt,dicts):
self.decoder = AMRDecoder(opt,dicts)
self.model, _, _ = load_old_model(dicts,opt,True)[0]
self.opt = opt
self.feature_extractor = AMRInputPreprocessor(opt,core_nlp_url)
self.dicts = d... | class AMRParser(object):
| """
AMR Parser class
"""
def __init__(self, opt,dicts):
self.decoder = AMRDecoder(opt,dicts)
self.model, _, _ = load_old_model(dicts,opt,True)[0]
self.opt = opt
self.feature_extractor = AMRInputPreprocessor(opt,core_nlp_url)
self.dicts = dicts
self.decoder... | tokens"]
data["ner"] = []
data["tok"] = []
data["lem"] = []
data["pos"] = []
data["anchors"] = []
for snt_tok in snt:
data["ner"].append(snt_tok['ner'])
data["tok"].append(snt_tok['word'])
# first add anchors as a dictionary here.
... | 256 | 256 | 1,124 | 6 | 249 | utahnlp/lapa-mrp | parser/AMRProcessors.py | Python | AMRParser | AMRParser | 239 | 312 | 239 | 239 | 89fb02bd30164dd3407d9452e010d91e86dfd38d | bigcode/the-stack | train |
3cf5988a353973005590348c | train | function | def graph_to_amr(G, sentence = None):
top = BOS_WORD
root = list(G[top].keys())[0]
uni = G.node[root]["value"]
if uni.is_constant():
G.node[root]["value"].cat = Rule_Concept
G.node[root]["value"].le = G.node[root]["value"].le.strip(":").strip("/")
if G.node[root]["value"].le == ... | def graph_to_amr(G, sentence = None):
| top = BOS_WORD
root = list(G[top].keys())[0]
uni = G.node[root]["value"]
if uni.is_constant():
G.node[root]["value"].cat = Rule_Concept
G.node[root]["value"].le = G.node[root]["value"].le.strip(":").strip("/")
if G.node[root]["value"].le == "":
G.node[root]["value"].... | [n].items():
if str(n1) < str(n2) and G.node[n1]["value"] == G.node[n2]["value"] and G.node[n1]["value"].is_constant():
for key1, edge1 in edge1_data.items():
for key2, edge2 in edge2_data.items():
if edge1["role"] == edge2["role"]... | 123 | 123 | 410 | 11 | 111 | utahnlp/lapa-mrp | parser/AMRProcessors.py | Python | graph_to_amr | graph_to_amr | 446 | 477 | 446 | 446 | 4788ee7ce3c3a9647804f6058b99306083176cc7 | bigcode/the-stack | train |
b21aa21b73a08f8dcc452583 | train | function | def my_contracted_nodes(G,n1,n2,self_loops=False):
d = G.node[n1]
# Pay attention, when contact,the key information will be lost. try to fixed that after contacting
# print ("before",G.node[n1])
G = nx.contracted_nodes(G, n1,n2,self_loops=self_loops)
# print ("after",G.node[n1])
for k in d:
... | def my_contracted_nodes(G,n1,n2,self_loops=False):
| d = G.node[n1]
# Pay attention, when contact,the key information will be lost. try to fixed that after contacting
# print ("before",G.node[n1])
G = nx.contracted_nodes(G, n1,n2,self_loops=self_loops)
# print ("after",G.node[n1])
for k in d:
G.node[n1][k] = d[k]
# print ("finally",G.node... | else:
s += str(nb)
else:
ss,visited,visited_edges = sub_to_amr(G,visited.union(to_be_visted),nb, visited_edges.union(to_be_visted_edge),d+1)
s += ss
s += ")"
return s,visited,visited_edges
def my_contracted_nodes... | 82 | 82 | 276 | 15 | 66 | utahnlp/lapa-mrp | parser/AMRProcessors.py | Python | my_contracted_nodes | my_contracted_nodes | 361 | 384 | 361 | 361 | 48666eac6e9b620bbcef52f3e9d09fe576dde288 | bigcode/the-stack | train |
30b76cf413d6ab6baa261305 | train | class | class AMRInputPreprocessor(object):
"""
A feature extractor for amr input
"""
def __init__(self, opt, url = core_nlp_url):
self.nlp = StanfordCoreNLP(url)
self.opt = opt
self.joints_map = self.readJoints()
self.number_texts = {"hundred", "thousand", "million", "billion", ... | class AMRInputPreprocessor(object):
| """
A feature extractor for amr input
"""
def __init__(self, opt, url = core_nlp_url):
self.nlp = StanfordCoreNLP(url)
self.opt = opt
self.joints_map = self.readJoints()
self.number_texts = {"hundred", "thousand", "million", "billion", "trillion", "hundreds", "thousands",... | R is import for later alignments
# But it may be not good for multi-task learning.
@author: Jie Cao(jiessie.cao@gmail.com)
@since: 2019-06-01
'''
from utility.amr_utils.AMRStringCopyRules import *
from utility.amr_utils.AMRReCategorization import *
from parser.Dict import seq_to_id
from utility.constants import core_... | 256 | 256 | 1,786 | 8 | 248 | utahnlp/lapa-mrp | parser/AMRProcessors.py | Python | AMRInputPreprocessor | AMRInputPreprocessor | 44 | 237 | 44 | 44 | 641a729420817f0624b5d37983c0aebab200304a | bigcode/the-stack | train |
4c046cf4165b55fbde34e805 | train | function | def sub_to_amr(G,visited,n,visited_edges,d=1):
uni = G.node[n]["value"]
if uni.is_constant():
if uni.cat == Rule_String:
return "\""+ uni.le+"\"",visited,visited_edges
return uni.le,visited,visited_edges
s = "("+str(n)+" /"+" "+ uni.le+uni.sense
to_be_visted_edge = set() #t... | def sub_to_amr(G,visited,n,visited_edges,d=1):
| uni = G.node[n]["value"]
if uni.is_constant():
if uni.cat == Rule_String:
return "\""+ uni.le+"\"",visited,visited_edges
return uni.le,visited,visited_edges
s = "("+str(n)+" /"+" "+ uni.le+uni.sense
to_be_visted_edge = set() #to_be_visted_edges around this node
to_be_vi... | src_text in src_text_batch ]
return self.parse_batch_preprocessed_data(all_data, set_wiki, normalize_mod)
def parse_one(self,src_text, set_wiki, normalize_mod):
return self.parse_batch([src_text], set_wiki, normalize_mod)
def mark_edge(n1,n2,edge,edges):
edges.add((n1,n2,edge))
inverse = ... | 137 | 137 | 457 | 16 | 120 | utahnlp/lapa-mrp | parser/AMRProcessors.py | Python | sub_to_amr | sub_to_amr | 320 | 359 | 320 | 320 | b12216ee0c5de4c30e6a186bb41f77e6b5afd899 | bigcode/the-stack | train |
9e3ae78aa517937794580c27 | train | function | def mark_edge(n1,n2,edge,edges):
edges.add((n1,n2,edge))
inverse = get_inversed_edge(edge)
edges.add((n2,n1,inverse))
| def mark_edge(n1,n2,edge,edges):
| edges.add((n1,n2,edge))
inverse = get_inversed_edge(edge)
edges.add((n2,n1,inverse))
| _batch ]
return self.parse_batch_preprocessed_data(all_data, set_wiki, normalize_mod)
def parse_one(self,src_text, set_wiki, normalize_mod):
return self.parse_batch([src_text], set_wiki, normalize_mod)
def mark_edge(n1,n2,edge,edges):
| 64 | 64 | 43 | 12 | 52 | utahnlp/lapa-mrp | parser/AMRProcessors.py | Python | mark_edge | mark_edge | 314 | 317 | 314 | 314 | b0de22bf13f325a483bb43ee5f1fa1d1e1e6a5d8 | bigcode/the-stack | train |
bd902513ffba0e2d0034ddf8 | train | function | def contract_graph(G):
NAMES = {}
for n in G.node:
if not G.node[n]["value"].cat == Rule_Frame:
continue
person = []
for nb, edges_data in G[n].items():
if G.node[nb]["value"].le == "person":
for key, edge in edges_data.items():
... | def contract_graph(G):
| NAMES = {}
for n in G.node:
if not G.node[n]["value"].cat == Rule_Frame:
continue
person = []
for nb, edges_data in G[n].items():
if G.node[nb]["value"].le == "person":
for key, edge in edges_data.items():
if edge["role"] == ":A... | edge_data in G.edges(keys=True, data=True):
if (un0 != n1 and un1 != n1):
continue
else:
required_key = edge_data["role"]
H.remove_edge(un0, un1, key=ori_key)
H.add_edge(un0, un1, key=required_key, role=required_key)
for akey, avalue in edge_d... | 170 | 170 | 569 | 5 | 165 | utahnlp/lapa-mrp | parser/AMRProcessors.py | Python | contract_graph | contract_graph | 388 | 444 | 388 | 388 | 84a8daa90c4fdb8f106c03c7fd4fb5c831052b86 | bigcode/the-stack | train |
c35e7bba4914312700896cfc | train | class | class AMRDecoder(object):
def __init__(self, opt,dicts, frame = "amr"):
"""
init the model for AMR Decoder in pytorch
Especially, it relys on the dicts/vocabularies for tokens and labels.
"""
self.frame = frame
self.opt = opt
self.dicts = dicts
# high... | class AMRDecoder(object):
| def __init__(self, opt,dicts, frame = "amr"):
"""
init the model for AMR Decoder in pytorch
Especially, it relys on the dicts/vocabularies for tokens and labels.
"""
self.frame = frame
self.opt = opt
self.dicts = dicts
# high frequency lemmas
... | in G.node:
logger.info("nodes: %s, %s, %s", n,G.node[n],G.node[n]["value"])
logger.info("visited nodes %s",visited)
logger.info("edges %s",G.edges)
logger.info("visited edges %s",visited_edges)
logger.info("amr: %s, sentence: %s", s,sentence)
... | 256 | 256 | 6,240 | 6 | 249 | utahnlp/lapa-mrp | parser/AMRProcessors.py | Python | AMRDecoder | AMRDecoder | 481 | 993 | 481 | 481 | ba57acd94cda4ce09cef3d50be0dbf88bfeaf2aa | bigcode/the-stack | train |
cfbe15feccb7fcdb9f06ecf0 | train | class | class AutodetectorTests(TestCase):
"""
Tests the migration autodetector.
"""
author_empty = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True))])
author_name = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=2... | class AutodetectorTests(TestCase):
| """
Tests the migration autodetector.
"""
author_empty = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True))])
author_name = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200))])
author_name_longer = Mod... | # encoding: utf8
from django.test import TestCase
from django.db.migrations.autodetector import MigrationAutodetector, MigrationQuestioner
from django.db.migrations.state import ProjectState, ModelState
from django.db.migrations.graph import MigrationGraph
from django.db import models
class AutodetectorTests(TestCase):... | 71 | 256 | 3,128 | 9 | 61 | schuyler1d/django | tests/migrations/test_autodetector.py | Python | AutodetectorTests | AutodetectorTests | 9 | 274 | 9 | 9 | b33b9b81a7f8f26bb49b57d5f578490398919b72 | bigcode/the-stack | train |
4924e0d6b501d2a70763f7a8 | train | class | class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="size", parent_name="ohlc.legendgrouptitle.font", **kwargs
):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kw... | class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
| def __init__(
self, plotly_name="size", parent_name="ohlc.legendgrouptitle.font", **kwargs
):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
min=kwargs.pop("min", 1... | import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
| 20 | 64 | 98 | 12 | 7 | mastermind88/plotly.py | packages/python/plotly/plotly/validators/ohlc/legendgrouptitle/font/_size.py | Python | SizeValidator | SizeValidator | 4 | 14 | 4 | 4 | 3b28b066f485d6c56b9d4adbec0d53f410bbc304 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.