{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_by_name(cls, name):\n try:\n return cls.query.filter_by(name=name).one()\n except NoResultFound:\n return None", "response": "Query group by a group name."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nquery by a list of group names.", "response": "def query_by_names(cls, names):\n \"\"\"Query group by a list of group names.\n\n :param list names: List of the group names.\n :returns: Query object.\n \"\"\"\n assert isinstance(names, list)\n return cls.query.filter(cls.name.in_(names))"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef query_by_user(cls, user, with_pending=False, eager=False):\n q1 = Group.query.join(Membership).filter_by(user_id=user.get_id())\n if not with_pending:\n q1 = q1.filter_by(state=MembershipState.ACTIVE)\n if eager:\n q1 = q1.options(joinedload(Group.members))\n\n q2 = Group.query.join(GroupAdmin).filter_by(\n admin_id=user.get_id(), admin_type=resolve_admin_type(user))\n if eager:\n q2 = q2.options(joinedload(Group.members))\n\n query = q1.union(q2).with_entities(Group.id)\n\n return Group.query.filter(Group.id.in_(query))", "response": "Query group by user."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef search(cls, query, q):\n return query.filter(Group.name.like('%{0}%'.format(q)))", "response": "Modify query as so include only specific group names."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef add_member(self, user, state=MembershipState.ACTIVE):\n return Membership.create(self, user, state)", "response": "Invite a user to a group."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ninvite a user to a group.", "response": "def invite(self, user, admin=None):\n \"\"\"Invite a user to a group (should be done by admins).\n\n Wrapper around ``add_member()`` to ensure proper membership state.\n\n :param user: User to invite.\n :param admin: Admin doing the action. If provided, user is only invited\n if the object is an admin for this group. Default: None.\n :returns: Newly created Membership or None.\n \"\"\"\n if admin is None or self.is_admin(admin):\n return self.add_member(user, state=MembershipState.PENDING_USER)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ninvites users to a group by emails.", "response": "def invite_by_emails(self, emails):\n \"\"\"Invite users to a group by emails.\n\n :param list emails: Emails of users that shall be invited.\n :returns list: Newly created Memberships or Nones.\n \"\"\"\n assert emails is None or isinstance(emails, list)\n\n results = []\n\n for email in emails:\n try:\n user = User.query.filter_by(email=email).one()\n results.append(self.invite(user))\n except NoResultFound:\n results.append(None)\n\n return results"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsubscribing a user to a group.", "response": "def subscribe(self, user):\n \"\"\"Subscribe a user to a group (done by users).\n\n Wrapper around ``add_member()`` which checks subscription policy.\n\n :param user: User to subscribe.\n :returns: Newly created Membership or None.\n \"\"\"\n if self.subscription_policy == SubscriptionPolicy.OPEN:\n return self.add_member(user)\n elif self.subscription_policy == SubscriptionPolicy.APPROVAL:\n return self.add_member(user, state=MembershipState.PENDING_ADMIN)\n elif self.subscription_policy == SubscriptionPolicy.CLOSED:\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nverifies if given user is a group member.", "response": "def is_member(self, user, with_pending=False):\n \"\"\"Verify if given user is a group member.\n\n :param user: User to be checked.\n :param bool with_pending: Whether to include pending users or not.\n :returns: True or False.\n \"\"\"\n m = Membership.get(self, user)\n if m is not None:\n if with_pending:\n return True\n elif m.state == MembershipState.ACTIVE:\n return True\n return False"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef can_see_members(self, user):\n if self.privacy_policy == PrivacyPolicy.PUBLIC:\n return True\n elif self.privacy_policy == PrivacyPolicy.MEMBERS:\n return self.is_member(user) or self.is_admin(user)\n elif self.privacy_policy == PrivacyPolicy.ADMINS:\n return self.is_admin(user)", "response": "Determine if given user can see other group members."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ndetermining if a user can invite people to a group.", "response": "def can_invite_others(self, user):\n \"\"\"Determine if user can invite people to a group.\n\n Be aware that this check is independent from the people (users) which\n are going to be invited. The checked user is the one who invites\n someone, NOT who is going to be invited.\n\n :param user: User to be checked.\n :returns: True or False.\n \"\"\"\n if self.is_managed:\n return False\n elif self.is_admin(user):\n return True\n elif self.subscription_policy != SubscriptionPolicy.CLOSED:\n return True\n else:\n return False"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get(cls, group, user):\n try:\n m = cls.query.filter_by(user_id=user.get_id(), group=group).one()\n return m\n except Exception:\n return None", "response": "Get the membership for given user and group."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nfilters a query result.", "response": "def _filter(cls, query, state=MembershipState.ACTIVE, eager=None):\n \"\"\"Filter a query result.\"\"\"\n query = query.filter_by(state=state)\n\n eager = eager or []\n for field in eager:\n query = query.options(joinedload(field))\n\n return query"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef query_by_user(cls, user, **kwargs):\n return cls._filter(\n cls.query.filter_by(user_id=user.get_id()),\n **kwargs\n )", "response": "Get a user s memberships."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef query_invitations(cls, user, eager=False):\n if eager:\n eager = [Membership.group]\n return cls.query_by_user(user, state=MembershipState.PENDING_USER,\n eager=eager)", "response": "Get all invitations for given user."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef query_requests(cls, admin, eager=False):\n # Get direct pending request\n if hasattr(admin, 'is_superadmin') and admin.is_superadmin:\n q1 = GroupAdmin.query.with_entities(\n GroupAdmin.group_id)\n else:\n q1 = GroupAdmin.query_by_admin(admin).with_entities(\n GroupAdmin.group_id)\n q2 = Membership.query.filter(\n Membership.state == MembershipState.PENDING_ADMIN,\n Membership.id_group.in_(q1),\n )\n\n # Get request from admin groups your are member of\n q3 = Membership.query_by_user(\n user=admin, state=MembershipState.ACTIVE\n ).with_entities(Membership.id_group)\n q4 = GroupAdmin.query.filter(\n GroupAdmin.admin_type == 'Group', GroupAdmin.admin_id.in_(q3)\n ).with_entities(GroupAdmin.group_id)\n q5 = Membership.query.filter(\n Membership.state == MembershipState.PENDING_ADMIN,\n Membership.id_group.in_(q4))\n\n query = q2.union(q5)\n\n return query", "response": "Get all pending group requests."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef query_by_group(cls, group_or_id, with_invitations=False, **kwargs):\n if isinstance(group_or_id, Group):\n id_group = group_or_id.id\n else:\n id_group = group_or_id\n\n if not with_invitations:\n return cls._filter(\n cls.query.filter_by(id_group=id_group),\n **kwargs\n )\n else:\n return cls.query.filter(\n Membership.id_group == id_group,\n db.or_(\n Membership.state == MembershipState.PENDING_USER,\n Membership.state == MembershipState.ACTIVE\n )\n )", "response": "Get a group s members."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef search(cls, query, q):\n query = query.join(User).filter(\n User.email.like('%{0}%'.format(q)),\n )\n return query", "response": "Modify query as so include only specific members."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nmodifies query as so to order the results.", "response": "def order(cls, query, field, s):\n \"\"\"Modify query as so to order the results.\n\n :param query: Query object.\n :param str s: Orderinig: ``asc`` or ``desc``.\n :returs: Query object.\n \"\"\"\n if s == 'asc':\n query = query.order_by(asc(field))\n elif s == 'desc':\n query = query.order_by(desc(field))\n return query"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef create(cls, group, user, state=MembershipState.ACTIVE):\n with db.session.begin_nested():\n membership = cls(\n user_id=user.get_id(),\n id_group=group.id,\n state=state,\n )\n db.session.add(membership)\n return membership", "response": "Create a new membership."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ncreating a new group admin.", "response": "def create(cls, group, admin):\n \"\"\"Create a new group admin.\n\n :param group: Group object.\n :param admin: Admin object.\n :returns: Newly created GroupAdmin object.\n :raises: IntegrityError\n \"\"\"\n with db.session.begin_nested():\n obj = cls(\n group=group,\n admin=admin,\n )\n db.session.add(obj)\n return obj"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nget specific GroupAdmin object.", "response": "def get(cls, group, admin):\n \"\"\"Get specific GroupAdmin object.\"\"\"\n try:\n ga = cls.query.filter_by(\n group=group, admin_id=admin.get_id(),\n admin_type=resolve_admin_type(admin)).one()\n return ga\n except Exception:\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef delete(cls, group, admin):\n with db.session.begin_nested():\n obj = cls.query.filter(\n cls.admin == admin, cls.group == group).one()\n db.session.delete(obj)", "response": "Delete admin from group."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngetting all groups for a specific admin.", "response": "def query_by_admin(cls, admin):\n \"\"\"Get all groups for for a specific admin.\"\"\"\n return cls.query.filter_by(\n admin_type=resolve_admin_type(admin), admin_id=admin.get_id())"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef query_admins_by_group_ids(cls, groups_ids=None):\n assert groups_ids is None or isinstance(groups_ids, list)\n\n query = db.session.query(\n Group.id, func.count(GroupAdmin.id)\n ).join(\n GroupAdmin\n ).group_by(\n Group.id\n )\n\n if groups_ids:\n query = query.filter(Group.id.in_(groups_ids))\n\n return query", "response": "Get count of admins per group."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef all(self):\n '''\n Get all social newtworks profiles\n '''\n\n response = self.api.get(url=PATHS['GET_PROFILES'])\n\n for raw_profile in response:\n self.append(Profile(self.api, raw_profile))\n\n return self", "response": "Get all social newtworks profiles"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn a new Profiles object containing only the items chosen by some criteria", "response": "def filter(self, **kwargs):\n '''\n Based on some criteria, filter the profiles and return a new Profiles\n Manager containing only the chosen items\n\n If the manager doen't have any items, get all the profiles from Buffer\n '''\n\n if not len(self):\n self.all()\n\n new_list = filter(lambda item: [True for arg in kwargs if item[arg] == kwargs[arg]] != [], self)\n\n return Profiles(self.api, new_list)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef dorun(SNR=20, sweeps=20, burn=8, noise_samples=10):\n radii = np.linspace(2,10,8, endpoint=False)\n crbs, vals, errs = [], [], []\n\n for radius in radii:\n print 'radius', radius\n s,im = pxint(radius=radius, factor=4)\n goodstate = s.state.copy()\n\n common.set_image(s, im, 1.0/SNR)\n tcrb = crb(s)\n tval, terr = sample(s, im, 1.0/SNR, N=noise_samples, sweeps=sweeps, burn=burn)\n crbs.append(tcrb)\n vals.append(tval)\n errs.append(terr)\n\n return np.array(crbs), np.array(vals), np.array(errs), radii", "response": "This function is used to plot the errors introduced by pixelation so we plot the CRB for the current node and the image of the next node."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn the skew parameter for direction d", "response": "def _skew(self, x, z, d=0):\n \"\"\" returns the kurtosis parameter for direction d, d=0 is rho, d=1 is z \"\"\"\n # get the top bound determined by the kurtosis\n kval = (np.tanh(self._poly(z, self._kurtosis_coeffs(d)))+1)/12.\n bdpoly = np.array([\n -1.142468e+04, 3.0939485e+03, -2.0283568e+02,\n -2.1047846e+01, 3.79808487e+00, 1.19679781e-02\n ])\n top = np.polyval(bdpoly, kval)\n\n # limit the skewval to be 0 -> top val\n skew = self._poly(z, self._skew_coeffs(d))\n skewval = top*(np.tanh(skew) + 1) - top\n\n return skewval*(3*x - x**3)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning the kurtosis parameter for direction d", "response": "def _kurtosis(self, x, z, d=0):\n \"\"\" returns the kurtosis parameter for direction d, d=0 is rho, d=1 is z \"\"\"\n val = self._poly(z, self._kurtosis_coeffs(d))\n return (np.tanh(val)+1)/12.*(3 - 6*x**2 + x**4)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nfits a separation of two parties into a single edge", "response": "def fit_edge(separation, radius=5.0, samples=100, imsize=64, sigma=0.05, axis='z'):\n \"\"\"\n axis is 'z' or 'xy'\n seps = np.linspace(0,2,20) 'z'\n seps = np.linspace(-2,2,20) 'xy'\n \"\"\"\n terrors = []\n berrors = []\n crbs = []\n\n for sep in separation:\n print '='*79\n print 'sep =', sep,\n\n s = init.create_two_particle_state(imsize, radius=radius, delta=sep, sigma=0.05,\n axis='z', psfargs={'params': (2.0,1.0,4.0), 'error': 1e-8},\n stateargs={'sigmapad': True, 'pad': const.PAD})\n\n # move off of a pixel edge (cheating for trackpy)\n d = np.array([0,0.5,0.5])\n s.obj.pos -= d\n s.reset()\n\n # move the particles to the edge\n bl = s.blocks_particle(0)\n s.update(bl[0], np.array([s.pad+radius]))\n\n bl = s.blocks_particle(1)\n s.update(bl[0], np.array([s.pad-radius]))\n\n if axis == 'z':\n bl = s.blocks_particle(1)\n s.update(bl[0], s.state[bl[0]]-sep)\n s.model_to_true_image()\n\n if axis == 'xy':\n bl = s.blocks_particle(1)\n s.update(bl[2], s.state[bl[2]]+sep)\n s.model_to_true_image()\n\n # save where the particles were originally so we can jiggle\n p = s.state[s.b_pos].reshape(-1,3).copy()\n\n print p[0], p[1]\n # calculate the CRB for this configuration\n bl = s.explode(s.b_pos)\n crbs.append(np.sqrt(np.diag(np.linalg.inv(s.fisher_information(blocks=bl)))).reshape(-1,3))\n\n # calculate the featuring errors\n tmp_tp, tmp_bf = [],[]\n for i in xrange(samples):\n print i\n bench.jiggle_particles(s, pos=p, sig=0.3, mask=np.array([1,1,1]))\n t = bench.trackpy(s)\n b = bench.bamfpy_positions(s, sweeps=15)\n\n tmp_tp.append(bench.error(s, t))\n tmp_bf.append(bench.error(s, b))\n terrors.append(tmp_tp)\n berrors.append(tmp_bf)\n\n return np.array(crbs), np.array(terrors), np.array(berrors)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef zjitter(jitter=0.0, radius=5):\n psfsize = np.array([2.0, 1.0, 3.0])\n\n # create a base image of one particle\n s0 = init.create_single_particle_state(imsize=4*radius, \n radius=radius, psfargs={'params': psfsize, 'error': 1e-6})\n sl = np.s_[s0.pad:-s0.pad,s0.pad:-s0.pad,s0.pad:-s0.pad]\n\n # add up a bunch of trajectories\n finalimage = 0*s0.get_model_image()[sl]\n position = 0*s0.obj.pos[0]\n\n for i in xrange(finalimage.shape[0]):\n offset = jitter*np.random.randn(3)*np.array([1,0,0])\n s0.obj.pos[0] = np.array(s0.image.shape)/2 + offset\n s0.reset()\n\n finalimage[i] = s0.get_model_image()[sl][i]\n position += s0.obj.pos[0]\n\n position /= float(finalimage.shape[0])\n\n # place that into a new image at the expected parameters\n s = init.create_single_particle_state(imsize=4*radius, sigma=0.05,\n radius=radius, psfargs={'params': psfsize, 'error': 1e-6})\n s.reset()\n\n # measure the true inferred parameters\n return s, finalimage, position", "response": "create a new state and a base image of one particle and a random position"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef dorun(SNR=20, njitters=20, samples=10, noise_samples=10, sweeps=20, burn=10):\n jitters = np.logspace(-6, np.log10(0.5), njitters)\n crbs, vals, errs, poss = [], [], [], []\n\n for i,t in enumerate(jitters):\n print '###### jitter', i, t\n\n for j in xrange(samples):\n print 'image', j, '|', \n s,im,pos = zjitter(jitter=t)\n\n # typical image\n common.set_image(s, im, 1.0/SNR)\n crbs.append(crb(s))\n\n val, err = sample(s, im, 1.0/SNR, N=noise_samples, sweeps=sweeps, burn=burn)\n poss.append(pos)\n vals.append(val)\n errs.append(err)\n\n\n shape0 = (njitters, samples, -1)\n shape1 = (njitters, samples, noise_samples, -1)\n\n crbs = np.array(crbs).reshape(shape0)\n vals = np.array(vals).reshape(shape1)\n errs = np.array(errs).reshape(shape1)\n poss = np.array(poss).reshape(shape0)\n\n return [crbs, vals, errs, poss, jitters]", "response": "This function is used to plot the errors introduced by pixelation so we plot the crbs and values and errors for the next time."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the detailed information on individual interactions with the social media update such as favorites retweets and likes.", "response": "def interactions(self):\n '''\n Returns the detailed information on individual interactions with the social\n media update such as favorites, retweets and likes.\n '''\n\n interactions = []\n url = PATHS['GET_INTERACTIONS'] % self.id\n\n response = self.api.get(url=url)\n for interaction in response['interactions']:\n interactions.append(ResponseObject(interaction))\n\n self.__interactions = interactions\n\n return self.__interactions"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef edit(self, text, media=None, utc=None, now=None):\n '''\n Edit an existing, individual status update.\n '''\n\n url = PATHS['EDIT'] % self.id\n\n post_data = \"text=%s&\" % text\n\n if now:\n post_data += \"now=%s&\" % now\n\n if utc:\n post_data += \"utc=%s&\" % utc\n\n if media:\n media_format = \"media[%s]=%s&\"\n\n for media_type, media_item in media.iteritems():\n post_data += media_format % (media_type, media_item)\n\n response = self.api.post(url=url, data=post_data)\n\n return Update(api=self.api, raw_response=response['update'])", "response": "Edit an existing individual status update."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef publish(self):\n '''\n Immediately shares a single pending update and recalculates times for\n updates remaining in the queue.\n '''\n\n url = PATHS['PUBLISH'] % self.id\n return self.api.post(url=url)", "response": "Publishes a single pending update and recalculates times for all updates remaining in the queue."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef move_to_top(self):\n '''\n Move an existing status update to the top of the queue and recalculate\n times for all updates in the queue. Returns the update with its new\n posting time.\n '''\n\n url = PATHS['MOVE_TO_TOP'] % self.id\n\n response = self.api.post(url=url)\n return Update(api=self.api, raw_response=response)", "response": "Move an existing status update to the top of the queue and recalculate the time for all updates in the queue. Returns the updated update with the new\n posting time."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nremove the noise poles from a 2d noise distribution to show that affects the real-space noise picture. noise -- fftshifted 2d array of q values poles -- N,2 list of pole locations. the last index is in the order y,x as determined by mpl interactive plots for example: poles = np.array([[190,277], [227,253], [233, 256]]", "response": "def pole_removal(noise, poles=None, sig=3):\n \"\"\"\n Remove the noise poles from a 2d noise distribution to show that affects\n the real-space noise picture. \n \n noise -- fftshifted 2d array of q values\n\n poles -- N,2 list of pole locations. the last index is in the order y,x as\n determined by mpl interactive plots\n\n for example: poles = np.array([[190,277], [227,253], [233, 256]]\n \"\"\"\n center = np.array(noise.shape)/2\n\n v = np.rollaxis(\n np.array(\n np.meshgrid(*(np.arange(s) for s in noise.shape), indexing='ij')\n ), 0, 3\n ).astype(\"float\")\n filter = np.zeros_like(noise, dtype='float')\n\n for p in poles:\n for pp in [p, center - (p-center)]:\n dist = ((v-pp)**2).sum(axis=-1)\n filter += np.exp(-dist / (2*sig**2))\n\n filter[filter > 1] = 1\n return noise*(1-filter)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef pending(self):\n '''\n Returns an array of updates that are currently in the buffer for an\n individual social media profile.\n '''\n\n pending_updates = []\n url = PATHS['GET_PENDING'] % self.profile_id\n\n response = self.api.get(url=url)\n for update in response['updates']:\n pending_updates.append(Update(api=self.api, raw_response=update))\n\n self.__pending = pending_updates\n\n return self.__pending", "response": "Returns an array of updates that are currently in the buffer for an individual social media profile."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef sent(self):\n '''\n Returns an array of updates that have been sent from the buffer for an\n individual social media profile.\n '''\n\n sent_updates = []\n url = PATHS['GET_SENT'] % self.profile_id\n\n response = self.api.get(url=url)\n for update in response['updates']:\n sent_updates.append(Update(api=self.api, raw_response=update))\n\n self.__sent = sent_updates\n\n return self.__sent", "response": "Returns an array of updates that have been sent from the buffer for an individual social media profile."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef shuffle(self, count=None, utc=None):\n '''\n Randomize the order at which statuses for the specified social media\n profile will be sent out of the buffer.\n '''\n\n url = PATHS['SHUFFLE'] % self.profile_id\n\n post_data = ''\n if count:\n post_data += 'count=%s&' % count\n if utc:\n post_data += 'utc=%s' % utc\n\n return self.api.post(url=url, data=post_data)", "response": "Randomize the order at which statuses for the specified social media offer will be sent out of the buffer."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef reorder(self, updates_ids, offset=None, utc=None):\n '''\n Edit the order at which statuses for the specified social media profile will\n be sent out of the buffer.\n '''\n\n url = PATHS['REORDER'] % self.profile_id\n\n order_format = \"order[]=%s&\"\n post_data = ''\n\n if offset:\n post_data += 'offset=%s&' % offset\n\n if utc:\n post_data += 'utc=%s&' % utc\n\n for update in updates_ids:\n post_data += order_format % update\n\n return self.api.post(url=url, data=post_data)", "response": "This method is used to reorder the items in a social media profile."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncreate one or more new status updates.", "response": "def new(self, text, shorten=None, now=None, top=None, media=None, when=None):\n '''\n Create one or more new status updates.\n '''\n\n url = PATHS['CREATE']\n\n post_data = \"text=%s&\" % text\n post_data += \"profile_ids[]=%s&\" % self.profile_id\n\n if shorten:\n post_data += \"shorten=%s&\" % shorten\n\n if now:\n post_data += \"now=%s&\" % now\n\n if top:\n post_data += \"top=%s&\" % top\n\n if when:\n post_data += \"scheduled_at=%s&\" % str(when)\n\n if media:\n media_format = \"media[%s]=%s&\"\n\n for media_type, media_item in media.iteritems():\n post_data += media_format % (media_type, media_item)\n\n response = self.api.post(url=url, data=post_data)\n new_update = Update(api=self.api, raw_response=response['updates'][0])\n\n self.append(new_update)\n\n return new_update"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nset the logging level of the handlers.", "response": "def set_level(self, level='info', handlers=None):\n \"\"\"\n Set the logging level (which types of logs are actually printed / recorded)\n to one of ['debug', 'info', 'warn', 'error', 'fatal'] in that order\n of severity\n \"\"\"\n for h in self.get_handlers(handlers):\n h.setLevel(levels[level])"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef set_formatter(self, formatter='standard', handlers=None):\n for h in self.get_handlers(handlers):\n h.setFormatter(logging.Formatter(formatters[formatter]))", "response": "Set the text format of messages to one of the pre - deterministic forms"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nadd a new handler to the logging system if not present already.", "response": "def add_handler(self, name='console-color', level='info', formatter='standard', **kwargs):\n \"\"\"\n Add another handler to the logging system if not present already.\n Available handlers are currently: ['console-bw', 'console-color', 'rotating-log']\n \"\"\"\n # make sure the the log file has a name\n if name == 'rotating-log' and 'filename' not in kwargs:\n kwargs.update({'filename': self.logfilename})\n\n # make sure the the log file has a name\n if name == 'stringio' and 'stringio' not in kwargs:\n kwargs.update({'stringio': StringIO.StringIO()})\n\n handler = types[name](**kwargs)\n self.add_handler_raw(handler, name, level=level, formatter=formatter)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef remove_handler(self, name):\n if name in self.handlers:\n self.log.removeHandler(self.handlers[name])", "response": "Remove a handler from the logging system if present."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nsetting the verbosity level of a certain log handler or all handlers.", "response": "def set_verbosity(self, verbosity='vvv', handlers=None):\n \"\"\"\n Set the verbosity level of a certain log handler or of all handlers.\n\n Parameters\n ----------\n verbosity : 'v' to 'vvvvv'\n the level of verbosity, more v's is more verbose\n\n handlers : string, or list of strings\n handler names can be found in ``peri.logger.types.keys()``\n Current set is::\n\n ['console-bw', 'console-color', 'rotating-log']\n \"\"\"\n self.verbosity = sanitize(verbosity)\n self.set_level(v2l[verbosity], handlers=handlers)\n self.set_formatter(v2f[verbosity], handlers=handlers)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef normalize(im, invert=False, scale=None, dtype=np.float64):\n if dtype not in {np.float16, np.float32, np.float64}:\n raise ValueError('dtype must be numpy.float16, float32, or float64.')\n out = im.astype('float').copy()\n\n scale = scale or (0.0, 255.0)\n l, u = (float(i) for i in scale)\n out = (out - l) / (u - l)\n if invert:\n out = -out + (out.max() + out.min())\n return out.astype(dtype)", "response": "Normalize a field to a range of exposure values."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ngenerates a centered boolean mask of a 3D sphere", "response": "def generate_sphere(radius):\n \"\"\"Generates a centered boolean mask of a 3D sphere\"\"\"\n rint = np.ceil(radius).astype('int')\n t = np.arange(-rint, rint+1, 1)\n x,y,z = np.meshgrid(t, t, t, indexing='ij')\n r = np.sqrt(x*x + y*y + z*z)\n sphere = r < radius\n return sphere"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef harris_feature(im, region_size=5, to_return='harris', scale=0.05):\n ndim = im.ndim\n #1. Gradient of image\n grads = [nd.sobel(im, axis=i) for i in range(ndim)]\n #2. Corner response matrix\n matrix = np.zeros((ndim, ndim) + im.shape)\n for a in range(ndim):\n for b in range(ndim):\n matrix[a,b] = nd.filters.gaussian_filter(grads[a]*grads[b],\n region_size)\n if to_return == 'matrix':\n return matrix\n #3. Trace, determinant\n trc = np.trace(matrix, axis1=0, axis2=1)\n det = np.linalg.det(matrix.T).T\n if to_return == 'trace-determinant':\n return trc, det\n else:\n #4. Harris detector:\n harris = det - scale*trc*trc\n return harris", "response": "Harris - motivated feature detection on a d - dimensional image."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nidentifies slabs in an image. Functions by running a Harris-inspired edge detection on the image, thresholding the edge, then clustering. Parameters ---------- im : numpy.ndarray 3D array of the image to analyze. sigma : Float, optional Gaussian blurring kernel to remove non-slab features such as noise and particles. Default is 5. region_size : Int, optional The size of region for Harris corner featuring. Default is 10 masscut : Float, optional The minimum number of pixels for a feature to be identified as a slab. Default is 1e4; should be smaller for smaller images. asdict : Bool, optional Set to True to return a list of dicts, with keys of ``'theta'`` and ``'phi'`` as rotation angles about the x- and z- axes, and of ``'zpos'`` for the z-position, i.e. a list of dicts which can be unpacked into a :class:``peri.comp.objs.Slab`` Returns ------- [poses, normals] : numpy.ndarray The positions and normals of each slab in the image; ``poses[i]`` and ``normals[i]`` are the ``i``th slab. Returned if ``asdict`` is False [list] A list of dictionaries. Returned if ``asdict`` is True", "response": "def identify_slab(im, sigma=5., region_size=10, masscut=1e4, asdict=False):\n \"\"\"\n Identifies slabs in an image.\n\n Functions by running a Harris-inspired edge detection on the image,\n thresholding the edge, then clustering.\n\n Parameters\n ----------\n im : numpy.ndarray\n 3D array of the image to analyze.\n sigma : Float, optional\n Gaussian blurring kernel to remove non-slab features such as\n noise and particles. Default is 5.\n region_size : Int, optional\n The size of region for Harris corner featuring. Default is 10\n masscut : Float, optional\n The minimum number of pixels for a feature to be identified as\n a slab. Default is 1e4; should be smaller for smaller images.\n asdict : Bool, optional\n Set to True to return a list of dicts, with keys of ``'theta'``\n and ``'phi'`` as rotation angles about the x- and z- axes, and\n of ``'zpos'`` for the z-position, i.e. a list of dicts which\n can be unpacked into a :class:``peri.comp.objs.Slab``\n\n Returns\n -------\n [poses, normals] : numpy.ndarray\n The positions and normals of each slab in the image; ``poses[i]``\n and ``normals[i]`` are the ``i``th slab. Returned if ``asdict``\n is False\n [list]\n A list of dictionaries. Returned if ``asdict`` is True\n \"\"\"\n #1. edge detect:\n fim = nd.filters.gaussian_filter(im, sigma)\n trc, det = harris_feature(fim, region_size, to_return='trace-determinant')\n #we want an edge == not a corner, so one eigenvalue is high and\n #one is low compared to the other.\n #So -- trc high, normalized det low:\n dnrm = det / (trc*trc)\n trc_cut = otsu_threshold(trc)\n det_cut = otsu_threshold(dnrm)\n slabs = (trc > trc_cut) & (dnrm < det_cut)\n labeled, nslabs = nd.label(slabs)\n #masscuts:\n masses = [(labeled == i).sum() for i in range(1, nslabs+1)]\n good = np.array([m > masscut for m in masses])\n inds = np.nonzero(good)[0] + 1 #+1 b/c the lowest label is the bkg\n #Slabs are identifiied, now getting the coords:\n poses = np.array(nd.measurements.center_of_mass(trc, labeled, inds))\n #normals from eigenvectors of the covariance matrix\n normals = []\n z = np.arange(im.shape[0]).reshape(-1,1,1).astype('float')\n y = np.arange(im.shape[1]).reshape(1,-1,1).astype('float')\n x = np.arange(im.shape[2]).reshape(1,1,-1).astype('float')\n #We also need to identify the direction of the normal:\n gim = [nd.sobel(fim, axis=i) for i in range(fim.ndim)]\n for i, p in zip(range(1, nslabs+1), poses):\n wts = trc * (labeled == i)\n wts /= wts.sum()\n zc, yc, xc = [xi-pi for xi, pi in zip([z,y,x],p.squeeze())]\n cov = [[np.sum(xi*xj*wts) for xi in [zc,yc,xc]] for xj in [zc,yc,xc]]\n vl, vc = np.linalg.eigh(cov)\n #lowest eigenvalue is the normal:\n normal = vc[:,0]\n #Removing the sign ambiguity:\n gn = np.sum([n*g[tuple(p.astype('int'))] for g,n in zip(gim, normal)])\n normal *= np.sign(gn)\n normals.append(normal)\n if asdict:\n get_theta = lambda n: -np.arctan2(n[1], -n[0])\n get_phi = lambda n: np.arcsin(n[2])\n return [{'zpos':p[0], 'angles':(get_theta(n), get_phi(n))}\n for p, n in zip(poses, normals)]\n else:\n return poses, np.array(normals)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nplot the errors for a single crystal.", "response": "def plot_errors_single(rad, crb, errors, labels=['trackpy', 'peri']):\n fig = pl.figure()\n comps = ['z', 'y', 'x']\n markers = ['o', '^', '*']\n colors = COLORS\n\n for i in reversed(range(3)):\n pl.plot(rad, crb[:,0,i], lw=2.5, label='CRB-'+comps[i], color=colors[i])\n\n for c, (error, label) in enumerate(zip(errors, labels)):\n mu = np.sqrt((error**2).mean(axis=1))[:,0,:]\n std = np.std(np.sqrt((error**2)), axis=1)[:,0,:]\n\n for i in reversed(range(len(mu[0]))):\n pl.plot(rad, mu[:,i], marker=markers[c], color=colors[i], lw=0, label=label+\"-\"+comps[i], ms=13)\n\n pl.ylim(1e-3, 8e0)\n pl.semilogy()\n pl.legend(loc='upper left', ncol=3, numpoints=1, prop={\"size\": 16})\n pl.xlabel(r\"radius (pixels)\")\n pl.ylabel(r\"CRB / $\\Delta$ (pixels)\")\n \"\"\" \n ax = fig.add_axes([0.6, 0.6, 0.28, 0.28])\n ax.plot(rad, crb[:,0,:], lw=2.5)\n for c, error in enumerate(errors):\n mu = np.sqrt((error**2).mean(axis=1))[:,0,:]\n std = np.std(np.sqrt((error**2)), axis=1)[:,0,:]\n\n for i in range(len(mu[0])):\n ax.errorbar(rad, mu[:,i], yerr=std[:,i], fmt=markers[c], color=colors[i], lw=1)\n ax.set_ylim(-0.1, 1.5)\n ax.grid('off')\n \"\"\""}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef sphere_analytical_gaussian(dr, a, alpha=0.2765):\n term1 = 0.5*(erf((dr+2*a)/(alpha*np.sqrt(2))) + erf(-dr/(alpha*np.sqrt(2))))\n term2 = np.sqrt(0.5/np.pi)*(alpha/(dr+a+1e-10)) * (\n np.exp(-0.5*dr**2/alpha**2) - np.exp(-0.5*(dr+2*a)**2/alpha**2)\n )\n return term1 - term2", "response": "Analytically calculate the sphere s functional form by convolving the solar system with first order approximation to the sinc a Gaussian."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nseeing sphere_analytical_gaussian_exact. I trimmed to terms from the functional form that are essentially zero (1e-8) for r0 > cut (~1.5), a fine approximation for these platonic anyway.", "response": "def sphere_analytical_gaussian_trim(dr, a, alpha=0.2765, cut=1.6):\n \"\"\"\n See sphere_analytical_gaussian_exact.\n\n I trimmed to terms from the functional form that are essentially zero (1e-8)\n for r0 > cut (~1.5), a fine approximation for these platonic anyway.\n \"\"\"\n m = np.abs(dr) <= cut\n\n # only compute on the relevant scales\n rr = dr[m]\n t = -rr/(alpha*np.sqrt(2))\n q = 0.5*(1 + erf(t)) - np.sqrt(0.5/np.pi)*(alpha/(rr+a+1e-10)) * np.exp(-t*t)\n\n # fill in the grid, inside the interpolation and outside where values are constant\n ans = 0*dr\n ans[m] = q\n ans[dr > cut] = 0\n ans[dr < -cut] = 1\n return ans"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nseeing sphere_analytical_gaussian_trim, but implemented in C with fast erf and exp approximations found at Abramowitz and Stegun: Handbook of Mathematical Functions A Fast, Compact Approximation of the Exponential Function The default cut 1.25 was chosen based on the accuracy of fast_erf", "response": "def sphere_analytical_gaussian_fast(dr, a, alpha=0.2765, cut=1.20):\n \"\"\"\n See sphere_analytical_gaussian_trim, but implemented in C with\n fast erf and exp approximations found at\n Abramowitz and Stegun: Handbook of Mathematical Functions\n A Fast, Compact Approximation of the Exponential Function\n\n The default cut 1.25 was chosen based on the accuracy of fast_erf\n \"\"\"\n\n code = \"\"\"\n double coeff1 = 1.0/(alpha*sqrt(2.0));\n double coeff2 = sqrt(0.5/pi)*alpha;\n\n for (int i=0; i -cut){\n double t = -dri*coeff1;\n ans[i] = 0.5*(1+fast_erf(t)) - coeff2/(dri+a+1e-10) * fast_exp(-t*t);\n } else {\n ans[i] = 0.0*(dri > cut) + 1.0*(dri < -cut);\n }\n }\n \"\"\"\n\n shape = r.shape\n r = r.flatten()\n N = self.N\n ans = r*0\n pi = np.pi\n\n inline(code, arg_names=['dr', 'a', 'alpha', 'cut', 'ans', 'pi', 'N'],\n support_code=functions, verbose=0)\n return ans.reshape(shape)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning the surface of a cubic interpolant constrained to be a sphere.", "response": "def sphere_constrained_cubic(dr, a, alpha):\n \"\"\"\n Sphere generated by a cubic interpolant constrained to be (1,0) on\n (r0-sqrt(3)/2, r0+sqrt(3)/2), the size of the cube in the (111) direction.\n \"\"\"\n sqrt3 = np.sqrt(3)\n\n b_coeff = a*0.5/sqrt3*(1 - 0.6*sqrt3*alpha)/(0.15 + a*a)\n rscl = np.clip(dr, -0.5*sqrt3, 0.5*sqrt3)\n\n a, d = rscl + 0.5*sqrt3, rscl - 0.5*sqrt3\n return alpha*d*a*rscl + b_coeff*d*a - d/sqrt3"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nperforms an iterative method to calculate the effective sphere that conserves volume.", "response": "def exact_volume_sphere(rvec, pos, radius, zscale=1.0, volume_error=1e-5,\n function=sphere_analytical_gaussian, max_radius_change=1e-2, args=()):\n \"\"\"\n Perform an iterative method to calculate the effective sphere that perfectly\n (up to the volume_error) conserves volume. Return the resulting image\n \"\"\"\n vol_goal = 4./3*np.pi*radius**3 / zscale\n rprime = radius\n\n dr = inner(rvec, pos, rprime, zscale=zscale)\n t = function(dr, rprime, *args)\n for i in range(MAX_VOLUME_ITERATIONS):\n vol_curr = np.abs(t.sum())\n if np.abs(vol_goal - vol_curr)/vol_goal < volume_error:\n break\n\n rprime = rprime + 1.0*(vol_goal - vol_curr) / (4*np.pi*rprime**2)\n\n if np.abs(rprime - radius)/radius > max_radius_change:\n break\n\n dr = inner(rvec, pos, rprime, zscale=zscale)\n t = function(dr, rprime, *args)\n\n return t"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nget the update tile surrounding particle n", "response": "def _tile(self, n):\n \"\"\"Get the update tile surrounding particle `n` \"\"\"\n pos = self._trans(self.pos[n])\n return Tile(pos, pos).pad(self.support_pad)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _p2i(self, param):\n g = param.split('-')\n if len(g) == 3:\n return g[2], int(g[1])\n else:\n raise ValueError('`param` passed as incorrect format')", "response": "Convert parameter to indices returns coord index"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ninitializing all objects and draw particles", "response": "def initialize(self):\n \"\"\"Start from scratch and initialize all objects / draw self.particles\"\"\"\n self.particles = np.zeros(self.shape.shape, dtype=self.float_precision)\n\n for p0, arg0 in zip(self.pos, self._drawargs()):\n self._draw_particle(p0, *listify(arg0))"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _vps(self, inds):\n return [j for j in inds if j >= 0 and j < self.N]", "response": "Clips a list of inds to be on [ 0 self. N )"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ntranslate index info to parameter name", "response": "def _i2p(self, ind, coord):\n \"\"\" Translate index info to parameter name \"\"\"\n return '-'.join([self.param_prefix, str(ind), coord])"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nget the amount of support size required for a particular update.", "response": "def get_update_tile(self, params, values):\n \"\"\" Get the amount of support size required for a particular update.\"\"\"\n doglobal, particles = self._update_type(params)\n if doglobal:\n return self.shape.copy()\n\n # 1) store the current parameters of interest\n values0 = self.get_values(params)\n # 2) calculate the current tileset\n tiles0 = [self._tile(n) for n in particles]\n\n # 3) update to newer parameters and calculate tileset\n self.set_values(params, values)\n tiles1 = [self._tile(n) for n in particles]\n\n # 4) revert parameters & return union of all tiles\n self.set_values(params, values0)\n return Tile.boundingtile(tiles0 + tiles1)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nupdating the particles field given new parameter values", "response": "def update(self, params, values):\n \"\"\"\n Update the particles field given new parameter values\n \"\"\"\n #1. Figure out if we're going to do a global update, in which\n # case we just draw from scratch.\n global_update, particles = self._update_type(params)\n\n # if we are doing a global update, everything must change, so\n # starting fresh will be faster instead of add subtract\n if global_update:\n self.set_values(params, values)\n self.initialize()\n return\n\n # otherwise, update individual particles. delete the current versions\n # of the particles update the particles, and redraw them anew at the\n # places given by (params, values)\n oldargs = self._drawargs()\n for n in particles:\n self._draw_particle(self.pos[n], *listify(oldargs[n]), sign=-1)\n\n self.set_values(params, values)\n\n newargs = self._drawargs()\n for n in particles:\n self._draw_particle(self.pos[n], *listify(newargs[n]), sign=+1)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngetting position and radius of one or more particles", "response": "def param_particle(self, ind):\n \"\"\" Get position and radius of one or more particles \"\"\"\n ind = self._vps(listify(ind))\n return [self._i2p(i, j) for i in ind for j in ['z', 'y', 'x', 'a']]"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef param_particle_pos(self, ind):\n ind = self._vps(listify(ind))\n return [self._i2p(i, j) for i in ind for j in ['z', 'y', 'x']]", "response": "Get position of one or more particles"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef param_particle_rad(self, ind):\n ind = self._vps(listify(ind))\n return [self._i2p(i, 'a') for i in ind]", "response": "Get radius of one or more particles"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef add_particle(self, pos, rad):\n rad = listify(rad)\n # add some zero mass particles to the list (same as not having these\n # particles in the image, which is true at this moment)\n inds = np.arange(self.N, self.N+len(rad))\n self.pos = np.vstack([self.pos, pos])\n self.rad = np.hstack([self.rad, np.zeros(len(rad))])\n\n # update the parameters globally\n self.setup_variables()\n self.trigger_parameter_change()\n\n # now request a drawing of the particle plz\n params = self.param_particle_rad(inds)\n self.trigger_update(params, rad)\n return inds", "response": "Add a particle or list of particles given by a list of positions and radii."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef remove_particle(self, inds):\n if self.rad.shape[0] == 0:\n return\n\n inds = listify(inds)\n\n # Here's the game plan:\n # 1. get all positions and sizes of particles that we will be\n # removing (to return to user)\n # 2. redraw those particles to 0.0 radius\n # 3. remove the particles and trigger changes\n # However, there is an issue -- if there are two particles at opposite\n # ends of the image, it will be significantly slower than usual\n pos = self.pos[inds].copy()\n rad = self.rad[inds].copy()\n\n self.trigger_update(self.param_particle_rad(inds), np.zeros(len(inds)))\n\n self.pos = np.delete(self.pos, inds, axis=0)\n self.rad = np.delete(self.rad, inds, axis=0)\n\n # update the parameters globally\n self.setup_variables()\n self.trigger_parameter_change()\n return np.array(pos).reshape(-1,3), np.array(rad).reshape(-1)", "response": "Removes the particle at the given indices. Returns the positions and radius of the particle at the given indices."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _update_type(self, params):\n dozscale = False\n particles = []\n for p in listify(params):\n typ, ind = self._p2i(p)\n particles.append(ind)\n dozscale = dozscale or typ == 'zscale'\n particles = set(particles)\n return dozscale, particles", "response": "Returns the dozscale and particle list of update"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _tile(self, n):\n zsc = np.array([1.0/self.zscale, 1, 1])\n pos, rad = self.pos[n], self.rad[n]\n pos = self._trans(pos)\n return Tile(pos - zsc*rad, pos + zsc*rad).pad(self.support_pad)", "response": "Get the tile surrounding particle n"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef update(self, params, values):\n # radparams = self.param_radii()\n params = listify(params)\n values = listify(values)\n for i, p in enumerate(params):\n # if (p in radparams) & (values[i] < 0):\n if (p[-2:] == '-a') and (values[i] < 0):\n values[i] = 0.0\n super(PlatonicSpheresCollection, self).update(params, values)", "response": "Calls an update but clips radii to be > 0"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef rmatrix(self):\n t = self.param_dict[self.lbl_theta]\n r0 = np.array([ [np.cos(t), -np.sin(t), 0],\n [np.sin(t), np.cos(t), 0],\n [0, 0, 1]])\n\n p = self.param_dict[self.lbl_phi]\n r1 = np.array([ [np.cos(p), 0, np.sin(p)],\n [0, 1, 0],\n [-np.sin(p), 0, np.cos(p)]])\n return np.dot(r1, r0)", "response": "Generate the composite rotation matrix that rotates the slab normal."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef j2(x):\n to_return = 2./(x+1e-15)*j1(x) - j0(x)\n to_return[x==0] = 0\n return to_return", "response": "A fast j2 function that returns the value of x."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef calc_pts_hg(npts=20):\n pts_hg, wts_hg = np.polynomial.hermite.hermgauss(npts*2)\n pts_hg = pts_hg[npts:]\n wts_hg = wts_hg[npts:] * np.exp(pts_hg*pts_hg)\n return pts_hg, wts_hg", "response": "Calculates the quadrature points for even functions"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef calc_pts_lag(npts=20):\n scl = { 15:0.072144,\n 20:0.051532,\n 25:0.043266}[npts]\n pts0, wts0 = np.polynomial.laguerre.laggauss(npts)\n pts = np.sinh(pts0*scl)\n wts = scl*wts0*np.cosh(pts0*scl)*np.exp(pts0)\n return pts, wts", "response": "Calculates Gauss - Laguerre quadrature points rescaled for a single line scan."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn the wavefront distortion due to z at a given cos_theta and z.", "response": "def f_theta(cos_theta, zint, z, n2n1=0.95, sph6_ab=None, **kwargs):\n \"\"\"\n Returns the wavefront aberration for an aberrated, defocused lens.\n\n Calculates the portions of the wavefront distortion due to z, theta\n only, for a lens with defocus and spherical aberration induced by\n coverslip mismatch. (The rho portion can be analytically integrated\n to Bessels.)\n\n Parameters\n ----------\n cos_theta : numpy.ndarray.\n The N values of cos(theta) at which to compute f_theta.\n zint : Float\n The position of the lens relative to the interface.\n z : numpy.ndarray\n The M z-values to compute f_theta at. `z.size` is unrelated\n to `cos_theta.size`\n n2n1: Float, optional\n The ratio of the index of the immersed medium to the optics.\n Default is 0.95\n sph6_ab : Float or None, optional\n Set sph6_ab to a nonzero value to add residual 6th-order\n spherical aberration that is proportional to sph6_ab. Default\n is None (i.e. doesn't calculate).\n\n Returns\n -------\n wvfront : numpy.ndarray\n The aberrated wavefront, as a function of theta and z.\n Shape is [z.size, cos_theta.size]\n \"\"\"\n wvfront = (np.outer(np.ones_like(z)*zint, cos_theta) -\n np.outer(zint+z, csqrt(n2n1**2-1+cos_theta**2)))\n if (sph6_ab is not None) and (not np.isnan(sph6_ab)):\n sec2_theta = 1.0/(cos_theta*cos_theta)\n wvfront += sph6_ab * (sec2_theta-1)*(sec2_theta-2)*cos_theta\n #Ensuring evanescent waves are always suppressed:\n if wvfront.dtype == np.dtype('complex128'):\n wvfront.imag = -np.abs(wvfront.imag)\n return wvfront"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_Kprefactor(z, cos_theta, zint=100.0, n2n1=0.95, get_hdet=False,\n **kwargs):\n \"\"\"\n Returns a prefactor in the electric field integral.\n\n This is an internal function called by get_K. The returned prefactor\n in the integrand is independent of which integral is being called;\n it is a combination of the exp(1j*phase) and apodization.\n\n Parameters\n ----------\n z : numpy.ndarray\n The values of z (distance along optical axis) at which to\n calculate the prefactor. Size is unrelated to the size of\n `cos_theta`\n cos_theta : numpy.ndarray\n The values of cos(theta) (i.e. position on the incoming\n focal spherical wavefront) at which to calculate the\n prefactor. Size is unrelated to the size of `z`\n zint : Float, optional\n The position of the optical interface, in units of 1/k.\n Default is 100.\n n2n1 : Float, optional\n The ratio of the index mismatch between the optics (n1) and\n the sample (n2). Default is 0.95\n get_hdet : Bool, optional\n Set to True to calculate the detection prefactor vs the\n illumination prefactor (i.e. False to include apodization).\n Default is False\n\n Returns\n -------\n numpy.ndarray\n The prefactor, of size [`z.size`, `cos_theta.size`], sampled\n at the values [`z`, `cos_theta`]\n \"\"\"\n phase = f_theta(cos_theta, zint, z, n2n1=n2n1, **kwargs)\n to_return = np.exp(-1j*phase)\n if not get_hdet:\n to_return *= np.outer(np.ones_like(z),np.sqrt(cos_theta))\n\n return to_return", "response": "Calculates the prefactor of the illumination for the given order of the electric field."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncalculating the symmetric and asymmetric portions of a confocal PSF.", "response": "def get_hsym_asym(rho, z, get_hdet=False, include_K3_det=True, **kwargs):\n \"\"\"\n Calculates the symmetric and asymmetric portions of a confocal PSF.\n\n Parameters\n ----------\n rho : numpy.ndarray\n Rho in cylindrical coordinates, in units of 1/k.\n z : numpy.ndarray\n Z in cylindrical coordinates, in units of 1/k. Must be the\n same shape as `rho`\n get_hdet : Bool, optional\n Set to True to get the detection portion of the psf; False\n to get the illumination portion of the psf. Default is True\n include_K3_det : Bool, optional.\n Flag to not calculate the `K3' component for the detection\n PSF, corresponding to (I think) a low-aperature focusing\n lens and no z-polarization of the focused light. Default\n is True, i.e. calculates the K3 component as if the focusing\n lens is high-aperture\n\n Other Parameters\n ----------------\n alpha : Float, optional\n The acceptance angle of the lens, on (0,pi/2). Default is 1.\n zint : Float, optional\n The distance of the len's unaberrated focal point from the\n optical interface, in units of 1/k. Default is 100.\n n2n1 : Float, optional\n The ratio n2/n1 of the index mismatch between the sample\n (index n2) and the optical train (index n1). Must be on\n [0,inf) but should be near 1. Default is 0.95\n\n Returns\n -------\n hsym : numpy.ndarray\n `rho`.shape numpy.array of the symmetric portion of the PSF\n hasym : numpy.ndarray\n `rho`.shape numpy.array of the asymmetric portion of the PSF\n \"\"\"\n\n K1, Kprefactor = get_K(rho, z, K=1, get_hdet=get_hdet, Kprefactor=None,\n return_Kprefactor=True, **kwargs)\n K2 = get_K(rho, z, K=2, get_hdet=get_hdet, Kprefactor=Kprefactor,\n return_Kprefactor=False, **kwargs)\n\n if get_hdet and not include_K3_det:\n K3 = 0*K1\n else:\n K3 = get_K(rho, z, K=3, get_hdet=get_hdet, Kprefactor=Kprefactor,\n return_Kprefactor=False, **kwargs)\n\n hsym = K1*K1.conj() + K2*K2.conj() + 0.5*(K3*K3.conj())\n hasym= K1*K2.conj() + K2*K1.conj() + 0.5*(K3*K3.conj())\n\n return hsym.real, hasym.real"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncalculating the perfect - pinhole PSF for a set of points x y z.", "response": "def calculate_pinhole_psf(x, y, z, kfki=0.89, zint=100.0, normalize=False,\n **kwargs):\n \"\"\"\n Calculates the perfect-pinhole PSF, for a set of points (x,y,z).\n\n Parameters\n -----------\n x : numpy.ndarray\n The x-coordinate of the PSF in units of 1/ the wavevector of\n the incoming light.\n y : numpy.ndarray\n The y-coordinate.\n z : numpy.ndarray\n The z-coordinate.\n kfki : Float\n The (scalar) ratio of wavevectors of the outgoing light to the\n incoming light. Default is 0.89.\n zint : Float\n The (scalar) distance from the interface, in units of\n 1/k_incoming. Default is 100.0\n normalize : Bool\n Set to True to normalize the psf correctly, accounting for\n intensity variations with depth. This will give a psf that does\n not sum to 1.\n\n Other Parameters\n ----------------\n alpha : Float\n The opening angle of the lens. Default is 1.\n n2n1 : Float\n The ratio of the index in the 2nd medium to that in the first.\n Default is 0.95\n\n Returns\n -------\n psf : numpy.ndarray, of shape x.shape\n\n Comments\n --------\n (1) The PSF is not necessarily centered on the z=0 pixel, since the\n calculation includes the shift.\n\n (2) If you want z-varying illumination of the psf then set\n normalize=True. This does the normalization by doing:\n hsym, hasym /= hsym.sum()\n hdet /= hdet.sum()\n and then calculating the psf that way. So if you want the\n intensity to be correct you need to use a large-ish array of\n roughly equally spaced points. Or do it manually by calling\n get_hsym_asym()\n \"\"\"\n rho = np.sqrt(x**2 + y**2)\n phi = np.arctan2(y, x)\n\n hsym, hasym = get_hsym_asym(rho, z, zint=zint, get_hdet=False, **kwargs)\n hdet, toss = get_hsym_asym(rho*kfki, z*kfki, zint=kfki*zint, get_hdet=True, **kwargs)\n\n if normalize:\n hasym /= hsym.sum()\n hsym /= hsym.sum()\n hdet /= hdet.sum()\n\n return (hsym + np.cos(2*phi)*hasym)*hdet"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncalculate a set of points and weights for a set of polydisp outgoing wavevectors.", "response": "def get_polydisp_pts_wts(kfki, sigkf, dist_type='gaussian', nkpts=3):\n \"\"\"\n Calculates a set of Gauss quadrature points & weights for polydisperse\n light.\n\n Returns a list of points and weights of the final wavevector's distri-\n bution, in units of the initial wavevector.\n\n Parameters\n ----------\n kfki : Float\n The mean of the polydisperse outgoing wavevectors.\n sigkf : Float\n The standard dev. of the polydisperse outgoing wavevectors.\n dist_type : {`gaussian`, `gamma`}, optional\n The distribution, gaussian or gamma, of the wavevectors.\n Default is `gaussian`\n nkpts : Int, optional\n The number of quadrature points to use. Default is 3\n Returns\n -------\n kfkipts : numpy.ndarray\n The Gauss quadrature points at which to calculate kfki.\n wts : numpy.ndarray\n The associated Gauss quadrature weights.\n \"\"\"\n if dist_type.lower() == 'gaussian':\n pts, wts = np.polynomial.hermite.hermgauss(nkpts)\n kfkipts = np.abs(kfki + sigkf*np.sqrt(2)*pts)\n elif dist_type.lower() == 'laguerre' or dist_type.lower() == 'gamma':\n k_scale = sigkf**2/kfki\n associated_order = kfki**2/sigkf**2 - 1\n #Associated Laguerre with alpha >~170 becomes numerically unstable, so:\n max_order=150\n if associated_order > max_order or associated_order < (-1+1e-3):\n warnings.warn('Numerically unstable sigk, clipping', RuntimeWarning)\n associated_order = np.clip(associated_order, -1+1e-3, max_order)\n kfkipts, wts = la_roots(nkpts, associated_order)\n kfkipts *= k_scale\n else:\n raise ValueError('dist_type must be either gaussian or laguerre')\n return kfkipts, wts/wts.sum()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncalculate the PSF for a set of points x y z.", "response": "def calculate_polychrome_pinhole_psf(x, y, z, normalize=False, kfki=0.889,\n sigkf=0.1, zint=100., nkpts=3, dist_type='gaussian', **kwargs):\n \"\"\"\n Calculates the perfect-pinhole PSF, for a set of points (x,y,z).\n\n Parameters\n -----------\n x : numpy.ndarray\n The x-coordinate of the PSF in units of 1/ the wavevector of\n the incoming light.\n y : numpy.ndarray\n The y-coordinate.\n z : numpy.ndarray\n The z-coordinate.\n kfki : Float\n The mean ratio of the outgoing light's wavevector to the incoming\n light's. Default is 0.89.\n sigkf : Float\n Standard deviation of kfki; the distribution of the light values\n will be approximately kfki +- sigkf.\n zint : Float\n The (scalar) distance from the interface, in units of\n 1/k_incoming. Default is 100.0\n dist_type: The distribution type of the polychromatic light.\n Can be one of 'laguerre'/'gamma' or 'gaussian.' If 'gaussian'\n the resulting k-values are taken in absolute value. Default\n is 'gaussian.'\n normalize : Bool\n Set to True to normalize the psf correctly, accounting for\n intensity variations with depth. This will give a psf that does\n not sum to 1. Default is False.\n\n Other Parameters\n ----------------\n alpha : Float\n The opening angle of the lens. Default is 1.\n n2n1 : Float\n The ratio of the index in the 2nd medium to that in the first.\n Default is 0.95\n\n Returns\n -------\n psf : numpy.ndarray, of shape x.shape\n\n Comments\n --------\n (1) The PSF is not necessarily centered on the z=0 pixel, since the\n calculation includes the shift.\n\n (2) If you want z-varying illumination of the psf then set\n normalize=True. This does the normalization by doing:\n hsym, hasym /= hsym.sum()\n hdet /= hdet.sum()\n and then calculating the psf that way. So if you want the\n intensity to be correct you need to use a large-ish array of\n roughly equally spaced points. Or do it manually by calling\n get_hsym_asym()\n \"\"\"\n #0. Setup\n kfkipts, wts = get_polydisp_pts_wts(kfki, sigkf, dist_type=dist_type,\n nkpts=nkpts)\n rho = np.sqrt(x**2 + y**2)\n phi = np.arctan2(y, x)\n\n #1. Hilm\n hsym, hasym = get_hsym_asym(rho, z, zint=zint, get_hdet=False, **kwargs)\n hilm = (hsym + np.cos(2*phi)*hasym)\n\n #2. Hdet\n hdet_func = lambda kfki: get_hsym_asym(rho*kfki, z*kfki,\n zint=kfki*zint, get_hdet=True, **kwargs)[0]\n inner = [wts[a] * hdet_func(kfkipts[a]) for a in range(nkpts)]\n hdet = np.sum(inner, axis=0)\n\n #3. Normalize and return\n if normalize:\n hilm /= hilm.sum()\n hdet /= hdet.sum()\n psf = hdet * hilm\n return psf if normalize else psf / psf.sum()"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_psf_scalar(x, y, z, kfki=1., zint=100.0, normalize=False, **kwargs):\n\n rho = np.sqrt(x**2 + y**2)\n phi = np.arctan2(y, x)\n\n K1 = get_K(rho, z, K=1,zint=zint,get_hdet=True, **kwargs)\n hilm = np.real( K1*K1.conj() )\n\n if np.abs(kfki - 1.0) > 1e-13:\n Kdet = get_K(rho*kfki, z*kfki, K=1, zint=zint*kfki, get_hdet=True,\n **kwargs)\n hdet = np.real( Kdet*Kdet.conj() )\n else:\n hdet = hilm.copy()\n\n if normalize:\n hilm /= hsym.sum()\n hdet /= hdet.sum()\n psf = hilm * hdet\n else:\n psf = hilm * hdet\n # psf /= psf.sum()\n\n return psf", "response": "Calculates the scalar PSF of a specific entry in the system."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncalculating the illumination PSF for a line - scanning confocal with the illuminating light.", "response": "def calculate_linescan_ilm_psf(y,z, polar_angle=0., nlpts=1,\n pinhole_width=1, use_laggauss=False, **kwargs):\n \"\"\"\n Calculates the illumination PSF for a line-scanning confocal with the\n confocal line oriented along the x direction.\n\n Parameters\n ----------\n y : numpy.ndarray\n The y points (in-plane, perpendicular to the line direction)\n at which to evaluate the illumination PSF, in units of 1/k.\n Arbitrary shape.\n z : numpy.ndarray\n The z points (optical axis) at which to evaluate the illum-\n ination PSF, in units of 1/k. Must be the same shape as `y`\n polar_angle : Float, optional\n The angle of the illuminating light's polarization with\n respect to the line's orientation along x. Default is 0.\n pinhole_width : Float, optional\n The width of the geometric image of the line projected onto\n the sample, in units of 1/k. Default is 1. The perfect line\n image is assumed to be a Gaussian. If `nlpts` is set to 1,\n the line will always be of zero width.\n nlpts : Int, optional\n The number of points to use for Hermite-gauss quadrature over\n the line's width. Default is 1, corresponding to a zero-width\n line.\n use_laggauss : Bool, optional\n Set to True to use a more-accurate sinh'd Laguerre-Gauss\n quadrature for integration over the line's length (more accurate\n in the same amount of time). Default is False for backwards\n compatibility. FIXME what did we do here?\n\n Other Parameters\n ----------------\n alpha : Float, optional\n The acceptance angle of the lens, on (0,pi/2). Default is 1.\n zint : Float, optional\n The distance of the len's unaberrated focal point from the\n optical interface, in units of 1/k. Default is 100.\n n2n1 : Float, optional\n The ratio n2/n1 of the index mismatch between the sample\n (index n2) and the optical train (index n1). Must be on\n [0,inf) but should be near 1. Default is 0.95\n\n Returns\n -------\n hilm : numpy.ndarray\n The line illumination, of the same shape as y and z.\n \"\"\"\n if use_laggauss:\n x_vals, wts = calc_pts_lag()\n else:\n x_vals, wts = calc_pts_hg()\n\n #I'm assuming that y,z are already some sort of meshgrid\n xg, yg, zg = [np.zeros( list(y.shape) + [x_vals.size] ) for a in range(3)]\n hilm = np.zeros(xg.shape)\n\n for a in range(x_vals.size):\n xg[...,a] = x_vals[a]\n yg[...,a] = y.copy()\n zg[...,a] = z.copy()\n\n y_pinhole, wts_pinhole = np.polynomial.hermite.hermgauss(nlpts)\n y_pinhole *= np.sqrt(2)*pinhole_width\n wts_pinhole /= np.sqrt(np.pi)\n\n #Pinhole hermgauss first:\n for yp, wp in zip(y_pinhole, wts_pinhole):\n rho = np.sqrt(xg*xg + (yg-yp)*(yg-yp))\n phi = np.arctan2(yg,xg)\n\n hsym, hasym = get_hsym_asym(rho,zg,get_hdet = False, **kwargs)\n hilm += wp*(hsym + np.cos(2*(phi-polar_angle))*hasym)\n\n #Now line hermgauss\n for a in range(x_vals.size):\n hilm[...,a] *= wts[a]\n\n return hilm.sum(axis=-1)*2."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef calculate_linescan_psf(x, y, z, normalize=False, kfki=0.889, zint=100.,\n polar_angle=0., wrap=True, **kwargs):\n \"\"\"\n Calculates the point spread function of a line-scanning confocal.\n\n Make x,y,z __1D__ numpy.arrays, with x the direction along the\n scan line. (to make the calculation faster since I dont' need the line\n ilm for each x).\n\n Parameters\n ----------\n x : numpy.ndarray\n _One_dimensional_ array of the x grid points (along the line\n illumination) at which to evaluate the psf. In units of\n 1/k_incoming.\n y : numpy.ndarray\n _One_dimensional_ array of the y grid points (in plane,\n perpendicular to the line illumination) at which to evaluate\n the psf. In units of 1/k_incoming.\n z : numpy.ndarray\n _One_dimensional_ array of the z grid points (along the\n optical axis) at which to evaluate the psf. In units of\n 1/k_incoming.\n normalize : Bool, optional\n Set to True to include the effects of PSF normalization on\n the image intensity. Default is False.\n kfki : Float, optional\n The ratio of the final light's wavevector to the incoming.\n Default is 0.889\n zint : Float, optional\n The position of the optical interface, in units of 1/k_incoming\n Default is 100.\n wrap : Bool, optional\n If True, wraps the psf calculation for speed, assuming that\n the input x, y are regularly-spaced points. If x,y are not\n regularly spaced then `wrap` must be set to False. Default is True.\n polar_angle : Float, optional\n The polarization angle of the light (radians) with respect to\n the line direction (x). Default is 0.\n\n Other Parameters\n ----------------\n alpha : Float\n The opening angle of the lens. Default is 1.\n n2n1 : Float\n The ratio of the index in the 2nd medium to that in the first.\n Default is 0.95\n\n Returns\n -------\n numpy.ndarray\n A 3D- numpy.array of the point-spread function. Indexing is\n psf[x,y,z]; shape is [x.size, y,size, z.size]\n \"\"\"\n\n #0. Set up vecs\n if wrap:\n xpts = vec_to_halfvec(x)\n ypts = vec_to_halfvec(y)\n x3, y3, z3 = np.meshgrid(xpts, ypts, z, indexing='ij')\n else:\n x3,y3,z3 = np.meshgrid(x, y, z, indexing='ij')\n rho3 = np.sqrt(x3*x3 + y3*y3)\n\n #1. Hilm\n if wrap:\n y2,z2 = np.meshgrid(ypts, z, indexing='ij')\n hilm0 = calculate_linescan_ilm_psf(y2, z2, zint=zint,\n polar_angle=polar_angle, **kwargs)\n if ypts[0] == 0:\n hilm = np.append(hilm0[-1:0:-1], hilm0, axis=0)\n else:\n hilm = np.append(hilm0[::-1], hilm0, axis=0)\n else:\n y2,z2 = np.meshgrid(y, z, indexing='ij')\n hilm = calculate_linescan_ilm_psf(y2, z2, zint=zint,\n polar_angle=polar_angle, **kwargs)\n\n #2. Hdet\n if wrap:\n #Lambda function that ignores its args but still returns correct values\n func = lambda *args: get_hsym_asym(rho3*kfki, z3*kfki, zint=kfki*zint,\n get_hdet=True, **kwargs)[0]\n hdet = wrap_and_calc_psf(xpts, ypts, z, func)\n else:\n hdet, toss = get_hsym_asym(rho3*kfki, z3*kfki, zint=kfki*zint,\n get_hdet=True, **kwargs)\n\n if normalize:\n hilm /= hilm.sum()\n hdet /= hdet.sum()\n\n for a in range(x.size):\n hdet[a] *= hilm\n\n return hdet if normalize else hdet / hdet.sum()", "response": "Calculates the point spread function of a line - scanning confocal."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef calculate_polychrome_linescan_psf(x, y, z, normalize=False, kfki=0.889,\n sigkf=0.1, zint=100., nkpts=3, dist_type='gaussian', wrap=True,\n **kwargs):\n \"\"\"\n Calculates the point spread function of a line-scanning confocal with\n polydisperse dye emission.\n\n Make x,y,z __1D__ numpy.arrays, with x the direction along the\n scan line. (to make the calculation faster since I dont' need the line\n ilm for each x).\n\n Parameters\n ----------\n x : numpy.ndarray\n _One_dimensional_ array of the x grid points (along the line\n illumination) at which to evaluate the psf. In units of\n 1/k_incoming.\n y : numpy.ndarray\n _One_dimensional_ array of the y grid points (in plane,\n perpendicular to the line illumination) at which to evaluate\n the psf. In units of 1/k_incoming.\n z : numpy.ndarray\n _One_dimensional_ array of the z grid points (along the\n optical axis) at which to evaluate the psf. In units of\n 1/k_incoming.\n normalize : Bool, optional\n Set to True to include the effects of PSF normalization on\n the image intensity. Default is False.\n kfki : Float, optional\n The mean of the ratio of the final light's wavevector to the\n incoming. Default is 0.889\n sigkf : Float, optional\n The standard deviation of the ratio of the final light's\n wavevector to the incoming. Default is 0.1\n zint : Float, optional\n The position of the optical interface, in units of 1/k_incoming\n Default is 100.\n dist_type : {`gaussian`, `gamma`}, optional\n The distribution of the outgoing light. If 'gaussian' the\n resulting k-values are taken in absolute value. Default\n is `gaussian`\n wrap : Bool, optional\n If True, wraps the psf calculation for speed, assuming that\n the input x, y are regularly-spaced points. If x,y are not\n regularly spaced then `wrap` must be set to False. Default is True.\n\n Other Parameters\n ----------------\n polar_angle : Float, optional\n The polarization angle of the light (radians) with respect to\n the line direction (x). Default is 0.\n alpha : Float\n The opening angle of the lens. Default is 1.\n n2n1 : Float\n The ratio of the index in the 2nd medium to that in the first.\n Default is 0.95\n\n Returns\n -------\n numpy.ndarray\n A 3D- numpy.array of the point-spread function. Indexing is\n psf[x,y,z]; shape is [x.size, y,size, z.size]\n Notes\n -----\n Neither distribution type is perfect. If sigkf/k0 is big (>0.5ish)\n then part of the Gaussian is negative. To avoid issues an abs() is\n taken, but then the actual mean and variance are not what is\n supplied. Conversely, if sigkf/k0 is small (<0.0815), then the\n requisite associated Laguerre quadrature becomes unstable. To\n prevent this sigkf/k0 is effectively clipped to be > 0.0815.\n \"\"\"\n kfkipts, wts = get_polydisp_pts_wts(kfki, sigkf, dist_type=dist_type,\n nkpts=nkpts)\n\n #0. Set up vecs\n if wrap:\n xpts = vec_to_halfvec(x)\n ypts = vec_to_halfvec(y)\n x3, y3, z3 = np.meshgrid(xpts, ypts, z, indexing='ij')\n else:\n x3,y3,z3 = np.meshgrid(x, y, z, indexing='ij')\n rho3 = np.sqrt(x3*x3 + y3*y3)\n\n #1. Hilm\n if wrap:\n y2,z2 = np.meshgrid(ypts, z, indexing='ij')\n hilm0 = calculate_linescan_ilm_psf(y2, z2, zint=zint, **kwargs)\n if ypts[0] == 0:\n hilm = np.append(hilm0[-1:0:-1], hilm0, axis=0)\n else:\n hilm = np.append(hilm0[::-1], hilm0, axis=0)\n else:\n y2,z2 = np.meshgrid(y, z, indexing='ij')\n hilm = calculate_linescan_ilm_psf(y2, z2, zint=zint, **kwargs)\n\n #2. Hdet\n if wrap:\n #Lambda function that ignores its args but still returns correct values\n func = lambda x,y,z, kfki=1.: get_hsym_asym(rho3*kfki, z3*kfki,\n zint=kfki*zint, get_hdet=True, **kwargs)[0]\n hdet_func = lambda kfki: wrap_and_calc_psf(xpts,ypts,z, func, kfki=kfki)\n else:\n hdet_func = lambda kfki: get_hsym_asym(rho3*kfki, z3*kfki,\n zint=kfki*zint, get_hdet=True, **kwargs)[0]\n #####\n inner = [wts[a] * hdet_func(kfkipts[a]) for a in range(nkpts)]\n hdet = np.sum(inner, axis=0)\n\n if normalize:\n hilm /= hilm.sum()\n hdet /= hdet.sum()\n for a in range(x.size):\n hdet[a] *= hilm\n\n return hdet if normalize else hdet / hdet.sum()", "response": "Calculates the point spread function of a line - scanning confocal with a poly - chrome line - scanning confocal with a single line - scanning system."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nwrap a point - spread function in x and y and z and return a numpy array of the wrapped and calculated psf.", "response": "def wrap_and_calc_psf(xpts, ypts, zpts, func, **kwargs):\n \"\"\"\n Wraps a point-spread function in x and y.\n\n Speeds up psf calculations by a factor of 4 for free / some broadcasting\n by exploiting the x->-x, y->-y symmetry of a psf function. Pass x and y\n as the positive (say) values of the coordinates at which to evaluate func,\n and it will return the function sampled at [x[::-1]] + x. Note it is not\n wrapped in z.\n\n Parameters\n ----------\n xpts : numpy.ndarray\n 1D N-element numpy.array of the x-points to evaluate func at.\n ypts : numpy.ndarray\n y-points to evaluate func at.\n zpts : numpy.ndarray\n z-points to evaluate func at.\n func : function\n The function to evaluate and wrap around. Syntax must be\n func(x,y,z, **kwargs)\n **kwargs : Any parameters passed to the function.\n\n Outputs\n -------\n to_return : numpy.ndarray\n The wrapped and calculated psf, of shape\n [2*x.size - x0, 2*y.size - y0, z.size], where x0=1 if x[0]=0, etc.\n\n Notes\n -----\n The coordinates should be something like numpy.arange(start, stop, diff),\n with start near 0. If x[0]==0, all of x is calcualted but only x[1:]\n is wrapped (i.e. it works whether or not x[0]=0).\n\n This doesn't work directly for a linescan psf because the illumination\n portion is not like a grid. However, the illumination and detection\n are already combined with wrap_and_calc in calculate_linescan_psf etc.\n \"\"\"\n #1. Checking that everything is hunky-dory:\n for t in [xpts,ypts,zpts]:\n if len(t.shape) != 1:\n raise ValueError('xpts,ypts,zpts must be 1D.')\n\n dx = 1 if xpts[0]==0 else 0\n dy = 1 if ypts[0]==0 else 0\n\n xg,yg,zg = np.meshgrid(xpts,ypts,zpts, indexing='ij')\n xs, ys, zs = [ pts.size for pts in [xpts,ypts,zpts] ]\n to_return = np.zeros([2*xs-dx, 2*ys-dy, zs])\n\n #2. Calculate:\n up_corner_psf = func(xg,yg,zg, **kwargs)\n\n to_return[xs-dx:,ys-dy:,:] = up_corner_psf.copy() #x>0, y>0\n if dx == 0:\n to_return[:xs-dx,ys-dy:,:] = up_corner_psf[::-1,:,:].copy() #x<0, y>0\n else:\n to_return[:xs-dx,ys-dy:,:] = up_corner_psf[-1:0:-1,:,:].copy() #x<0, y>0\n if dy == 0:\n to_return[xs-dx:,:ys-dy,:] = up_corner_psf[:,::-1,:].copy() #x>0, y<0\n else:\n to_return[xs-dx:,:ys-dy,:] = up_corner_psf[:,-1:0:-1,:].copy() #x>0, y<0\n if (dx == 0) and (dy == 0):\n to_return[:xs-dx,:ys-dy,:] = up_corner_psf[::-1,::-1,:].copy() #x<0,y<0\n elif (dx == 0) and (dy != 0):\n to_return[:xs-dx,:ys-dy,:] = up_corner_psf[::-1,-1:0:-1,:].copy() #x<0,y<0\n elif (dy == 0) and (dx != 0):\n to_return[:xs-dx,:ys-dy,:] = up_corner_psf[-1:0:-1,::-1,:].copy() #x<0,y<0\n else: #dx==1 and dy==1\n to_return[:xs-dx,:ys-dy,:] = up_corner_psf[-1:0:-1,-1:0:-1,:].copy()#x<0,y<0\n\n return to_return"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ntransforms a vector np. arange - N M dx to np. arange - N M dx", "response": "def vec_to_halfvec(vec):\n \"\"\"Transforms a vector np.arange(-N, M, dx) to np.arange(min(|vec|), max(N,M),dx)]\"\"\"\n d = vec[1:] - vec[:-1]\n if ((d/d.mean()).std() > 1e-14) or (d.mean() < 0):\n raise ValueError('vec must be np.arange() in increasing order')\n dx = d.mean()\n lowest = np.abs(vec).min()\n highest = np.abs(vec).max()\n return np.arange(lowest, highest + 0.1*dx, dx).astype(vec.dtype)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nconverting a scalar a to a list and all iterables to list as well.", "response": "def listify(a):\n \"\"\"\n Convert a scalar ``a`` to a list and all iterables to list as well.\n\n Examples\n --------\n >>> listify(0)\n [0]\n\n >>> listify([1,2,3])\n [1, 2, 3]\n\n >>> listify('a')\n ['a']\n\n >>> listify(np.array([1,2,3]))\n [1, 2, 3]\n\n >>> listify('string')\n ['string']\n \"\"\"\n if a is None:\n return []\n elif not isinstance(a, (tuple, list, np.ndarray)):\n return [a]\n return list(a)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn a list of objects that are not in a single element list.", "response": "def delistify(a, b=None):\n \"\"\"\n If a single element list, extract the element as an object, otherwise\n leave as it is.\n\n Examples\n --------\n >>> delistify('string')\n 'string'\n\n >>> delistify(['string'])\n 'string'\n\n >>> delistify(['string', 'other'])\n ['string', 'other']\n\n >>> delistify(np.array([1.0]))\n 1.0\n\n >>> delistify([1, 2, 3])\n [1, 2, 3]\n \"\"\"\n if isinstance(b, (tuple, list, np.ndarray)):\n if isinstance(a, (tuple, list, np.ndarray)):\n return type(b)(a)\n return type(b)([a])\n else:\n if isinstance(a, (tuple, list, np.ndarray)) and len(a) == 1:\n return a[0]\n return a\n return a"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef aN(a, dim=3, dtype='int'):\n if not hasattr(a, '__iter__'):\n return np.array([a]*dim, dtype=dtype)\n return np.array(a).astype(dtype)", "response": "Convert an integer or iterable list to numpy array of length dim."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef cdd(d, k):\n if not isinstance(k, list):\n k = [k]\n for i in k:\n if i in d:\n d.pop(i)", "response": "Conditionally delete key or list of keys from dict d"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef patch_docs(subclass, superclass):\n funcs0 = inspect.getmembers(subclass, predicate=inspect.ismethod)\n funcs1 = inspect.getmembers(superclass, predicate=inspect.ismethod)\n\n funcs1 = [f[0] for f in funcs1]\n\n for name, func in funcs0:\n if name.startswith('_'):\n continue\n\n if name not in funcs1:\n continue\n\n if func.__doc__ is None:\n func = getattr(subclass, name)\n func.__func__.__doc__ = getattr(superclass, name).__func__.__doc__", "response": "Apply the documentation from subclass to superclass by filling the documentation from all overridden member function docstrings with those from the\n parent class\n "}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef indir(path):\n cwd = os.getcwd()\n\n try:\n os.chdir(path)\n yield\n except Exception as e:\n raise\n finally:\n os.chdir(cwd)", "response": "Context manager for switching the current path of the process."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\narrays slicer object for this tile", "response": "def slicer(self):\n \"\"\"\n Array slicer object for this tile\n\n >>> Tile((2,3)).slicer\n (slice(0, 2, None), slice(0, 3, None))\n\n >>> np.arange(10)[Tile((4,)).slicer]\n array([0, 1, 2, 3])\n \"\"\"\n return tuple(np.s_[l:r] for l,r in zip(*self.bounds))"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef oslicer(self, tile):\n mask = None\n vecs = tile.coords(form='meshed')\n for v in vecs:\n v[self.slicer] = -1\n mask = mask & (v > 0) if mask is not None else (v>0)\n return tuple(np.array(i).astype('int') for i in zip(*[v[mask] for v in vecs]))", "response": "Opposite slicer the outer part wrt to a field"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef kcenter(self):\n return np.array([\n np.abs(np.fft.fftshift(np.fft.fftfreq(q))).argmin()\n for q in self.shape\n ]).astype('float')", "response": "Return the frequency center of the tile"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef corners(self):\n corners = []\n for ind in itertools.product(*((0,1),)*self.dim):\n ind = np.array(ind)\n corners.append(self.l + ind*self.r)\n return np.array(corners)", "response": "Iterate the vector of all corners of the hyperrectangles"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nformats a 3d vector field in certain ways see coords for a description of each formatting method.", "response": "def _format_vector(self, vecs, form='broadcast'):\n \"\"\"\n Format a 3d vector field in certain ways, see `coords` for a description\n of each formatting method.\n \"\"\"\n if form == 'meshed':\n return np.meshgrid(*vecs, indexing='ij')\n elif form == 'vector':\n vecs = np.meshgrid(*vecs, indexing='ij')\n return np.rollaxis(np.array(np.broadcast_arrays(*vecs)),0,self.dim+1)\n elif form == 'flat':\n return vecs\n else:\n return [v[self._coord_slicers[i]] for i,v in enumerate(vecs)]"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef coords(self, norm=False, form='broadcast'):\n if norm is False:\n norm = 1\n if norm is True:\n norm = np.array(self.shape)\n norm = aN(norm, self.dim, dtype='float')\n\n v = list(np.arange(self.l[i], self.r[i]) / norm[i] for i in range(self.dim))\n return self._format_vector(v, form=form)", "response": "Returns the coordinates of the tile."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef kvectors(self, norm=False, form='broadcast', real=False, shift=False):\n if norm is False:\n norm = 1\n if norm is True:\n norm = np.array(self.shape)\n norm = aN(norm, self.dim, dtype='float')\n\n v = list(np.fft.fftfreq(self.shape[i])/norm[i] for i in range(self.dim))\n\n if shift:\n v = list(np.fft.fftshift(t) for t in v)\n\n if real:\n v[-1] = v[-1][:(self.shape[-1]+1)//2]\n\n return self._format_vector(v, form=form)", "response": "Return the kvectors associated with this tile."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef contains(self, items, pad=0):\n o = ((items >= self.l-pad) & (items < self.r+pad))\n if len(o.shape) == 2:\n o = o.all(axis=-1)\n elif len(o.shape) == 1:\n o = o.all()\n return o", "response": "Test whether the given items are contained within this tile."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ntranslating a tile by an amount dr", "response": "def translate(self, dr):\n \"\"\"\n Translate a tile by an amount dr\n\n >>> Tile(5).translate(1)\n Tile [1, 1, 1] -> [6, 6, 6] ([5, 5, 5])\n \"\"\"\n tile = self.copy()\n tile.l += dr\n tile.r += dr\n return tile"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\npadding this tile by an equal amount on each side as specified by pad", "response": "def pad(self, pad):\n \"\"\"\n Pad this tile by an equal amount on each side as specified by pad\n\n >>> Tile(10).pad(2)\n Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14])\n\n >>> Tile(10).pad([1,2,3])\n Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16])\n \"\"\"\n tile = self.copy()\n tile.l -= pad\n tile.r += pad\n return tile"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef overhang(self, tile):\n ll = np.abs(amin(self.l - tile.l, aN(0, dim=self.dim)))\n rr = np.abs(amax(self.r - tile.r, aN(0, dim=self.dim)))\n return ll, rr", "response": "Get the left and right absolute overflow of a given tile"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef reflect_overhang(self, clip):\n orig = self.copy()\n tile = self.copy()\n\n hangl, hangr = tile.overhang(clip)\n tile = tile.pad(hangl)\n tile = tile.pad(hangr)\n\n inner = Tile.intersection([clip, orig])\n outer = Tile.intersection([clip, tile])\n return inner, outer", "response": "Compute the overhang and reflect it internally so respect periodic\n padding rules. Returns both the inner tile and the outer tile with necessary pad."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning a filtered image after applying the Fourier - space filters", "response": "def filtered_image(self, im):\n \"\"\"Returns a filtered image after applying the Fourier-space filters\"\"\"\n q = np.fft.fftn(im)\n for k,v in self.filters:\n q[k] -= v\n return np.real(np.fft.ifftn(q))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef set_filter(self, slices, values):\n self.filters = [[sl,values[sl]] for sl in slices]", "response": "Sets the Fourier - space filters for the image."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nloads the image from the file and perform any transforms to get a loaded image", "response": "def load_image(self):\n \"\"\" Read the file and perform any transforms to get a loaded image \"\"\"\n try:\n image = initializers.load_tiff(self.filename)\n image = initializers.normalize(\n image, invert=self.invert, scale=self.exposure,\n dtype=self.float_precision\n )\n except IOError as e:\n log.error(\"Could not find image '%s'\" % self.filename)\n raise e\n\n return image"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns the minimum and maximum of the image in this object.", "response": "def get_scale(self):\n \"\"\"\n If exposure was not set in the __init__, get the exposure associated\n with this RawImage so that it may be used in other\n :class:`~peri.util.RawImage`. This is useful for transferring exposure\n parameters to a series of images.\n\n Returns\n -------\n exposure : tuple of floats\n The (emin, emax) which get mapped to (0, 1)\n \"\"\"\n if self.exposure is not None:\n return self.exposure\n\n raw = initializers.load_tiff(self.filename)\n return raw.min(), raw.max()"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_scale_from_raw(raw, scaled):\n t0, t1 = scaled.min(), scaled.max()\n r0, r1 = float(raw.min()), float(raw.max())\n\n rmin = (t1*r0 - t0*r1) / (t1 - t0)\n rmax = (r1 - r0) / (t1 - t0) + rmin\n return (rmin, rmax)", "response": "This function takes a raw image and a scaled version of the same image and returns the exposure parameters associated with those images."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef update(self, value=0):\n self._deltas.append(time.time())\n\n self.value = value\n self._percent = 100.0 * self.value / self.num\n\n if self.bar:\n self._bars = self._bar_symbol*int(np.round(self._percent / 100. * self._barsize))\n\n if (len(self._deltas) < 2) or (self._deltas[-1] - self._deltas[-2]) > 1e-1:\n self._estimate_time()\n self._draw()\n\n if self.value == self.num:\n self.end()", "response": "Update the value of the progress and update the progress bar."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nchecks that the modelstr and varmap are consistent across the many components.", "response": "def check_consistency(self):\n \"\"\"\n Make sure that the required comps are included in the list of\n components supplied by the user. Also check that the parameters are\n consistent across the many components.\n \"\"\"\n error = False\n regex = re.compile('([a-zA-Z_][a-zA-Z0-9_]*)')\n\n # there at least must be the full model, not necessarily partial updates\n if 'full' not in self.modelstr:\n raise ModelError(\n 'Model must contain a `full` key describing '\n 'the entire image formation'\n )\n\n # Check that the two model descriptors are consistent\n for name, eq in iteritems(self.modelstr):\n var = regex.findall(eq)\n for v in var:\n # remove the derivative signs if there (dP -> P)\n v = re.sub(r\"^d\", '', v)\n if v not in self.varmap:\n log.error(\n \"Variable '%s' (eq. '%s': '%s') not found in category map %r\" %\n (v, name, eq, self.varmap)\n )\n error = True\n\n if error:\n raise ModelError('Inconsistent varmap and modelstr descriptions')"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef check_inputs(self, comps):\n error = False\n compcats = [c.category for c in comps]\n\n # Check that the components are all provided, given the categories\n for k, v in iteritems(self.varmap):\n if k not in self.modelstr['full']:\n log.warn('Component (%s : %s) not used in model.' % (k,v))\n\n if v not in compcats:\n log.error('Map component (%s : %s) not found in list of components.' % (k,v))\n error = True\n\n if error:\n raise ModelError('Component list incomplete or incorrect')", "response": "Check that the list of components comp is compatible with both the varmap and modelstr for this Model\n "}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngets the model corresponding to a variation wrt a category. For example is H + B.", "response": "def get_difference_model(self, category):\n \"\"\"\n Get the equation corresponding to a variation wrt category. For example\n if::\n\n modelstr = {\n 'full' :'H(I) + B',\n 'dH' : 'dH(I)',\n 'dI' : 'H(dI)',\n 'dB' : 'dB'\n }\n\n varmap = {'H': 'psf', 'I': 'obj', 'B': 'bkg'}\n\n then ``get_difference_model('obj') == modelstr['dI'] == 'H(dI)'``\n \"\"\"\n name = self.diffname(self.ivarmap[category])\n return self.modelstr.get(name)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nmapping component function funcname result into model variables dictionary for use in eval of the model.", "response": "def map_vars(self, comps, funcname='get', diffmap=None, **kwargs):\n \"\"\"\n Map component function ``funcname`` result into model variables\n dictionary for use in eval of the model. If ``diffmap`` is provided then\n that symbol is translated into 'd'+diffmap.key and is replaced by\n diffmap.value. ``**kwargs` are passed to the ``comp.funcname(**kwargs)``.\n \"\"\"\n out = {}\n diffmap = diffmap or {}\n\n for c in comps:\n cat = c.category\n\n if cat in diffmap:\n symbol = self.diffname(self.ivarmap[cat])\n out[symbol] = diffmap[cat]\n else:\n symbol = self.ivarmap[cat]\n out[symbol] = getattr(c, funcname)(**kwargs)\n\n return out"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef evaluate(self, comps, funcname='get', diffmap=None, **kwargs):\n evar = self.map_vars(comps, funcname, diffmap=diffmap)\n\n if diffmap is None:\n return eval(self.get_base_model(), evar)\n else:\n compname = list(diffmap.keys())[0]\n return eval(self.get_difference_model(compname), evar)", "response": "Evaluate the model of a set of components and return the output of a model."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef lbl(axis, label, size=22):\n at = AnchoredText(label, loc=2, prop=dict(size=size), frameon=True)\n at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.0\")\n #bb = axis.get_yaxis_transform()\n #at = AnchoredText(label,\n # loc=3, prop=dict(size=18), frameon=True,\n # bbox_to_anchor=(-0.5,1),#(-.255, 0.90),\n # bbox_transform=bb,#axis.transAxes\n # )\n axis.add_artist(at)", "response": "Put a figure label in an axis"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef generative_model(s,x,y,z,r, factor=1.1):\n pl.close('all')\n\n slicez = int(round(z.mean()))\n slicex = s.image.shape[2]//2\n slicer1 = np.s_[slicez,s.pad:-s.pad,s.pad:-s.pad]\n slicer2 = np.s_[s.pad:-s.pad,s.pad:-s.pad,slicex]\n center = (slicez, s.image.shape[1]//2, slicex)\n\n fig = pl.figure(figsize=(factor*13,factor*10))\n\n #=========================================================================\n #=========================================================================\n gs1 = ImageGrid(fig, rect=[0.0, 0.6, 1.0, 0.35], nrows_ncols=(1,3),\n axes_pad=0.1)\n ax_real = gs1[0]\n ax_fake = gs1[1]\n ax_diff = gs1[2]\n\n diff = s.get_model_image() - s.image\n ax_real.imshow(s.image[slicer1], cmap=pl.cm.bone_r)\n ax_real.set_xticks([])\n ax_real.set_yticks([])\n ax_real.set_title(\"Confocal image\", fontsize=24)\n ax_fake.imshow(s.get_model_image()[slicer1], cmap=pl.cm.bone_r)\n ax_fake.set_xticks([])\n ax_fake.set_yticks([])\n ax_fake.set_title(\"Model image\", fontsize=24)\n ax_diff.imshow(diff[slicer1], cmap=pl.cm.RdBu, vmin=-0.1, vmax=0.1)\n ax_diff.set_xticks([])\n ax_diff.set_yticks([])\n ax_diff.set_title(\"Difference\", fontsize=24)\n\n #=========================================================================\n #=========================================================================\n gs2 = ImageGrid(fig, rect=[0.1, 0.0, 0.4, 0.55], nrows_ncols=(3,2),\n axes_pad=0.1)\n ax_plt1 = fig.add_subplot(gs2[0])\n ax_plt2 = fig.add_subplot(gs2[1])\n ax_ilm1 = fig.add_subplot(gs2[2])\n ax_ilm2 = fig.add_subplot(gs2[3])\n ax_psf1 = fig.add_subplot(gs2[4])\n ax_psf2 = fig.add_subplot(gs2[5])\n\n c = int(z.mean()), int(y.mean())+s.pad, int(x.mean())+s.pad\n if s.image.shape[0] > 2*s.image.shape[1]//3:\n w = s.image.shape[2] - 2*s.pad\n h = 2*w//3\n else:\n h = s.image.shape[0] - 2*s.pad\n w = 3*h//2\n\n w,h = w//2, h//2\n xyslice = np.s_[slicez, c[1]-h:c[1]+h, c[2]-w:c[2]+w]\n yzslice = np.s_[c[0]-h:c[0]+h, c[1]-w:c[1]+w, slicex]\n\n #h = s.image.shape[2]/2 - s.image.shape[0]/2\n #slicer2 = np.s_[s.pad:-s.pad, s.pad:-s.pad, slicex]\n #slicer3 = np.s_[slicez, s.pad+h:-s.pad-h, s.pad:-s.pad]\n\n ax_plt1.imshow(1-s.obj.get_field()[xyslice], cmap=pl.cm.bone_r, vmin=0, vmax=1)\n ax_plt1.set_xticks([])\n ax_plt1.set_yticks([])\n ax_plt1.set_ylabel(\"Platonic\", fontsize=22)\n ax_plt1.set_title(\"x-y\", fontsize=24)\n ax_plt2.imshow(1-s._platonic_image()[yzslice], cmap=pl.cm.bone_r, vmin=0, vmax=1)\n ax_plt2.set_xticks([])\n ax_plt2.set_yticks([])\n ax_plt2.set_title(\"y-z\", fontsize=24)\n\n ax_ilm1.imshow(s.ilm.get_field()[xyslice], cmap=pl.cm.bone_r)\n ax_ilm1.set_xticks([])\n ax_ilm1.set_yticks([])\n ax_ilm1.set_ylabel(\"ILM\", fontsize=22)\n ax_ilm2.imshow(s.ilm.get_field()[yzslice], cmap=pl.cm.bone_r)\n ax_ilm2.set_xticks([])\n ax_ilm2.set_yticks([])\n\n t = s.ilm.get_field().copy()\n t *= 0\n t[c] = 1\n s.psf.set_tile(util.Tile(t.shape))\n psf = (s.psf.execute(t)+5e-5)**0.1\n\n ax_psf1.imshow(psf[xyslice], cmap=pl.cm.bone)\n ax_psf1.set_xticks([])\n ax_psf1.set_yticks([])\n ax_psf1.set_ylabel(\"PSF\", fontsize=22)\n ax_psf2.imshow(psf[yzslice], cmap=pl.cm.bone)\n ax_psf2.set_xticks([])\n ax_psf2.set_yticks([])\n\n #=========================================================================\n #=========================================================================\n ax_zoom = fig.add_axes([0.48, 0.018, 0.45, 0.52])\n\n #s.model_to_true_image()\n im = s.image[slicer1]\n sh = np.array(im.shape)\n cx = x.mean()\n cy = y.mean()\n\n extent = [0,sh[0],0,sh[1]]\n ax_zoom.set_xticks([])\n ax_zoom.set_yticks([])\n ax_zoom.imshow(im, extent=extent, cmap=pl.cm.bone_r)\n ax_zoom.set_xlim(cx-12, cx+12)\n ax_zoom.set_ylim(cy-12, cy+12)\n ax_zoom.set_title(\"Sampled positions\", fontsize=24)\n ax_zoom.hexbin(x,y, gridsize=32, mincnt=0, cmap=pl.cm.hot)\n\n zoom1 = zoomed_inset_axes(ax_zoom, 30, loc=3)\n zoom1.imshow(im, extent=extent, cmap=pl.cm.bone_r)\n zoom1.set_xlim(cx-1.0/6, cx+1.0/6)\n zoom1.set_ylim(cy-1.0/6, cy+1.0/6)\n zoom1.hexbin(x,y,gridsize=32, mincnt=5, cmap=pl.cm.hot)\n zoom1.set_xticks([])\n zoom1.set_yticks([])\n zoom1.hlines(cy-1.0/6 + 1.0/32, cx-1.0/6+5e-2, cx-1.0/6+5e-2+1e-1, lw=3)\n zoom1.text(cx-1.0/6 + 1.0/24, cy-1.0/6+5e-2, '0.1px')\n mark_inset(ax_zoom, zoom1, loc1=2, loc2=4, fc=\"none\", ec=\"0.0\")", "response": "Generate a model for the state s."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef examine_unexplained_noise(state, bins=1000, xlim=(-10,10)):\n r = state.residuals\n q = np.fft.fftn(r)\n #Get the expected values of `sigma`:\n calc_sig = lambda x: np.sqrt(np.dot(x,x) / x.size)\n rh, xr = np.histogram(r.ravel() / calc_sig(r.ravel()), bins=bins,\n density=True)\n bigq = np.append(q.real.ravel(), q.imag.ravel())\n qh, xq = np.histogram(bigq / calc_sig(q.real.ravel()), bins=bins,\n density=True)\n xr = 0.5*(xr[1:] + xr[:-1])\n xq = 0.5*(xq[1:] + xq[:-1])\n\n gauss = lambda t : np.exp(-t*t*0.5) / np.sqrt(2*np.pi)\n\n plt.figure(figsize=[16,8])\n axes = []\n for a, (x, r, lbl) in enumerate([[xr, rh, 'Real'], [xq, qh, 'Fourier']]):\n ax = plt.subplot(1,2,a+1)\n ax.semilogy(x, r, label='Data')\n ax.plot(x, gauss(x), label='Gauss Fit', scalex=False, scaley=False)\n ax.set_xlabel('Residuals value $r/\\sigma$')\n ax.set_ylabel('Probability $P(r/\\sigma)$')\n ax.legend(loc='upper right')\n ax.set_title('{}-Space'.format(lbl))\n ax.set_xlim(xlim)\n axes.append(ax)\n return axes", "response": "Examines a state s residuals in real and Fourier space with a Gaussian."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef compare_data_model_residuals(s, tile, data_vmin='calc', data_vmax='calc',\n res_vmin=-0.1, res_vmax=0.1, edgepts='calc', do_imshow=True,\n data_cmap=plt.cm.bone, res_cmap=plt.cm.RdBu):\n \"\"\"\n Compare the data, model, and residuals of a state.\n\n Makes an image of any 2D slice of a state that compares the data,\n model, and residuals. The upper left portion of the image is the raw\n data, the central portion the model, and the lower right portion the\n image. Either plots the image using plt.imshow() or returns a\n np.ndarray of the image pixels for later use.\n\n Parameters\n ----------\n st : peri.ImageState object\n The state to plot.\n tile : peri.util.Tile object\n The slice of the image to plot. Can be any xy, xz, or yz\n projection, but it must return a valid 2D slice (the slice is\n squeezed internally).\n\n data_vmin : {Float, `calc`}, optional\n vmin for the imshow for the data and generative model (shared).\n Default is 'calc' = 0.5(data.min() + model.min())\n data_vmax : {Float, `calc`}, optional\n vmax for the imshow for the data and generative model (shared).\n Default is 'calc' = 0.5(data.max() + model.max())\n res_vmin : Float, optional\n vmin for the imshow for the residuals. Default is -0.1\n Default is 'calc' = 0.5(data.min() + model.min())\n res_vmax : Float, optional\n vmax for the imshow for the residuals. Default is +0.1\n edgepts : {Nested list-like, Float, 'calc'}, optional.\n The vertices of the triangles which determine the splitting of\n the image. The vertices are at (image corner, (edge, y), and\n (x,edge), where edge is the appropriate edge of the image.\n edgepts[0] : (x,y) points for the upper edge\n edgepts[1] : (x,y) points for the lower edge\n where `x` is the coordinate along the image's 0th axis and `y`\n along the images 1st axis. Default is 'calc,' which calculates\n edge points by splitting the image into 3 regions of equal\n area. If edgepts is a float scalar, calculates the edge points\n based on a constant fraction of distance from the edge.\n do_imshow : Bool\n If True, imshow's and returns the returned handle.\n If False, returns the array as a [M,N,4] array.\n data_cmap : matplotlib colormap instance\n The colormap to use for the data and model.\n res_cmap : matplotlib colormap instance\n The colormap to use for the residuals.\n\n Returns\n -------\n image : {matplotlib.pyplot.AxesImage, numpy.ndarray}\n If `do_imshow` == True, the returned handle from imshow.\n If `do_imshow` == False, an [M,N,4] np.ndarray of the image\n pixels.\n \"\"\"\n # This could be modified to alpha the borderline... or to embiggen\n # the image and slice it more finely\n residuals = s.residuals[tile.slicer].squeeze()\n data = s.data[tile.slicer].squeeze()\n model = s.model[tile.slicer].squeeze()\n if data.ndim != 2:\n raise ValueError('tile does not give a 2D slice')\n\n im = np.zeros([data.shape[0], data.shape[1], 4])\n if data_vmin == 'calc':\n data_vmin = 0.5*(data.min() + model.min())\n if data_vmax == 'calc':\n data_vmax = 0.5*(data.max() + model.max())\n\n #1. Get masks:\n upper_mask, center_mask, lower_mask = trisect_image(im.shape, edgepts)\n\n #2. Get colorbar'd images\n gm = data_cmap(center_data(model, data_vmin, data_vmax))\n dt = data_cmap(center_data(data, data_vmin, data_vmax))\n rs = res_cmap(center_data(residuals, res_vmin, res_vmax))\n\n for a in range(4):\n im[:,:,a][upper_mask] = rs[:,:,a][upper_mask]\n im[:,:,a][center_mask] = gm[:,:,a][center_mask]\n im[:,:,a][lower_mask] = dt[:,:,a][lower_mask]\n if do_imshow:\n return plt.imshow(im)\n else:\n return im", "response": "Compare the data model and residuals of a state."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ntrisects an image into 3 triangular portions.", "response": "def trisect_image(imshape, edgepts='calc'):\n \"\"\"\n Returns 3 masks that trisect an image into 3 triangular portions.\n\n Parameters\n ----------\n imshape : 2-element list-like of ints\n The shape of the image. Elements after the first 2 are ignored.\n\n edgepts : Nested list-like, float, or `calc`, optional.\n The vertices of the triangles which determine the splitting of\n the image. The vertices are at (image corner, (edge, y), and\n (x,edge), where edge is the appropriate edge of the image.\n edgepts[0] : (x,y) points for the upper edge\n edgepts[1] : (x,y) points for the lower edge\n where `x` is the coordinate along the image's 0th axis and `y`\n along the images 1st axis. Default is 'calc,' which calculates\n edge points by splitting the image into 3 regions of equal\n area. If edgepts is a float scalar, calculates the edge points\n based on a constant fraction of distance from the edge.\n\n Returns\n -------\n upper_mask : numpy.ndarray\n Boolean array; True in the image's upper region.\n center_mask : numpy.ndarray\n Boolean array; True in the image's center region.\n lower_mask : numpy.ndarray\n Boolean array; True in the image's lower region.\n \"\"\"\n im_x, im_y = np.meshgrid(np.arange(imshape[0]), np.arange(imshape[1]),\n indexing='ij')\n if np.size(edgepts) == 1:\n #Gets equal-area sections, at sqrt(2/3) of the sides\n f = np.sqrt(2./3.) if edgepts == 'calc' else edgepts\n # f = np.sqrt(2./3.)\n lower_edge = (imshape[0] * (1-f), imshape[1] * f)\n upper_edge = (imshape[0] * f, imshape[1] * (1-f))\n else:\n upper_edge, lower_edge = edgepts\n\n #1. Get masks\n lower_slope = lower_edge[1] / max(float(imshape[0] - lower_edge[0]), 1e-9)\n upper_slope = (imshape[1] - upper_edge[1]) / float(upper_edge[0])\n #and the edge points are the x or y intercepts\n lower_intercept = -lower_slope * lower_edge[0]\n upper_intercept = upper_edge[1]\n lower_mask = im_y < (im_x * lower_slope + lower_intercept)\n upper_mask = im_y > (im_x * upper_slope + upper_intercept)\n\n center_mask= -(lower_mask | upper_mask)\n return upper_mask, center_mask, lower_mask"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef center_data(data, vmin, vmax):\n ans = data - vmin\n ans /= (vmax - vmin)\n return np.clip(ans, 0, 1)", "response": "Clips data on vmin vmax then rescales to 1"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef crb_compare(state0, samples0, state1, samples1, crb0=None, crb1=None,\n zlayer=None, xlayer=None):\n \"\"\"\n To run, do:\n\n s,h = pickle...\n s1,h1 = pickle...\n i.e. /media/scratch/bamf/vacancy/vacancy_zoom-1.tif_t002.tif-featured-v2.pkl\n i.e. /media/scratch/bamf/frozen-particles/0.tif-featured-full.pkl\n crb0 = diag_crb_particles(s); crb1 = diag_crb_particles(s1)\n crb_compare(s,h[-25:],s1,h1[-25:], crb0, crb1)\n \"\"\"\n s0 = state0\n s1 = state1\n h0 = np.array(samples0)\n h1 = np.array(samples1)\n\n slicez = zlayer or s0.image.shape[0]//2\n slicex = xlayer or s0.image.shape[2]//2\n slicer1 = np.s_[slicez,s0.pad:-s0.pad,s0.pad:-s0.pad]\n slicer2 = np.s_[s0.pad:-s0.pad,s0.pad:-s0.pad,slicex]\n center = (slicez, s0.image.shape[1]//2, slicex)\n\n mu0 = h0.mean(axis=0)\n mu1 = h1.mean(axis=0)\n\n std0 = h0.std(axis=0)\n std1 = h1.std(axis=0)\n\n mask0 = (s0.state[s0.b_typ]==1.) & (\n analyze.trim_box(s0, mu0[s0.b_pos].reshape(-1,3)))\n mask1 = (s1.state[s1.b_typ]==1.) & (\n analyze.trim_box(s1, mu1[s1.b_pos].reshape(-1,3)))\n active0 = np.arange(s0.N)[mask0]#s0.state[s0.b_typ]==1.]\n active1 = np.arange(s1.N)[mask1]#s1.state[s1.b_typ]==1.]\n\n pos0 = mu0[s0.b_pos].reshape(-1,3)[active0]\n pos1 = mu1[s1.b_pos].reshape(-1,3)[active1]\n rad0 = mu0[s0.b_rad][active0]\n rad1 = mu1[s1.b_rad][active1]\n\n link = analyze.nearest(pos0, pos1)\n dpos = pos0 - pos1[link]\n drad = rad0 - rad1[link]\n\n drift = dpos.mean(axis=0)\n log.info('drift {}'.format(drift))\n\n dpos -= drift\n\n fig = pl.figure(figsize=(24,10))\n\n #=========================================================================\n #=========================================================================\n gs0 = ImageGrid(fig, rect=[0.02, 0.4, 0.4, 0.60], nrows_ncols=(2,3), axes_pad=0.1)\n\n lbl(gs0[0], 'A')\n for i,slicer in enumerate([slicer1, slicer2]):\n ax_real = gs0[3*i+0]\n ax_fake = gs0[3*i+1]\n ax_diff = gs0[3*i+2]\n\n diff0 = s0.get_model_image() - s0.image\n diff1 = s1.get_model_image() - s1.image\n a = (s0.image - s1.image)\n b = (s0.get_model_image() - s1.get_model_image())\n c = (diff0 - diff1)\n\n ptp = 0.7*max([np.abs(a).max(), np.abs(b).max(), np.abs(c).max()])\n cmap = pl.cm.RdBu_r\n ax_real.imshow(a[slicer], cmap=cmap, vmin=-ptp, vmax=ptp)\n ax_real.set_xticks([])\n ax_real.set_yticks([])\n ax_fake.imshow(b[slicer], cmap=cmap, vmin=-ptp, vmax=ptp)\n ax_fake.set_xticks([])\n ax_fake.set_yticks([])\n ax_diff.imshow(c[slicer], cmap=cmap, vmin=-ptp, vmax=ptp)#cmap=pl.cm.RdBu, vmin=-1.0, vmax=1.0)\n ax_diff.set_xticks([])\n ax_diff.set_yticks([])\n\n if i == 0:\n ax_real.set_title(r\"$\\Delta$ Confocal image\", fontsize=24)\n ax_fake.set_title(r\"$\\Delta$ Model image\", fontsize=24)\n ax_diff.set_title(r\"$\\Delta$ Difference\", fontsize=24)\n ax_real.set_ylabel('x-y')\n else:\n ax_real.set_ylabel('x-z')\n\n #=========================================================================\n #=========================================================================\n gs1 = GridSpec(1,3, left=0.05, bottom=0.125, right=0.42, top=0.37,\n wspace=0.15, hspace=0.05)\n\n spos0 = std0[s0.b_pos].reshape(-1,3)[active0]\n spos1 = std1[s1.b_pos].reshape(-1,3)[active1]\n srad0 = std0[s0.b_rad][active0]\n srad1 = std1[s1.b_rad][active1]\n\n def hist(ax, vals, bins, *args, **kwargs):\n y,x = np.histogram(vals, bins=bins)\n x = (x[1:] + x[:-1])/2\n y /= len(vals)\n ax.plot(x,y, *args, **kwargs)\n\n def pp(ind, tarr, tsim, tcrb, var='x'):\n bins = 10**np.linspace(-3, 0.0, 30)\n bin2 = 10**np.linspace(-3, 0.0, 100)\n bins = np.linspace(0.0, 0.2, 30)\n bin2 = np.linspace(0.0, 0.2, 100)\n xlim = (0.0, 0.12)\n #xlim = (1e-3, 1e0)\n ylim = (1e-2, 30)\n\n ticks = ticker.FuncFormatter(lambda x, pos: '{:0.0f}'.format(np.log10(x)))\n scaler = lambda x: x #np.log10(x)\n\n ax_crb = pl.subplot(gs1[0,ind])\n ax_crb.hist(scaler(np.abs(tarr)), bins=bins,\n normed=True, alpha=0.7, histtype='stepfilled', lw=1)\n ax_crb.hist(scaler(np.abs(tcrb)).ravel(), bins=bin2,\n normed=True, alpha=1.0, histtype='step', ls='solid', lw=1.5, color='k')\n ax_crb.hist(scaler(np.abs(tsim).ravel()), bins=bin2,\n normed=True, alpha=1.0, histtype='step', lw=3)\n ax_crb.set_xlabel(r\"$\\Delta = |%s(t_1) - %s(t_0)|$\" % (var,var), fontsize=24)\n #ax_crb.semilogx()\n ax_crb.set_xlim(xlim)\n #ax_crb.semilogy()\n #ax_crb.set_ylim(ylim)\n #ax_crb.xaxis.set_major_formatter(ticks)\n ax_crb.grid(b=False, which='both', axis='both')\n\n if ind == 0:\n lbl(ax_crb, 'B')\n ax_crb.set_ylabel(r\"$P(\\Delta)$\")\n else:\n ax_crb.set_yticks([])\n\n ax_crb.locator_params(axis='x', nbins=3)\n\n f,g = 1.5, 1.95\n sim = f*sim_crb_diff(spos0[:,1], spos1[:,1][link])\n crb = g*sim_crb_diff(crb0[0][:,1][active0], crb1[0][:,1][active1][link])\n pp(0, dpos[:,1], sim, crb, 'x')\n\n sim = f*sim_crb_diff(spos0[:,0], spos1[:,0][link])\n crb = g*sim_crb_diff(crb0[0][:,0][active0], crb1[0][:,0][active1][link])\n pp(1, dpos[:,0], sim, crb, 'z')\n\n sim = f*sim_crb_diff(srad0, srad1[link])\n crb = g*sim_crb_diff(crb0[1][active0], crb1[1][active1][link])\n pp(2, drad, sim, crb, 'a')\n\n #ax_crb_r.locator_params(axis='both', nbins=3)\n #gs1.tight_layout(fig)\n\n #=========================================================================\n #=========================================================================\n gs2 = GridSpec(2,2, left=0.48, bottom=0.12, right=0.99, top=0.95,\n wspace=0.35, hspace=0.35)\n\n ax_hist = pl.subplot(gs2[0,0])\n ax_hist.hist(std0[s0.b_pos], bins=np.logspace(-3.0, 0, 50), alpha=0.7, label='POS', histtype='stepfilled')\n ax_hist.hist(std0[s0.b_rad], bins=np.logspace(-3.0, 0, 50), alpha=0.7, label='RAD', histtype='stepfilled')\n ax_hist.set_xlim((10**-3.0, 1))\n ax_hist.semilogx()\n ax_hist.set_xlabel(r\"$\\bar{\\sigma}$\")\n ax_hist.set_ylabel(r\"$P(\\bar{\\sigma})$\")\n ax_hist.legend(loc='upper right')\n lbl(ax_hist, 'C')\n\n imdiff = ((s0.get_model_image() - s0.image)/s0._sigma_field)[s0.image_mask==1.].ravel()\n mu = imdiff.mean()\n #sig = imdiff.std()\n #print mu, sig\n x = np.linspace(-5,5,10000)\n\n ax_diff = pl.subplot(gs2[0,1])\n ax_diff.plot(x, 1.0/np.sqrt(2*np.pi) * np.exp(-(x-mu)**2 / 2), '-', alpha=0.7, color='k', lw=2)\n ax_diff.hist(imdiff, bins=1000, histtype='step', alpha=0.7, normed=True)\n ax_diff.semilogy()\n ax_diff.set_ylabel(r\"$P(\\delta)$\")\n ax_diff.set_xlabel(r\"$\\delta = (M_i - d_i)/\\sigma_i$\")\n ax_diff.locator_params(axis='x', nbins=5)\n ax_diff.grid(b=False, which='minor', axis='y')\n ax_diff.set_xlim(-5, 5)\n ax_diff.set_ylim(1e-4, 1e0)\n lbl(ax_diff, 'D')\n\n pos = mu0[s0.b_pos].reshape(-1,3)\n rad = mu0[s0.b_rad]\n mask = analyze.trim_box(s0, pos)\n pos = pos[mask]\n rad = rad[mask]\n\n gx, gy = analyze.gofr(pos, rad, mu0[s0.b_zscale][0], resolution=5e-2,mask_start=0.5)\n mask = gx < 5\n gx = gx[mask]\n gy = gy[mask]\n ax_gofr = pl.subplot(gs2[1,0])\n ax_gofr.plot(gx, gy, '-', lw=1)\n ax_gofr.set_xlabel(r\"$r/a$\")\n ax_gofr.set_ylabel(r\"$g(r/a)$\")\n ax_gofr.locator_params(axis='both', nbins=5)\n #ax_gofr.semilogy()\n lbl(ax_gofr, 'E')\n\n gx, gy = analyze.gofr(pos, rad, mu0[s0.b_zscale][0], method='surface')\n mask = gx < 5\n gx = gx[mask]\n gy = gy[mask]\n gy[gy <= 0.] = gy[gy>0].min()\n ax_gofrs = pl.subplot(gs2[1,1])\n ax_gofrs.plot(gx, gy, '-', lw=1)\n ax_gofrs.set_xlabel(r\"$r/a$\")\n ax_gofrs.set_ylabel(r\"$g_{\\rm{surface}}(r/a)$\")\n ax_gofrs.locator_params(axis='both', nbins=5)\n ax_gofrs.grid(b=False, which='minor', axis='y')\n #ax_gofrs.semilogy()\n lbl(ax_gofrs, 'F')\n\n ylim = ax_gofrs.get_ylim()\n ax_gofrs.set_ylim(gy.min(), ylim[1])", "response": "Compare two states and returns the crb of the two states."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nplots two parts of the ortho view the two sections of the ortho view.", "response": "def twoslice(field, center=None, size=6.0, cmap='bone_r', vmin=0, vmax=1,\n orientation='vertical', figpad=1.09, off=0.01):\n \"\"\"\n Plot two parts of the ortho view, the two sections given by ``orientation``.\n \"\"\"\n center = center or [i//2 for i in field.shape]\n slices = []\n for i,c in enumerate(center):\n blank = [np.s_[:]]*len(center)\n blank[i] = c\n slices.append(tuple(blank))\n\n z,y,x = [float(i) for i in field.shape]\n w = float(x + z)\n h = float(y + z)\n\n def show(field, ax, slicer, transpose=False):\n tmp = field[slicer] if not transpose else field[slicer].T\n ax.imshow(\n tmp, cmap=cmap, interpolation='nearest',\n vmin=vmin, vmax=vmax\n )\n ax.set_xticks([])\n ax.set_yticks([])\n ax.grid('off')\n\n if orientation.startswith('v'):\n # rect = l,b,w,h\n log.info('{} {} {} {} {} {}'.format(x, y, z, w, h, x/h))\n r = x/h\n q = y/h\n f = 1 / (1 + 3*off)\n fig = pl.figure(figsize=(size*r, size*f))\n ax1 = fig.add_axes((off, f*(1-q)+2*off, f, f*q))\n ax2 = fig.add_axes((off, off, f, f*(1-q)))\n\n show(field, ax1, slices[0])\n show(field, ax2, slices[1])\n else:\n # rect = l,b,w,h\n r = y/w\n q = x/w\n f = 1 / (1 + 3*off)\n fig = pl.figure(figsize=(size*f, size*r))\n ax1 = fig.add_axes((off, off, f*q, f))\n ax2 = fig.add_axes((2*off+f*q, off, f*(1-q), f))\n\n show(field, ax1, slices[0])\n show(field, ax2, slices[2], transpose=True)\n\n return fig, ax1, ax2"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef circles(st, layer, axis, ax=None, talpha=1.0, cedge='white', cface='white'):\n pos = st.obj_get_positions()\n rad = st.obj_get_radii()\n shape = st.ishape.shape.tolist()\n shape.pop(axis) #shape is now the shape of the image\n if ax is None:\n fig = plt.figure()\n axisbg = 'white' if cface == 'black' else 'black'\n sx, sy = ((1,shape[1]/float(shape[0])) if shape[0] > shape[1] else\n (shape[0]/float(shape[1]), 1))\n ax = fig.add_axes((0,0, sx, sy), axisbg=axisbg)\n # get the index of the particles we want to include\n particles = np.arange(len(pos))[np.abs(pos[:,axis] - layer) < rad]\n\n # for each of these particles display the effective radius\n # in the proper place\n scale = 1.0 #np.max(shape).astype('float')\n for i in particles:\n p = pos[i].copy()\n r = 2*np.sqrt(rad[i]**2 - (p[axis] - layer)**2)\n #CIRCLE IS IN FIGURE COORDINATES!!!\n if axis==0:\n ix = 1; iy = 2\n elif axis == 1:\n ix = 0; iy = 2\n elif axis==2:\n ix = 0; iy = 1\n c = Circle((p[ix]/scale, p[iy]/scale), radius=r/2/scale, fc=cface,\n ec=cedge, alpha=talpha)\n ax.add_patch(c)\n # plt.axis([0,1,0,1])\n plt.axis('equal') #circles not ellipses\n return ax", "response": "Returns a set of circles corresponding to a slice through the platonic\n structure."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ncreate a two particle state and compare it to featuring using a single particle guess", "response": "def missing_particle(separation=0.0, radius=RADIUS, SNR=20):\n \"\"\" create a two particle state and compare it to featuring using a single particle guess \"\"\"\n # create a base image of one particle\n s = init.create_two_particle_state(imsize=6*radius+4, axis='x', sigma=1.0/SNR,\n delta=separation, radius=radius, stateargs={'varyn': True}, psfargs={'error': 1e-6})\n s.obj.typ[1] = 0.\n s.reset()\n\n return s, s.obj.pos.copy()"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncalculating a random approximation to J by returning J only at the given indices.", "response": "def get_rand_Japprox(s, params, num_inds=1000, include_cost=False, **kwargs):\n \"\"\"\n Calculates a random approximation to J by returning J only at a\n set of random pixel/voxel locations.\n\n Parameters\n ----------\n s : :class:`peri.states.State`\n The state to calculate J for.\n params : List\n The list of parameter names to calculate the gradient of.\n num_inds : Int, optional.\n The number of pix/voxels at which to calculate the random\n approximation to J. Default is 1000.\n include_cost : Bool, optional\n Set to True to append a finite-difference measure of the full\n cost gradient onto the returned J.\n\n Other Parameters\n ----------------\n All kwargs parameters get passed to s.gradmodel only.\n\n Returns\n -------\n J : numpy.ndarray\n [d, num_inds] array of J, at the given indices.\n\n return_inds : numpy.ndarray or slice\n [num_inds] element array or slice(0, None) of the model\n indices at which J was evaluated.\n \"\"\"\n start_time = time.time()\n tot_pix = s.residuals.size\n if num_inds < tot_pix:\n inds = np.random.choice(tot_pix, size=num_inds, replace=False)\n slicer = None\n return_inds = np.sort(inds)\n else:\n inds = None\n return_inds = slice(0, None)\n slicer = [slice(0, None)]*len(s.residuals.shape)\n if include_cost:\n Jact, ge = s.gradmodel_e(params=params, inds=inds, slicer=slicer,flat=False,\n **kwargs)\n Jact *= -1\n J = [Jact, ge]\n else:\n J = -s.gradmodel(params=params, inds=inds, slicer=slicer, flat=False,\n **kwargs)\n CLOG.debug('J:\\t%f' % (time.time()-start_time))\n return J, return_inds"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn a list of the global parameter names of the state s.", "response": "def name_globals(s, remove_params=None):\n \"\"\"\n Returns a list of the global parameter names.\n\n Parameters\n ----------\n s : :class:`peri.states.ImageState`\n The state to name the globals of.\n remove_params : Set or None\n A set of unique additional parameters to remove from the globals\n list.\n\n Returns\n -------\n all_params : list\n The list of the global parameter names, with each of\n remove_params removed.\n \"\"\"\n all_params = s.params\n for p in s.param_particle(np.arange(s.obj_get_positions().shape[0])):\n all_params.remove(p)\n if remove_params is not None:\n for p in set(remove_params):\n all_params.remove(p)\n return all_params"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncalculate the number of pixels to use for a given state and parameters.", "response": "def get_num_px_jtj(s, nparams, decimate=1, max_mem=1e9, min_redundant=20):\n \"\"\"\n Calculates the number of pixels to use for J at a given memory usage.\n\n Tries to pick a number of pixels as (size of image / `decimate`).\n However, clips this to a maximum size and minimum size to ensure that\n (1) too much memory isn't used and (2) J has enough elements so that\n the inverse of JTJ will be well-conditioned.\n\n Parameters\n ----------\n s : :class:`peri.states.State`\n The state on which to calculate J.\n nparams : Int\n The number of parameters that will be included in J.\n decimate : Int, optional\n The amount to decimate the number of pixels in the image by,\n i.e. tries to pick num_px = size of image / decimate.\n Default is 1\n max_mem : Numeric, optional\n The maximum allowed memory, in bytes, for J to occupy at\n double-precision. Default is 1e9.\n min_redundant : Int, optional\n The number of pixels must be at least `min_redundant` *\n `nparams`. If not, an error is raised. Default is 20\n\n Returns\n -------\n num_px : Int\n The number of pixels at which to calcualte J.\n \"\"\"\n #1. Max for a given max_mem:\n px_mem = int(max_mem // 8 // nparams) #1 float = 8 bytes\n #2. num_pix for a given redundancy\n px_red = min_redundant*nparams\n #3. And # desired for decimation\n px_dec = s.residuals.size//decimate\n\n if px_red > px_mem:\n raise RuntimeError('Insufficient max_mem for desired redundancy.')\n num_px = np.clip(px_dec, px_red, px_mem).astype('int')\n return num_px"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef vectorize_damping(params, damping=1.0, increase_list=[['psf-', 1e4]]):\n damp_vec = np.ones(len(params)) * damping\n for nm, fctr in increase_list:\n for a in range(damp_vec.size):\n if nm in params[a]:\n damp_vec[a] *= fctr\n return damp_vec", "response": "Vectorizes the damping of a set of parameters."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef low_mem_sq(m, step=100000):\n if not m.flags.c_contiguous:\n raise ValueError('m must be C ordered for this to work with less mem.')\n # -- can make this even faster with pre-allocating arrays, but not worth it\n # right now\n # mmt = np.zeros([m.shape[0], m.shape[0]]) #6us\n # mt_tmp = np.zeros([step, m.shape[0]])\n # for a in range(0, m.shape[1], step):\n # mx = min(a+step, m.shape[1])\n # mt_tmp[:mx-a,:] = m.T[a:mx]\n # # np.dot(m_tmp, m.T, out=mmt[a:mx])\n # # np.dot(m, m[a:mx].T, out=mmt[:, a:mx])\n # np.dot(m[:,a:mx], mt_tmp[:mx], out=mmt)\n # return mmt\n mmt = np.zeros([m.shape[0], m.shape[0]]) #6us\n # m_tmp = np.zeros([step, m.shape[1]])\n for a in range(0, m.shape[0], step):\n mx = min(a+step, m.shape[1])\n # m_tmp[:] = m[a:mx]\n # np.dot(m_tmp, m.T, out=mmt[a:mx])\n mmt[:, a:mx] = np.dot(m, m[a:mx].T)\n return mmt", "response": "Compute the low mem vector for a given set of tables."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nfinding the particles in a tile as numpy. ndarray of ints.", "response": "def find_particles_in_tile(positions, tile):\n \"\"\"\n Finds the particles in a tile, as numpy.ndarray of ints.\n\n Parameters\n ----------\n positions : `numpy.ndarray`\n [N,3] array of the particle positions to check in the tile\n tile : :class:`peri.util.Tile` instance\n Tile of the region inside which to check for particles.\n\n Returns\n -------\n numpy.ndarray, int\n The indices of the particles in the tile.\n \"\"\"\n bools = tile.contains(positions)\n return np.arange(bools.size)[bools]"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef separate_particles_into_groups(s, region_size=40, bounds=None,\n doshift=False):\n \"\"\"\n Separates particles into convenient groups for optimization.\n\n Given a state, returns a list of groups of particles. Each group of\n particles are located near each other in the image. Every particle\n located in the desired region is contained in exactly 1 group.\n\n Parameters\n ----------\n s : :class:`peri.states.ImageState`\n The peri state to find particles in.\n region_size : Int or 3-element list-like of ints, optional\n The size of the box. Groups particles into boxes of shape\n (region_size[0], region_size[1], region_size[2]). If region_size\n is a scalar, the box is a cube of length region_size.\n Default is 40.\n bounds : 2-element list-like of 3-element lists, optional\n The sub-region of the image over which to look for particles.\n bounds[0]: The lower-left corner of the image region.\n bounds[1]: The upper-right corner of the image region.\n Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n image size, i.e. the default places every particle in the image\n somewhere in the groups.\n doshift : {True, False, `'rand'`}, optional\n Whether or not to shift the tile boxes by half a region size, to\n prevent the same particles to be chosen every time. If `'rand'`,\n randomly chooses either True or False. Default is False\n\n Returns\n -------\n particle_groups : List\n Each element of particle_groups is an int numpy.ndarray of the\n group of nearby particles. Only contains groups with a nonzero\n number of particles, so the elements don't necessarily correspond\n to a given image region.\n \"\"\"\n imtile = s.oshape.translate(-s.pad)\n bounding_tile = (imtile if bounds is None else Tile(bounds[0], bounds[1]))\n rs = (np.ones(bounding_tile.dim, dtype='int')*region_size if\n np.size(region_size) == 1 else np.array(region_size))\n\n n_translate = np.ceil(bounding_tile.shape.astype('float')/rs).astype('int')\n particle_groups = []\n tile = Tile(left=bounding_tile.l, right=bounding_tile.l + rs)\n if doshift == 'rand':\n doshift = np.random.choice([True, False])\n if doshift:\n shift = rs // 2\n n_translate += 1\n else:\n shift = 0\n deltas = np.meshgrid(*[np.arange(i) for i in n_translate])\n positions = s.obj_get_positions()\n if bounds is None:\n # FIXME this (deliberately) masks a problem where optimization\n # places particles outside the image. However, it ensures that\n # all particles are in at least one group when `bounds is None`,\n # which is the use case within opt. The 1e-3 is to ensure that\n # they are inside the box and not on the edge.\n positions = np.clip(positions, imtile.l+1e-3, imtile.r-1e-3)\n groups = list(map(lambda *args: find_particles_in_tile(positions,\n tile.translate( np.array(args) * rs - shift)), *[d.ravel()\n for d in deltas]))\n\n for i in range(len(groups)-1, -1, -1):\n if groups[i].size == 0:\n groups.pop(i)\n assert _check_groups(s, groups)\n return groups", "response": "Separates particles into convenient groups for optimization."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _check_groups(s, groups):\n ans = []\n for g in groups:\n ans.extend(g)\n if np.unique(ans).size != np.size(ans):\n return False\n elif np.unique(ans).size != s.obj_get_positions().shape[0]:\n return False\n else:\n return (np.arange(s.obj_get_radii().size) == np.sort(ans)).all()", "response": "Ensures that all particles in exactly 1 group are included in exactly 1 group"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncalculating the size of the region size of the particle group.", "response": "def calc_particle_group_region_size(s, region_size=40, max_mem=1e9, **kwargs):\n \"\"\"\n Finds the biggest region size for LM particle optimization with a\n given memory constraint.\n\n Input Parameters\n ----------------\n s : :class:`peri.states.ImageState`\n The state with the particles\n region_size : Int or 3-element list-like of ints, optional.\n The initial guess for the region size. Default is 40\n max_mem : Numeric, optional\n The maximum memory for the optimizer to take. Default is 1e9\n\n Other Parameters\n ----------------\n bounds: 2-element list-like of 3-element lists.\n The sub-region of the image over which to look for particles.\n bounds[0]: The lower-left corner of the image region.\n bounds[1]: The upper-right corner of the image region.\n Default (None -> ([0,0,0], s.oshape.shape)) is a box of the entire\n image size, i.e. the default places every particle in the image\n somewhere in the groups.\n Returns\n -------\n region_size : numpy.ndarray of ints of the region size.\n \"\"\"\n region_size = np.array(region_size).astype('int')\n\n def calc_mem_usage(region_size):\n rs = np.array(region_size)\n particle_groups = separate_particles_into_groups(s, region_size=\n rs.tolist(), **kwargs)\n # The actual mem usage is the max of the memory usage of all the\n # particle groups. However this is too slow. So instead we use the\n # max of the memory of the biggest 5 particle groups:\n numpart = [np.size(g) for g in particle_groups]\n biggroups = [particle_groups[i] for i in np.argsort(numpart)[-5:]]\n def get_tile_jsize(group):\n nms = s.param_particle(group)\n tile = s.get_update_io_tiles(nms, s.get_values(nms))[2]\n return tile.shape.prod() * len(nms)\n mems = [8*get_tile_jsize(g) for g in biggroups] # 8 for bytes/float64\n return np.max(mems)\n\n im_shape = s.oshape.shape\n if calc_mem_usage(region_size) > max_mem:\n while ((calc_mem_usage(region_size) > max_mem) and\n np.any(region_size > 2)):\n region_size = np.clip(region_size-1, 2, im_shape)\n else:\n while ((calc_mem_usage(region_size) < max_mem) and\n np.any(region_size < im_shape)):\n region_size = np.clip(region_size+1, 2, im_shape)\n region_size -= 1 #need to be < memory, so we undo 1 iteration\n\n return region_size"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning a new state with the same state and a tile that is in the unpadded image.", "response": "def get_residuals_update_tile(st, padded_tile):\n \"\"\"\n Translates a tile in the padded image to the unpadded image.\n\n Given a state and a tile that corresponds to the padded image, returns\n a tile that corresponds to the the corresponding pixels of the difference\n image\n\n Parameters\n ----------\n st : :class:`peri.states.State`\n The state\n padded_tile : :class:`peri.util.Tile`\n The tile in the padded image.\n\n Returns\n -------\n :class:`peri.util.Tile`\n The tile corresponding to padded_tile in the unpadded image.\n \"\"\"\n inner_tile = st.ishape.intersection([st.ishape, padded_tile])\n return inner_tile.translate(-st.pad)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef find_best_step(err_vals):\n if np.all(np.isnan(err_vals)):\n raise ValueError('All err_vals are nans!')\n return np.nanargmin(err_vals)", "response": "Returns the index of the lowest of the passed values. Catches nans etc."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nrun Levenberg-Marquardt optimization on a state. Convenience wrapper for LMGlobals. Same keyword args, but the defaults have been set to useful values for optimizing globals. See LMGlobals and LMEngine for documentation. See Also -------- do_levmarq_particles : Levenberg-Marquardt optimization of a specified set of particles. do_levmarq_all_particle_groups : Levenberg-Marquardt optimization of all the particles in the state. LMGlobals : Optimizer object; the workhorse of do_levmarq. LMEngine : Engine superclass for all the optimizers.", "response": "def do_levmarq(s, param_names, damping=0.1, decrease_damp_factor=10.,\n run_length=6, eig_update=True, collect_stats=False, rz_order=0,\n run_type=2, **kwargs):\n \"\"\"\n Runs Levenberg-Marquardt optimization on a state.\n\n Convenience wrapper for LMGlobals. Same keyword args, but the defaults\n have been set to useful values for optimizing globals.\n See LMGlobals and LMEngine for documentation.\n\n See Also\n --------\n do_levmarq_particles : Levenberg-Marquardt optimization of a\n specified set of particles.\n\n do_levmarq_all_particle_groups : Levenberg-Marquardt optimization\n of all the particles in the state.\n\n LMGlobals : Optimizer object; the workhorse of do_levmarq.\n\n LMEngine : Engine superclass for all the optimizers.\n \"\"\"\n if rz_order > 0:\n aug = AugmentedState(s, param_names, rz_order=rz_order)\n lm = LMAugmentedState(aug, damping=damping, run_length=run_length,\n decrease_damp_factor=decrease_damp_factor, eig_update=\n eig_update, **kwargs)\n else:\n lm = LMGlobals(s, param_names, damping=damping, run_length=run_length,\n decrease_damp_factor=decrease_damp_factor, eig_update=\n eig_update, **kwargs)\n if run_type == 2:\n lm.do_run_2()\n elif run_type == 1:\n lm.do_run_1()\n else:\n raise ValueError('run_type=1,2 only')\n if collect_stats:\n return lm.get_termination_stats()"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef do_levmarq_particles(s, particles, damping=1.0, decrease_damp_factor=10.,\n run_length=4, collect_stats=False, max_iter=2, **kwargs):\n \"\"\"\n Levenberg-Marquardt optimization on a set of particles.\n\n Convenience wrapper for LMParticles. Same keyword args, but the\n defaults have been set to useful values for optimizing particles.\n See LMParticles and LMEngine for documentation.\n\n See Also\n --------\n do_levmarq_all_particle_groups : Levenberg-Marquardt optimization\n of all the particles in the state.\n\n do_levmarq : Levenberg-Marquardt optimization of the entire state;\n useful for optimizing global parameters.\n\n LMParticles : Optimizer object; the workhorse of do_levmarq_particles.\n\n LMEngine : Engine superclass for all the optimizers.\n \"\"\"\n lp = LMParticles(s, particles, damping=damping, run_length=run_length,\n decrease_damp_factor=decrease_damp_factor, max_iter=max_iter,\n **kwargs)\n lp.do_run_2()\n if collect_stats:\n return lp.get_termination_stats()", "response": "Wrapper for Levenberg - Marquardt optimization on a set of particles."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef do_levmarq_all_particle_groups(s, region_size=40, max_iter=2, damping=1.0,\n decrease_damp_factor=10., run_length=4, collect_stats=False, **kwargs):\n \"\"\"\n Levenberg-Marquardt optimization for every particle in the state.\n\n Convenience wrapper for LMParticleGroupCollection. Same keyword args,\n but I've set the defaults to what I've found to be useful values for\n optimizing particles. See LMParticleGroupCollection for documentation.\n\n See Also\n --------\n do_levmarq_particles : Levenberg-Marquardt optimization of a\n specified set of particles.\n\n do_levmarq : Levenberg-Marquardt optimization of the entire state;\n useful for optimizing global parameters.\n\n LMParticleGroupCollection : The workhorse of do_levmarq.\n\n LMEngine : Engine superclass for all the optimizers.\n \"\"\"\n lp = LMParticleGroupCollection(s, region_size=region_size, damping=damping,\n run_length=run_length, decrease_damp_factor=decrease_damp_factor,\n get_cos=collect_stats, max_iter=max_iter, **kwargs)\n lp.do_run_2()\n if collect_stats:\n return lp.stats", "response": "This function is used to run all the particle groups of a state."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef burn(s, n_loop=6, collect_stats=False, desc='', rz_order=0, fractol=1e-4,\n errtol=1e-2, mode='burn', max_mem=1e9, include_rad=True,\n do_line_min='default', partial_log=False, dowarn=True):\n \"\"\"\n Optimizes all the parameters of a state.\n\n Burns a state through calling LMParticleGroupCollection and LMGlobals/\n LMAugmentedState.\n\n Parameters\n ----------\n s : :class:`peri.states.ImageState`\n The state to optimize\n n_loop : Int, optional\n The number of times to loop over in the optimizer. Default is 6.\n collect_stats : Bool, optional\n Whether or not to collect information on the optimizer's\n performance. Default is False.\n desc : string, optional\n Description to append to the states.save() call every loop.\n Set to None to avoid saving. Default is '', which selects\n one of 'burning', 'polishing', 'doing_positions'\n rz_order: Int, optional\n Set to an int > 0 to optimize with an augmented state (R(z) as\n a global parameter) vs. with the normal global parameters;\n rz_order is the order of the polynomial approximate for R(z).\n Default is 0 (no augmented state).\n fractol : Float, optional\n Fractional change in error at which to terminate. Default 1e-4\n errtol : Float, optional\n Absolute change in error at which to terminate. Default 1e-2\n mode : {'burn', 'do-particles', or 'polish'}, optional\n What mode to optimize with.\n * 'burn' : Your state is far from the minimum.\n * 'do-particles' : Positions far from minimum, globals well-fit.\n * 'polish' : The state is close to the minimum.\n 'burn' is the default. Only `polish` will get to the global\n minimum.\n max_mem : Numeric, optional\n The maximum amount of memory allowed for the optimizers' J's,\n for both particles & globals. Default is 1e9, i.e. 1GB per\n optimizer.\n do_line_min : Bool or 'default', optional\n Set to True to do an additional, third optimization per loop\n which optimizes along the subspace spanned by the last 3 steps\n of the burn()'s trajectory. In principle this should signifi-\n cantly speed up the convergence; in practice it sometimes does,\n sometimes doesn't. Default is 'default', which picks by mode:\n * 'burn' : False\n * 'do-particles' : False\n * 'polish' : True\n dowarn : Bool, optional\n Whether to log a warning if termination results from finishing\n loops rather than from convergence. Default is True.\n\n Returns\n -------\n dictionary\n Dictionary of convergence information. Contains whether the\n optimization has converged (key ``'converged'``), the values of the\n state after each loop (key ``'all_loop_values'``).\n The values of the state's parameters after each part of the\n loop: globals, particles, linemin. If ``collect_stats`` is set,\n then also contains lists of termination dicts from globals,\n particles, and line minimization (keys ``'global_stats'``,\n ``'particle_stats'``, and ``'line_stats``').\n\n Notes\n -----\n Proceeds by alternating between one Levenberg-Marquardt step\n optimizing the globals, one optimizing the particles, and repeating\n until termination.\n\n In addition, if `do_line_min` is True, at the end of each loop\n step an additional optimization is tried along the subspaced spanned\n by the steps taken during the last 3 loops. Ideally, this changes the\n convergence from linear to quadratic, but it doesn't always do much.\n\n Each of the 3 options proceed by optimizing as follows:\n * burn : lm.do_run_2(), lp.do_run_2(). No psf, 2 loops on lm.\n * do-particles : lp.do_run_2(), scales for ilm, bkg's\n * polish : lm.do_run_2(), lp.do_run_2(). Everything, 1 loop each.\n where lm is a globals LMGlobals instance, and lp a\n LMParticleGroupCollection instance.\n \"\"\"\n # It would be nice if some of these magic #'s (region size,\n # num_eig_dirs, etc) were calculated in a good way. FIXME\n mode = mode.lower()\n if mode not in {'burn', 'do-particles', 'polish'}:\n raise ValueError('mode must be one of burn, do-particles, polish')\n\n #1. Setting Defaults\n if desc is '':\n desc = mode + 'ing' if mode != 'do-particles' else 'doing-particles'\n\n eig_update = (mode != 'do-particles')\n glbl_run_length = 3 if mode == 'do-particles' else 6\n glbl_mx_itr = 2 if mode == 'burn' else 1\n use_accel = (mode == 'burn')\n rz_order = int(rz_order)\n if do_line_min == 'default':\n # do_line_min = (mode == 'polish')\n # temporary fix until we solve the particles-leaving-image issue:\n do_line_min = False\n\n if mode == 'do-particles':\n # FIXME explicit params\n # We pick some parameters for an overall illumination scale:\n glbl_nms = ['ilm-scale', 'ilm-xy-0-0', 'bkg-xy-0-0', 'offset']\n # And now, since we have explicit parameters, we check that they\n # are actually in the state:\n glbl_nms = [nm for nm in glbl_nms if nm in s.params]\n else:\n if mode == 'polish':\n remove_params = None\n else:\n # FIXME explicit params\n remove_params = s.get('psf').params\n if ('zscale' not in remove_params) and ('zscale' in s.params):\n remove_params.append('zscale')\n glbl_nms = name_globals(s, remove_params=remove_params)\n\n all_lp_stats = []\n all_lm_stats = []\n all_line_stats = []\n all_loop_values = []\n\n _delta_vals = [] # storing the directions we've moved along for line min\n #2. Optimize\n CLOG.info('Start of loop %d:\\t%f' % (0, s.error))\n for a in range(n_loop):\n start_err = s.error\n start_params = np.copy(s.state[s.params])\n #2a. Globals\n # glbl_dmp = 0.3 if a == 0 else 3e-2\n ####FIXME we damp degenerate but convenient spaces in the ilm, bkg\n ####manually, but we should do it more betterer.\n BAD_DAMP = 1e7\n BAD_LIST = [['ilm-scale', BAD_DAMP], ['ilm-off', BAD_DAMP], ['ilm-z-0',\n BAD_DAMP], ['bkg-z-0', BAD_DAMP]]\n ####\n glbl_dmp = vectorize_damping(glbl_nms + ['rz']*rz_order, damping=1.0,\n increase_list=[['psf-', 3e1]] + BAD_LIST)\n if a != 0 or mode != 'do-particles':\n if partial_log:\n log.set_level('debug')\n gstats = do_levmarq(s, glbl_nms, max_iter=glbl_mx_itr, run_length=\n glbl_run_length, eig_update=eig_update, num_eig_dirs=10,\n eig_update_frequency=3, rz_order=rz_order, damping=\n glbl_dmp, decrease_damp_factor=10., use_accel=use_accel,\n collect_stats=collect_stats, fractol=0.1*fractol,\n max_mem=max_mem)\n if partial_log:\n log.set_level('info')\n all_lm_stats.append(gstats)\n if desc is not None:\n states.save(s, desc=desc)\n CLOG.info('Globals, loop {}:\\t{}'.format(a, s.error))\n all_loop_values.append(s.values)\n\n #2b. Particles\n prtl_dmp = 1.0 if a==0 else 1e-2\n #For now, I'm calculating the region size. This might be a bad idea\n #because 1 bad particle can spoil the whole group.\n pstats = do_levmarq_all_particle_groups(s, region_size=40, max_iter=1,\n do_calc_size=True, run_length=4, eig_update=False,\n damping=prtl_dmp, fractol=0.1*fractol, collect_stats=\n collect_stats, max_mem=max_mem, include_rad=include_rad)\n all_lp_stats.append(pstats)\n if desc is not None:\n states.save(s, desc=desc)\n CLOG.info('Particles, loop {}:\\t{}'.format(a, s.error))\n gc.collect()\n all_loop_values.append(s.values)\n\n #2c. Line min?\n end_params = np.copy(s.state[s.params])\n _delta_vals.append(start_params - end_params)\n if do_line_min:\n all_line_stats.append(do_levmarq_n_directions(s, _delta_vals[-3:],\n collect_stats=collect_stats))\n if desc is not None:\n states.save(s, desc=desc)\n CLOG.info('Line min., loop {}:\\t{}'.format(a, s.error))\n all_loop_values.append(s.values)\n\n #2d. terminate?\n new_err = s.error\n derr = start_err - new_err\n dobreak = (derr/new_err < fractol) or (derr < errtol)\n if dobreak:\n break\n\n if dowarn and (not dobreak):\n CLOG.warn('burn() did not converge; consider re-running')\n\n d = {'converged':dobreak, 'all_loop_values':all_loop_values}\n if collect_stats:\n d.update({'global_stats':all_lm_stats, 'particle_stats':all_lp_stats,\n 'line_stats':all_line_stats})\n return d", "response": "Burns a state through the LMParticleGroupCollection and LMAugmentedState LMGlobalGlobal and LMGlobalGlobalGlobalGlobalGlobalGlobal and LMParticleGroupCollection and LMAugmentedState and LMAugmentedState LMAugmentedState. LMState. LMA"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncrawls slowly to the minimum-cost state. Blocks the global parameters into small enough sections such that each can be optimized separately while including all the pixels (i.e. no decimation). Optimizes the globals, then the psf separately if desired, then particles, then a line minimization along the step direction to speed up convergence. Parameters ---------- s : :class:`peri.states.ImageState` The state to optimize desc : string, optional Description to append to the states.save() call every loop. Set to `None` to avoid saving. Default is `'finish'`. n_loop : Int, optional The number of times to loop over in the optimizer. Default is 4. max_mem : Numeric, optional The maximum amount of memory allowed for the optimizers' J's, for both particles & globals. Default is 1e9. separate_psf : Bool, optional If True, does the psf optimization separately from the rest of the globals, since the psf has a more tortuous fit landscape. Default is True. fractol : Float, optional Fractional change in error at which to terminate. Default 1e-4 errtol : Float, optional Absolute change in error at which to terminate. Default 1e-2 dowarn : Bool, optional Whether to log a warning if termination results from finishing loops rather than from convergence. Default is True. Returns ------- dictionary Information about the optimization. Has two keys: ``'converged'``, a Bool which of whether optimization stopped due to convergence (True) or due to max number of iterations (False), and ``'loop_values'``, a [n_loop+1, N] ``numpy.ndarray`` of the state's values, at the start of optimization and at the end of each loop, before the line minimization.", "response": "def finish(s, desc='finish', n_loop=4, max_mem=1e9, separate_psf=True,\n fractol=1e-7, errtol=1e-3, dowarn=True):\n \"\"\"\n Crawls slowly to the minimum-cost state.\n\n Blocks the global parameters into small enough sections such that each\n can be optimized separately while including all the pixels (i.e. no\n decimation). Optimizes the globals, then the psf separately if desired,\n then particles, then a line minimization along the step direction to\n speed up convergence.\n\n Parameters\n ----------\n s : :class:`peri.states.ImageState`\n The state to optimize\n desc : string, optional\n Description to append to the states.save() call every loop.\n Set to `None` to avoid saving. Default is `'finish'`.\n n_loop : Int, optional\n The number of times to loop over in the optimizer. Default is 4.\n max_mem : Numeric, optional\n The maximum amount of memory allowed for the optimizers' J's,\n for both particles & globals. Default is 1e9.\n separate_psf : Bool, optional\n If True, does the psf optimization separately from the rest of\n the globals, since the psf has a more tortuous fit landscape.\n Default is True.\n fractol : Float, optional\n Fractional change in error at which to terminate. Default 1e-4\n errtol : Float, optional\n Absolute change in error at which to terminate. Default 1e-2\n dowarn : Bool, optional\n Whether to log a warning if termination results from finishing\n loops rather than from convergence. Default is True.\n\n Returns\n -------\n dictionary\n Information about the optimization. Has two keys: ``'converged'``,\n a Bool which of whether optimization stopped due to convergence\n (True) or due to max number of iterations (False), and\n ``'loop_values'``, a [n_loop+1, N] ``numpy.ndarray`` of the\n state's values, at the start of optimization and at the end of\n each loop, before the line minimization.\n \"\"\"\n values = [np.copy(s.state[s.params])]\n remove_params = s.get('psf').params if separate_psf else None\n # FIXME explicit params\n global_params = name_globals(s, remove_params=remove_params)\n #FIXME this could be done much better, since much of the globals such\n #as the ilm are local. Could be done with sparse matrices and/or taking\n #nearby globals in a group and using the update tile only as the slicer,\n #rather than the full residuals.\n gs = np.floor(max_mem / s.residuals.nbytes).astype('int')\n groups = [global_params[a:a+gs] for a in range(0, len(global_params), gs)]\n CLOG.info('Start ``finish``:\\t{}'.format(s.error))\n for a in range(n_loop):\n start_err = s.error\n #1. Min globals:\n for g in groups:\n do_levmarq(s, g, damping=0.1, decrease_damp_factor=20.,\n max_iter=1, max_mem=max_mem, eig_update=False)\n if separate_psf:\n do_levmarq(s, remove_params, max_mem=max_mem, max_iter=4,\n eig_update=False)\n CLOG.info('Globals, loop {}:\\t{}'.format(a, s.error))\n if desc is not None:\n states.save(s, desc=desc)\n #2. Min particles\n do_levmarq_all_particle_groups(s, max_iter=1, max_mem=max_mem)\n CLOG.info('Particles, loop {}:\\t{}'.format(a, s.error))\n if desc is not None:\n states.save(s, desc=desc)\n #3. Append vals, line min:\n values.append(np.copy(s.state[s.params]))\n # dv = (np.array(values[1:]) - np.array(values[0]))[-3:]\n # do_levmarq_n_directions(s, dv, damping=1e-2, max_iter=2, errtol=3e-4)\n # CLOG.info('Line min., loop {}:\\t{}'.format(a, s.error))\n # if desc is not None:\n # states.save(s, desc=desc)\n #4. terminate?\n new_err = s.error\n derr = start_err - new_err\n dobreak = (derr/new_err < fractol) or (derr < errtol)\n if dobreak:\n break\n\n if dowarn and (not dobreak):\n CLOG.warn('finish() did not converge; consider re-running')\n return {'converged':dobreak, 'loop_values':np.array(values)}"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nfit a new component to an old component and returns a new object.", "response": "def fit_comp(new_comp, old_comp, **kwargs):\n \"\"\"\n Fits a new component to an old component\n\n Calls do_levmarq to match the .get() fields of the two objects. The\n parameters of new_comp are modified in place.\n\n Parameters\n ----------\n new_comp : :class:`peri.comps.comp`\n The new object, whose parameters to update to fit the field of\n `old_comp`. Must have a .get() attribute which returns an ndarray\n old_comp : peri.comp\n The old ilm to match to.\n\n Other Parameters\n ----------------\n Any keyword arguments to be passed to the optimizer LMGlobals\n through do_levmarq.\n\n See Also\n --------\n do_levmarq : Levenberg-Marquardt minimization using a random subset\n of the image pixels.\n \"\"\"\n #resetting the category to ilm:\n new_cat = new_comp.category\n new_comp.category = 'ilm'\n fake_s = states.ImageState(Image(old_comp.get().copy()), [new_comp], pad=0,\n mdl=mdl.SmoothFieldModel())\n do_levmarq(fake_s, new_comp.params, **kwargs)\n new_comp.category = new_cat"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nresetting all the internal state of the object to its initial state.", "response": "def reset(self, new_damping=None):\n \"\"\"\n Keeps all user supplied options the same, but resets counters etc.\n \"\"\"\n self._num_iter = 0\n self._inner_run_counter = 0\n self._J_update_counter = self.update_J_frequency\n self._fresh_JTJ = False\n self._has_run = False\n if new_damping is not None:\n self.damping = np.array(new_damping).astype('float')\n self._set_err_paramvals()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef do_run_1(self):\n while not self.check_terminate():\n self._has_run = True\n self._run1()\n self._num_iter += 1; self._inner_run_counter += 1", "response": "Run the LM run until the run is complete."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef do_run_2(self):\n while not self.check_terminate():\n self._has_run = True\n self._run2()\n self._num_iter += 1", "response": "Runs 2 steps until the process terminate."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef find_LM_updates(self, grad, do_correct_damping=True, subblock=None):\n if subblock is not None:\n if (subblock.sum() == 0) or (subblock.size == 0):\n CLOG.fatal('Empty subblock in find_LM_updates')\n raise ValueError('Empty sub-block')\n j = self.J[subblock]\n JTJ = np.dot(j, j.T)\n damped_JTJ = self._calc_damped_jtj(JTJ, subblock=subblock)\n grad = grad[subblock] #select the subblock of the grad\n else:\n damped_JTJ = self._calc_damped_jtj(self.JTJ, subblock=subblock)\n\n delta = self._calc_lm_step(damped_JTJ, grad, subblock=subblock)\n\n if self.use_accel:\n accel_correction = self.calc_accel_correction(damped_JTJ, delta)\n nrm_d0 = np.sqrt(np.sum(delta**2))\n nrm_corr = np.sqrt(np.sum(accel_correction**2))\n CLOG.debug('|correction| / |LM step|\\t%e' % (nrm_corr/nrm_d0))\n if nrm_corr/nrm_d0 < self.max_accel_correction:\n delta += accel_correction\n elif do_correct_damping:\n CLOG.debug('Untrustworthy step! Increasing damping...')\n self.increase_damping()\n damped_JTJ = self._calc_damped_jtj(self.JTJ, subblock=subblock)\n delta = self._calc_lm_step(damped_JTJ, grad, subblock=subblock)\n\n if np.any(np.isnan(delta)):\n CLOG.fatal('Calculated steps have nans!?')\n raise FloatingPointError('Calculated steps have nans!?')\n return delta", "response": "Calculates the LM updates for the current state of the object."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _calc_lm_step(self, damped_JTJ, grad, subblock=None):\n delta0, res, rank, s = np.linalg.lstsq(damped_JTJ, -0.5*grad,\n rcond=self.min_eigval)\n if self._fresh_JTJ:\n CLOG.debug('%d degenerate of %d total directions' % (\n delta0.size-rank, delta0.size))\n if subblock is not None:\n delta = np.zeros(self.J.shape[0])\n delta[subblock] = delta0\n else:\n delta = delta0.copy()\n return delta", "response": "Calculates a Levenberg - Marquard step w / o acceleration"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef update_param_vals(self, new_vals, incremental=False):\n self._last_vals = self.param_vals.copy()\n if incremental:\n self.param_vals += new_vals\n else:\n self.param_vals = new_vals.copy()\n #And we've updated, so JTJ is no longer valid:\n self._fresh_JTJ = False", "response": "Updates the current set of parameter values and previous values."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef find_expected_error(self, delta_params='calc'):\n grad = self.calc_grad()\n if list(delta_params) in [list('calc'), list('perfect')]:\n jtj = (self.JTJ if delta_params == 'perfect' else\n self._calc_damped_jtj(self.JTJ))\n delta_params = self._calc_lm_step(jtj, self.calc_grad())\n #If the model were linear, then the cost would be quadratic,\n #with Hessian 2*`self.JTJ` and gradient `grad`\n expected_error = (self.error + np.dot(grad, delta_params) +\n np.dot(np.dot(self.JTJ, delta_params), delta_params))\n return expected_error", "response": "Calculates the expected error after an update."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncalculate the cosine of the residuals with the model.", "response": "def calc_model_cosine(self, decimate=None, mode='err'):\n \"\"\"\n Calculates the cosine of the residuals with the model.\n\n Parameters\n ----------\n decimate : Int or None, optional\n Decimate the residuals by `decimate` pixels. If None, no\n decimation is used. Valid only with mode='svd'. Default\n is None\n mode : {'svd', 'err'}\n Which mode to use; see Notes section. Default is 'err'.\n\n Returns\n -------\n abs_cos : numpy.float64\n The absolute value of the model cosine.\n\n Notes\n -----\n The model cosine is defined in terms of the geometric view of\n curve-fitting, as a model manifold embedded in a high-dimensional\n space. The model cosine is the cosine of the residuals vector\n with its projection on the tangent space: :math:`cos(phi) = |P^T r|/|r|`\n where :math:`P^T` is the projection operator onto the model manifold\n and :math:`r` the residuals. This can be calculated two ways: By\n calculating the projection operator P directly with SVD (mode=`svd`),\n or by using the expected error if the model were linear to calculate\n a model sine first (mode=`err`). Since the SVD of a large matrix is\n slow, mode=`err` is faster.\n\n `decimate` allows for every nth pixel only to be counted in the\n SVD matrix of J for speed. While this is n x faster, it is\n considerably less accurate, so the default is no decimation.\n \"\"\"\n if mode == 'svd':\n slicer = slice(0, None, decimate)\n\n #1. Calculate projection term\n u, sig, v = np.linalg.svd(self.J[:,slicer], full_matrices=False) #slow part\n # p = np.dot(v.T, v) - memory error, so term-by-term\n r = self.calc_residuals()[slicer]\n abs_r = np.sqrt((r*r).sum())\n\n v_r = np.dot(v,r/abs_r)\n projected = np.dot(v.T, v_r)\n\n abs_cos = np.sqrt((projected*projected).sum())\n elif mode == 'err':\n expected_error = self.find_expected_error(delta_params='perfect')\n model_sine_2 = expected_error / self.error #error = distance^2\n abs_cos = np.sqrt(1 - model_sine_2)\n else:\n raise ValueError('mode must be one of `svd`, `err`')\n return abs_cos"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn a dict of termination statistics for the current J.", "response": "def get_termination_stats(self, get_cos=True):\n \"\"\"\n Returns a dict of termination statistics\n\n Parameters\n ----------\n get_cos : Bool, optional\n Whether or not to calcualte the cosine of the residuals\n with the tangent plane of the model using the current J.\n The calculation may take some time. Default is True\n\n Returns\n -------\n dict\n Has keys\n delta_vals : The last change in parameter values.\n delta_err : The last change in the error.\n exp_err : The expected (last) change in the error.\n frac_err : The fractional change in the error.\n num_iter : The number of iterations completed.\n error : The current error.\n \"\"\"\n delta_vals = self._last_vals - self.param_vals\n delta_err = self._last_error - self.error\n frac_err = delta_err / self.error\n to_return = {'delta_vals':delta_vals, 'delta_err':delta_err,\n 'num_iter':1*self._num_iter, 'frac_err':frac_err,\n 'error':self.error, 'exp_err':self._exp_err}\n if get_cos:\n model_cosine = self.calc_model_cosine()\n to_return.update({'model_cosine':model_cosine})\n return to_return"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nchecks if the algorithm has found a satisfactory minimum", "response": "def check_completion(self):\n \"\"\"\n Returns a Bool of whether the algorithm has found a satisfactory minimum\n \"\"\"\n terminate = False\n term_dict = self.get_termination_stats(get_cos=self.costol is not None)\n terminate |= np.all(np.abs(term_dict['delta_vals']) < self.paramtol)\n terminate |= (term_dict['delta_err'] < self.errtol)\n terminate |= (term_dict['exp_err'] < self.exptol)\n terminate |= (term_dict['frac_err'] < self.fractol)\n if self.costol is not None:\n terminate |= (curcos < term_dict['model_cosine'])\n\n return terminate"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef check_terminate(self):\n if not self._has_run:\n return False\n else:\n #1-3. errtol, paramtol, model cosine low enough?\n terminate = self.check_completion()\n\n #4. too many iterations??\n terminate |= (self._num_iter >= self.max_iter)\n return terminate", "response": "Checks whether a satisfactory minimum has been found and whether to terminate."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef check_update_J(self):\n self._J_update_counter += 1\n update = self._J_update_counter >= self.update_J_frequency\n return update & (not self._fresh_JTJ)", "response": "Checks if the full J should be updated."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef update_J(self):\n self.calc_J()\n # np.dot(j, j.T) is slightly faster but 2x as much mem\n step = np.ceil(1e-2 * self.J.shape[1]).astype('int') # 1% more mem...\n self.JTJ = low_mem_sq(self.J, step=step)\n #copies still, since J is not C -ordered but a slice of j_e...\n #doing self.J.copy() works but takes 2x as much ram..\n self._fresh_JTJ = True\n self._J_update_counter = 0\n if np.any(np.isnan(self.JTJ)):\n raise FloatingPointError('J, JTJ have nans.')\n #Update self._exp_err\n self._exp_err = self.error - self.find_expected_error(delta_params='perfect')", "response": "Updates J TJ and internal counters."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef calc_grad(self):\n residuals = self.calc_residuals()\n return 2*np.dot(self.J, residuals)", "response": "Calculates the gradient of the cost w. r. t. the parameters."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nupdating the internal J matrix with the new values.", "response": "def _rank_1_J_update(self, direction, values):\n \"\"\"\n Does J += np.outer(direction, new_values - old_values) without\n using lots of memory\n \"\"\"\n vals_to_sub = np.dot(direction, self.J)\n delta_vals = values - vals_to_sub\n for a in range(direction.size):\n self.J[a] += direction[a] * delta_vals"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef update_Broyden_J(self):\n CLOG.debug('Broyden update.')\n delta_vals = self.param_vals - self._last_vals\n delta_residuals = self.calc_residuals() - self._last_residuals\n nrm = np.sqrt(np.dot(delta_vals, delta_vals))\n direction = delta_vals / nrm\n vals = delta_residuals / nrm\n self._rank_1_J_update(direction, vals)\n self.JTJ = np.dot(self.J, self.J.T)", "response": "Execute a Broyden update of J"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nexecute an eigen update of J", "response": "def update_eig_J(self):\n \"\"\"Execute an eigen update of J\"\"\"\n CLOG.debug('Eigen update.')\n vls, vcs = np.linalg.eigh(self.JTJ)\n res0 = self.calc_residuals()\n for a in range(min([self.num_eig_dirs, vls.size])):\n #1. Finding stiff directions\n stif_dir = vcs[-(a+1)] #already normalized\n\n #2. Evaluating derivative along that direction, we'll use dl=5e-4:\n dl = self.eig_dl #1e-5\n _ = self.update_function(self.param_vals + dl*stif_dir)\n res1 = self.calc_residuals()\n\n #3. Updating\n grad_stif = (res1-res0)/dl\n self._rank_1_J_update(stif_dir, grad_stif)\n\n self.JTJ = np.dot(self.J, self.J.T)\n #Putting the parameters back:\n _ = self.update_function(self.param_vals)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef calc_accel_correction(self, damped_JTJ, delta0):\n #Get the derivative:\n _ = self.update_function(self.param_vals)\n rm0 = self.calc_residuals().copy()\n _ = self.update_function(self.param_vals + delta0)\n rm1 = self.calc_residuals().copy()\n _ = self.update_function(self.param_vals - delta0)\n rm2 = self.calc_residuals().copy()\n der2 = (rm2 + rm1 - 2*rm0)\n\n corr, res, rank, s = np.linalg.lstsq(damped_JTJ, np.dot(self.J, der2),\n rcond=self.min_eigval)\n corr *= -0.5\n return corr", "response": "Calculates the acceleration correction for a given set of geodesic acceleration in the LM step."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nupdating the J matrix with the values of the parameters in the boolean taxonomy.", "response": "def update_select_J(self, blk):\n \"\"\"\n Updates J only for certain parameters, described by the boolean\n mask `blk`.\n \"\"\"\n p0 = self.param_vals.copy()\n self.update_function(p0) #in case things are not put back...\n r0 = self.calc_residuals().copy()\n dl = np.zeros(p0.size, dtype='float')\n blk_J = []\n for i in np.nonzero(blk)[0]:\n dl *= 0; dl[i] = self.eig_dl\n self.update_function(p0 + dl)\n r1 = self.calc_residuals().copy()\n blk_J.append((r1-r0)/self.eig_dl)\n self.J[blk] = np.array(blk_J)\n self.update_function(p0)\n #Then we also need to update JTJ:\n self.JTJ = np.dot(self.J, self.J.T)\n if np.any(np.isnan(self.J)) or np.any(np.isnan(self.JTJ)):\n raise FloatingPointError('J, JTJ have nans.')"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsetting error and param_vals for the exception.", "response": "def _set_err_paramvals(self):\n \"\"\"\n Must update:\n self.error, self._last_error, self.param_vals, self._last_vals\n \"\"\"\n # self.param_vals = p0 #sloppy...\n self._last_vals = self.param_vals.copy()\n self.error = self.update_function(self.param_vals)\n self._last_error = (1 + 2*self.fractol) * self.error"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef calc_J(self):\n del self.J\n self.J = np.zeros([self.param_vals.size, self.data.size])\n dp = np.zeros_like(self.param_vals)\n f0 = self.model.copy()\n for a in range(self.param_vals.size):\n dp *= 0\n dp[a] = self.dl[a]\n f1 = self.func(self.param_vals + dp, *self.func_args, **self.func_kwargs)\n grad_func = (f1 - f0) / dp[a]\n #J = grad(residuals) = -grad(model)\n self.J[a] = -grad_func", "response": "Updates self. J and returns nothing"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ntaking an array param_vals updates function returns the new error", "response": "def update_function(self, param_vals):\n \"\"\"Takes an array param_vals, updates function, returns the new error\"\"\"\n self.model = self.func(param_vals, *self.func_args, **self.func_kwargs)\n d = self.calc_residuals()\n return np.dot(d.flat, d.flat)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef update_function(self, param_vals):\n self.opt_obj.update_function(param_vals)\n return self.opt_obj.get_error()", "response": "Updates the opt_obj returns new error."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef update_function(self, param_vals):\n dp = np.zeros(self.p0.size)\n for a in range(param_vals.size):\n dp += param_vals[a] * self.directions[a]\n self.state.update(self.state.params, self.p0 + dp)\n self.param_vals[:] = param_vals\n return None", "response": "Updates with param_vals = distance from self. p0 along self. direction."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef calc_J(self):\n r0 = self.state.residuals.copy().ravel()\n dl = np.zeros(self.param_vals.size)\n p0 = self.param_vals.copy()\n J = []\n for a in range(self.param_vals.size):\n dl *= 0\n dl[a] += self.dl\n self.update_function(p0 + dl)\n r1 = self.state.residuals.copy().ravel()\n J.append( (r1-r0)/self.dl)\n self.update_function(p0)\n return np.array(J)", "response": "Calculates the J along the direction."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef update_select_J(self, blk):\n self.update_function(self.param_vals)\n params = np.array(self.param_names)[blk].tolist()\n blk_J = -self.state.gradmodel(params=params, inds=self._inds, flat=False)\n self.J[blk] = blk_J\n #Then we also need to update JTJ:\n self.JTJ = np.dot(self.J, self.J.T)\n if np.any(np.isnan(self.J)) or np.any(np.isnan(self.JTJ)):\n raise FloatingPointError('J, JTJ have nans.')", "response": "Updates J only for certain parameters described by the boolean\n mask blk."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nfinding the expected error after an update.", "response": "def find_expected_error(self, delta_params='calc', adjust=True):\n \"\"\"\n Returns the error expected after an update if the model were linear.\n\n Parameters\n ----------\n delta_params : {numpy.ndarray, 'calc', or 'perfect'}, optional\n The relative change in parameters. If 'calc', uses update\n calculated from the current damping, J, etc; if 'perfect',\n uses the update calculated with zero damping.\n\n Returns\n -------\n numpy.float64\n The expected error after the update with `delta_params`\n \"\"\"\n expected_error = super(LMGlobals, self).find_expected_error(\n delta_params=delta_params)\n if adjust:\n #adjust for num_pix\n derr = (expected_error - self.error) * (self.state.residuals.size /\n float(self.num_pix))\n expected_error = self.error + derr\n return expected_error"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef calc_model_cosine(self, decimate=None, mode='err'):\n #we calculate the model cosine only in the data space of the\n #sampled indices\n if mode == 'err':\n expected_error = self.find_expected_error(delta_params='perfect',\n adjust=False)\n derr = self.error - expected_error\n residuals_err = lambda r: np.dot(r,r).sum()\n current_partial_error = residuals_err(self.calc_residuals())\n expected_partial_error = current_partial_error - derr\n model_sine_2 = expected_partial_error / current_partial_error\n abs_cos = np.sqrt(1 - model_sine_2)\n else:\n #superclass is fine\n abs_cos = super(self.__class__, self).calc_model_cosine(decimate=\n decimate, mode=mode)\n return abs_cos", "response": "Calculates the model cosine of the residuals with the model."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncalculate the gradient of the cost w. r. t. the parameters.", "response": "def calc_grad(self):\n \"\"\"The gradient of the cost w.r.t. the parameters.\"\"\"\n if self._fresh_JTJ:\n return self._graderr\n else:\n residuals = self.calc_residuals()\n return 2*np.dot(self.J, residuals)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreset the particle groups and optionally the region size and damping of the particle groups.", "response": "def reset(self, new_region_size=None, do_calc_size=True, new_damping=None,\n new_max_mem=None):\n \"\"\"\n Resets the particle groups and optionally the region size and damping.\n\n Parameters\n ----------\n new_region_size : : Int or 3-element list-like of ints, optional\n The region size for sub-blocking particles. Default is 40\n do_calc_size : Bool, optional\n If True, calculates the region size internally based on\n the maximum allowed memory. Default is True\n new_damping : Float or None, optional\n The new damping of the optimizer. Set to None to leave\n as the default for LMParticles. Default is None.\n new_max_mem : Numeric, optional\n The maximum allowed memory for J to occupy. Default is 1e9\n \"\"\"\n if new_region_size is not None:\n self.region_size = new_region_size\n if new_max_mem != None:\n self.max_mem = new_max_mem\n if do_calc_size:\n self.region_size = calc_particle_group_region_size(self.state,\n region_size=self.region_size, max_mem=self.max_mem)\n self.stats = []\n self.particle_groups = separate_particles_into_groups(self.state,\n self.region_size, doshift='rand')\n if new_damping is not None:\n self._kwargs.update({'damping':new_damping})\n if self.save_J:\n if len(self.particle_groups) > 90:\n CLOG.warn('Attempting to create many open files. Consider increasing max_mem and/or region_size to avoid crashes.')\n self._tempfiles = []\n self._has_saved_J = []\n for a in range(len(self.particle_groups)):\n #TemporaryFile is automatically deleted\n for _ in ['j','tile']:\n self._tempfiles.append(tempfile.TemporaryFile(dir=os.getcwd()))\n self._has_saved_J.append(False)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _do_run(self, mode='1'):\n for a in range(len(self.particle_groups)):\n group = self.particle_groups[a]\n lp = LMParticles(self.state, group, **self._kwargs)\n if mode == 'internal':\n lp.J, lp.JTJ, lp._dif_tile = self._load_j_diftile(a)\n\n if mode == '1':\n lp.do_run_1()\n if mode == '2':\n lp.do_run_2()\n if mode == 'internal':\n lp.do_internal_run()\n\n self.stats.append(lp.get_termination_stats(get_cos=self.get_cos))\n if self.save_J and (mode != 'internal'):\n self._dump_j_diftile(a, lp.J, lp._dif_tile)\n self._has_saved_J[a] = True", "response": "workhorse for the self. do_run_xx methods."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncalling self. _do_internal_run for each group of particles.", "response": "def do_internal_run(self):\n \"\"\"Calls LMParticles.do_internal_run for each group of particles.\"\"\"\n if not self.save_J:\n raise RuntimeError('self.save_J=True required for do_internal_run()')\n if not np.all(self._has_saved_J):\n raise RuntimeError('J, JTJ have not been pre-computed. Call do_run_1 or do_run_2')\n self._do_run(mode='internal')"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef reset(self):\n inds = list(range(self.state.obj_get_positions().shape[0]))\n self._rad_nms = self.state.param_particle_rad(inds)\n self._pos_nms = self.state.param_particle_pos(inds)\n self._initial_rad = np.copy(self.state.state[self._rad_nms])\n self._initial_pos = np.copy(self.state.state[self._pos_nms]).reshape((-1,3))\n self.param_vals[self.rscale_mask] = 0", "response": "Resets the initial radii used for updating the particles."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nrighting now legval z", "response": "def _poly(self, z):\n \"\"\"Right now legval(z)\"\"\"\n shp = self.state.oshape.shape\n zmax = float(shp[0])\n zmin = 0.0\n zmid = zmax * 0.5\n\n coeffs = self.param_vals[self.rscale_mask].copy()\n if coeffs.size == 0:\n ans = 0*z\n else:\n ans = np.polynomial.legendre.legval((z-zmid)/zmid,\n self.param_vals[self.rscale_mask])\n return ans"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef update(self, param_vals):\n self.update_rscl_x_params(param_vals[self.rscale_mask])\n self.state.update(self.param_names, param_vals[self.globals_mask])\n self.param_vals[:] = param_vals.copy()\n if np.any(np.isnan(self.state.residuals)):\n raise FloatingPointError('state update caused nans in residuals')", "response": "Updates all the parameters of the state + rscale x"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef reset(self, **kwargs):\n self.aug_state.reset()\n super(LMAugmentedState, self).reset(**kwargs)", "response": "Resets the aug_state and the LMEngine"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn a list of objects with a numbers of shares a link has had using Buffer.", "response": "def get_shares(self):\n '''\n Returns an object with a the numbers of shares a link has had using\n Buffer.\n\n www will be stripped, but other subdomains will not.\n '''\n\n self.shares = self.api.get(url=PATHS['GET_SHARES'] % self.url)['shares']\n\n return self.shares"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ntake a sample from a field given flat indices or a shaped slice", "response": "def sample(field, inds=None, slicer=None, flat=True):\n \"\"\"\n Take a sample from a field given flat indices or a shaped slice\n\n Parameters\n -----------\n inds : list of indices\n One dimensional (raveled) indices to return from the field\n\n slicer : slice object\n A shaped (3D) slicer that returns a section of image\n\n flat : boolean\n Whether to flatten the sampled item before returning\n \"\"\"\n if inds is not None:\n out = field.ravel()[inds]\n elif slicer is not None:\n out = field[slicer].ravel()\n else:\n out = field\n\n if flat:\n return out.ravel()\n return out"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef save(state, filename=None, desc='', extra=None):\n if isinstance(state.image, util.RawImage):\n desc = desc or 'save'\n filename = filename or state.image.filename + '-peri-' + desc + '.pkl'\n else:\n if not filename:\n raise AttributeError(\"Must provide filename since RawImage is not used\")\n\n if extra is None:\n save = state\n else:\n save = [state] + extra\n\n if os.path.exists(filename):\n ff = \"{}-tmp-for-copy\".format(filename)\n\n if os.path.exists(ff):\n os.remove(ff)\n\n os.rename(filename, ff)\n\n pickle.dump(save, open(filename, 'wb'), protocol=2)", "response": "Save the current state of the state object to a file."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef load(filename):\n path, name = os.path.split(filename)\n path = path or '.'\n\n with util.indir(path):\n return pickle.load(open(name, 'rb'))", "response": "Load the state from a file."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef error(self):\n r = self.residuals.ravel()\n return np.dot(r,r)", "response": "Sum of the squared errors"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef loglikelihood(self):\n sig = self.hyper_parameters.get_values('sigma')\n err = self.error\n N = np.size(self.data)\n return -0.5*err/sig**2 - np.log(np.sqrt(2*np.pi)*sig)*N", "response": "Loglikelihood calculated by the model error"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nupdate a single parameter or group of parameters params with values.", "response": "def update(self, params, values):\n \"\"\"\n Update a single parameter or group of parameters ``params``\n with ``values``.\n\n Parameters\n ----------\n params : string or list of strings\n Parameter names which to update\n\n value : number or list of numbers\n Values of those parameters which to update\n \"\"\"\n return super(State, self).update(params, values)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nperforming a parameter update and keep track of the change on the state.", "response": "def push_update(self, params, values):\n \"\"\"\n Perform a parameter update and keep track of the change on the state.\n Same call structure as :func:`peri.states.States.update`\n \"\"\"\n curr = self.get_values(params)\n self.stack.append((params, curr))\n self.update(params, values)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\npopping the last update from the stack push by the PeriState. update method.", "response": "def pop_update(self):\n \"\"\"\n Pop the last update from the stack push by\n :func:`peri.states.States.push_update` by undoing the chnage last\n performed.\n \"\"\"\n params, values = self.stack.pop()\n self.update(params, values)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _hess_two_param(self, funct, p0, p1, dl=2e-5, rts=False, **kwargs):\n vals0 = self.get_values(p0)\n vals1 = self.get_values(p1)\n\n f00 = funct(**kwargs)\n\n self.update(p0, vals0+dl)\n f10 = funct(**kwargs)\n\n self.update(p1, vals1+dl)\n f11 = funct(**kwargs)\n\n self.update(p0, vals0)\n f01 = funct(**kwargs)\n\n if rts:\n self.update(p0, vals0)\n self.update(p1, vals1)\n return (f11 - f10 - f01 + f00) / (dl**2)", "response": "Hessian of funct wrt two parameters p0 and p1."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _jtj(self, funct, params=None, dl=2e-5, rts=False, **kwargs):\n grad = self._grad(funct=funct, params=params, dl=dl, rts=rts, **kwargs)\n return np.dot(grad, grad.T)", "response": "get the JTJ of a function wrt to parmaeters params"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef build_funcs(self):\n # create essentially lambda functions, but with a nice signature\n def m(inds=None, slicer=None, flat=True):\n return sample(self.model, inds=inds, slicer=slicer, flat=flat).copy()\n\n def r(inds=None, slicer=None, flat=True):\n return sample(self.residuals, inds=inds, slicer=slicer, flat=flat).copy()\n\n def l():\n return self.loglikelihood\n\n def r_e(**kwargs):\n \"\"\"sliced etc residuals, with state.error appended on\"\"\"\n return r(**kwargs), np.copy(self.error)\n\n def m_e(**kwargs):\n \"\"\"sliced etc residuals, with state.error appended on\"\"\"\n return m(**kwargs), np.copy(self.error)\n\n # set the member functions using partial\n self.fisherinformation = partial(self._jtj, funct=m)\n self.gradloglikelihood = partial(self._grad, funct=l)\n self.hessloglikelihood = partial(self._hess, funct=l)\n self.gradmodel = partial(self._grad, funct=m)\n self.hessmodel = partial(self._hess, funct=m)\n self.JTJ = partial(self._jtj, funct=r)\n self.J = partial(self._grad, funct=r)\n self.J_e = partial(self._grad, funct=r_e, nout=2)\n self.gradmodel_e = partial(self._grad, funct=m_e, nout=2)\n\n # add the appropriate documentation to the following functions\n self.fisherinformation.__doc__ = _graddoc + _sampledoc\n self.gradloglikelihood.__doc__ = _graddoc\n self.hessloglikelihood.__doc__ = _graddoc\n self.gradmodel.__doc__ = _graddoc + _sampledoc\n self.hessmodel.__doc__ = _graddoc + _sampledoc\n self.JTJ.__doc__ = _graddoc + _sampledoc\n self.J.__doc__ = _graddoc + _sampledoc\n\n # add documentation to the private functions as well. this is done\n # slightly differently, hence the function call\n self._dograddoc(self._grad_one_param)\n self._dograddoc(self._hess_two_param)\n self._dograddoc(self._grad)\n self._dograddoc(self._hess)\n\n # the state object is a workaround so that other interfaces still\n # work. this should probably be removed in the long run\n class _Statewrap(object):\n def __init__(self, obj):\n self.obj = obj\n def __getitem__(self, d=None):\n if d is None:\n d = self.obj.params\n return util.delistify(self.obj.get_values(d), d)\n\n self.state = _Statewrap(self)", "response": "Builds the gradients and hessian functions based on the properties of the state."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ncalculating the diagonal elements of the minimum covariance of the model containing the model with respect to parameters params.", "response": "def crb(self, params=None, *args, **kwargs):\n \"\"\"\n Calculate the diagonal elements of the minimum covariance of the model\n with respect to parameters params. ``*args`` and ``**kwargs`` go to\n ``fisherinformation``.\n \"\"\"\n fish = self.fisherinformation(params=params, *args, **kwargs)\n return np.sqrt(np.diag(np.linalg.inv(fish))) * self.sigma"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nset the model of the image.", "response": "def set_model(self, mdl):\n \"\"\"\n Setup the image model formation equation and corresponding objects into\n their various objects. `mdl` is a `peri.models.Model` object\n \"\"\"\n self.mdl = mdl\n self.mdl.check_inputs(self.comps)\n\n for c in self.comps:\n setattr(self, '_comp_'+c.category, c)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nupdates the current comparison ( real ) image", "response": "def set_image(self, image):\n \"\"\"\n Update the current comparison (real) image\n \"\"\"\n if isinstance(image, np.ndarray):\n image = util.Image(image)\n\n if isinstance(image, util.NullImage):\n self.model_as_data = True\n else:\n self.model_as_data = False\n\n self.image = image\n self._data = self.image.get_padded_image(self.pad)\n\n # set up various slicers and Tiles associated with the image and pad\n self.oshape = util.Tile(self._data.shape)\n self.ishape = self.oshape.pad(-self.pad)\n self.inner = self.ishape.slicer\n\n for c in self.comps:\n c.set_shape(self.oshape, self.ishape)\n\n self._model = np.zeros(self._data.shape, dtype=np.float64)\n self._residuals = np.zeros(self._data.shape, dtype=np.float64)\n self.calculate_model()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nswitching out the data for the model s recreation of the data.", "response": "def model_to_data(self, sigma=0.0):\n \"\"\" Switch out the data for the model's recreation of the data. \"\"\"\n im = self.model.copy()\n im += sigma*np.random.randn(*im.shape)\n self.set_image(util.NullImage(image=im))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get_update_io_tiles(self, params, values):\n # get the affected area of the model image\n otile = self.get_update_tile(params, values)\n if otile is None:\n return [None]*3\n ptile = self.get_padding_size(otile) or util.Tile(0, dim=otile.dim)\n\n otile = util.Tile.intersection(otile, self.oshape)\n\n if (otile.shape <= 0).any():\n raise UpdateError(\"update triggered invalid tile size\")\n\n if (ptile.shape < 0).any() or (ptile.shape > self.oshape.shape).any():\n raise UpdateError(\"update triggered invalid padding tile size\")\n\n # now remove the part of the tile that is outside the image and pad the\n # interior part with that overhang. reflect the necessary padding back\n # into the image itself for the outer slice which we will call outer\n outer = otile.pad((ptile.shape+1)//2)\n inner, outer = outer.reflect_overhang(self.oshape)\n iotile = inner.translate(-outer.l)\n\n outer = util.Tile.intersection(outer, self.oshape)\n inner = util.Tile.intersection(inner, self.oshape)\n return outer, inner, iotile", "response": "Get the tile that needs to be updated. Inputs are the parameters and values. Returns the tile that needs to be updated."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef update(self, params, values):\n # FIXME needs to update priors\n comps = self.affected_components(params)\n\n if len(comps) == 0:\n return False\n\n # get the affected area of the model image\n otile, itile, iotile = self.get_update_io_tiles(params, values)\n\n if otile is None:\n return False\n\n # have all components update their tiles\n self.set_tile(otile)\n\n oldmodel = self._model[itile.slicer].copy()\n\n # here we diverge depending if there is only one component update\n # (so that we may calculate a variation / difference image) or if many\n # parameters are being update (should just update the whole model).\n if len(comps) == 1 and self.mdl.get_difference_model(comps[0].category):\n comp = comps[0]\n model0 = copy.deepcopy(comp.get())\n super(ImageState, self).update(params, values)\n model1 = copy.deepcopy(comp.get())\n\n diff = model1 - model0\n diff = self.mdl.evaluate(\n self.comps, 'get', diffmap={comp.category: diff}\n )\n\n if isinstance(model0, (float, int)):\n self._model[itile.slicer] += diff\n else:\n self._model[itile.slicer] += diff[iotile.slicer]\n else:\n super(ImageState, self).update(params, values)\n\n # allow the model to be evaluated using our components\n diff = self.mdl.evaluate(self.comps, 'get')\n self._model[itile.slicer] = diff[iotile.slicer]\n\n newmodel = self._model[itile.slicer].copy()\n\n # use the model image update to modify other class variables which\n # are hard to compute globally for small local updates\n self.update_from_model_change(oldmodel, newmodel, itile)\n return True", "response": "Update the state based on a set of parameters and values."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn component by category name", "response": "def get(self, name):\n \"\"\" Return component by category name \"\"\"\n for c in self.comps:\n if c.category == name:\n return c\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _calc_loglikelihood(self, model=None, tile=None):\n if model is None:\n res = self.residuals\n else:\n res = model - self._data[tile.slicer]\n\n sig, isig = self.sigma, 1.0/self.sigma\n nlogs = -np.log(np.sqrt(2*np.pi)*sig)*res.size\n return -0.5*isig*isig*np.dot(res.flat, res.flat) + nlogs", "response": "Calculates the log - likelihood of the current state of the object."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nupdating the internal variables of the internal variables based on the model changes.", "response": "def update_from_model_change(self, oldmodel, newmodel, tile):\n \"\"\"\n Update various internal variables from a model update from oldmodel to\n newmodel for the tile `tile`\n \"\"\"\n self._loglikelihood -= self._calc_loglikelihood(oldmodel, tile=tile)\n self._loglikelihood += self._calc_loglikelihood(newmodel, tile=tile)\n self._residuals[tile.slicer] = self._data[tile.slicer] - newmodel"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nsets the memory usage level of the state.", "response": "def set_mem_level(self, mem_level='hi'):\n \"\"\"\n Sets the memory usage level of the state.\n\n Parameters\n ----------\n mem_level : string\n Can be set to one of:\n * hi : all mem's are np.float64\n * med-hi : image, platonic are float32, rest are float64\n * med : all mem's are float32\n * med-lo : image, platonic are float16, rest float32\n * lo : all are float16, which is bad for accuracy.\n\n Notes\n -----\n Right now the PSF is not affected by the mem-level changes, which is\n OK for mem but it means that self._model, self._residuals are always\n float64, which can be a chunk of mem.\n \"\"\"\n #A little thing to parse strings for convenience:\n key = ''.join([c if c in 'mlh' else '' for c in mem_level])\n if key not in ['h','mh','m','ml','m', 'l']:\n raise ValueError('mem_level must be one of hi, med-hi, med, med-lo, lo.')\n mem_levels = { 'h': [np.float64, np.float64],\n 'mh': [np.float64, np.float32],\n 'm': [np.float32, np.float32],\n 'ml': [np.float32, np.float16],\n 'l': [np.float16, np.float16]\n }\n hi_lvl, lo_lvl = mem_levels[key]\n cat_lvls = {'obj':lo_lvl,\n 'ilm':hi_lvl,\n 'bkg':lo_lvl\n } #no psf...\n\n self.image.float_precision = hi_lvl\n self.image.image = self.image.image.astype(lo_lvl)\n self.set_image(self.image)\n\n for cat in cat_lvls.keys():\n obj = self.get(cat)\n #check if it's a component collection\n if hasattr(obj, 'comps'):\n for c in obj.comps:\n c.float_precision = lo_lvl\n else:\n obj.float_precision = lo_lvl\n self._model = self._model.astype(hi_lvl)\n self._residuals = self._model.astype(hi_lvl)\n self.reset()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef create_img():\n # 1. particles + coverslip\n rad = 0.5 * np.random.randn(POS.shape[0]) + 4.5 # 4.5 +- 0.5 px particles\n part = objs.PlatonicSpheresCollection(POS, rad, zscale=0.89)\n slab = objs.Slab(zpos=4.92, angles=(-4.7e-3, -7.3e-4))\n objects = comp.ComponentCollection([part, slab], category='obj')\n\n # 2. psf, ilm\n p = exactpsf.FixedSSChebLinePSF(kfki=1.07, zslab=-29.3, alpha=1.17,\n n2n1=0.98, sigkf=-0.33, zscale=0.89, laser_wavelength=0.45)\n i = ilms.BarnesStreakLegPoly2P1D(npts=(16,10,8,4), zorder=8)\n b = ilms.LegendrePoly2P1D(order=(7,2,2), category='bkg')\n off = comp.GlobalScalar(name='offset', value=-2.11)\n mdl = models.ConfocalImageModel()\n st = states.ImageState(util.NullImage(shape=[48,64,64]),\n [objects, p, i, b, off], mdl=mdl, model_as_data=True)\n b.update(b.params, BKGVALS)\n i.update(i.params, ILMVALS)\n im = st.model + np.random.randn(*st.model.shape) * 0.03\n return util.Image(im)", "response": "Creates an image which is similar to the image in the tutorial"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nget the values of a list or single parameter.", "response": "def get_values(self, params):\n \"\"\"\n Get the value of a list or single parameter.\n\n Parameters\n ----------\n params : string, list of string\n name of parameters which to retrieve\n \"\"\"\n return util.delistify(\n [self.param_dict[p] for p in util.listify(params)], params\n )"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef set_values(self, params, values):\n for p, v in zip(util.listify(params), util.listify(values)):\n self.param_dict[p] = v", "response": "Directly set the values corresponding to certain parameters."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nset the overall shape of the image.", "response": "def set_shape(self, shape, inner):\n \"\"\"\n Set the overall shape of the calculation area. The total shape of that\n the calculation can possibly occupy, in pixels. The second, inner, is\n the region of interest within the image.\n \"\"\"\n if self.shape != shape or self.inner != inner:\n self.shape = shape\n self.inner = inner\n self.initialize()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nnotify parent of a parameter change", "response": "def trigger_update(self, params, values):\n \"\"\" Notify parent of a parameter change \"\"\"\n if self._parent:\n self._parent.trigger_update(params, values)\n else:\n self.update(params, values)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef split_params(self, params, values=None):\n pc, vc = [], []\n\n returnvalues = values is not None\n if values is None:\n values = [0]*len(util.listify(params))\n\n for c in self.comps:\n tp, tv = [], []\n for p,v in zip(util.listify(params), util.listify(values)):\n if not p in self.lmap:\n raise NotAParameterError(\"%r does not belong to %r\" % (p, self))\n\n if c in self.pmap[p]:\n tp.append(p)\n tv.append(v)\n\n pc.append(tp)\n vc.append(tv)\n\n if returnvalues:\n return pc, vc\n return pc", "response": "Split params values into groups that correspond to the ordering in\n self. comps."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ncombine the fields from all components", "response": "def get(self):\n \"\"\" Combine the fields from all components \"\"\"\n fields = [c.get() for c in self.comps]\n return self.field_reduce_func(fields)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nset the shape of the component.", "response": "def set_shape(self, shape, inner):\n \"\"\" Set the shape for all components \"\"\"\n for c in self.comps:\n c.set_shape(shape, inner)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef sync_params(self):\n def _normalize(comps, param):\n vals = [c.get_values(param) for c in comps]\n diff = any([vals[i] != vals[i+1] for i in range(len(vals)-1)])\n\n if diff:\n for c in comps:\n c.set_values(param, vals[0])\n\n for param, comps in iteritems(self.lmap):\n if isinstance(comps, list) and len(comps) > 1:\n _normalize(comps, param)", "response": "Ensure that shared parameters are the same value everywhere"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef setup_passthroughs(self):\n self._nopickle = []\n\n for c in self.comps:\n # take all member functions that start with 'param_'\n funcs = inspect.getmembers(c, predicate=inspect.ismethod)\n for func in funcs:\n if func[0].startswith('param_'):\n setattr(self, func[0], func[1])\n self._nopickle.append(func[0])\n\n # add everything from exports\n funcs = c.exports()\n for func in funcs:\n newname = c.category + '_' + func.__func__.__name__\n setattr(self, newname, func)\n self._nopickle.append(newname)", "response": "Set up the attributes that are used by the object to be used by the object."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn the path to the configuration file for the current project.", "response": "def get_conf_filename():\n \"\"\"\n The configuration file either lives in ~/.peri.json or is specified on the\n command line via the environment variables PERI_CONF_FILE\n \"\"\"\n default = os.path.join(os.path.expanduser(\"~\"), \".peri.json\")\n return os.environ.get('PERI_CONF_FILE', default)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef read_environment():\n out = {}\n for k,v in iteritems(os.environ):\n if transform(k) in default_conf:\n out[transform(k)] = v\n return out", "response": "Read all environment variables to see if they contain PERI"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nload the configuration file with the priority", "response": "def load_conf():\n \"\"\"\n Load the configuration with the priority:\n 1. environment variables\n 2. configuration file\n 3. defaults here (default_conf)\n \"\"\"\n try:\n conf = copy.copy(default_conf)\n conf.update(json.load(open(get_conf_filename())))\n conf.update(read_environment())\n return conf\n except IOError as e:\n create_default_conf()\n return load_conf()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nuse for breadcrumb dynamic_list_constructor. Returns the group name.", "response": "def get_group_name(id_group):\n \"\"\"Used for breadcrumb dynamic_list_constructor.\"\"\"\n group = Group.query.get(id_group)\n if group is not None:\n return group.name"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef index():\n page = request.args.get('page', 1, type=int)\n per_page = request.args.get('per_page', 5, type=int)\n q = request.args.get('q', '')\n\n groups = Group.query_by_user(current_user, eager=True)\n if q:\n groups = Group.search(groups, q)\n groups = groups.paginate(page, per_page=per_page)\n\n requests = Membership.query_requests(current_user).count()\n invitations = Membership.query_invitations(current_user).count()\n\n return render_template(\n 'invenio_groups/index.html',\n groups=groups,\n requests=requests,\n invitations=invitations,\n page=page,\n per_page=per_page,\n q=q\n )", "response": "List all user memberships."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef requests():\n page = request.args.get('page', 1, type=int)\n per_page = request.args.get('per_page', 5, type=int)\n memberships = Membership.query_requests(current_user, eager=True).all()\n\n return render_template(\n 'invenio_groups/pending.html',\n memberships=memberships,\n requests=True,\n page=page,\n per_page=per_page,\n )", "response": "List all pending memberships listed only for group admins."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef invitations():\n page = request.args.get('page', 1, type=int)\n per_page = request.args.get('per_page', 5, type=int)\n memberships = Membership.query_invitations(current_user, eager=True).all()\n\n return render_template(\n 'invenio_groups/pending.html',\n memberships=memberships,\n page=page,\n per_page=per_page,\n )", "response": "List all pending memberships."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nlist user group members.", "response": "def members(group_id):\n \"\"\"List user group members.\"\"\"\n page = request.args.get('page', 1, type=int)\n per_page = request.args.get('per_page', 5, type=int)\n q = request.args.get('q', '')\n s = request.args.get('s', '')\n\n group = Group.query.get_or_404(group_id)\n if group.can_see_members(current_user):\n members = Membership.query_by_group(group_id, with_invitations=True)\n if q:\n members = Membership.search(members, q)\n if s:\n members = Membership.order(members, Membership.state, s)\n members = members.paginate(page, per_page=per_page)\n\n return render_template(\n \"invenio_groups/members.html\",\n group=group,\n members=members,\n page=page,\n per_page=per_page,\n q=q,\n s=s,\n )\n\n flash(\n _(\n 'You are not allowed to see members of this group %(group_name)s.',\n group_name=group.name\n ),\n 'error'\n )\n return redirect(url_for('.index'))"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef remove(group_id, user_id):\n group = Group.query.get_or_404(group_id)\n user = User.query.get_or_404(user_id)\n\n if group.can_edit(current_user):\n try:\n group.remove_member(user)\n except Exception as e:\n flash(str(e), \"error\")\n return redirect(urlparse(request.referrer).path)\n\n flash(_('User %(user_email)s was removed from %(group_name)s group.',\n user_email=user.email, group_name=group.name), 'success')\n return redirect(urlparse(request.referrer).path)\n\n flash(\n _(\n 'You cannot delete users of the group %(group_name)s',\n group_name=group.name\n ),\n 'error'\n )\n return redirect(url_for('.index'))", "response": "Remove a user from a group."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nadding ( invite ) new member.", "response": "def new_member(group_id):\n \"\"\"Add (invite) new member.\"\"\"\n group = Group.query.get_or_404(group_id)\n\n if group.can_invite_others(current_user):\n form = NewMemberForm()\n\n if form.validate_on_submit():\n emails = filter(None, form.data['emails'].splitlines())\n group.invite_by_emails(emails)\n flash(_('Requests sent!'), 'success')\n return redirect(url_for('.members', group_id=group.id))\n\n return render_template(\n \"invenio_groups/new_member.html\",\n group=group,\n form=form\n )\n\n flash(\n _(\n 'You cannot invite users or yourself (i.e. join) to the group '\n '%(group_name)s',\n group_name=group.name\n ),\n 'error'\n )\n return redirect(url_for('.index'))"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns a sequence of initial featuring of spheres in an image.", "response": "def locate_spheres(image, feature_rad, dofilter=False, order=(3 ,3, 3),\n trim_edge=True, **kwargs):\n \"\"\"\n Get an initial featuring of sphere positions in an image.\n\n Parameters\n -----------\n image : :class:`peri.util.Image` object\n Image object which defines the image file as well as the region.\n\n feature_rad : float\n Radius of objects to find, in pixels. This is a featuring radius\n and not a real radius, so a better value is frequently smaller\n than the real radius (half the actual radius is good). If ``use_tp``\n is True, then the twice ``feature_rad`` is passed as trackpy's\n ``diameter`` keyword.\n\n dofilter : boolean, optional\n Whether to remove the background before featuring. Doing so can\n often greatly increase the success of initial featuring and\n decrease later optimization time. Filtering functions by fitting\n the image to a low-order polynomial and featuring the residuals.\n In doing so, this will change the mean intensity of the featured\n image and hence the good value of ``minmass`` will change when\n ``dofilter`` is True. Default is False.\n\n order : 3-element tuple, optional\n If `dofilter`, the 2+1D Leg Poly approximation to the background\n illumination field. Default is (3,3,3).\n\n Other Parameters\n ----------------\n invert : boolean, optional\n Whether to invert the image for featuring. Set to True if the\n image is dark particles on a bright background. Default is True\n minmass : Float or None, optional\n The minimum mass/masscut of a particle. Default is None, which\n calculates internally.\n use_tp : Bool, optional\n Whether or not to use trackpy. Default is False, since trackpy\n cuts out particles at the edge.\n\n Returns\n --------\n positions : np.ndarray [N,3]\n Positions of the particles in order (z,y,x) in image pixel units.\n\n Notes\n -----\n Optionally filters the image by fitting the image I(x,y,z) to a\n polynomial, then subtracts this fitted intensity variation and uses\n centroid methods to find the particles.\n \"\"\"\n # We just want a smoothed field model of the image so that the residuals\n # are simply the particles without other complications\n m = models.SmoothFieldModel()\n I = ilms.LegendrePoly2P1D(order=order, constval=image.get_image().mean())\n s = states.ImageState(image, [I], pad=0, mdl=m)\n if dofilter:\n opt.do_levmarq(s, s.params)\n pos = addsub.feature_guess(s, feature_rad, trim_edge=trim_edge, **kwargs)[0]\n return pos"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_initial_featuring(statemaker, feature_rad, actual_rad=None,\n im_name=None, tile=None, invert=True, desc='', use_full_path=False,\n featuring_params={}, statemaker_kwargs={}, **kwargs):\n \"\"\"\n Completely optimizes a state from an image of roughly monodisperse\n particles.\n\n The user can interactively select the image. The state is periodically\n saved during optimization, with different filename for different stages\n of the optimization.\n\n Parameters\n ----------\n statemaker : Function\n A statemaker function. Given arguments `im` (a\n :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),\n and any additional `statemaker_kwargs`, must return a\n :class:`~peri.states.ImageState`. There is an example function in\n scripts/statemaker_example.py\n feature_rad : Int, odd\n The particle radius for featuring, as passed to locate_spheres.\n actual_rad : Float, optional\n The actual radius of the particles. Default is feature_rad\n im_name : string, optional\n The file name of the image to load. If not set, it is selected\n interactively through Tk.\n tile : :class:`peri.util.Tile`, optional\n The tile of the raw image to be analyzed. Default is None, the\n entire image.\n invert : Bool, optional\n Whether to invert the image for featuring, as passed to trackpy.\n Default is True.\n desc : String, optional\n A description to be inserted in saved state. The save name will\n be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n use_full_path : Bool, optional\n Set to True to use the full path name for the image. Default\n is False.\n featuring_params : Dict, optional\n kwargs-like dict of any additional keyword arguments to pass to\n ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.\n Default is ``{}``.\n statemaker_kwargs : Dict, optional\n kwargs-like dict of any additional keyword arguments to pass to\n the statemaker function. Default is ``{}``.\n\n Other Parameters\n ----------------\n max_mem : Numeric\n The maximum additional memory to use for the optimizers, as\n passed to optimize.burn. Default is 1e9.\n min_rad : Float, optional\n The minimum particle radius, as passed to addsubtract.add_subtract.\n Particles with a fitted radius smaller than this are identified\n as fake and removed. Default is 0.5 * actual_rad.\n max_rad : Float, optional\n The maximum particle radius, as passed to addsubtract.add_subtract.\n Particles with a fitted radius larger than this are identified\n as fake and removed. Default is 1.5 * actual_rad, however you\n may find better results if you make this more stringent.\n rz_order : int, optional\n If nonzero, the order of an additional augmented rscl(z)\n parameter for optimization. Default is 0; i.e. no rscl(z)\n optimization.\n zscale : Float, optional\n The zscale of the image. Default is 1.0\n\n Returns\n -------\n s : :class:`peri.states.ImageState`\n The optimized state.\n\n See Also\n --------\n feature_from_pos_rad : Using a previous state's globals and\n user-provided positions and radii as an initial guess,\n completely optimizes a state.\n\n get_particle_featuring : Using a previous state's globals and\n positions as an initial guess, completely optimizes a state.\n\n translate_featuring : Use a previous state's globals and\n centroids methods for an initial particle guess, completely\n optimizes a state.\n\n Notes\n -----\n Proceeds by centroid-featuring the image for an initial guess of\n particle positions, then optimizing the globals + positions until\n termination as called in _optimize_from_centroid.\n The ``Other Parameters`` are passed to _optimize_from_centroid.\n \"\"\"\n if actual_rad is None:\n actual_rad = feature_rad\n\n _, im_name = _pick_state_im_name('', im_name, use_full_path=use_full_path)\n im = util.RawImage(im_name, tile=tile)\n\n pos = locate_spheres(im, feature_rad, invert=invert, **featuring_params)\n if np.size(pos) == 0:\n msg = 'No particles found. Try using a smaller `feature_rad`.'\n raise ValueError(msg)\n\n rad = np.ones(pos.shape[0], dtype='float') * actual_rad\n s = statemaker(im, pos, rad, **statemaker_kwargs)\n RLOG.info('State Created.')\n if desc is not None:\n states.save(s, desc=desc+'initial')\n optimize_from_initial(s, invert=invert, desc=desc, **kwargs)\n return s", "response": "This function is used to get the initial state from an image of roughly monodisperse\n particles."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning a state from an image and an initial guess of the particle positions and radii.", "response": "def feature_from_pos_rad(statemaker, pos, rad, im_name=None, tile=None,\n desc='', use_full_path=False, statemaker_kwargs={}, **kwargs):\n \"\"\"\n Gets a completely-optimized state from an image and an initial guess of\n particle positions and radii.\n\n The state is periodically saved during optimization, with different\n filename for different stages of the optimization. The user can select\n the image.\n\n Parameters\n ----------\n statemaker : Function\n A statemaker function. Given arguments `im` (a\n :class:`~peri.util.Image`), `pos` (numpy.ndarray), `rad` (ndarray),\n and any additional `statemaker_kwargs`, must return a\n :class:`~peri.states.ImageState`. There is an example function in\n scripts/statemaker_example.py\n pos : [N,3] element numpy.ndarray.\n The initial guess for the N particle positions.\n rad : N element numpy.ndarray.\n The initial guess for the N particle radii.\n im_name : string or None, optional\n The filename of the image to feature. Default is None, in which\n the user selects the image.\n tile : :class:`peri.util.Tile`, optional\n A tile of the sub-region of the image to feature. Default is\n None, i.e. entire image.\n desc : String, optional\n A description to be inserted in saved state. The save name will\n be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n use_full_path : Bool, optional\n Set to True to use the full path name for the image. Default\n is False.\n statemaker_kwargs : Dict, optional\n kwargs-like dict of any additional keyword arguments to pass to\n the statemaker function. Default is ``{}``.\n\n Other Parameters\n ----------------\n max_mem : Numeric\n The maximum additional memory to use for the optimizers, as\n passed to optimize.burn. Default is 1e9.\n min_rad : Float, optional\n The minimum particle radius, as passed to addsubtract.add_subtract.\n Particles with a fitted radius smaller than this are identified\n as fake and removed. Default is 0.5 * actual_rad.\n max_rad : Float, optional\n The maximum particle radius, as passed to addsubtract.add_subtract.\n Particles with a fitted radius larger than this are identified\n as fake and removed. Default is 1.5 * actual_rad, however you\n may find better results if you make this more stringent.\n invert : {'guess', True, False}\n Whether to invert the image for featuring, as passed to\n addsubtract.add_subtract. Default is to guess from the\n current state's particle positions.\n rz_order : int, optional\n If nonzero, the order of an additional augmented rscl(z)\n parameter for optimization. Default is 0; i.e. no rscl(z)\n optimization.\n zscale : Float, optional\n The zscale of the image. Default is 1.0\n\n Returns\n -------\n s : :class:`peri.states.ImageState`\n The optimized state.\n\n See Also\n --------\n get_initial_featuring : Features an image from scratch, using\n centroid methods as initial particle locations.\n\n get_particle_featuring : Using a previous state's globals and\n positions as an initial guess, completely optimizes a state.\n\n translate_featuring : Use a previous state's globals and\n centroids methods for an initial particle guess, completely\n optimizes a state.\n\n Notes\n -----\n The ``Other Parameters`` are passed to _optimize_from_centroid.\n Proceeds by centroid-featuring the image for an initial guess of\n particle positions, then optimizing the globals + positions until\n termination as called in _optimize_from_centroid.\n \"\"\"\n if np.size(pos) == 0:\n raise ValueError('`pos` is an empty array.')\n elif np.shape(pos)[1] != 3:\n raise ValueError('`pos` must be an [N,3] element numpy.ndarray.')\n _, im_name = _pick_state_im_name('', im_name, use_full_path=use_full_path)\n im = util.RawImage(im_name, tile=tile)\n s = statemaker(im, pos, rad, **statemaker_kwargs)\n RLOG.info('State Created.')\n if desc is not None:\n states.save(s, desc=desc+'initial')\n optimize_from_initial(s, desc=desc, **kwargs)\n return s"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef optimize_from_initial(s, max_mem=1e9, invert='guess', desc='', rz_order=3,\n min_rad=None, max_rad=None):\n \"\"\"\n Optimizes a state from an initial set of positions and radii, without\n any known microscope parameters.\n\n Parameters\n ----------\n s : :class:`peri.states.ImageState`\n The state to optimize. It is modified internally and returned.\n max_mem : Numeric, optional\n The maximum memory for the optimizer to use. Default is 1e9 (bytes)\n invert : Bool or `'guess'`, optional\n Set to True if the image is dark particles on a bright\n background, False otherwise. Used for add-subtract. The\n default is to guess from the state's current particles.\n desc : String, optional\n An additional description to infix for periodic saving along the\n way. Default is the null string ``''``.\n rz_order : int, optional\n ``rz_order`` as passed to opt.burn. Default is 3\n min_rad : Float or None, optional\n The minimum radius to identify a particles as bad, as passed to\n add-subtract. Default is None, which picks half the median radii.\n If your sample is not monodisperse you should pick a different\n value.\n max_rad : Float or None, optional\n The maximum radius to identify a particles as bad, as passed to\n add-subtract. Default is None, which picks 1.5x the median radii.\n If your sample is not monodisperse you should pick a different\n value.\n\n Returns\n -------\n s : :class:`peri.states.ImageState`\n The optimized state, which is the same as the input ``s`` but\n modified in-place.\n \"\"\"\n RLOG.info('Initial burn:')\n if desc is not None:\n desc_burn = desc + 'initial-burn'\n desc_polish = desc + 'addsub-polish'\n else:\n desc_burn, desc_polish = [None] * 2\n opt.burn(s, mode='burn', n_loop=3, fractol=0.1, desc=desc_burn,\n max_mem=max_mem, include_rad=False, dowarn=False)\n opt.burn(s, mode='burn', n_loop=3, fractol=0.1, desc=desc_burn,\n max_mem=max_mem, include_rad=True, dowarn=False)\n\n RLOG.info('Start add-subtract')\n rad = s.obj_get_radii()\n if min_rad is None:\n min_rad = 0.5 * np.median(rad)\n if max_rad is None:\n max_rad = 1.5 * np.median(rad)\n addsub.add_subtract(s, tries=30, min_rad=min_rad, max_rad=max_rad,\n invert=invert)\n if desc is not None:\n states.save(s, desc=desc + 'initial-addsub')\n\n RLOG.info('Final polish:')\n d = opt.burn(s, mode='polish', n_loop=8, fractol=3e-4, desc=desc_polish,\n max_mem=max_mem, rz_order=rz_order, dowarn=False)\n if not d['converged']:\n RLOG.warn('Optimization did not converge; consider re-running')\n return s", "response": "Optimize a state from an initial set of positions and radii."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef translate_featuring(state_name=None, im_name=None, use_full_path=False,\n **kwargs):\n \"\"\"\n Translates one optimized state into another image where the particles\n have moved by a small amount (~1 particle radius).\n\n Returns a completely-optimized state. The user can interactively\n selects the initial state and the second raw image. The state is\n periodically saved during optimization, with different filename for\n different stages of the optimization.\n\n Parameters\n ----------\n state_name : String or None, optional\n The name of the initially-optimized state. Default is None,\n which prompts the user to select the name interactively\n through a Tk window.\n im_name : String or None, optional\n The name of the new image to optimize. Default is None,\n which prompts the user to select the name interactively\n through a Tk window.\n use_full_path : Bool, optional\n Set to True to use the full path of the state instead of\n partial path names (e.g. /full/path/name/state.pkl vs\n state.pkl). Default is False\n\n Other Parameters\n ----------------\n max_mem : Numeric\n The maximum additional memory to use for the optimizers, as\n passed to optimize.burn. Default is 1e9.\n desc : String, optional\n A description to be inserted in saved state. The save name will\n be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n min_rad : Float, optional\n The minimum particle radius, as passed to addsubtract.add_subtract.\n Particles with a fitted radius smaller than this are identified\n as fake and removed. Default is 0.5 * actual_rad.\n max_rad : Float, optional\n The maximum particle radius, as passed to addsubtract.add_subtract.\n Particles with a fitted radius larger than this are identified\n as fake and removed. Default is 1.5 * actual_rad, however you\n may find better results if you make this more stringent.\n invert : {True, False, 'guess'}\n Whether to invert the image for featuring, as passed to\n addsubtract.add_subtract. Default is to guess from the\n state's current particles.\n rz_order : int, optional\n If nonzero, the order of an additional augmented rscl(z)\n parameter for optimization. Default is 0; i.e. no rscl(z)\n optimization.\n do_polish : Bool, optional\n Set to False to only optimize the particles and add-subtract.\n Default is True, which then runs a polish afterwards.\n\n Returns\n -------\n s : :class:`peri.states.ImageState`\n The optimized state.\n\n See Also\n --------\n get_initial_featuring : Features an image from scratch, using\n centroid methods as initial particle locations.\n\n feature_from_pos_rad : Using a previous state's globals and\n user-provided positions and radii as an initial guess,\n completely optimizes a state.\n\n get_particle_featuring : Using a previous state's globals and\n positions as an initial guess, completely optimizes a state.\n\n Notes\n -----\n The ``Other Parameters`` are passed to _translate_particles.\n Proceeds by:\n 1. Optimize particle positions only.\n 2. Optimize particle positions and radii only.\n 3. Add-subtract missing and bad particles.\n 4. If polish, optimize the illumination, background, and particles.\n 5. If polish, optimize everything.\n \"\"\"\n state_name, im_name = _pick_state_im_name(\n state_name, im_name, use_full_path=use_full_path)\n\n s = states.load(state_name)\n im = util.RawImage(im_name, tile=s.image.tile)\n\n s.set_image(im)\n _translate_particles(s, **kwargs)\n return s", "response": "Translate a single state into another state."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_particles_featuring(feature_rad, state_name=None, im_name=None,\n use_full_path=False, actual_rad=None, invert=True, featuring_params={},\n **kwargs):\n \"\"\"\n Combines centroid featuring with the globals from a previous state.\n\n Runs trackpy.locate on an image, sets the globals from a previous state,\n calls _translate_particles\n\n Parameters\n ----------\n feature_rad : Int, odd\n The particle radius for featuring, as passed to locate_spheres.\n\n state_name : String or None, optional\n The name of the initially-optimized state. Default is None,\n which prompts the user to select the name interactively\n through a Tk window.\n im_name : String or None, optional\n The name of the new image to optimize. Default is None,\n which prompts the user to select the name interactively\n through a Tk window.\n use_full_path : Bool, optional\n Set to True to use the full path of the state instead of\n partial path names (e.g. /full/path/name/state.pkl vs\n state.pkl). Default is False\n actual_rad : Float or None, optional\n The initial guess for the particle radii. Default is the median\n of the previous state.\n invert : Bool\n Whether to invert the image for featuring, as passed to\n addsubtract.add_subtract and locate_spheres. Set to False\n if the image is bright particles on a dark background.\n Default is True (dark particles on bright background).\n featuring_params : Dict, optional\n kwargs-like dict of any additional keyword arguments to pass to\n ``get_initial_featuring``, such as ``'use_tp'`` or ``'minmass'``.\n Default is ``{}``.\n\n\n Other Parameters\n ----------------\n max_mem : Numeric\n The maximum additional memory to use for the optimizers, as\n passed to optimize.burn. Default is 1e9.\n desc : String, optional\n A description to be inserted in saved state. The save name will\n be, e.g., '0.tif-peri-' + desc + 'initial-burn.pkl'. Default is ''\n min_rad : Float, optional\n The minimum particle radius, as passed to addsubtract.add_subtract.\n Particles with a fitted radius smaller than this are identified\n as fake and removed. Default is 0.5 * actual_rad.\n max_rad : Float, optional\n The maximum particle radius, as passed to addsubtract.add_subtract.\n Particles with a fitted radius larger than this are identified\n as fake and removed. Default is 1.5 * actual_rad, however you\n may find better results if you make this more stringent.\n rz_order : int, optional\n If nonzero, the order of an additional augmented rscl(z)\n parameter for optimization. Default is 0; i.e. no rscl(z)\n optimization.\n do_polish : Bool, optional\n Set to False to only optimize the particles and add-subtract.\n Default is True, which then runs a polish afterwards.\n\n Returns\n -------\n s : :class:`peri.states.ImageState`\n The optimized state.\n\n See Also\n --------\n get_initial_featuring : Features an image from scratch, using\n centroid methods as initial particle locations.\n\n feature_from_pos_rad : Using a previous state's globals and\n user-provided positions and radii as an initial guess,\n completely optimizes a state.\n\n translate_featuring : Use a previous state's globals and\n centroids methods for an initial particle guess, completely\n optimizes a state.\n\n Notes\n -----\n The ``Other Parameters`` are passed to _translate_particles.\n Proceeds by:\n 1. Find a guess of the particle positions through centroid methods.\n 2. Optimize particle positions only.\n 3. Optimize particle positions and radii only.\n 4. Add-subtract missing and bad particles.\n 5. If polish, optimize the illumination, background, and particles.\n 6. If polish, optimize everything.\n \"\"\"\n state_name, im_name = _pick_state_im_name(\n state_name, im_name, use_full_path=use_full_path)\n s = states.load(state_name)\n\n if actual_rad is None:\n actual_rad = np.median(s.obj_get_radii())\n im = util.RawImage(im_name, tile=s.image.tile)\n pos = locate_spheres(im, feature_rad, invert=invert, **featuring_params)\n _ = s.obj_remove_particle(np.arange(s.obj_get_radii().size))\n s.obj_add_particle(pos, np.ones(pos.shape[0])*actual_rad)\n\n s.set_image(im)\n _translate_particles(s, invert=invert, **kwargs)\n return s", "response": "Returns a new state with the given particle radius and state name."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _pick_state_im_name(state_name, im_name, use_full_path=False):\n initial_dir = os.getcwd()\n if (state_name is None) or (im_name is None):\n wid = tk.Tk()\n wid.withdraw()\n if state_name is None:\n state_name = tkfd.askopenfilename(\n initialdir=initial_dir, title='Select pre-featured state')\n os.chdir(os.path.dirname(state_name))\n\n if im_name is None:\n im_name = tkfd.askopenfilename(\n initialdir=initial_dir, title='Select new image')\n\n if (not use_full_path) and (os.path.dirname(im_name) != ''):\n im_path = os.path.dirname(im_name)\n os.chdir(im_path)\n im_name = os.path.basename(im_name)\n else:\n os.chdir(initial_dir)\n return state_name, im_name", "response": "Picks the state and image name from the Tk file system."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ntranslating a set of particles into a single set of states.", "response": "def _translate_particles(s, max_mem=1e9, desc='', min_rad='calc',\n max_rad='calc', invert='guess', rz_order=0, do_polish=True):\n \"\"\"\n Workhorse for translating particles. See get_particles_featuring for docs.\n \"\"\"\n if desc is not None:\n desc_trans = desc + 'translate-particles'\n desc_burn = desc + 'addsub_burn'\n desc_polish = desc + 'addsub_polish'\n else:\n desc_trans, desc_burn, desc_polish = [None]*3\n RLOG.info('Translate Particles:')\n opt.burn(s, mode='do-particles', n_loop=4, fractol=0.1, desc=desc_trans,\n max_mem=max_mem, include_rad=False, dowarn=False)\n opt.burn(s, mode='do-particles', n_loop=4, fractol=0.05, desc=desc_trans,\n max_mem=max_mem, include_rad=True, dowarn=False)\n\n RLOG.info('Start add-subtract')\n addsub.add_subtract(s, tries=30, min_rad=min_rad, max_rad=max_rad,\n invert=invert)\n if desc is not None:\n states.save(s, desc=desc + 'translate-addsub')\n\n if do_polish:\n RLOG.info('Final Burn:')\n opt.burn(s, mode='burn', n_loop=3, fractol=3e-4, desc=desc_burn,\n max_mem=max_mem, rz_order=rz_order,dowarn=False)\n RLOG.info('Final Polish:')\n d = opt.burn(s, mode='polish', n_loop=4, fractol=3e-4, desc=desc_polish,\n max_mem=max_mem, rz_order=rz_order, dowarn=False)\n if not d['converged']:\n RLOG.warn('Optimization did not converge; consider re-running')"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef link_zscale(st):\n # FIXME should be made more generic to other parameters and categories\n psf = st.get('psf')\n psf.param_dict['zscale'] = psf.param_dict['psf-zscale']\n psf.params[psf.params.index('psf-zscale')] = 'zscale'\n psf.global_zscale = True\n psf.param_dict.pop('psf-zscale')\n st.trigger_parameter_change()\n st.reset()", "response": "Links the state st psf zscale with the global zscale"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef finish_state(st, desc='finish-state', invert='guess'):\n for minmass in [None, 0]:\n for _ in range(3):\n npart, poses = addsub.add_subtract_locally(st, region_depth=7,\n minmass=minmass, invert=invert)\n if npart == 0:\n break\n opt.finish(st, n_loop=1, separate_psf=True, desc=desc, dowarn=False)\n opt.burn(st, mode='polish', desc=desc, n_loop=2, dowarn=False)\n d = opt.finish(st, desc=desc, n_loop=4, dowarn=False)\n if not d['converged']:\n RLOG.warn('Optimization did not converge; consider re-running')", "response": "Finishes the state of the best - possible state."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\noptimize a particle by computing the gradients and hessian of the particle at the given index.", "response": "def optimize_particle(state, index, method='gn', doradius=True):\n \"\"\"\n Methods available are\n gn : Gauss-Newton with JTJ (recommended)\n nr : Newton-Rhaphson with hessian\n\n if doradius, also optimize the radius.\n \"\"\"\n blocks = state.param_particle(index)\n\n if not doradius:\n blocks = blocks[:-1]\n\n g = state.gradloglikelihood(blocks=blocks)\n if method == 'gn':\n h = state.jtj(blocks=blocks)\n if method == 'nr':\n h = state.hessloglikelihood(blocks=blocks)\n step = np.linalg.solve(h, g)\n\n h = np.zeros_like(g)\n for i in range(len(g)):\n state.update(blocks[i], state.state[blocks[i]] - step[i])\n return g,h"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ncreate a new image state with an initial centroid of the image.", "response": "def makestate(im, pos, rad, slab=None, mem_level='hi'):\n \"\"\"\n Workhorse for creating & optimizing states with an initial centroid\n guess.\n\n This is an example function that works for a particular microscope. For\n your own microscope, you'll need to change particulars such as the psf\n type and the orders of the background and illumination.\n\n Parameters\n ----------\n im : :class:`~peri.util.RawImage`\n A RawImage of the data.\n pos : [N,3] element numpy.ndarray.\n The initial guess for the N particle positions.\n rad : N element numpy.ndarray.\n The initial guess for the N particle radii.\n\n slab : :class:`peri.comp.objs.Slab` or None, optional\n If not None, a slab corresponding to that in the image. Default\n is None.\n mem_level : {'lo', 'med-lo', 'med', 'med-hi', 'hi'}, optional\n A valid memory level for the state to control the memory overhead\n at the expense of accuracy. Default is `'hi'`\n\n Returns\n -------\n :class:`~peri.states.ImageState`\n An ImageState with a linked z-scale, a ConfocalImageModel, and\n all the necessary components with orders at which are useful for\n my particular test case.\n \"\"\"\n if slab is not None:\n o = comp.ComponentCollection(\n [\n objs.PlatonicSpheresCollection(pos, rad, zscale=zscale),\n slab\n ],\n category='obj'\n )\n else:\n o = objs.PlatonicSpheresCollection(pos, rad, zscale=zscale)\n\n p = exactpsf.FixedSSChebLinePSF()\n npts, iorder = _calc_ilm_order(im.get_image().shape)\n i = ilms.BarnesStreakLegPoly2P1D(npts=npts, zorder=iorder)\n b = ilms.LegendrePoly2P1D(order=(9 ,3, 5), category='bkg')\n c = comp.GlobalScalar('offset', 0.0)\n s = states.ImageState(im, [o, i, b, c, p])\n runner.link_zscale(s)\n if mem_level != 'hi':\n s.set_mem_level(mem_level)\n\n opt.do_levmarq(s, ['ilm-scale'], max_iter=1, run_length=6, max_mem=1e4)\n return s"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _calc_ilm_order(imshape):\n zorder = int(imshape[0] / 6.25) + 1\n l_npts = int(imshape[1] / 42.5)+1\n npts = ()\n for a in range(l_npts):\n if a < 5:\n npts += (int(imshape[2] * [59, 39, 29, 19, 14][a]/512.) + 1,)\n else:\n npts += (int(imshape[2] * 11/512.) + 1,)\n return npts, zorder", "response": "Calculates an ilm order based on the shape of an image."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _check_for_inception(self, root_dict):\n '''\n Used to check if there is a dict in a dict\n '''\n\n for key in root_dict:\n if isinstance(root_dict[key], dict):\n root_dict[key] = ResponseObject(root_dict[key])\n\n return root_dict", "response": "Checks if the dict contains any inceptions"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncreating random parameters for this ILM that mimic experiments .", "response": "def randomize_parameters(self, ptp=0.2, fourier=False, vmin=None, vmax=None):\n \"\"\"\n Create random parameters for this ILM that mimic experiments\n as closely as possible without real assumptions.\n \"\"\"\n if vmin is not None and vmax is not None:\n ptp = vmax - vmin\n elif vmax is not None and vmin is None:\n vmin = vmax - ptp\n elif vmin is not None and vmax is None:\n vmax = vmin + ptp\n else:\n vmax = 1.0\n vmin = vmax - ptp\n\n self.set_values(self.category+'-scale', 1.0)\n self.set_values(self.category+'-off', 0.0)\n\n for k, v in iteritems(self.poly_params):\n norm = (self.zorder + 1.0)*2\n self.set_values(k, ptp*(np.random.rand() - 0.5) / norm)\n\n for i, p in enumerate(self.barnes_params):\n N = len(p)\n if fourier:\n t = ((np.random.rand(N)-0.5) + 1.j*(np.random.rand(N)-0.5))/(np.arange(N)+1)\n q = np.real(np.fft.ifftn(t)) / (i+1)\n else:\n t = ptp*np.sqrt(N)*(np.random.rand(N)-0.5)\n q = np.cumsum(t) / (i+1)\n\n q = ptp * q / q.ptp() / len(self.barnes_params)\n q -= q.mean()\n self.set_values(p, q)\n\n self._norm_stat = [ptp, vmin]\n\n if self.shape:\n self.initialize()\n\n if self._parent:\n param = self.category+'-scale'\n self.trigger_update(param, self.get_values(param))"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncreates a barnes interpolant and calculates its values", "response": "def _barnes(self, pos):\n \"\"\"Creates a barnes interpolant & calculates its values\"\"\"\n b_in = self.b_in\n dist = lambda x: np.sqrt(np.dot(x,x))\n #we take a filter size as the max distance between the grids along\n #x or y:\n sz = self.npts[1]\n coeffs = self.get_values(self.barnes_params)\n\n b = BarnesInterpolationND(\n b_in, coeffs, filter_size=self.filtsize, damp=0.9, iterations=3,\n clip=self.local_updates, clipsize=self.barnes_clip_size,\n blocksize=100 # FIXME magic blocksize\n )\n return b(pos)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn the details of the posting schedules associated with a social media profile.", "response": "def schedules(self):\n '''\n Returns details of the posting schedules associated with a social media\n profile.\n '''\n\n url = PATHS['GET_SCHEDULES'] % self.id\n\n self.__schedules = self.api.get(url=url)\n\n return self.__schedules"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef schedules(self, schedules):\n '''\n Set the posting schedules for the specified social media profile.\n '''\n\n url = PATHS['UPDATE_SCHEDULES'] % self.id\n\n data_format = \"schedules[0][%s][]=%s&\"\n post_data = \"\"\n\n for format_type, values in schedules.iteritems():\n for value in values:\n post_data += data_format % (format_type, value)\n\n self.api.post(url=url, data=post_data)", "response": "Updates the posting schedules for the specified social media profile."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncalculating the moments of the probability distribution p with vector v", "response": "def moment(p, v, order=1):\n \"\"\" Calculates the moments of the probability distribution p with vector v \"\"\"\n if order == 1:\n return (v*p).sum()\n elif order == 2:\n return np.sqrt( ((v**2)*p).sum() - (v*p).sum()**2 )"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncalculate the 3D PSF at a particular z pixel height.", "response": "def psf_slice(self, zint, size=11, zoffset=0., getextent=False):\n \"\"\"\n Calculates the 3D psf at a particular z pixel height\n\n Parameters\n ----------\n zint : float\n z pixel height in image coordinates , converted to 1/k by the\n function using the slab position as well\n\n size : int, list, tuple\n The size over which to calculate the psf, can be 1 or 3 elements\n for the different axes in image pixel coordinates\n\n zoffset : float\n Offset in pixel units to use in the calculation of the psf\n\n cutval : float\n If not None, the psf will be cut along a curve corresponding to\n p(r) == 0 with exponential damping exp(-d^4)\n\n getextent : boolean\n If True, also return the extent of the psf in pixels for example\n to get the support size. Can only be used with cutval.\n \"\"\"\n # calculate the current pixel value in 1/k, making sure we are above the slab\n zint = max(self._p2k(self._tz(zint)), 0)\n offset = np.array([zoffset*(zint>0), 0, 0])\n scale = [self.param_dict[self.zscale], 1.0, 1.0]\n\n # create the coordinate vectors for where to actually calculate the\n tile = util.Tile(left=0, size=size, centered=True)\n vecs = tile.coords(form='flat')\n vecs = [self._p2k(s*i+o) for i,s,o in zip(vecs, scale, offset)]\n\n psf = self.psffunc(*vecs[::-1], zint=zint, **self.pack_args()).T\n vec = tile.coords(form='meshed')\n\n # create a smoothly varying point spread function by cutting off the psf\n # at a certain value and smoothly taking it to zero\n if self.cutoffval is not None and not self.cutbyval:\n # find the edges of the PSF\n edge = psf > psf.max() * self.cutoffval\n dd = nd.morphology.distance_transform_edt(~edge)\n\n # calculate the new PSF and normalize it to the new support\n psf = psf * np.exp(-dd**4)\n psf /= psf.sum()\n\n if getextent:\n # the size is determined by the edge plus a 2 pad for the\n # exponential damping to zero at the edge\n size = np.array([\n (vec*edge).min(axis=(1,2,3))-2,\n (vec*edge).max(axis=(1,2,3))+2,\n ]).T\n return psf, vec, size\n return psf, vec\n\n # perform a cut by value instead\n if self.cutoffval is not None and self.cutbyval:\n cutval = self.cutoffval * psf.max()\n\n dd = (psf - cutval) / cutval\n dd[dd > 0] = 0.\n\n # calculate the new PSF and normalize it to the new support\n psf = psf * np.exp(-(dd / self.cutfallrate)**4)\n psf /= psf.sum()\n\n # let the small values determine the edges\n edge = psf > cutval * self.cutedgeval\n if getextent:\n # the size is determined by the edge plus a 2 pad for the\n # exponential damping to zero at the edge\n size = np.array([\n (vec*edge).min(axis=(1,2,3))-2,\n (vec*edge).max(axis=(1,2,3))+2,\n ]).T\n return psf, vec, size\n return psf, vec\n\n return psf, vec"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nconverting from pixel to k_incoming units", "response": "def _p2k(self, v):\n \"\"\" Convert from pixel to 1/k_incoming (laser_wavelength/(2\\pi)) units \"\"\"\n return 2*np.pi*self.pxsize*v/self.param_dict['psf-laser-wavelength']"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ntransforming z to real - space coordinates from tile coordinates", "response": "def _tz(self, z):\n \"\"\" Transform z to real-space coordinates from tile coordinates \"\"\"\n return (z-self.param_dict['psf-zslab'])*self.param_dict[self.zscale]"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nmeasuring the size of the psf in each direction a particular z", "response": "def measure_size_drift(self, z, size=31, zoffset=0.):\n \"\"\" Returns the 'size' of the psf in each direction a particular z (px) \"\"\"\n drift = 0.0\n for i in range(self.measurement_iterations):\n psf, vec = self.psf_slice(z, size=size, zoffset=zoffset+drift)\n psf = psf / psf.sum()\n\n drift += moment(psf, vec[0], order=1)\n psize = [moment(psf, j, order=2) for j in vec]\n return np.array(psize), drift"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ncharacterizes the current set of parameters", "response": "def characterize_psf(self):\n \"\"\" Get support size and drift polynomial for current set of params \"\"\"\n # there may be an issue with the support and characterization--\n # it might be best to do the characterization with the same support\n # as the calculated psf.\n l,u = max(self.zrange[0], self.param_dict['psf-zslab']), self.zrange[1]\n\n size_l, drift_l = self.measure_size_drift(l)\n size_u, drift_u = self.measure_size_drift(u)\n\n # must be odd for now or have a better system for getting the center\n self.support = util.oddify(2*self.support_factor*size_u.astype('int'))\n self.drift_poly = np.polyfit([l, u], [drift_l, drift_u], 1)\n\n if self.cutoffval is not None:\n psf, vec, size_l = self.psf_slice(l, size=51, zoffset=drift_l, getextent=True)\n psf, vec, size_u = self.psf_slice(u, size=51, zoffset=drift_u, getextent=True)\n\n ss = [np.abs(i).sum(axis=-1) for i in [size_l, size_u]]\n self.support = util.oddify(util.amax(*ss))"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _kpad(self, field, finalshape, zpad=False, norm=True):\n currshape = np.array(field.shape)\n\n if any(finalshape < currshape):\n raise IndexError(\"PSF tile size is less than minimum support size\")\n\n d = finalshape - currshape\n\n # fix off-by-one issues when going odd to even tile sizes\n o = d % 2\n d = np.floor_divide(d, 2)\n\n if not zpad:\n o[0] = 0\n\n axes = None\n pad = tuple((d[i]+o[i],d[i]) for i in [0,1,2])\n rpsf = np.pad(field, pad, mode='constant', constant_values=0)\n rpsf = np.fft.ifftshift(rpsf, axes=axes)\n kpsf = fft.rfftn(rpsf, **fftkwargs)\n\n if norm:\n kpsf /= kpsf[0,0,0]\n return kpsf", "response": "This function will take a field and pad it with zeros until it has size finalshape."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\npacking the parameters into the form necessary for the integration routines above.", "response": "def pack_args(self):\n \"\"\"\n Pack the parameters into the form necessary for the integration\n routines above. For example, packs for calculate_linescan_psf\n \"\"\"\n mapper = {\n 'psf-kfki': 'kfki',\n 'psf-alpha': 'alpha',\n 'psf-n2n1': 'n2n1',\n 'psf-sigkf': 'sigkf',\n 'psf-sph6-ab': 'sph6_ab',\n 'psf-laser-wavelength': 'laser_wavelength',\n 'psf-pinhole-width': 'pinhole_width'\n }\n bads = [self.zscale, 'psf-zslab']\n\n d = {}\n for k,v in iteritems(mapper):\n if k in self.param_dict:\n d[v] = self.param_dict[k]\n\n d.update({\n 'polar_angle': self.polar_angle,\n 'normalize': self.normalize,\n 'include_K3_det':self.use_J1\n })\n\n if self.polychromatic:\n d.update({'nkpts': self.nkpts})\n d.update({'k_dist': self.k_dist})\n\n if self.do_pinhole:\n d.update({'nlpts': self.num_line_pts})\n\n d.update({'use_laggauss': True})\n return d"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef psffunc(self, *args, **kwargs):\n if self.polychromatic:\n func = psfcalc.calculate_polychrome_linescan_psf\n else:\n func = psfcalc.calculate_linescan_psf\n return func(*args, **kwargs)", "response": "Calculates a linescan psf"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef psffunc(self, x, y, z, **kwargs):\n #do_pinhole?? FIXME\n if self.polychromatic:\n func = psfcalc.calculate_polychrome_pinhole_psf\n else:\n func = psfcalc.calculate_pinhole_psf\n x0, y0 = [psfcalc.vec_to_halfvec(v) for v in [x,y]]\n vls = psfcalc.wrap_and_calc_psf(x0, y0, z, func, **kwargs)\n return vls / vls.sum()", "response": "Calculates a pinhole psf"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncharacterize the psf of the current set of parameters.", "response": "def characterize_psf(self):\n \"\"\" Get support size and drift polynomial for current set of params \"\"\"\n l,u = max(self.zrange[0], self.param_dict['psf-zslab']), self.zrange[1]\n\n size_l, drift_l = self.measure_size_drift(l, size=self.support)\n size_u, drift_u = self.measure_size_drift(u, size=self.support)\n\n self.drift_poly = np.polyfit([l, u], [drift_l, drift_u], 1)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _req(self, url, method='GET', **kw):\n '''Make request and convert JSON response to python objects'''\n send = requests.post if method == 'POST' else requests.get\n try:\n r = send(\n url,\n headers=self._token_header(),\n timeout=self.settings['timeout'],\n **kw)\n except requests.exceptions.Timeout:\n raise ApiError('Request timed out (%s seconds)' % self.settings['timeout'])\n try:\n json = r.json()\n except ValueError:\n raise ApiError('Received not JSON response from API')\n if json.get('status') != 'ok':\n raise ApiError('API error: received unexpected json from API: %s' % json)\n return json", "response": "Make request and convert JSON response to python objects"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_active_bets(self, project_id=None):\n '''Returns all active bets'''\n url = urljoin(\n self.settings['bets_url'],\n 'bets?state=fresh,active,accept_end&page=1&page_size=100')\n\n if project_id is not None:\n url += '&kava_project_id={}'.format(project_id)\n\n bets = []\n has_next_page = True\n while has_next_page:\n res = self._req(url)\n bets.extend(res['bets']['results'])\n url = res['bets'].get('next')\n has_next_page = bool(url)\n\n return bets", "response": "Returns all active bets"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nget all bets in a given type and state.", "response": "def get_bets(self, type=None, order_by=None, state=None, project_id=None,\n page=None, page_size=None):\n \"\"\"Return bets with given filters and ordering.\n\n :param type: return bets only with this type.\n Use None to include all (default).\n :param order_by: '-last_stake' or 'last_stake' to sort by stake's\n created date or None for default ordering.\n :param state: one of 'active', 'closed', 'all' (default 'active').\n :param project_id: return bets associated with given project id in kava\n :param page: default 1.\n :param page_site: page size (default 100).\n \"\"\"\n if page is None:\n page = 1\n if page_size is None:\n page_size = 100\n if state == 'all':\n _states = [] # all states == no filter\n elif state == 'closed':\n _states = self.CLOSED_STATES\n else:\n _states = self.ACTIVE_STATES\n\n url = urljoin(\n self.settings['bets_url'],\n 'bets?page={}&page_size={}'.format(page, page_size))\n url += '&state={}'.format(','.join(_states))\n if type is not None:\n url += '&type={}'.format(type)\n if order_by in ['-last_stake', 'last_stake']:\n url += '&order_by={}'.format(order_by)\n if project_id is not None:\n url += '&kava_project_id={}'.format(project_id)\n\n res = self._req(url)\n return res['bets']['results']"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn slug of a project that given bet is associated with", "response": "def get_project_slug(self, bet):\n '''Return slug of a project that given bet is associated with\n or None if bet is not associated with any project.\n '''\n if bet.get('form_params'):\n params = json.loads(bet['form_params'])\n return params.get('project')\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef subscribe(self, event, bet_ids):\n '''Subscribe to event for given bet ids.'''\n if not self._subscriptions.get(event):\n self._subscriptions[event] = set()\n self._subscriptions[event] = self._subscriptions[event].union(bet_ids)", "response": "Subscribe to event for given bet ids."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef preview(context):\n\n config = context.obj\n\n pelican(config, '--verbose', '--ignore-cache')\n\n server_proc = None\n os.chdir(config['OUTPUT_DIR'])\n try:\n try:\n command = 'python -m http.server ' + str(PORT)\n server_proc = run(command, bg=True)\n\n time.sleep(3)\n click.launch('http://localhost:8000')\n\n time.sleep(5)\n pelican(config, '--autoreload')\n except Exception:\n if server_proc is not None:\n server_proc.kill()\n raise\n except KeyboardInterrupt:\n abort(context)", "response": "Opens local preview of your blog website"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_collection_endpoint(cls):\n return cls.Meta.collection_endpoint if cls.Meta.collection_endpoint is not None else cls.__name__.lower() + \"s/\"", "response": "Get the relative path to the API resource collection\n "}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef send(self, url, http_method, **client_args):\n return self.client.send(url, http_method, **client_args)", "response": "Send the request to the API"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get(self, resource_id):\n response = self.send(self.get_resource_endpoint(resource_id), \"get\")\n\n try:\n resource = self.resource_class(self.client)\n except (ValueError, TypeError):\n return None\n else:\n resource.update_from_dict(self.client.get_response_data(response, self.Meta.parse_json))\n return resource", "response": "Get one single resource from the API\n endpoint."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef filter(self, **search_args):\n search_args = search_args or {}\n raw_resources = []\n\n for url, paginator_params in self.paginator.get_urls(self.get_collection_endpoint()):\n search_args.update(paginator_params)\n response = self.paginator.process_response(self.send(url, \"get\", params=search_args))\n raw_resources += self.client.get_response_data(response, self.Meta.parse_json)[self.json_collection_attribute] if self.json_collection_attribute is not None else self.client.get_response_data(response, self.Meta.parse_json)\n\n resources = []\n\n for raw_resource in raw_resources:\n try:\n resource = self.resource_class(self.client)\n except (ValueError, TypeError):\n continue\n else:\n resource.update_from_dict(raw_resource)\n resources.append(resource)\n\n return resources", "response": "Get a filtered list of resources by name."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef create(self, **kwargs):\n resource = self.resource_class(self.client)\n resource.update_from_dict(kwargs)\n resource.save(force_create=True)\n\n return resource", "response": "Create a resource on the server\n "}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nsend a request to the base url with the given http_method and optional kargs.", "response": "def send(self, relative_path, http_method, **requests_args):\n \"\"\"\n Subclasses must implement this method, that will be used to send API requests with proper auth\n :param relative_path: URL path relative to self.base_url\n :param http_method: HTTP method\n :param requests_args: kargs to be sent to requests\n :return:\n \"\"\"\n url = urljoin(self.base_url, relative_path)\n\n return self.session.request(http_method, url, **requests_args)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_response_data(self, response, parse_json=True):\n if response.status_code in (requests.codes.ok, requests.codes.created):\n if parse_json:\n return response.json()\n return response.content\n elif response.status_code == requests.codes.bad_request:\n response_json = response.json()\n raise BadRequestException(response_json.get(\"error\", False) or response_json.get(\"errors\",\n _(\"Bad Request: {text}\").format(text=response.text)))\n elif response.status_code == requests.codes.not_found:\n raise NotFoundException(_(\"Resource not found: {url}\").format(url=response.url))\n elif response.status_code == requests.codes.internal_server_error:\n raise ServerErrorException(_(\"Internal server error\"))\n elif response.status_code in (requests.codes.unauthorized, requests.codes.forbidden):\n raise AuthErrorException(_(\"Access denied\"))\n elif response.status_code == requests.codes.too_many_requests:\n raise RateLimitException(_(response.text))\n else:\n raise ServerErrorException(_(\"Unknown error occurred\"))", "response": "Get response data or throw an appropiate exception\n "}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef send(self, relative_path, http_method, **requests_args):\n if http_method != \"get\":\n warnings.warn(_(\"You are using methods other than get with no authentication!!!\"))\n\n return super(NoAuthClient, self).send(relative_path, http_method, **requests_args)", "response": "Make a unauthorized request to the base_url"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nwriting a new article to the content directory", "response": "def write(context):\n \"\"\"Starts a new article\"\"\"\n\n config = context.obj\n\n title = click.prompt('Title')\n author = click.prompt('Author', default=config.get('DEFAULT_AUTHOR'))\n\n slug = slugify(title)\n creation_date = datetime.now()\n basename = '{:%Y-%m-%d}_{}.md'.format(creation_date, slug)\n meta = (\n ('Title', title),\n ('Date', '{:%Y-%m-%d %H:%M}:00'.format(creation_date)),\n ('Modified', '{:%Y-%m-%d %H:%M}:00'.format(creation_date)),\n ('Author', author),\n )\n\n file_content = ''\n for key, value in meta:\n file_content += '{}: {}\\n'.format(key, value)\n file_content += '\\n\\n'\n file_content += 'Text...\\n\\n'\n file_content += '\\n\\n'\n file_content += 'Text...\\n\\n'\n\n os.makedirs(config['CONTENT_DIR'], exist_ok=True)\n path = os.path.join(config['CONTENT_DIR'], basename)\n with click.open_file(path, 'w') as f:\n f.write(file_content)\n\n click.echo(path)\n click.launch(path)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nlook for errors in source code of your blog", "response": "def lint(context):\n \"\"\"Looks for errors in source code of your blog\"\"\"\n\n config = context.obj\n try:\n run('flake8 {dir} --exclude={exclude}'.format(\n dir=config['CWD'],\n exclude=','.join(EXCLUDE),\n ))\n except SubprocessError:\n context.exit(1)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nset the real value class of the resource.", "response": "def set_real_value_class(self):\n \"\"\"\n value_class is initially a string with the import path to the resource class, but we need to get the actual class before doing any work\n\n We do not expect the actual clas to be in value_class since the beginning to avoid nasty import egg-before-chicken errors\n \"\"\"\n if self.value_class is not None and isinstance(self.value_class, str):\n module_name, dot, class_name = self.value_class.rpartition(\".\")\n module = __import__(module_name, fromlist=[class_name])\n self.value_class = getattr(module, class_name)\n self._initialized = True"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nsaving changes and sends them to GitHub", "response": "def publish(context):\n \"\"\"Saves changes and sends them to GitHub\"\"\"\n\n header('Recording changes...')\n run('git add -A')\n\n header('Displaying changes...')\n run('git -c color.status=always status')\n\n if not click.confirm('\\nContinue publishing'):\n run('git reset HEAD --')\n abort(context)\n\n header('Saving changes...')\n try:\n run('git commit -m \"{message}\"'.format(\n message='Publishing {}'.format(choose_commit_emoji())\n ), capture=True)\n except subprocess.CalledProcessError as e:\n if 'nothing to commit' not in e.stdout:\n raise\n else:\n click.echo('Nothing to commit.')\n\n header('Pushing to GitHub...')\n branch = get_branch()\n run('git push origin {branch}:{branch}'.format(branch=branch))\n\n pr_link = get_pr_link(branch)\n if pr_link:\n click.launch(pr_link)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef deploy(context):\n\n config = context.obj\n\n header('Generating HTML...')\n pelican(config, '--verbose', production=True)\n\n header('Removing unnecessary output...')\n unnecessary_paths = [\n 'author', 'category', 'tag', 'feeds', 'tags.html',\n 'authors.html', 'categories.html', 'archives.html',\n ]\n for path in unnecessary_paths:\n remove_path(os.path.join(config['OUTPUT_DIR'], path))\n\n if os.environ.get('TRAVIS'): # Travis CI\n header('Setting up Git...')\n run(\n 'git config user.name ' +\n run('git show --format=\"%cN\" -s', capture=True)\n )\n run(\n 'git config user.email ' +\n run('git show --format=\"%cE\" -s', capture=True)\n )\n\n github_token = os.environ.get('GITHUB_TOKEN')\n repo_slug = os.environ.get('TRAVIS_REPO_SLUG')\n origin = 'https://{}@github.com/{}.git'.format(github_token, repo_slug)\n run('git remote set-url origin ' + origin)\n\n header('Rewriting gh-pages branch...')\n run('ghp-import -m \"{message}\" {dir}'.format(\n message='Deploying {}'.format(choose_commit_emoji()),\n dir=config['OUTPUT_DIR'],\n ))\n\n header('Pushing to GitHub...')\n run('git push origin gh-pages:gh-pages --force')", "response": "Deploy the blog website to the GitHub repository"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the given number as a string with a sign in front of it ie. + - otherwise.", "response": "def signed_number(number, precision=2):\n \"\"\"\n Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise.\n \"\"\"\n prefix = '' if number <= 0 else '+'\n number_str = '{}{:.{precision}f}'.format(prefix, number, precision=precision)\n\n return number_str"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nshow Zebra balance. Like the hours balance, vacation left, etc.", "response": "def balance(ctx):\n \"\"\"\n Show Zebra balance.\n\n Like the hours balance, vacation left, etc.\n \"\"\"\n backend = plugins_registry.get_backends_by_class(ZebraBackend)[0]\n\n timesheet_collection = get_timesheet_collection_for_context(ctx, None)\n hours_to_be_pushed = timesheet_collection.get_hours(pushed=False, ignored=False, unmapped=False)\n\n today = datetime.date.today()\n user_info = backend.get_user_info()\n timesheets = backend.get_timesheets(get_first_dow(today), get_last_dow(today))\n total_duration = sum([float(timesheet['time']) for timesheet in timesheets])\n\n vacation = hours_to_days(user_info['vacation']['difference'])\n vacation_balance = '{} days, {:.2f} hours'.format(*vacation)\n\n hours_balance = user_info['hours']['hours']['balance']\n\n click.echo(\"Hours balance: {}\".format(signed_number(hours_balance)))\n click.echo(\"Hours balance after push: {}\".format(signed_number(hours_balance + hours_to_be_pushed)))\n click.echo(\"Hours done this week: {:.2f}\".format(total_duration))\n click.echo(\"Vacation left: {}\".format(vacation_balance))"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef to_zebra_params(params):\n def to_zebra_value(value):\n transform_funcs = {\n bool: lambda v: 'true' if v else 'false',\n }\n\n return transform_funcs.get(type(value), lambda v: v)(value)\n\n return {param: to_zebra_value(value) for param, value in params.items()}", "response": "Transforms the given params dict to values that are understood by Zebra"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nshows all messages in the messages key of the given dict.", "response": "def show_response_messages(response_json):\n \"\"\"\n Show all messages in the `messages` key of the given dict.\n \"\"\"\n message_type_kwargs = {\n 'warning': {'fg': 'yellow'},\n 'error': {'fg': 'red'},\n }\n for message in response_json.get('messages', []):\n click.secho(message['text'], **message_type_kwargs.get(message['type'], {}))"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nupdate the mapping for an alias.", "response": "def update_alias_mapping(settings, alias, new_mapping):\n \"\"\"\n Override `alias` mapping in the user configuration file with the given `new_mapping`, which should be a tuple with\n 2 or 3 elements (in the form `(project_id, activity_id, role_id)`).\n \"\"\"\n mapping = aliases_database[alias]\n new_mapping = Mapping(mapping=new_mapping, backend=mapping.backend)\n aliases_database[alias] = new_mapping\n settings.add_alias(alias, new_mapping)\n settings.write_config()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef photos(context, path):\n\n config = context.obj\n\n header('Looking for the latest article...')\n article_filename = find_last_article(config['CONTENT_DIR'])\n if not article_filename:\n return click.secho('No articles.', fg='red')\n click.echo(os.path.basename(article_filename))\n\n header('Looking for images...')\n images = list(sorted(find_images(path)))\n if not images:\n return click.secho('Found no images.', fg='red')\n\n for filename in images:\n click.secho(filename, fg='green')\n\n if not click.confirm('\\nAdd these images to the latest article'):\n abort(config)\n\n url_prefix = os.path.join('{filename}', IMAGES_PATH)\n images_dir = os.path.join(config['CONTENT_DIR'], IMAGES_PATH)\n os.makedirs(images_dir, exist_ok=True)\n\n header('Processing images...')\n urls = []\n for filename in images:\n image_basename = os.path.basename(filename).replace(' ', '-').lower()\n urls.append(os.path.join(url_prefix, image_basename))\n image_filename = os.path.join(images_dir, image_basename)\n print(filename, image_filename)\n import_image(filename, image_filename)\n\n content = '\\n'\n for url in urls:\n url = url.replace('\\\\', '/')\n content += '\\n\\n'.format(url)\n\n header('Adding to article: {}'.format(article_filename))\n with click.open_file(article_filename, 'a') as f:\n f.write(content)\n click.launch(article_filename)", "response": "Adds images to the latest article"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_node(self, string_key):\n pos = self.get_node_pos(string_key)\n if pos is None:\n return None\n return self.ring[self._sorted_keys[pos]]", "response": "Given a string key returns the corresponding node in the hash ring."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_node_pos(self, string_key):\n if not self.ring:\n return None\n\n key = self.gen_key(string_key)\n\n nodes = self._sorted_keys\n pos = bisect(nodes, key)\n\n if pos == len(nodes):\n return 0\n else:\n return pos", "response": "Given a string key returns the node in the hash ring along with its position in the ring."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ngive a string key it returns the nodes as a generator that can hold the key.", "response": "def iterate_nodes(self, string_key, distinct=True):\n \"\"\"Given a string key it returns the nodes as a generator that can hold the key.\n\n The generator iterates one time through the ring\n starting at the correct position.\n\n if `distinct` is set, then the nodes returned will be unique,\n i.e. no virtual copies will be returned.\n \"\"\"\n if not self.ring:\n yield None, None\n\n returned_values = set()\n\n def distinct_filter(value):\n if str(value) not in returned_values:\n returned_values.add(str(value))\n return value\n\n pos = self.get_node_pos(string_key)\n for key in self._sorted_keys[pos:]:\n val = distinct_filter(self.ring[key])\n if val:\n yield val\n\n for i, key in enumerate(self._sorted_keys):\n if i < pos:\n val = distinct_filter(self.ring[key])\n if val:\n yield val"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngives a string key it returns a long value", "response": "def gen_key(self, key):\n \"\"\"Given a string key it returns a long value,\n this long value represents a place on the hash ring.\n\n md5 is currently used because it mixes well.\n \"\"\"\n b_key = self._hash_digest(key)\n return self._hash_val(b_key, lambda x: x)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_number_of_app_ports(app):\n mode = _get_networking_mode(app)\n ports_list = None\n if mode == 'host':\n ports_list = _get_port_definitions(app)\n elif mode == 'container/bridge':\n ports_list = _get_port_definitions(app)\n if ports_list is None:\n ports_list = _get_container_port_mappings(app)\n elif mode == 'container':\n ports_list = _get_ip_address_discovery_ports(app)\n # Marathon 1.5+: the ipAddress field is missing -> ports_list is None\n # Marathon <1.5: the ipAddress field can be present, but ports_list can\n # still be empty while the container port mapping is not :-/\n if not ports_list:\n ports_list = _get_container_port_mappings(app)\n else:\n raise RuntimeError(\n \"Unknown Marathon networking mode '{}'\".format(mode))\n\n return len(ports_list)", "response": "Get the number of ports for the given app JSON."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _get_networking_mode(app):\n # Marathon 1.5+: there is a `networks` field\n networks = app.get('networks')\n if networks:\n # Modes cannot be mixed, so assigning the last mode is fine\n return networks[-1].get('mode', 'container')\n\n # Older Marathon: determine equivalent network mode\n container = app.get('container')\n if container is not None and 'docker' in container:\n docker_network = container['docker'].get('network')\n if docker_network == 'USER':\n return 'container'\n elif docker_network == 'BRIDGE':\n return 'container/bridge'\n\n return 'container' if _is_legacy_ip_per_task(app) else 'host'", "response": "Get the Marathon networking mode for the app."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _get_container_port_mappings(app):\n container = app['container']\n\n # Marathon 1.5+: container.portMappings field\n port_mappings = container.get('portMappings')\n\n # Older Marathon: container.docker.portMappings field\n if port_mappings is None and 'docker' in container:\n port_mappings = container['docker'].get('portMappings')\n\n return port_mappings", "response": "Get the portMappings field for the app container."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ngive a list of PEM objects sort them into the private key leaf certificate and list of CA certificates.", "response": "def sort_pem_objects(pem_objects):\n \"\"\"\n Given a list of pem objects, sort the objects into the private key, leaf\n certificate, and list of CA certificates in the trust chain. This function\n assumes that the list of pem objects will contain exactly one private key\n and exactly one leaf certificate and that only key and certificate type\n objects are provided.\n \"\"\"\n keys, certs, ca_certs = [], [], []\n for pem_object in pem_objects:\n if isinstance(pem_object, pem.Key):\n keys.append(pem_object)\n else:\n # This assumes all pem objects provided are either of type pem.Key\n # or pem.Certificate. Technically, there are CSR and CRL types, but\n # we should never be passed those.\n if _is_ca(pem_object):\n ca_certs.append(pem_object)\n else:\n certs.append(pem_object)\n\n [key], [cert] = keys, certs\n return key, cert, ca_certs"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngiving a non - None response from Vault key value store convert the key - value pairs into PEM objects.", "response": "def _cert_data_to_pem_objects(cert_data):\n \"\"\"\n Given a non-None response from the Vault key/value store, convert the\n key/values into a list of PEM objects.\n \"\"\"\n pem_objects = []\n for key in ['privkey', 'cert', 'chain']:\n pem_objects.extend(pem.parse(cert_data[key].encode('utf-8')))\n\n return pem_objects"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef raise_for_not_ok_status(response):\n if response.code != OK:\n raise HTTPError('Non-200 response code (%s) for url: %s' % (\n response.code, uridecode(response.request.absoluteURI)))\n\n return response", "response": "Raises an exception if the response is not 200."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _sse_content_with_protocol(response, handler, **sse_kwargs):\n protocol = SseProtocol(handler, **sse_kwargs)\n finished = protocol.when_finished()\n\n response.deliverBody(protocol)\n\n return finished, protocol", "response": "This function is used to send the Sse content to the response."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _request(self, failure, endpoints, *args, **kwargs):\n # We've run out of endpoints, fail\n if not endpoints:\n return failure\n\n endpoint = endpoints.pop(0)\n d = super(MarathonClient, self).request(*args, url=endpoint, **kwargs)\n\n # If something goes wrong, call ourselves again with the remaining\n # endpoints\n d.addErrback(self._request, endpoints, *args, **kwargs)\n return d", "response": "A wrapper for the base class method _request."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nperforming a GET request and get the contents of the JSON response. Marathon's JSON responses tend to contain an object with a single key which points to the actual data of the response. For example /v2/apps returns something like {\"apps\": [ {\"app1\"}, {\"app2\"} ]}. We're interested in the contents of \"apps\". This method will raise an error if: * There is an error response code * The field with the given name cannot be found", "response": "def get_json_field(self, field, **kwargs):\n \"\"\"\n Perform a GET request and get the contents of the JSON response.\n\n Marathon's JSON responses tend to contain an object with a single key\n which points to the actual data of the response. For example /v2/apps\n returns something like {\"apps\": [ {\"app1\"}, {\"app2\"} ]}. We're\n interested in the contents of \"apps\".\n\n This method will raise an error if:\n * There is an error response code\n * The field with the given name cannot be found\n \"\"\"\n d = self.request(\n 'GET', headers={'Accept': 'application/json'}, **kwargs)\n d.addCallback(raise_for_status)\n d.addCallback(raise_for_header, 'Content-Type', 'application/json')\n d.addCallback(json_content)\n d.addCallback(self._get_json_field, field)\n return d"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _get_json_field(self, response_json, field_name):\n if field_name not in response_json:\n raise KeyError('Unable to get value for \"%s\" from Marathon '\n 'response: \"%s\"' % (\n field_name, json.dumps(response_json),))\n\n return response_json[field_name]", "response": "Get a JSON field from the response."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_events(self, callbacks):\n d = self.request(\n 'GET', path='/v2/events', unbuffered=True,\n # The event_type parameter was added in Marathon 1.3.7. It can be\n # used to specify which event types we are interested in. On older\n # versions of Marathon it is ignored, and we ignore events we're\n # not interested in anyway.\n params={'event_type': sorted(callbacks.keys())},\n headers={\n 'Accept': 'text/event-stream',\n 'Cache-Control': 'no-store'\n })\n\n def handler(event, data):\n callback = callbacks.get(event)\n # Deserialize JSON if a callback is present\n if callback is not None:\n callback(json.loads(data))\n\n return d.addCallback(\n sse_content, handler, reactor=self._reactor, **self._sse_kwargs)", "response": "Get events from Marathon."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef parse(\n self,\n value: str,\n type_: typing.Type[typing.Any] = str,\n subtype: typing.Type[typing.Any] = str,\n ) -> typing.Any:\n \"\"\"\n Parse value from string.\n\n Convert :code:`value` to\n\n .. code-block:: python\n\n >>> parser = Config()\n >>> parser.parse('12345', type_=int)\n <<< 12345\n >>>\n >>> parser.parse('1,2,3,4', type_=list, subtype=int)\n <<< [1, 2, 3, 4]\n\n :param value: string\n :param type\\\\_: the type to return\n :param subtype: subtype for iterator types\n :return: the parsed config value\n\n \"\"\"\n if type_ is bool:\n return type_(value.lower() in self.TRUE_STRINGS)\n\n try:\n if isinstance(type_, type) and issubclass(\n type_, (list, tuple, set, frozenset)\n ):\n return type_(\n self.parse(v.strip(\" \"), subtype)\n for v in value.split(\",\")\n if value.strip(\" \")\n )\n\n return type_(value)\n except ValueError as e:\n raise ConfigError(*e.args)", "response": "Parse a string value from a config file."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nparse a value from an environment variable.", "response": "def get(\n self,\n key: str,\n default: typing.Any = UNSET,\n type_: typing.Type[typing.Any] = str,\n subtype: typing.Type[typing.Any] = str,\n mapper: typing.Optional[typing.Callable[[object], object]] = None,\n ) -> typing.Any:\n \"\"\"\n Parse a value from an environment variable.\n\n .. code-block:: python\n\n >>> os.environ['FOO']\n <<< '12345'\n >>>\n >>> os.environ['BAR']\n <<< '1,2,3,4'\n >>>\n >>> 'BAZ' in os.environ\n <<< False\n >>>\n >>> parser = Config()\n >>> parser.get('FOO', type_=int)\n <<< 12345\n >>>\n >>> parser.get('BAR', type_=list, subtype=int)\n <<< [1, 2, 3, 4]\n >>>\n >>> parser.get('BAZ', default='abc123')\n <<< 'abc123'\n >>>\n >>> parser.get('FOO', type_=int, mapper=lambda x: x*10)\n <<< 123450\n\n :param key: the key to look up the value under\n :param default: default value to return when when no value is present\n :param type\\\\_: the type to return\n :param subtype: subtype for iterator types\n :param mapper: a function to post-process the value with\n :return: the parsed config value\n\n \"\"\"\n value = self.environ.get(key, UNSET)\n\n if value is UNSET and default is UNSET:\n raise ConfigError(\"Unknown environment variable: {0}\".format(key))\n\n if value is UNSET:\n value = default\n else:\n value = self.parse(typing.cast(str, value), type_, subtype)\n\n if mapper:\n value = mapper(value)\n\n return value"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nperforms a request to a specific endpoint. Raise an error if the status is not OK.", "response": "def _request(self, endpoint, *args, **kwargs):\n \"\"\"\n Perform a request to a specific endpoint. Raise an error if the status\n code indicates a client or server error.\n \"\"\"\n kwargs['url'] = endpoint\n return (super(MarathonLbClient, self).request(*args, **kwargs)\n .addCallback(raise_for_status))"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _check_request_results(self, results):\n responses = []\n failed_endpoints = []\n for index, result_tuple in enumerate(results):\n success, result = result_tuple\n if success:\n responses.append(result)\n else:\n endpoint = self.endpoints[index]\n self.log.failure(\n 'Failed to make a request to a marathon-lb instance: '\n '{endpoint}', result, LogLevel.error, endpoint=endpoint)\n responses.append(None)\n failed_endpoints.append(endpoint)\n\n if len(failed_endpoints) == len(self.endpoints):\n raise RuntimeError(\n 'Failed to make a request to all marathon-lb instances')\n\n if failed_endpoints:\n self.log.error(\n 'Failed to make a request to {x}/{y} marathon-lb instances: '\n '{endpoints}', x=len(failed_endpoints), y=len(self.endpoints),\n endpoints=failed_endpoints)\n\n return responses", "response": "Check the result of each request that we made and return a list of responses with a None value for any requests that failed."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ncreates a client key if one does not exist already.", "response": "def maybe_key(pem_path):\n \"\"\"\n Set up a client key if one does not exist already.\n\n https://gist.github.com/glyph/27867a478bb71d8b6046fbfb176e1a33#file-local-certs-py-L32-L50\n\n :type pem_path: twisted.python.filepath.FilePath\n :param pem_path:\n The path to the certificate directory to use.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n acme_key_file = pem_path.child(u'client.key')\n if acme_key_file.exists():\n key = _load_pem_private_key_bytes(acme_key_file.getContent())\n else:\n key = generate_private_key(u'rsa')\n acme_key_file.setContent(_dump_pem_private_key_bytes(key))\n return succeed(JWKRSA(key=key))"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncreate a client key in Vault if one does not exist already.", "response": "def maybe_key_vault(client, mount_path):\n \"\"\"\n Set up a client key in Vault if one does not exist already.\n\n :param client:\n The Vault API client to use.\n :param mount_path:\n The Vault key/value mount path to use.\n :rtype: twisted.internet.defer.Deferred\n \"\"\"\n d = client.read_kv2('client_key', mount_path=mount_path)\n\n def get_or_create_key(client_key):\n if client_key is not None:\n key_data = client_key['data']['data']\n key = _load_pem_private_key_bytes(key_data['key'].encode('utf-8'))\n return JWKRSA(key=key)\n else:\n key = generate_private_key(u'rsa')\n key_data = {\n 'key': _dump_pem_private_key_bytes(key).decode('utf-8')\n }\n d = client.create_or_update_kv2(\n 'client_key', key_data, mount_path=mount_path)\n\n return d.addCallback(lambda _result: JWKRSA(key=key))\n\n return d.addCallback(get_or_create_key)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef create_txacme_client_creator(key, reactor, url, alg=RS256):\n # Creating an Agent without specifying a pool gives us the default pool\n # which is non-persistent.\n jws_client = JWSClient(HTTPClient(agent=Agent(reactor)), key, alg)\n\n return partial(txacme_Client.from_url, reactor, url, key, alg, jws_client)", "response": "Create a creator for txacme clients."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngenerates a wildcard certificate valid for otope 10 years.", "response": "def generate_wildcard_pem_bytes():\n \"\"\"\n Generate a wildcard (subject name '*') self-signed certificate valid for\n 10 years.\n\n https://cryptography.io/en/latest/x509/tutorial/#creating-a-self-signed-certificate\n\n :return: Bytes representation of the PEM certificate data\n \"\"\"\n key = generate_private_key(u'rsa')\n name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'*')])\n cert = (\n x509.CertificateBuilder()\n .issuer_name(name)\n .subject_name(name)\n .not_valid_before(datetime.today() - timedelta(days=1))\n .not_valid_after(datetime.now() + timedelta(days=3650))\n .serial_number(int(uuid.uuid4()))\n .public_key(key.public_key())\n .sign(\n private_key=key,\n algorithm=hashes.SHA256(),\n backend=default_backend())\n )\n\n return b''.join((\n key.private_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PrivateFormat.TraditionalOpenSSL,\n encryption_algorithm=serialization.NoEncryption()),\n cert.public_bytes(serialization.Encoding.PEM)\n ))"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef from_env(cls, reactor=None, env=os.environ):\n address = env.get('VAULT_ADDR', 'https://127.0.0.1:8200')\n # This seems to be what the Vault CLI defaults to\n token = env.get('VAULT_TOKEN', 'TEST')\n\n ca_cert = env.get('VAULT_CACERT')\n tls_server_name = env.get('VAULT_TLS_SERVER_NAME')\n client_cert = env.get('VAULT_CLIENT_CERT')\n client_key = env.get('VAULT_CLIENT_KEY')\n cf = ClientPolicyForHTTPS.from_pem_files(\n caKey=ca_cert, privateKey=client_key, certKey=client_cert,\n tls_server_name=tls_server_name\n )\n client, reactor = default_client(reactor, contextFactory=cf)\n\n return cls(address, token, client=client, reactor=reactor)", "response": "Create a new client with configuration from the environment variables."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreading data from Vault. Returns the JSON - decoded response.", "response": "def read(self, path, **params):\n \"\"\"\n Read data from Vault. Returns the JSON-decoded response.\n \"\"\"\n d = self.request('GET', '/v1/' + path, params=params)\n return d.addCallback(self._handle_response)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef write(self, path, **data):\n d = self.request('PUT', '/v1/' + path, json=data)\n return d.addCallback(self._handle_response, check_cas=True)", "response": "Write data to Vault. Returns the JSON - decoded response."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreads some data from a key value version 2 secret engine.", "response": "def read_kv2(self, path, version=None, mount_path='secret'):\n \"\"\"\n Read some data from a key/value version 2 secret engine.\n \"\"\"\n params = {}\n if version is not None:\n params['version'] = version\n\n read_path = '{}/data/{}'.format(mount_path, path)\n return self.read(read_path, **params)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef create_or_update_kv2(self, path, data, cas=None, mount_path='secret'):\n params = {\n 'options': {},\n 'data': data\n }\n if cas is not None:\n params['options']['cas'] = cas\n\n write_path = '{}/data/{}'.format(mount_path, path)\n return self.write(write_path, **params)", "response": "Create or update a key - value entry in a key - value version 2 secret engine."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nget a single value for the given key out of the given set of headers.", "response": "def get_single_header(headers, key):\n \"\"\"\n Get a single value for the given key out of the given set of headers.\n\n :param twisted.web.http_headers.Headers headers:\n The set of headers in which to look for the header value\n :param str key:\n The header key\n \"\"\"\n raw_headers = headers.getRawHeaders(key)\n if raw_headers is None:\n return None\n\n # Take the final header as the authorative\n header, _ = cgi.parse_header(raw_headers[-1])\n return header"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nraising an exception if the response did not succeed.", "response": "def raise_for_status(response):\n \"\"\"\n Raises a `requests.exceptions.HTTPError` if the response did not succeed.\n Adapted from the Requests library:\n https://github.com/kennethreitz/requests/blob/v2.8.1/requests/models.py#L825-L837\n \"\"\"\n http_error_msg = ''\n\n if 400 <= response.code < 500:\n http_error_msg = '%s Client Error for url: %s' % (\n response.code, uridecode(response.request.absoluteURI))\n\n elif 500 <= response.code < 600:\n http_error_msg = '%s Server Error for url: %s' % (\n response.code, uridecode(response.request.absoluteURI))\n\n if http_error_msg:\n raise HTTPError(http_error_msg, response=response)\n\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _compose_url(self, url, kwargs):\n if url is None:\n url = self.url\n\n if url is None:\n raise ValueError(\n 'url not provided and this client has no url attribute')\n\n split_result = urisplit(url)\n userinfo = split_result.userinfo\n\n # Build up the kwargs to pass to uricompose\n compose_kwargs = {}\n for key in ['scheme', 'host', 'port', 'path', 'fragment']:\n if key in kwargs:\n compose_kwargs[key] = kwargs.pop(key)\n else:\n compose_kwargs[key] = getattr(split_result, key)\n\n if 'params' in kwargs:\n compose_kwargs['query'] = kwargs.pop('params')\n else:\n compose_kwargs['query'] = split_result.query\n\n # Take the userinfo out of the URL and pass as 'auth' to treq so it can\n # be used for HTTP basic auth headers\n if 'auth' not in kwargs and userinfo is not None:\n # treq expects a 2-tuple (username, password)\n kwargs['auth'] = tuple(userinfo.split(':', 2))\n\n return uricompose(**compose_kwargs)", "response": "Compose a URL with the given kwargs."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nperforming a request to the specified URL.", "response": "def request(self, method, url=None, **kwargs):\n \"\"\"\n Perform a request.\n\n :param: method:\n The HTTP method to use (example is `GET`).\n :param: url:\n The URL to use. The default value is the URL this client was\n created with (`self.url`) (example is `http://localhost:8080`)\n :param: kwargs:\n Any other parameters that will be passed to `treq.request`, for\n example headers. Or any URL parameters to override, for example\n path, query or fragment.\n \"\"\"\n url = self._compose_url(url, kwargs)\n\n kwargs.setdefault('timeout', self._timeout)\n\n d = self._client.request(method, url, reactor=self._reactor, **kwargs)\n\n d.addCallback(self._log_request_response, method, url, kwargs)\n d.addErrback(self._log_request_error, url)\n\n return d"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef listen(self, reactor, endpoint_description):\n endpoint = serverFromString(reactor, endpoint_description)\n return endpoint.listen(Site(self.app.resource()))", "response": "Start the server listening for requests on the given host and port."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef health(self, request):\n if self.health_handler is None:\n return self._no_health_handler(request)\n\n health = self.health_handler()\n response_code = OK if health.healthy else SERVICE_UNAVAILABLE\n request.setResponseCode(response_code)\n write_request_json(request, health.json_message)", "response": "Listens to incoming health checks from Marathon on / health."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef parse_listen_addr(listen_addr):\n if ':' not in listen_addr:\n raise ValueError(\n \"'%s' does not have the correct form for a listen address: \"\n '[ipaddress]:port' % (listen_addr,))\n host, port = listen_addr.rsplit(':', 1)\n\n # Validate the host\n if host == '':\n protocol = 'tcp'\n interface = None\n else:\n if host.startswith('[') and host.endswith(']'): # IPv6 wrapped in []\n host = host[1:-1]\n ip_address = ipaddress.ip_address(_to_unicode(host))\n protocol = 'tcp6' if ip_address.version == 6 else 'tcp'\n interface = str(ip_address)\n\n # Validate the port\n if not port.isdigit() or int(port) < 1 or int(port) > 65535:\n raise ValueError(\n \"'%s' does not appear to be a valid port number\" % (port,))\n\n args = [protocol, port]\n kwargs = {'interface': interface} if interface is not None else {}\n\n return _create_tx_endpoints_string(args, kwargs)", "response": "Parses a listen address into a Twisted\n endpoint description string for use with with\n ."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef create_marathon_acme(\n client_creator, cert_store, acme_email, allow_multiple_certs,\n marathon_addrs, marathon_timeout, sse_timeout, mlb_addrs, group,\n reactor):\n \"\"\"\n Create a marathon-acme instance.\n\n :param client_creator:\n The txacme client creator function.\n :param cert_store:\n The txacme certificate store instance.\n :param acme_email:\n Email address to use when registering with the ACME service.\n :param allow_multiple_certs:\n Whether to allow multiple certificates per app port.\n :param marathon_addr:\n Address for the Marathon instance to find app domains that require\n certificates.\n :param marathon_timeout:\n Amount of time in seconds to wait for response headers to be received\n from Marathon.\n :param sse_timeout:\n Amount of time in seconds to wait for some event data to be received\n from Marathon.\n :param mlb_addrs:\n List of addresses for marathon-lb instances to reload when a new\n certificate is issued.\n :param group:\n The marathon-lb group (``HAPROXY_GROUP``) to consider when finding\n app domains.\n :param reactor: The reactor to use.\n \"\"\"\n marathon_client = MarathonClient(marathon_addrs, timeout=marathon_timeout,\n sse_kwargs={'timeout': sse_timeout},\n reactor=reactor)\n marathon_lb_client = MarathonLbClient(mlb_addrs, reactor=reactor)\n\n return MarathonAcme(\n marathon_client,\n group,\n cert_store,\n marathon_lb_client,\n client_creator,\n reactor,\n acme_email,\n allow_multiple_certs\n )", "response": "Create a Marathon - acme instance."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ninitialise the storage directory with the certificates directory and the default wildcard self - signed certificate for HAProxy.", "response": "def init_storage_dir(storage_dir):\n \"\"\"\n Initialise the storage directory with the certificates directory and a\n default wildcard self-signed certificate for HAProxy.\n\n :return: the storage path and certs path\n \"\"\"\n storage_path = FilePath(storage_dir)\n\n # Create the default wildcard certificate if it doesn't already exist\n default_cert_path = storage_path.child('default.pem')\n if not default_cert_path.exists():\n default_cert_path.setContent(generate_wildcard_pem_bytes())\n\n # Create a directory for unmanaged certs. We don't touch this again, but it\n # needs to be there and it makes sense to create it at the same time as\n # everything else.\n unmanaged_certs_path = storage_path.child('unmanaged-certs')\n if not unmanaged_certs_path.exists():\n unmanaged_certs_path.createDirectory()\n\n # Store certificates in a directory inside the storage directory, so\n # HAProxy will read just the certificates there.\n certs_path = storage_path.child('certs')\n if not certs_path.exists():\n certs_path.createDirectory()\n\n return storage_path, certs_path"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ninitialise the logging by adding an observer to the global log publisher.", "response": "def init_logging(log_level):\n \"\"\"\n Initialise the logging by adding an observer to the global log publisher.\n\n :param str log_level: The minimum log level to log messages for.\n \"\"\"\n log_level_filter = LogLevelFilterPredicate(\n LogLevel.levelWithName(log_level))\n log_level_filter.setLogLevelForNamespace(\n 'twisted.web.client._HTTP11ClientFactory', LogLevel.warn)\n log_observer = FilteringLogObserver(\n textFileLogObserver(sys.stdout), [log_level_filter])\n globalLogPublisher.addObserver(log_observer)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _parse_field_value(line):\n if line.startswith(':'):\n # Ignore the line\n return None, None\n\n if ':' not in line:\n # Treat the entire line as the field, use empty string as value\n return line, ''\n\n # Else field is before the ':' and value is after\n field, value = line.split(':', 1)\n\n # If value starts with a space, remove it.\n value = value[1:] if value.startswith(' ') else value\n\n return field, value", "response": "Parse the field and value from a line."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _abortConnection(self):\n transport = self.transport\n if isinstance(transport, TransportProxyProducer):\n transport = transport._producer\n\n if hasattr(transport, 'abortConnection'):\n transport.abortConnection()\n else:\n self.log.error(\n 'Transport {} has no abortConnection method'.format(transport))", "response": "Aborts the connection to the specified object."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncall by the protocol class when data is received.", "response": "def dataReceived(self, data):\n \"\"\"\n Translates bytes into lines, and calls lineReceived.\n\n Copied from ``twisted.protocols.basic.LineOnlyReceiver`` but using\n str.splitlines() to split on ``\\r\\n``, ``\\n``, and ``\\r``.\n \"\"\"\n self.resetTimeout()\n lines = (self._buffer + data).splitlines()\n\n # str.splitlines() doesn't split the string after a trailing newline\n # character so we must check if there is a trailing newline and, if so,\n # clear the buffer as the line is \"complete\". Else, the line is\n # incomplete and we keep the last line in the buffer.\n if data.endswith(b'\\n') or data.endswith(b'\\r'):\n self._buffer = b''\n else:\n self._buffer = lines.pop(-1)\n\n for line in lines:\n if self.transport.disconnecting:\n # this is necessary because the transport may be told to lose\n # the connection by a line within a larger packet, and it is\n # important to disregard all the lines in that packet following\n # the one that told it to close.\n return\n if len(line) > self._max_length:\n self.lineLengthExceeded(line)\n return\n else:\n self.lineReceived(line)\n if len(self._buffer) > self._max_length:\n self.lineLengthExceeded(self._buffer)\n return"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nhandles the field and value pair.", "response": "def _handle_field_value(self, field, value):\n \"\"\" Handle the field, value pair. \"\"\"\n if field == 'event':\n self._event = value\n elif field == 'data':\n self._data_lines.append(value)\n elif field == 'id':\n # Not implemented\n pass\n elif field == 'retry':\n # Not implemented\n pass"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _dispatch_event(self):\n data = self._prepare_data()\n if data is not None:\n self._handler(self._event, data)\n\n self._reset_event_data()", "response": "Dispatch the event to the handler."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nlisten for events from Marathon.", "response": "def listen_events(self, reconnects=0):\n \"\"\"\n Start listening for events from Marathon, running a sync when we first\n successfully subscribe and triggering a sync on API request events.\n \"\"\"\n self.log.info('Listening for events from Marathon...')\n self._attached = False\n\n def on_finished(result, reconnects):\n # If the callback fires then the HTTP request to the event stream\n # went fine, but the persistent connection for the SSE stream was\n # dropped. Just reconnect for now- if we can't actually connect\n # then the errback will fire rather.\n self.log.warn('Connection lost listening for events, '\n 'reconnecting... ({reconnects} so far)',\n reconnects=reconnects)\n reconnects += 1\n return self.listen_events(reconnects)\n\n def log_failure(failure):\n self.log.failure('Failed to listen for events', failure)\n return failure\n\n return self.marathon_client.get_events({\n 'event_stream_attached': self._sync_on_event_stream_attached,\n 'api_post_event': self._sync_on_api_post_event\n }).addCallbacks(on_finished, log_failure, callbackArgs=[reconnects])"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef sync(self):\n self.log.info('Starting a sync...')\n\n def log_success(result):\n self.log.info('Sync completed successfully')\n return result\n\n def log_failure(failure):\n self.log.failure('Sync failed', failure, LogLevel.error)\n return failure\n\n return (self.marathon_client.get_apps()\n .addCallback(self._apps_acme_domains)\n .addCallback(self._filter_new_domains)\n .addCallback(self._issue_certs)\n .addCallbacks(log_success, log_failure))", "response": "Fetch the list of apps from Marathon and issue certificates for any domains that require a certificate."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _issue_cert(self, domain):\n def errback(failure):\n # Don't fail on some of the errors we could get from the ACME\n # server, rather just log an error so that we can continue with\n # other domains.\n failure.trap(txacme_ServerError)\n acme_error = failure.value.message\n\n if acme_error.code in ['rateLimited', 'serverInternal',\n 'connection', 'unknownHost']:\n # TODO: Fire off an error to Sentry or something?\n self.log.error(\n 'Error ({code}) issuing certificate for \"{domain}\": '\n '{detail}', code=acme_error.code, domain=domain,\n detail=acme_error.detail)\n else:\n # There are more error codes but if they happen then something\n # serious has gone wrong-- carry on error-ing.\n return failure\n\n d = self.txacme_service.issue_cert(domain)\n return d.addErrback(errback)", "response": "Issue a certificate for the given domain."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef warn_if_detached(func):\n @wraps(func)\n def wrapped(this, *args, **kwargs):\n # Check for _detached in __dict__ instead of using hasattr\n # to avoid infinite loop in __getattr__\n if '_detached' in this.__dict__ and this._detached:\n warnings.warn('here')\n return func(this, *args, **kwargs)\n return wrapped", "response": "Decorator to warn if self / cls is detached."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nensuring that self/cls contains a Storage backend.", "response": "def has_storage(func):\n \"\"\" Ensure that self/cls contains a Storage backend. \"\"\"\n @wraps(func)\n def wrapped(*args, **kwargs):\n me = args[0]\n if not hasattr(me, '_storage') or \\\n not me._storage:\n raise exceptions.ImproperConfigurationError(\n 'No storage backend attached to schema <{0}>.'\n .format(me._name.upper())\n )\n return func(*args, **kwargs)\n return wrapped"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef rm_fwd_refs(obj):\n for stack, key in obj._backrefs_flat:\n\n # Unpack stack\n backref_key, parent_schema_name, parent_field_name = stack\n\n # Get parent info\n parent_schema = obj._collections[parent_schema_name]\n parent_key_store = parent_schema._pk_to_storage(key)\n parent_object = parent_schema.load(parent_key_store)\n if parent_object is None:\n continue\n\n # Remove forward references\n if parent_object._fields[parent_field_name]._list:\n getattr(parent_object, parent_field_name).remove(obj)\n else:\n parent_field_object = parent_object._fields[parent_field_name]\n setattr(parent_object, parent_field_name, parent_field_object._gen_default())\n\n # Save\n parent_object.save()", "response": "When removing an object other objects with forward references to the current object should remove those references. This function identifies objects\n with forward references to the current object then removes those references."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef rm_back_refs(obj):\n for ref in _collect_refs(obj):\n ref['value']._remove_backref(\n ref['field_instance']._backref_field_name,\n obj,\n ref['field_name'],\n strict=False\n )", "response": "When removing an object with foreign fields back - references from other objects to the current object should be deleted."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nensuring that all forward references on the provided object have the appropriate backreferences.", "response": "def ensure_backrefs(obj, fields=None):\n \"\"\"Ensure that all forward references on the provided object have the\n appropriate backreferences.\n\n :param StoredObject obj: Database record\n :param list fields: Optional list of field names to check\n\n \"\"\"\n for ref in _collect_refs(obj, fields):\n updated = ref['value']._update_backref(\n ref['field_instance']._backref_field_name,\n obj,\n ref['field_name'],\n )\n if updated:\n logging.debug('Updated reference {}:{}:{}:{}:{}'.format(\n obj._name, obj._primary_key, ref['field_name'],\n ref['value']._name, ref['value']._primary_key,\n ))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _remove_by_pk(self, key, flush=True):\n try:\n del self.store[key]\n except Exception as error:\n pass\n if flush:\n self.flush()", "response": "Retrieve value from store."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ninitialize the bot plugins and everything.", "response": "def start(self):\n \"\"\"Initializes the bot, plugins, and everything.\"\"\"\n self.bot_start_time = datetime.now()\n self.webserver = Webserver(self.config['webserver']['host'], self.config['webserver']['port'])\n self.plugins.load()\n self.plugins.load_state()\n self._find_event_handlers()\n self.sc = ThreadedSlackClient(self.config['slack_token'])\n\n self.always_send_dm = ['_unauthorized_']\n if 'always_send_dm' in self.config:\n self.always_send_dm.extend(map(lambda x: '!' + x, self.config['always_send_dm']))\n\n # Rocket is very noisy at debug\n logging.getLogger('Rocket.Errors.ThreadPool').setLevel(logging.INFO)\n\n self.is_setup = True\n if self.test_mode:\n self.metrics['startup_time'] = (datetime.now() - self.bot_start_time).total_seconds() * 1000.0"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nrun the main loop of the slack RTM API.", "response": "def run(self, start=True):\n \"\"\"\n Connects to slack and enters the main loop.\n\n * start - If True, rtm.start API is used. Else rtm.connect API is used\n\n For more info, refer to\n https://python-slackclient.readthedocs.io/en/latest/real_time_messaging.html#rtm-start-vs-rtm-connect\n \"\"\"\n # Fail out if setup wasn't run\n if not self.is_setup:\n raise NotSetupError\n\n # Start the web server\n self.webserver.start()\n\n first_connect = True\n\n try:\n while self.runnable:\n if self.reconnect_needed:\n if not self.sc.rtm_connect(with_team_state=start):\n return False\n self.reconnect_needed = False\n if first_connect:\n first_connect = False\n self.plugins.connect()\n\n # Get all waiting events - this always returns a list\n try:\n events = self.sc.rtm_read()\n except AttributeError:\n self.log.exception('Something has failed in the slack rtm library. This is fatal.')\n self.runnable = False\n events = []\n except:\n self.log.exception('Unhandled exception in rtm_read()')\n self.reconnect_needed = True\n events = []\n for e in events:\n try:\n self._handle_event(e)\n except KeyboardInterrupt:\n # Gracefully shutdown\n self.runnable = False\n except:\n self.log.exception('Unhandled exception in event handler')\n sleep(0.1)\n except KeyboardInterrupt:\n # On ctrl-c, just exit\n pass\n except:\n self.log.exception('Unhandled exception')"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef stop(self):\n if self.webserver is not None:\n self.webserver.stop()\n if not self.test_mode:\n self.plugins.save_state()", "response": "Does cleanup of bot and plugins."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nsend a message to the specified channel.", "response": "def send_message(self, channel, text, thread=None, reply_broadcast=None):\n \"\"\"\n Sends a message to the specified channel\n\n * channel - The channel to send to. This can be a SlackChannel object, a channel id, or a channel name\n (without the #)\n * text - String to send\n * thread - reply to the thread. See https://api.slack.com/docs/message-threading#threads_party\n * reply_broadcast - Set to true to indicate your reply is germane to all members of a channel\n \"\"\"\n # This doesn't want the # in the channel name\n if isinstance(channel, SlackRoomIMBase):\n channel = channel.id\n self.log.debug(\"Trying to send to %s: %s\", channel, text)\n self.sc.rtm_send_message(channel, text, thread=thread, reply_broadcast=reply_broadcast)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsending a message to a user as an IM", "response": "def send_im(self, user, text):\n \"\"\"\n Sends a message to a user as an IM\n\n * user - The user to send to. This can be a SlackUser object, a user id, or the username (without the @)\n * text - String to send\n \"\"\"\n if isinstance(user, SlackUser):\n user = user.id\n channelid = self._find_im_channel(user)\n else:\n channelid = user.id\n self.send_message(channelid, text)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ncheck if a token is correct.", "response": "def token_is_correct(self, token):\n \"\"\"\n \u041f\u043e\u0434\u0445\u043e\u0434\u0438\u0442 \u043b\u0438 \u0442\u043e\u043a\u0435\u043d, \u0434\u043b\u044f \u0433\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u0438 \u0442\u0435\u043a\u0441\u0442\u0430.\n \u0414\u043e\u043f\u0443\u0441\u043a\u0430\u044e\u0442\u0441\u044f \u0440\u0443\u0441\u0441\u043a\u0438\u0435 \u0441\u043b\u043e\u0432\u0430, \u0437\u043d\u0430\u043a\u0438 \u043f\u0440\u0435\u043f\u0438\u043d\u0430\u043d\u0438\u044f \u0438 \u0441\u0438\u043c\u0432\u043e\u043b\u044b \u043d\u0430\u0447\u0430\u043b\u0430 \u0438 \u043a\u043e\u043d\u0446\u0430.\n \"\"\"\n if self.is_rus_word(token):\n return True\n elif self.ONLY_MARKS.search(token):\n return True\n elif self.END_TOKENS.search(token):\n return True\n elif token in \"$^\":\n return True\n return False"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn a list of optimal variants.", "response": "def get_optimal_variant(self, variants, start_words, **kwargs):\n \"\"\"\n \u0412\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u043e\u043f\u0442\u0438\u043c\u0430\u043b\u044c\u043d\u044b\u0439 \u0432\u0430\u0440\u0438\u0430\u043d\u0442, \u0438\u0437 \u0432\u044b\u0431\u043e\u0440\u043a\u0438.\n \"\"\"\n\n if not start_words:\n return (choice(variants), {})\n\n _variants = []\n _weights = []\n for tok in frozenset(variants):\n if not self.token_is_correct(tok):\n continue\n weight = variants.count(tok)\n for word in start_words:\n for token in self.ONLY_WORDS.finditer(word.strip().lower()):\n if token.group() == tok:\n weight <<= 1\n _variants.append(tok)\n _weights.append(weight)\n\n if not _variants:\n return (choice(variants), {})\n\n return (choices(_variants, weights=_weights, k=1)[0], {})"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nstarts generation of the user s succesfully.", "response": "def start_generation(self, *start_words, **kwargs):\n \"\"\"\n \u0413\u0435\u043d\u0435\u0440\u0438\u0440\u0443\u0435\u0442 \u043f\u0440\u0435\u0434\u043b\u043e\u0436\u0435\u043d\u0438\u0435.\n :start_words: \u041f\u043e\u043f\u044b\u0442\u0430\u0442\u044c\u0441\u044f \u043d\u0430\u0447\u0430\u0442\u044c \u043f\u0440\u0435\u0434\u043b\u043e\u0436\u0435\u043d\u0438\u0435 \u0441 \u044d\u0442\u0438\u0445 \u0441\u043b\u043e\u0432.\n \"\"\"\n out_text = \"\"\n _need_capialize = True\n for token in self._get_generate_tokens(*start_words, **kwargs):\n if token in \"$^\":\n _need_capialize = True\n continue\n if self.ONLY_WORDS.search(token):\n out_text += \" \"\n if _need_capialize:\n _need_capialize = False\n token = token.title()\n out_text += token\n\n return out_text.strip()"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_start_array(self, *start_words, **kwargs):\n if not self.start_arrays:\n raise MarkovTextExcept(\"\u041d\u0435 \u0441 \u0447\u0435\u0433\u043e \u043d\u0430\u0447\u0438\u043d\u0430\u0442\u044c \u0433\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u044e.\")\n if not start_words:\n return choice(self.start_arrays)\n\n _variants = []\n _weights = []\n for tokens in self.start_arrays:\n weight = 0b1\n for word in start_words:\n word = word.strip().lower()\n for token in self.ONLY_WORDS.finditer(word):\n if token.group() in tokens:\n weight <<= 1\n if weight > 0b1:\n _variants.append(tokens)\n _weights.append(weight)\n\n if not _variants:\n return choice(self.start_arrays)\n\n return choices(_variants, weights=_weights, k=1)[0]", "response": "returns a list of start_words"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef create_base(self):\n self.base_dict = {}\n _start_arrays = []\n for tokens, word in self.chain_generator():\n self.base_dict.setdefault(tokens, []).append(word)\n if tokens[0] == \"^\": # \u041f\u0435\u0440\u0432\u044b\u0435 \u043a\u043b\u044e\u0447\u0438, \u0434\u043b\u044f \u043d\u0430\u0447\u0430\u043b\u0430 \u0433\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u0438.\n _start_arrays.append(tokens)\n\n self.start_arrays = tuple(\n frozenset(self.get_corrected_arrays(_start_arrays))\n )", "response": "\u041c\u0435\u0442\u043e\u0434 \u0441\u043e\u0437\u0434\u0430\u0451\u0442 \u0431\u0430\u0437\u043e\u0432\u044b\u0439 \u0441\u043b\u043e\u0432\u0430\u0440\u044c, \u043d\u0430 \u043e\u0441\u043d\u043e\u0432\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u0430 \u0442\u043e\u043a\u0435\u043d\u043e\u0432.\n \u0412\u044b\u0437\u044b\u0432\u0430\u0435\u0442\u0441\u044f \u0438\u0437 \u043c\u0435\u0442\u043e\u0434\u0430 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u044f."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nsetting the vocabulary of the user.", "response": "def set_vocabulary(self, peer_id, from_dialogue=None, update=False):\n \"\"\"\n \u041f\u043e\u043b\u0443\u0447\u0430\u0435\u0442 \u0432\u043e\u043a\u0430\u0431\u0443\u043b\u0430\u0440 \u0438\u0437 \u0444\u0443\u043d\u043a\u0446\u0438\u0438 get_vocabulary \u0438 \u0434\u0435\u043b\u0430\u0435\u0442 \u0435\u0433\u043e \u0430\u043a\u0442\u0438\u0432\u043d\u044b\u043c.\n \"\"\"\n\n self.tokens_array = self.get_vocabulary(\n peer_id,\n from_dialogue,\n update\n )\n self.create_base()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncreate a dump of the current state of the current object.", "response": "def create_dump(self, name=None):\n \"\"\"\n \u0421\u043e\u0445\u0440\u0430\u043d\u044f\u0435\u0442 \u0442\u0435\u043a\u0443\u0449\u0443\u044e \u0431\u0430\u0437\u0443 \u043d\u0430 \u0436\u0451\u0441\u0442\u043a\u0438\u0439 \u0434\u0438\u0441\u043a.\n :name: \u0418\u043c\u044f \u0444\u0430\u0439\u043b\u0430, \u0431\u0435\u0437 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043d\u0438\u044f.\n \"\"\"\n name = name or \"vocabularDump\"\n backup_dump_file = os_join(\n self.temp_folder,\n \"{0}.backup\".format(name)\n )\n dump_file = os_join(\n self.temp_folder,\n \"{0}.json\".format(name)\n )\n with open(backup_dump_file, \"w\", encoding=\"utf-8\") as js_file:\n json.dump(self.tokens_array, js_file, ensure_ascii=False)\n copy2(backup_dump_file, dump_file)\n remove(backup_dump_file)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef load_dump(self, name=None):\n name = name or \"vocabularDump\"\n dump_file = os_join(\n self.temp_folder,\n \"{0}.json\".format(name)\n )\n if not isfile(dump_file):\n raise MarkovTextExcept(\"\u0424\u0430\u0439\u043b {0!r} \u043d\u0435 \u043d\u0430\u0439\u0434\u0435\u043d.\".format(dump_file))\n with open(dump_file, \"rb\") as js_file:\n self.tokens_array = tuple(json.load(js_file))\n self.create_base()", "response": "Load a dump file and create a base object."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_vocabulary(self, target, user=None, update=False):\n if not self.vk_object:\n raise MarkovTextExcept(\"\u041e\u0431\u044a\u0435\u043a\u0442 \u0431\u043e\u0442\u0430 \u043d\u0435 \u0437\u0430\u0434\u0430\u043d.\")\n\n json_name = \"{0}{1}_{2}\".format(\n target.__class__.__name__,\n target.id,\n user.id\n )\n json_file = os_join(self.temp_folder, \"{0}.json\".format(json_name))\n\n if not update:\n result = self.vocabulars.get(json_name, None)\n if result:\n return result\n elif isfile(json_file):\n with open(json_file, \"rb\") as js_file:\n result = self.vocabulars[json_name] = tuple(\n json.load(js_file)\n )\n return result\n\n _tokens_array = tuple(self.__parse_from_vk_dialogue(target, user))\n\n backup_file = \"{0}.backup\".format(splitext(json_file)[0])\n with open(backup_file, \"w\", encoding=\"utf-8\") as js_file:\n json.dump(_tokens_array, js_file, ensure_ascii=False)\n\n copy2(backup_file, json_file)\n remove(backup_file)\n self.vocabulars[json_name] = _tokens_array\n return _tokens_array", "response": "Returns a list of the vocabulary of the user."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nupdate the internal list with the given data.", "response": "def update(self, data, fromfile=True):\n \"\"\"\n \u041f\u0440\u0438\u043d\u0438\u043c\u0430\u0435\u0442 \u0442\u0435\u043a\u0441\u0442, \u0438\u043b\u0438 \u043f\u0443\u0442\u044c \u043a \u0444\u0430\u0439\u043b\u0443 \u0438 \u043e\u0431\u043d\u043e\u0432\u043b\u044f\u0435\u0442 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044e\u0449\u0443\u044e \u0431\u0430\u0437\u0443.\n \"\"\"\n func = (self._parse_from_file if fromfile else self._parse_from_text)\n new_data = tuple(func(data))\n if new_data:\n self.tokens_array += new_data\n self.create_base()"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _parse_from_text(self, text):\n if not isinstance(text, str):\n raise MarkovTextExcept(\"\u041f\u0435\u0440\u0435\u0434\u0430\u043d \u043d\u0435 \u0442\u0435\u043a\u0441\u0442.\")\n text = text.strip().lower()\n need_start_token = True\n token = \"$\" # \u041d\u0430 \u0441\u043b\u0443\u0447\u0430\u0439, \u0435\u0441\u043b\u0438 \u043f\u0435\u0440\u0435\u0434\u0430\u043d\u043d\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 \u043f\u0443\u0441\u0442\u0430.\n for token in self.WORD_OR_MARKS.finditer(text):\n token = token.group()\n if need_start_token:\n need_start_token = False\n yield \"^\"\n yield token\n if self.END_TOKENS.search(token):\n need_start_token = True\n yield \"$\"\n if token != \"$\":\n yield \"$\"", "response": "Parse a text string into a list of strings."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _parse_from_file(self, file_path):\n file_path = abspath(file_path)\n if not isfile(file_path):\n raise MarkovTextExcept(\"\u041f\u0435\u0440\u0435\u0434\u0430\u043d \u043d\u0435 \u0444\u0430\u0439\u043b.\")\n with open(file_path, \"rb\") as txt_file:\n for line in txt_file:\n text = line.decode(\"utf-8\", \"ignore\").strip()\n if not text:\n continue\n yield from self._parse_from_text(text)", "response": "A generator that yields MarkovItem objects from a file."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ntake a SlackEvent parses it for a command and runs it against the registered plugin s command queue and returns the command and the command and the command itself.", "response": "def push(self, message):\n \"\"\"\n Takes a SlackEvent, parses it for a command, and runs against registered plugin\n \"\"\"\n if self._ignore_event(message):\n return None, None\n args = self._parse_message(message)\n self.log.debug(\"Searching for command using chunks: %s\", args)\n cmd, msg_args = self._find_longest_prefix_command(args)\n if cmd is not None:\n if message.user is None:\n self.log.debug(\"Discarded message with no originating user: %s\", message)\n return None, None\n sender = message.user.username\n if message.channel is not None:\n sender = \"#%s/%s\" % (message.channel.name, sender)\n self.log.info(\"Received from %s: %s, args %s\", sender, cmd, msg_args)\n f = self._get_command(cmd, message.user)\n if f:\n if self._is_channel_ignored(f, message.channel):\n self.log.info(\"Channel %s is ignored, discarding command %s\", message.channel, cmd)\n return '_ignored_', \"\"\n return cmd, f.execute(message, msg_args)\n return '_unauthorized_', \"Sorry, you are not authorized to run %s\" % cmd\n return None, None"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _ignore_event(self, message):\n if hasattr(message, 'subtype') and message.subtype in self.ignored_events:\n return True\n return False", "response": "Check if the message is not truly an event and ignore it."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef register_plugin(self, plugin):\n self.log.info(\"Registering plugin %s\", type(plugin).__name__)\n self._register_commands(plugin)\n plugin.on_load()", "response": "Registers a plugin and commands with the dispatcher for push"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef acl_show(self, msg, args):\n name = args[0] if len(args) > 0 else None\n if name is None:\n return \"%s: The following ACLs are defined: %s\" % (msg.user, ', '.join(self._acl.keys()))\n\n if name not in self._acl:\n return \"Sorry, couldn't find an acl named '%s'\" % name\n\n return '\\n'.join([\n \"%s: ACL '%s' is defined as follows:\" % (msg.user, name),\n \"allow: %s\" % ', '.join(self._acl[name]['allow']),\n \"deny: %s\" % ', '.join(self._acl[name]['deny'])\n ])", "response": "Show current allow and deny blocks for the given acl."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nadding a user to the given acl allow block.", "response": "def add_user_to_allow(self, name, user):\n \"\"\"Add a user to the given acl allow block.\"\"\"\n\n # Clear user from both allow and deny before adding\n if not self.remove_user_from_acl(name, user):\n return False\n\n if name not in self._acl:\n return False\n\n self._acl[name]['allow'].append(user)\n return True"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef remove_user_from_acl(self, name, user):\n if name not in self._acl:\n return False\n if user in self._acl[name]['allow']:\n self._acl[name]['allow'].remove(user)\n if user in self._acl[name]['deny']:\n self._acl[name]['deny'].remove(user)\n return True", "response": "Remove a user from the given acl."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ncreate a new acl.", "response": "def create_acl(self, name):\n \"\"\"Create a new acl.\"\"\"\n if name in self._acl:\n return False\n\n self._acl[name] = {\n 'allow': [],\n 'deny': []\n }\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef mongo(daemon=False, port=20771):\n '''Run the mongod process.\n '''\n cmd = \"mongod --port {0}\".format(port)\n if daemon:\n cmd += \" --fork\"\n run(cmd)", "response": "Run the mongod process."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef proxy_factory(BaseSchema, label, ProxiedClass, get_key):\n def local():\n key = get_key()\n try:\n return proxies[BaseSchema][label][key]\n except KeyError:\n proxies[BaseSchema][label][key] = ProxiedClass()\n return proxies[BaseSchema][label][key]\n return LocalProxy(local)", "response": "Create a proxy to a class instance stored in proxies."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef with_proxies(proxy_map, get_key):\n def wrapper(cls):\n for label, ProxiedClass in six.iteritems(proxy_map):\n proxy = proxy_factory(cls, label, ProxiedClass, get_key)\n setattr(cls, label, proxy)\n return cls\n return wrapper", "response": "Class decorator factory that adds proxies to target class."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nconverting a value to a primary key.", "response": "def _to_primary_key(self, value):\n \"\"\"\n Return primary key; if value is StoredObject, verify\n that it is loaded.\n\n \"\"\"\n if value is None:\n return None\n if isinstance(value, self.base_class):\n if not value._is_loaded:\n raise exceptions.DatabaseError('Record must be loaded.')\n return value._primary_key\n\n return self.base_class._to_primary_key(value)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nassigning to a nested dictionary.", "response": "def set_nested(data, value, *keys):\n \"\"\"Assign to a nested dictionary.\n\n :param dict data: Dictionary to mutate\n :param value: Value to set\n :param list *keys: List of nested keys\n\n >>> data = {}\n >>> set_nested(data, 'hi', 'k0', 'k1', 'k2')\n >>> data\n {'k0': {'k1': {'k2': 'hi'}}}\n\n \"\"\"\n if len(keys) == 1:\n data[keys[0]] = value\n else:\n if keys[0] not in data:\n data[keys[0]] = {}\n set_nested(data[keys[0]], value, *keys[1:])"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nretrieves user by username", "response": "def get_by_username(self, username):\n \"\"\"Retrieve user by username\"\"\"\n res = filter(lambda x: x.username == username, self.users.values())\n if len(res) > 0:\n return res[0]\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef set(self, user):\n\n self.log.info(\"Loading user information for %s/%s\", user.id, user.username)\n self.load_user_info(user)\n self.log.info(\"Loading user rights for %s/%s\", user.id, user.username)\n self.load_user_rights(user)\n self.log.info(\"Added user: %s/%s\", user.id, user.username)\n self._add_user_to_cache(user)\n return user", "response": "Adds a SlackUser object to the user manager"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nsetting permissions on user object", "response": "def load_user_rights(self, user):\n \"\"\"Sets permissions on user object\"\"\"\n if user.username in self.admins:\n user.is_admin = True\n elif not hasattr(user, 'is_admin'):\n user.is_admin = False"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef send_message(self, channel, text):\n if isinstance(channel, SlackIM) or isinstance(channel, SlackUser):\n self._bot.send_im(channel, text)\n elif isinstance(channel, SlackRoom):\n self._bot.send_message(channel, text)\n elif isinstance(channel, basestring):\n if channel[0] == '@':\n self._bot.send_im(channel[1:], text)\n elif channel[0] == '#':\n self._bot.send_message(channel[1:], text)\n else:\n self._bot.send_message(channel, text)\n else:\n self._bot.send_message(channel, text)", "response": "Send a message to the specified channel."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nschedule a function to be called after some period of time.", "response": "def start_timer(self, duration, func, *args):\n \"\"\"\n Schedules a function to be called after some period of time.\n\n * duration - time in seconds to wait before firing\n * func - function to be called\n * args - arguments to pass to the function\n \"\"\"\n t = threading.Timer(duration, self._timer_callback, (func, args))\n self._timer_callbacks[func] = t\n t.start()\n self.log.info(\"Scheduled call to %s in %ds\", func.__name__, duration)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef stop_timer(self, func):\n if func in self._timer_callbacks:\n t = self._timer_callbacks[func]\n t.cancel()\n del self._timer_callbacks[func]", "response": "Stops a timer if it has not fired yet"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nprinting translate result in a better format", "response": "def print_res(data):\n \"\"\" Print translate result in a better format\n Args:\n data(str): result\n \"\"\"\n print('===================================')\n main_part = data['data']\n print(main_part['word_name'])\n symbols = main_part['symbols'][0]\n print(\"\u7f8e\u5f0f\u97f3\u6807\uff1a[\" + symbols['ph_am'] + \"]\")\n print(\"\u82f1\u5f0f\u97f3\u6807\uff1a[\" + symbols['ph_en'] + \"]\")\n print('-----------------------------------')\n parts = symbols['parts']\n for part in parts:\n print(part['part'])\n for mean in part['means']:\n print(\" \", mean)\n print('===================================')"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _get_underlying_data(self, instance):\n self._touch(instance)\n return self.data.get(instance, None)", "response": "Return data from raw data store rather than overridden\n __get__ methods. Should NOT be overwritten."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncasts value to its frozen counterpart.", "response": "def freeze(value):\n \"\"\" Cast value to its frozen counterpart. \"\"\"\n if isinstance(value, list):\n return FrozenList(*value)\n if isinstance(value, dict):\n return FrozenDict(**value)\n return value"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef help(self, msg, args):\n output = []\n if len(args) == 0:\n commands = sorted(self._bot.dispatcher.commands.items(), key=itemgetter(0))\n commands = filter(lambda x: x[1].is_subcmd is False, commands)\n # Filter commands if auth is enabled, hide_admin_commands is enabled, and user is not admin\n if self._should_filter_help_commands(msg.user):\n commands = filter(lambda x: x[1].admin_only is False, commands)\n for name, cmd in commands:\n output.append(self._get_short_help_for_command(name))\n else:\n name = '!' + args[0]\n output = [self._get_help_for_command(name)]\n return '\\n'.join(output)", "response": "Displays help for each command"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nsaving the current state of the plugin to the backend.", "response": "def save(self, msg, args):\n \"\"\"Causes the bot to write its current state to backend.\"\"\"\n self.send_message(msg.channel, \"Saving current state...\")\n self._bot.plugins.save_state()\n self.send_message(msg.channel, \"Done.\")"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef shutdown(self, msg, args):\n self.log.info(\"Received shutdown from %s\", msg.user.username)\n self._bot.runnable = False\n return \"Shutting down...\"", "response": "Called when a shutdown message is received."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nprints information about the user and bot version.", "response": "def whoami(self, msg, args):\n \"\"\"Prints information about the user and bot version.\"\"\"\n output = [\"Hello %s\" % msg.user]\n if hasattr(self._bot.dispatcher, 'auth_manager') and msg.user.is_admin is True:\n output.append(\"You are a *bot admin*.\")\n output.append(\"Bot version: %s-%s\" % (self._bot.version, self._bot.commit))\n return '\\n'.join(output)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nattempt to ignore all messages from the specified channel.", "response": "def sleep(self, channel):\n \"\"\"Causes the bot to ignore all messages from the channel.\n\n Usage:\n !sleep [channel name] - ignore the specified channel (or current if none specified)\n \"\"\"\n self.log.info('Sleeping in %s', channel)\n self._bot.dispatcher.ignore(channel)\n self.send_message(channel, 'Good night')"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef wake(self, channel):\n self.log.info('Waking up in %s', channel)\n self._bot.dispatcher.unignore(channel)\n self.send_message(channel, 'Hello, how may I be of service?')", "response": "Wake up the channel."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _arg_name(self, name, types, prefix=\"--\"):\n if 'type:a10_nullable' in types:\n return self._arg_name(name, types['type:a10_nullable'], prefix)\n\n if 'type:a10_list' in types:\n return self._arg_name(name, types['type:a10_list'], prefix)\n\n if 'type:a10_reference' in types:\n if name.endswith('_id'):\n name = name[:-3]\n\n \"\"\"--shish-kabob it\"\"\"\n return prefix + name.replace('_', '-')", "response": "Return the argument name for the user."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _sort_by(key):\n\n @staticmethod\n def sort_by(p_list, reverse=False):\n return sorted(\n p_list,\n key=lambda p: getattr(p, key),\n reverse=reverse,\n )\n\n return sort_by", "response": "High order function for sort methods."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nselecting path by criterion.", "response": "def select(self, filters=all_true, recursive=True):\n \"\"\"Select path by criterion.\n\n :param filters: a lambda function that take a `pathlib.Path` as input,\n boolean as a output.\n :param recursive: include files in subfolder or not.\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u8def\u5f84\u3002\n \"\"\"\n self.assert_is_dir_and_exists()\n\n if recursive:\n for p in self.glob(\"**/*\"):\n if filters(p):\n yield p\n else:\n for p in self.iterdir():\n if filters(p):\n yield p"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nselects file path by criterion.", "response": "def select_file(self, filters=all_true, recursive=True):\n \"\"\"Select file path by criterion.\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u6839\u636efilters\u4e2d\u5b9a\u4e49\u7684\u6761\u4ef6\u9009\u62e9\u6587\u4ef6\u3002\n \"\"\"\n for p in self.select(filters, recursive):\n if p.is_file():\n yield p"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef select_dir(self, filters=all_true, recursive=True):\n for p in self.select(filters, recursive):\n if p.is_dir():\n yield p", "response": "Select all directories in the database."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ncounts how many files in this directory. Including file in sub folder.", "response": "def n_file(self):\n \"\"\"\n Count how many files in this directory. Including file in sub folder.\n \"\"\"\n self.assert_is_dir_and_exists()\n n = 0\n for _ in self.select_file(recursive=True):\n n += 1\n return n"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncounts how many folders in this directory. Including folder in sub folder.", "response": "def n_dir(self):\n \"\"\"\n Count how many folders in this directory. Including folder in sub folder.\n \"\"\"\n self.assert_is_dir_and_exists()\n n = 0\n for _ in self.select_dir(recursive=True):\n n += 1\n return n"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncounting how many subfiles in this directory.", "response": "def n_subfile(self):\n \"\"\"\n Count how many files in this directory (doesn't include files in\n sub folders).\n \"\"\"\n self.assert_is_dir_and_exists()\n n = 0\n for _ in self.select_file(recursive=False):\n n += 1\n return n"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef n_subdir(self):\n self.assert_is_dir_and_exists()\n n = 0\n for _ in self.select_dir(recursive=False):\n n += 1\n return n", "response": "Count how many subfolders in this directory."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef select_by_ext(self, ext, recursive=True):\n ext = [ext.strip().lower() for ext in ensure_list(ext)]\n\n def filters(p): return p.suffix.lower() in ext\n\n return self.select_file(filters, recursive)", "response": "Select file path by extension."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef select_by_pattern_in_fname(self,\n pattern,\n recursive=True,\n case_sensitive=False):\n \"\"\"\n Select file path by text pattern in file name.\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u9009\u62e9\u6587\u4ef6\u540d\u4e2d\u5305\u542b\u6307\u5b9a\u5b50\u5b57\u7b26\u4e32\u7684\u6587\u4ef6\u3002\n \"\"\"\n if case_sensitive:\n def filters(p):\n return pattern in p.fname\n else:\n pattern = pattern.lower()\n\n def filters(p):\n return pattern in p.fname.lower()\n\n return self.select_file(filters, recursive)", "response": "Select file path by text pattern in file name."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nselecting file path by text pattern in absolute path.", "response": "def select_by_pattern_in_abspath(self,\n pattern,\n recursive=True,\n case_sensitive=False):\n \"\"\"\n Select file path by text pattern in absolute path.\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u9009\u62e9\u7edd\u5bf9\u8def\u5f84\u4e2d\u5305\u542b\u6307\u5b9a\u5b50\u5b57\u7b26\u4e32\u7684\u6587\u4ef6\u3002\n \"\"\"\n if case_sensitive:\n def filters(p):\n return pattern in p.abspath\n else:\n pattern = pattern.lower()\n\n def filters(p):\n return pattern in p.abspath.lower()\n\n return self.select_file(filters, recursive)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef select_by_size(self, min_size=0, max_size=1 << 40, recursive=True):\n\n def filters(p): return min_size <= p.size <= max_size\n\n return self.select_file(filters, recursive)", "response": "Select file path by size."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nselecting file path by modify time.", "response": "def select_by_mtime(self, min_time=0, max_time=ts_2100,\n recursive=True):\n \"\"\"\n Select file path by modify time.\n\n :param min_time: lower bound timestamp\n :param max_time: upper bound timestamp\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.mtime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n \"\"\"\n\n def filters(p): return min_time <= p.mtime <= max_time\n\n return self.select_file(filters, recursive)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nselecting file path by access time.", "response": "def select_by_atime(self, min_time=0, max_time=ts_2100, recursive=True):\n \"\"\"\n Select file path by access time.\n\n :param min_time: lower bound timestamp\n :param max_time: upper bound timestamp\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.atime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n \"\"\"\n\n def filters(p): return min_time <= p.atime <= max_time\n\n return self.select_file(filters, recursive)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nselect file path by create time.", "response": "def select_by_ctime(self, min_time=0, max_time=ts_2100,\n recursive=True):\n \"\"\"\n Select file path by create time.\n\n :param min_time: lower bound timestamp\n :param max_time: upper bound timestamp\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u9009\u62e9\u6240\u6709 :attr:`pathlib_mate.pathlib2.Path.ctime` \u5728\u4e00\u5b9a\u8303\u56f4\u5185\u7684\u6587\u4ef6\u3002\n \"\"\"\n\n def filters(p): return min_time <= p.ctime <= max_time\n\n return self.select_file(filters, recursive)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef dirsize(self):\n total = 0\n for p in self.select_file(recursive=True):\n try:\n total += p.size\n except: # pragma: no cover\n print(\"Unable to get file size of: %s\" % p)\n return total", "response": "Return total file size of the file."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef make_zip_archive(self,\n dst=None,\n filters=all_true,\n compress=True,\n overwrite=False,\n makedirs=False,\n verbose=False): # pragma: no cover\n \"\"\"\n Make a zip archive.\n\n :param dst: output file path. if not given, will be automatically assigned.\n :param filters: custom path filter. By default it allows any file.\n :param compress: compress or not.\n :param overwrite: overwrite exists or not.\n :param verbose: display log or not.\n :return:\n \"\"\"\n self.assert_exists()\n\n if dst is None:\n dst = self._auto_zip_archive_dst()\n else:\n dst = self.change(new_abspath=dst)\n\n if not dst.basename.lower().endswith(\".zip\"):\n raise ValueError(\"zip archive name has to be endswith '.zip'!\")\n\n if dst.exists():\n if not overwrite:\n raise IOError(\"'%s' already exists!\" % dst)\n\n if compress:\n compression = ZIP_DEFLATED\n else:\n compression = ZIP_STORED\n\n if not dst.parent.exists():\n if makedirs:\n os.makedirs(dst.parent.abspath)\n\n if verbose:\n msg = \"Making zip archive for '%s' ...\" % self\n print(msg)\n\n current_dir = os.getcwd()\n\n if self.is_dir():\n total_size = 0\n selected = list()\n for p in self.glob(\"**/*\"):\n if filters(p):\n selected.append(p)\n total_size += p.size\n\n if verbose:\n msg = \"Got {} files, total size is {}, compressing ...\".format(\n len(selected), repr_data_size(total_size),\n )\n print(msg)\n\n with ZipFile(dst.abspath, \"w\", compression) as f:\n os.chdir(self.abspath)\n for p in selected:\n relpath = p.relative_to(self).__str__()\n f.write(relpath)\n\n elif self.is_file():\n with ZipFile(dst.abspath, \"w\", compression) as f:\n os.chdir(self.parent.abspath)\n f.write(self.basename)\n\n os.chdir(current_dir)\n\n if verbose:\n msg = \"Complete! Archive size is {}.\".format(dst.size_in_text)\n print(msg)", "response": "Makes a zip archive of the current directory."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef backup(self,\n dst=None,\n ignore=None,\n ignore_ext=None,\n ignore_pattern=None,\n ignore_size_smaller_than=None,\n ignore_size_larger_than=None,\n case_sensitive=False): # pragma: no cover\n \"\"\"\n Create a compressed zip archive backup for a directory.\n\n :param dst: the output file path.\n :param ignore: file or directory defined in this list will be ignored.\n :param ignore_ext: file with extensions defined in this list will be ignored.\n :param ignore_pattern: any file or directory that contains this pattern\n will be ignored.\n :param ignore_size_smaller_than: any file size smaller than this\n will be ignored.\n :param ignore_size_larger_than: any file size larger than this\n will be ignored.\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u4e3a\u4e00\u4e2a\u76ee\u5f55\u521b\u5efa\u4e00\u4e2a\u5907\u4efd\u538b\u7f29\u5305\u3002\u53ef\u4ee5\u901a\u8fc7\u8fc7\u6ee4\u5668\u9009\u62e9\u4f60\u8981\u5907\u4efd\u7684\u6587\u4ef6\u3002\n \"\"\"\n\n def preprocess_arg(arg): # pragma: no cover\n if arg is None:\n return []\n\n if isinstance(arg, (tuple, list)):\n return list(arg)\n else:\n return [arg, ]\n\n self.assert_is_dir_and_exists()\n\n ignore = preprocess_arg(ignore)\n for i in ignore:\n if i.startswith(\"/\") or i.startswith(\"\\\\\"):\n raise ValueError\n\n ignore_ext = preprocess_arg(ignore_ext)\n for ext in ignore_ext:\n if not ext.startswith(\".\"):\n raise ValueError\n\n ignore_pattern = preprocess_arg(ignore_pattern)\n\n if case_sensitive:\n pass\n else:\n ignore = [i.lower() for i in ignore]\n ignore_ext = [i.lower() for i in ignore_ext]\n ignore_pattern = [i.lower() for i in ignore_pattern]\n\n def filters(p):\n relpath = p.relative_to(self).abspath\n if not case_sensitive:\n relpath = relpath.lower()\n\n # ignore\n for i in ignore:\n if relpath.startswith(i):\n return False\n\n # ignore_ext\n if case_sensitive:\n ext = p.ext\n else:\n ext = p.ext.lower()\n\n if ext in ignore_ext:\n return False\n\n # ignore_pattern\n for pattern in ignore_pattern:\n if pattern in relpath:\n return False\n\n # ignore_size_smaller_than\n if ignore_size_smaller_than:\n if p.size < ignore_size_smaller_than:\n return False\n\n # ignore_size_larger_than\n if ignore_size_larger_than:\n if p.size > ignore_size_larger_than:\n return False\n\n return True\n\n self.make_zip_archive(\n dst=dst, filters=filters, compress=True, overwrite=False, verbose=True,\n )", "response": "Create a compressed zip archive for a directory."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef acquire_lock(func):\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n with self.locker as r:\n # get the result\n acquired, code, _ = r\n if acquired:\n try:\n r = func(self, *args, **kwargs)\n except Exception as err:\n e = str(err)\n else:\n e = None\n else:\n warnings.warn(\"code %s. Unable to aquire the lock when calling '%s'. You may try again!\"%(code,func.__name__) )\n e = None\n r = None\n # raise error after exiting with statement and releasing the lock!\n if e is not None:\n traceback.print_stack()\n raise Exception(e)\n return r\n return wrapper", "response": "Decorate methods when locking repository is required."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef sync_required(func):\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n if not self._keepSynchronized:\n r = func(self, *args, **kwargs)\n else:\n state = self._load_state()\n #print(\"-----------> \",state, self.state)\n if state is None:\n r = func(self, *args, **kwargs)\n elif state == self.state:\n r = func(self, *args, **kwargs)\n else:\n warnings.warn(\"Repository at '%s' is out of date. Need to load it again to avoid conflict.\"%self.path)\n r = None\n return r\n return wrapper", "response": "Decorate methods when synchronizing repository is required."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_list_representation(self):\n if self.__path is None:\n return []\n repr = [ self.__path+\":[\"+','.join(list(dict.__getitem__(self, 'files')))+']' ]\n # walk directories\n for directory in sorted(list(self.walk_directories_relative_path())):\n directoryRepr = os.path.normpath(directory)\n # get directory info\n dirInfoDict, errorMessage = self.get_directory_info(directory)\n assert dirInfoDict is not None, errorMessage\n directoryRepr += \":[\"+','.join( list(dict.__getitem__(dirInfoDict, 'files')))+']'\n repr.append(directoryRepr)\n return repr", "response": "Gets a list representation of the Repository content in a list of directories ( files ) format."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef walk_files_relative_path(self, relativePath=\"\"):\n def walk_files(directory, relativePath):\n directories = dict.__getitem__(directory, 'directories')\n files = dict.__getitem__(directory, 'files')\n for f in sorted(files):\n yield os.path.join(relativePath, f)\n for k in sorted(dict.keys(directories)):\n path = os.path.join(relativePath, k)\n dir = directories.__getitem__(k)\n for e in walk_files(dir, path):\n yield e\n dir, errorMessage = self.get_directory_info(relativePath)\n assert dir is not None, errorMessage\n return walk_files(dir, relativePath='')", "response": "Walk the repository and yield all found files relative path joined with file name."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef walk_files_info(self, relativePath=\"\"):\n def walk_files(directory, relativePath):\n directories = dict.__getitem__(directory, 'directories')\n files = dict.__getitem__(directory, 'files')\n for fname in sorted(files):\n info = dict.__getitem__(files,fname)\n yield os.path.join(relativePath, fname), info\n for k in sorted(dict.keys(directories)):\n path = os.path.join(relativePath, k)\n dir = dict.__getitem__(directories, k)\n for e in walk_files(dir, path):\n yield e\n dir, errorMessage = self.get_directory_info(relativePath)\n assert dir is not None, errorMessage\n return walk_files(dir, relativePath='')", "response": "Walk the repository and yield tuples as the following:\\n\n relative path to relativePath joined with file name file info dict."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef walk_directories_relative_path(self, relativePath=\"\"):\n def walk_directories(directory, relativePath):\n directories = dict.__getitem__(directory, 'directories')\n dirNames = dict.keys(directories)\n for d in sorted(dirNames):\n yield os.path.join(relativePath, d)\n for k in sorted(dict.keys(directories)):\n path = os.path.join(relativePath, k)\n dir = dict.__getitem__(directories, k)\n for e in walk_directories(dir, path):\n yield e\n dir, errorMessage = self.get_directory_info(relativePath)\n assert dir is not None, errorMessage\n return walk_directories(dir, relativePath='')", "response": "Walks the repository and yield all found directories relative path\nCOOKIE"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef walk_directories_info(self, relativePath=\"\"):\n def walk_directories(directory, relativePath):\n directories = dict.__getitem__(directory, 'directories')\n for fname in sorted(directories):\n info = dict.__getitem__(directories,fname)\n yield os.path.join(relativePath, fname), info\n for k in sorted(dict.keys(directories)):\n path = os.path.join(relativePath, k)\n dir = dict.__getitem__(directories, k)\n for e in walk_directories(dir, path):\n yield e\n dir, errorMessage = self.get_directory_info(relativePath)\n assert dir is not None, errorMessage\n return walk_directories(dir, relativePath='')", "response": "Walk repository and yield all found directories relative path."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef walk_directory_directories_relative_path(self, relativePath=\"\"):\n # get directory info dict\n errorMessage = \"\"\n relativePath = os.path.normpath(relativePath)\n dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n assert dirInfoDict is not None, errorMessage\n for dname in dict.__getitem__(dirInfoDict, \"directories\"):\n yield os.path.join(relativePath, dname)", "response": "Walk a certain directory in repository and yield all found directories relative path."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nwalks a certain directory and yield tuples as the following:\\ n relative path joined with directory name file info dict.", "response": "def walk_directory_directories_info(self, relativePath=\"\"):\n \"\"\"\n Walk a certain directory in repository and yield tuples as the following:\\n\n (relative path joined with directory name, file info dict).\n\n :parameters:\n #. relativePath (str): The relative path of the directory.\n \"\"\"\n # get directory info dict\n relativePath = os.path.normpath(relativePath)\n dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n assert dirInfoDict is not None, errorMessage\n for fname in dict.__getitem__(dirInfoDict, \"directories\"):\n yield os.path.join(relativePath, fname), dict.__getitem__(dirInfoDict, \"directories\")[fname]"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef synchronize(self, verbose=False):\n if self.__path is None:\n return\n # walk directories\n for dirPath in sorted(list(self.walk_directories_relative_path())):\n realPath = os.path.join(self.__path, dirPath)\n # if directory exist\n if os.path.isdir(realPath):\n continue\n if verbose: warnings.warn(\"%s directory is missing\"%realPath)\n # loop to get dirInfoDict\n keys = dirPath.split(os.sep)\n dirInfoDict = self\n for idx in range(len(keys)-1):\n dirs = dict.get(dirInfoDict, 'directories', None)\n if dirs is None: break\n dirInfoDict = dict.get(dirs, keys[idx], None)\n if dirInfoDict is None: break\n # remove dirInfoDict directory if existing\n if dirInfoDict is not None:\n dirs = dict.get(dirInfoDict, 'directories', None)\n if dirs is not None:\n dict.pop( dirs, keys[-1], None )\n # walk files\n for filePath in sorted(list(self.walk_files_relative_path())):\n realPath = os.path.join(self.__path, filePath)\n # if file exists\n if os.path.isfile( realPath ):\n continue\n if verbose: warnings.warn(\"%s file is missing\"%realPath)\n # loop to get dirInfoDict\n keys = filePath.split(os.sep)\n dirInfoDict = self\n for idx in range(len(keys)-1):\n dirs = dict.get(dirInfoDict, 'directories', None)\n if dirs is None: break\n dirInfoDict = dict.get(dirs, keys[idx], None)\n if dirInfoDict is None: break\n # remove dirInfoDict file if existing\n if dirInfoDict is not None:\n files = dict.get(dirInfoDict, 'files', None)\n if files is not None:\n dict.pop( files, keys[-1], None )", "response": "Synchronizes the Repository information with the directory."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nloads the current instance of the current repository from a directory path and updates the current instance with the loaded data.", "response": "def load_repository(self, path):\n \"\"\"\n Load repository from a directory path and update the current instance.\n\n :Parameters:\n #. path (string): The path of the directory from where to load the repository.\n If '.' or an empty string is passed, the current working directory will be used.\n\n :Returns:\n #. repository (pyrep.Repository): returns self repository with loaded data.\n \"\"\"\n # try to open\n if path.strip() in ('','.'):\n path = os.getcwd()\n repoPath = os.path.realpath( os.path.expanduser(path) )\n if not self.is_repository(repoPath):\n raise Exception(\"no repository found in '%s'\"%str(repoPath))\n # get pyrepinfo path\n repoInfoPath = os.path.join(repoPath, \".pyrepinfo\")\n try:\n fd = open(repoInfoPath, 'rb')\n except Exception as e:\n raise Exception(\"unable to open repository file(%s)\"%e)\n # before doing anything try to lock repository\n # can't decorate with @acquire_lock because this will point to old repository\n # path or to current working directory which might not be the path anyways\n L = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(repoPath, \".pyreplock\"))\n acquired, code = L.acquire_lock()\n # check if acquired.\n if not acquired:\n warnings.warn(\"code %s. Unable to aquire the lock when calling 'load_repository'. You may try again!\"%(code,) )\n return\n try:\n # unpickle file\n try:\n repo = pickle.load( fd )\n except Exception as e:\n fd.close()\n raise Exception(\"unable to pickle load repository (%s)\"%e)\n finally:\n fd.close()\n # check if it's a PyrepInfo instance\n if not isinstance(repo, Repository):\n raise Exception(\".pyrepinfo in '%s' is not a repository instance.\"%s)\n else:\n # update info path\n self.__reset_repository()\n self.__update_repository(repo)\n self.__path = repoPath\n # set timestamp\n self.__state = self._get_or_create_state()\n except Exception as e:\n L.release_lock()\n raise Exception(e)\n finally:\n L.release_lock()\n # set loaded repo locker path to L because repository have been moved to another directory\n self.__locker = L\n # return\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ncreates a repository in a directory. This method insures the creation of the directory in the system if it is missing.\\n **N.B. This method erases existing pyrep repository in the path but not the repository files.** :Parameters: #. path (string): The real absolute path where to create the Repository. If '.' or an empty string is passed, the current working directory will be used. #. info (None, object): Any information that can identify the repository. #. verbose (boolean): Whether to be warn and informed about any abnormalities.", "response": "def create_repository(self, path, info=None, verbose=True):\n \"\"\"\n create a repository in a directory.\n This method insures the creation of the directory in the system if it is missing.\\n\n\n **N.B. This method erases existing pyrep repository in the path but not the repository files.**\n\n :Parameters:\n #. path (string): The real absolute path where to create the Repository.\n If '.' or an empty string is passed, the current working directory will be used.\n #. info (None, object): Any information that can identify the repository.\n #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n \"\"\"\n try:\n info = copy.deepcopy( info )\n except:\n raise Exception(\"Repository info must be a copyable python object.\")\n # get real path\n if path.strip() in ('','.'):\n path = os.getcwd()\n realPath = os.path.realpath( os.path.expanduser(path) )\n # create directory if not existing\n if not os.path.isdir(realPath):\n os.makedirs(realPath)\n self.__path = realPath\n self.__info = info\n # reset if replace is set to True\n if self.is_repository(realPath):\n if verbose:\n warnings.warn(\"A pyrep Repository already exists in the given path '%s' and therefore it has been erased and replaced by a fresh repository.\"%path)\n # reset repository\n self.__reset_repository()\n # update locker because normally this is done in __update_repository method\n lp = '.pyreplock'\n if self.__path is not None:\n lp = os.path.join(self.__path,lp)\n self.__locker.set_lock_path(lp)\n self.__locker.set_lock_pass(str(uuid.uuid1()))\n # save repository\n self.save()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ncreating a repository at given real path or load any existing one.", "response": "def get_repository(self, path, info=None, verbose=True):\n \"\"\"\n Create a repository at given real path or load any existing one.\n This method insures the creation of the directory in the system if it is missing.\\n\n Unlike create_repository, this method doesn't erase any existing repository\n in the path but loads it instead.\n\n **N.B. On some systems and some paths, creating a directory may requires root permissions.**\n\n :Parameters:\n #. path (string): The real absolute path where to create the Repository.\n If '.' or an empty string is passed, the current working directory will be used.\n #. info (None, object): Any information that can identify the repository.\n #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n \"\"\"\n # get real path\n if path.strip() in ('','.'):\n path = os.getcwd()\n realPath = os.path.realpath( os.path.expanduser(path) )\n # create directory if not existing\n if not os.path.isdir(realPath):\n os.makedirs(realPath)\n # create Repository\n if not self.is_repository(realPath):\n self.create_repository(realPath, info=info, verbose=verbose)\n else:\n self.load_repository(realPath)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef remove_repository(self, path=None, relatedFiles=False, relatedFolders=False, verbose=True):\n if path is not None:\n realPath = os.path.realpath( os.path.expanduser(path) )\n else:\n realPath = self.__path\n if realPath is None:\n if verbose: warnings.warn('path is None and current Repository is not initialized!')\n return\n if not self.is_repository(realPath):\n if verbose: warnings.warn(\"No repository found in '%s'!\"%realPath)\n return\n # check for security\n if realPath == os.path.realpath('/..') :\n if verbose: warnings.warn('You are about to wipe out your system !!! action aboarded')\n return\n # get repo\n if path is not None:\n repo = Repository()\n repo.load_repository(realPath)\n else:\n repo = self\n # delete files\n if relatedFiles:\n for relativePath in repo.walk_files_relative_path():\n realPath = os.path.join(repo.path, relativePath)\n if not os.path.isfile(realPath):\n continue\n if not os.path.exists(realPath):\n continue\n os.remove( realPath )\n # delete directories\n if relatedFolders:\n for relativePath in reversed(list(repo.walk_directories_relative_path())):\n realPath = os.path.join(repo.path, relativePath)\n # protect from wiping out the system\n if not os.path.isdir(realPath):\n continue\n if not os.path.exists(realPath):\n continue\n if not len(os.listdir(realPath)):\n os.rmdir( realPath )\n # delete repository\n os.remove( os.path.join(repo.path, \".pyrepinfo\" ) )\n for fname in (\".pyrepstate\", \".pyreplock\"):\n p = os.path.join(repo.path, fname )\n if os.path.exists( p ):\n os.remove( p )\n # remove main directory if empty\n if os.path.isdir(repo.path):\n if not len(os.listdir(repo.path)):\n os.rmdir( repo.path )\n # reset repository\n repo.__reset_repository()", "response": "Removes a repository from the system."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef save(self):\n # open file\n repoInfoPath = os.path.join(self.__path, \".pyrepinfo\")\n try:\n fdinfo = open(repoInfoPath, 'wb')\n except Exception as e:\n raise Exception(\"unable to open repository info for saving (%s)\"%e)\n # save repository\n try:\n pickle.dump( self, fdinfo, protocol=2 )\n except Exception as e:\n fdinfo.flush()\n os.fsync(fdinfo.fileno())\n fdinfo.close()\n raise Exception( \"Unable to save repository info (%s)\"%e )\n finally:\n fdinfo.flush()\n os.fsync(fdinfo.fileno())\n fdinfo.close()\n # save timestamp\n repoTimePath = os.path.join(self.__path, \".pyrepstate\")\n try:\n self.__state = (\"%.6f\"%time.time()).encode()\n with open(repoTimePath, 'wb') as fdtime:\n fdtime.write( self.__state )\n fdtime.flush()\n os.fsync(fdtime.fileno())\n except Exception as e:\n raise Exception(\"unable to open repository time stamp for saving (%s)\"%e)", "response": "Save the current state of the object to disk."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncreates a tar file package of all the files and directories in the repository.", "response": "def create_package(self, path=None, name=None, mode=None):\n \"\"\"\n Create a tar file package of all the repository files and directories.\n Only files and directories that are stored in the repository info\n are stored in the package tar file.\n\n **N.B. On some systems packaging requires root permissions.**\n\n :Parameters:\n #. path (None, string): The real absolute path where to create the package.\n If None, it will be created in the same directory as the repository\n If '.' or an empty string is passed, the current working directory will be used.\n #. name (None, string): The name to give to the package file\n If None, the package directory name will be used with the appropriate extension added.\n #. mode (None, string): The writing mode of the tarfile.\n If None, automatically the best compression mode will be chose.\n Available modes are ('w', 'w:', 'w:gz', 'w:bz2')\n \"\"\"\n # check mode\n assert mode in (None, 'w', 'w:', 'w:gz', 'w:bz2'), 'unkown archive mode %s'%str(mode)\n if mode is None:\n mode = 'w:bz2'\n mode = 'w:'\n # get root\n if path is None:\n root = os.path.split(self.__path)[0]\n elif path.strip() in ('','.'):\n root = os.getcwd()\n else:\n root = os.path.realpath( os.path.expanduser(path) )\n assert os.path.isdir(root), 'absolute path %s is not a valid directory'%path\n # get name\n if name is None:\n ext = mode.split(\":\")\n if len(ext) == 2:\n if len(ext[1]):\n ext = \".\"+ext[1]\n else:\n ext = '.tar'\n else:\n ext = '.tar'\n name = os.path.split(self.__path)[1]+ext\n # save repository\n self.save()\n # create tar file\n tarfilePath = os.path.join(root, name)\n try:\n tarHandler = tarfile.TarFile.open(tarfilePath, mode=mode)\n except Exception as e:\n raise Exception(\"Unable to create package (%s)\"%e)\n # walk directory and create empty directories\n for directory in sorted(list(self.walk_directories_relative_path())):\n t = tarfile.TarInfo( directory )\n t.type = tarfile.DIRTYPE\n tarHandler.addfile(t)\n # walk files and add to tar\n for file in self.walk_files_relative_path():\n tarHandler.add(os.path.join(self.__path,file), arcname=file)\n # save repository .pyrepinfo\n tarHandler.add(os.path.join(self.__path,\".pyrepinfo\"), arcname=\".pyrepinfo\")\n # close tar file\n tarHandler.close()"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nchecking if there is a repository in path.", "response": "def is_repository(self, path):\n \"\"\"\n Check if there is a Repository in path.\n\n :Parameters:\n #. path (string): The real path of the directory where to check if there is a repository.\n\n :Returns:\n #. result (boolean): Whether its a repository or not.\n \"\"\"\n realPath = os.path.realpath( os.path.expanduser(path) )\n if not os.path.isdir(realPath):\n return False\n if \".pyrepinfo\" not in os.listdir(realPath):\n return False\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_directory_info(self, relativePath):\n relativePath = os.path.normpath(relativePath)\n # if root directory\n if relativePath in ('','.'):\n return self, \"\"\n currentDir = self.__path\n dirInfoDict = self\n for dir in relativePath.split(os.sep):\n dirInfoDict = dict.__getitem__(dirInfoDict, \"directories\")\n currentDir = os.path.join(currentDir, dir)\n # check if path exists\n if not os.path.exists(currentDir):\n return None, \"directory '%s' is not found\"%currentDir\n val = dirInfoDict.get(dir, None)\n # check if directory is registered in repository\n if val is None:\n return None, \"directory '%s' is not registered in PyrepInfo\"%currentDir\n dirInfoDict = val\n return dirInfoDict, \"\"", "response": "Returns the directory information dictionary and the error message if any error has occurred."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_parent_directory_info(self, relativePath):\n relativePath = os.path.normpath(relativePath)\n # if root directory\n if relativePath in ('','.'):\n return self, \"relativePath is empty pointing to the repostitory itself.\"\n # split path\n parentDirPath, _ = os.path.split(relativePath)\n # get parent directory info\n return self.get_directory_info(parentDirPath)", "response": "Get the parent directory info of a file or directory from the Repository."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nget file information dict from the repository given its relative path and name.", "response": "def get_file_info(self, relativePath, name=None):\n \"\"\"\n get file information dict from the repository given its relative path and name.\n\n :Parameters:\n #. relativePath (string): The relative to the repository path of the directory where the file is.\n #. name (string): The file name.\n If None is given, name will be split from relativePath.\n\n :Returns:\n #. info (None, dictionary): The file information dictionary.\n If None, it means an error has occurred.\n #. errorMessage (string): The error message if any error occurred.\n \"\"\"\n # normalize relative path and name\n relativePath = os.path.normpath(relativePath)\n if relativePath == '.':\n relativePath = ''\n assert name != '.pyrepinfo', \"'.pyrepinfo' can't be a file name.\"\n if name is None:\n assert len(relativePath), \"name must be given when relative path is given as empty string or as a simple dot '.'\"\n relativePath,name = os.path.split(relativePath)\n # initialize message\n errorMessage = \"\"\n # get directory info\n dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n if dirInfoDict is None:\n return None, errorMessage\n # get file info\n fileInfo = dict.__getitem__(dirInfoDict, \"files\").get(name, None)\n if fileInfo is None:\n errorMessage = \"file %s does not exist in relative path '%s'\"%(name, relativePath)\n return fileInfo, errorMessage"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_file_info_by_id(self, id):\n for path, info in self.walk_files_info():\n if info['id']==id:\n return path, info\n # none was found\n return None, None", "response": "Given an id get the corresponding file info dictionary."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_file_relative_path_by_id(self, id):\n for path, info in self.walk_files_info():\n if info['id']==id:\n return path\n # none was found\n return None", "response": "Given an id get the corresponding file info relative path joined with file name."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_file_relative_path_by_name(self, name, skip=0):\n if skip is None:\n paths = []\n else:\n paths = None\n for path, info in self.walk_files_info():\n _, n = os.path.split(path)\n if n==name:\n if skip is None:\n paths.append(path)\n elif skip>0:\n skip -= 1\n else:\n paths = path\n break\n return paths", "response": "Get file relative path given the file name."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef add_directory(self, relativePath, info=None):\n path = os.path.normpath(relativePath)\n # create directories\n currentDir = self.path\n currentDict = self\n if path in (\"\",\".\"):\n return currentDict\n save = False\n for dir in path.split(os.sep):\n dirPath = os.path.join(currentDir, dir)\n # create directory\n if not os.path.exists(dirPath):\n os.mkdir(dirPath)\n # create dictionary key\n currentDict = dict.__getitem__(currentDict, \"directories\")\n if currentDict.get(dir, None) is None:\n save = True\n currentDict[dir] = {\"directories\":{}, \"files\":{},\n \"timestamp\":datetime.utcnow(),\n \"id\":str(uuid.uuid1()),\n \"info\": info} # INFO MUST BE SET ONLY FOR THE LAST DIRECTORY\n\n currentDict = currentDict[dir]\n currentDir = dirPath\n # save repository\n if save:\n self.save()\n # return currentDict\n return currentDict", "response": "Adds a directory in the repository and creates its\n attribute in the Repository with utc timestamp."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nremoving a directory from the repository.", "response": "def remove_directory(self, relativePath, removeFromSystem=False):\n \"\"\"\n Remove directory from repository.\n\n :Parameters:\n #. relativePath (string): The relative to the repository path of the directory to remove from the repository.\n #. removeFromSystem (boolean): Whether to also remove directory and all files from the system.\\n\n Only files saved in the repository will be removed and empty left directories.\n \"\"\"\n # get parent directory info\n relativePath = os.path.normpath(relativePath)\n parentDirInfoDict, errorMessage = self.get_parent_directory_info(relativePath)\n assert parentDirInfoDict is not None, errorMessage\n # split path\n path, name = os.path.split(relativePath)\n if dict.__getitem__(parentDirInfoDict, 'directories').get(name, None) is None:\n raise Exception(\"'%s' is not a registered directory in repository relative path '%s'\"%(name, path))\n # remove from system\n if removeFromSystem:\n # remove files\n for rp in self.walk_files_relative_path(relativePath=relativePath):\n ap = os.path.join(self.__path, relativePath, rp)\n if not os.path.isfile(ap):\n continue\n if not os.path.exists(ap):\n continue\n if os.path.isfile(ap):\n os.remove( ap )\n # remove directories\n for rp in self.walk_directories_relative_path(relativePath=relativePath):\n ap = os.path.join(self.__path, relativePath, rp)\n if not os.path.isdir(ap):\n continue\n if not os.path.exists(ap):\n continue\n if not len(os.listdir(ap)):\n os.rmdir(ap)\n # pop directory from repo\n dict.__getitem__(parentDirInfoDict, 'directories').pop(name, None)\n ap = os.path.join(self.__path, relativePath)\n if not os.path.isdir(ap):\n if not len(os.listdir(ap)):\n os.rmdir(ap)\n # save repository\n self.save()"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef move_directory(self, relativePath, relativeDestination, replace=False, verbose=True):\n # normalize path\n relativePath = os.path.normpath(relativePath)\n relativeDestination = os.path.normpath(relativeDestination)\n # get files and directories\n filesInfo = list( self.walk_files_info(relativePath=relativePath) )\n dirsPath = list( self.walk_directories_relative_path(relativePath=relativePath) )\n dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n assert dirInfoDict is not None, errorMessage\n # remove directory info only\n self.remove_directory(relativePath=relativePath, removeFromSystem=False)\n # create new relative path\n self.add_directory(relativeDestination)\n # move files\n for RP, info in filesInfo:\n source = os.path.join(self.__path, relativePath, RP)\n destination = os.path.join(self.__path, relativeDestination, RP)\n # add directory\n newDirRP, fileName = os.path.split(os.path.join(relativeDestination, RP))\n dirInfoDict = self.add_directory( newDirRP )\n # move file\n if os.path.isfile(destination):\n if replace:\n os.remove(destination)\n if verbose:\n warnings.warn(\"file '%s' is copied replacing existing one in destination '%s'.\"%(fileName, newDirRP))\n else:\n if verbose:\n warnings.warn(\"file '%s' is not copied because the same file exists in destination '%s'.\"%(fileName,destination))\n continue\n os.rename(source, destination)\n # set file information\n dict.__getitem__(dirInfoDict, \"files\")[fileName] = info\n # save repository\n self.save()", "response": "Move a directory from one place to another."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef rename_file(self, relativePath, name, newName, replace=False, verbose=True):\n # normalize path\n relativePath = os.path.normpath(relativePath)\n if relativePath == '.':\n relativePath = ''\n dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n assert dirInfoDict is not None, errorMessage\n # check directory in repository\n assert name in dict.__getitem__(dirInfoDict, \"files\"), \"file '%s' is not found in repository relative path '%s'\"%(name, relativePath)\n # get real path\n realPath = os.path.join(self.__path, relativePath, name)\n assert os.path.isfile(realPath), \"file '%s' is not found in system\"%realPath\n # assert directory new name doesn't exist in repository\n assert newName not in dict.__getitem__(dirInfoDict, \"files\"), \"file '%s' already exists in repository relative path '%s'\"%(newName, relativePath)\n # check new directory in system\n newRealPath = os.path.join(self.__path, relativePath, newName)\n if os.path.isfile( newRealPath ):\n if replace:\n os.remove(newRealPath)\n if verbose:\n warnings.warn( \"file '%s' already exists found in system, it is now replaced by '%s' because 'replace' flag is True.\"%(newRealPath,realPath) )\n else:\n raise Exception( \"file '%s' already exists in system but not registered in repository.\"%newRealPath )\n # rename file\n os.rename(realPath, newRealPath)\n dict.__setitem__( dict.__getitem__(dirInfoDict, \"files\"),\n newName,\n dict.__getitem__(dirInfoDict, \"files\").pop(name) )\n # save repository\n self.save()", "response": "Rename a file in the repository. It insures renaming the file in the system."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef remove_file(self, relativePath, name=None, removeFromSystem=False):\n # get relative path normalized\n relativePath = os.path.normpath(relativePath)\n if relativePath == '.':\n relativePath = ''\n assert name != '.pyrepinfo', \"'.pyrepinfo' is not allowed as file name in main repository directory\"\n assert name != '.pyrepstate', \"'.pyrepstate' is not allowed as file name in main repository directory\"\n assert name != '.pyreplock', \"'.pyreplock' is not allowed as file name in main repository directory\"\n if name is None:\n assert len(relativePath), \"name must be given when relative path is given as empty string or as a simple dot '.'\"\n relativePath, name = os.path.split(relativePath)\n # get file info dict\n dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n assert dirInfoDict is not None, errorMessage\n # check directory in repository\n assert name in dict.__getitem__(dirInfoDict, \"files\"), \"file '%s' is not found in repository relative path '%s'\"%(name, relativePath)\n # remove file from repo\n dict.__getitem__(dirInfoDict, \"files\").pop(name)\n # remove file from system\n if removeFromSystem:\n ap = os.path.join(self.__path, relativePath, name )\n if os.path.isfile(ap):\n os.remove( ap )\n # save repository\n self.save()", "response": "Removes a file from the repository."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ndump an exisitng system file into the repository with utc timestamp.", "response": "def dump_copy(self, path, relativePath, name=None,\n description=None,\n replace=False, verbose=False):\n \"\"\"\n Copy an exisitng system file to the repository.\n attribute in the Repository with utc timestamp.\n\n :Parameters:\n #. path (str): The full path of the file to copy into the repository.\n #. relativePath (str): The relative to the repository path of the directory where the file should be dumped.\n If relativePath does not exist, it will be created automatically.\n #. name (string): The file name.\n If None is given, name will be split from path.\n #. description (None, string, pickable object): Any random description about the file.\n #. replace (boolean): Whether to replace any existing file with the same name if existing.\n #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n \"\"\"\n relativePath = os.path.normpath(relativePath)\n if relativePath == '.':\n relativePath = ''\n if name is None:\n _,name = os.path.split(path)\n # ensure directory added\n self.add_directory(relativePath)\n # ger real path\n realPath = os.path.join(self.__path, relativePath)\n # get directory info dict\n dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n assert dirInfoDict is not None, errorMessage\n if name in dict.__getitem__(dirInfoDict, \"files\"):\n if not replace:\n if verbose:\n warnings.warn(\"a file with the name '%s' is already defined in repository dictionary info. Set replace flag to True if you want to replace the existing file\"%(name))\n return\n # convert dump and pull methods to strings\n dump = \"raise Exception(\\\"dump is ambiguous for copied file '$FILE_PATH' \\\")\"\n pull = \"raise Exception(\\\"pull is ambiguous for copied file '$FILE_PATH' \\\")\"\n # dump file\n try:\n shutil.copyfile(path, os.path.join(realPath,name))\n except Exception as e:\n if verbose:\n warnings.warn(e)\n return\n # set info\n klass = None\n # save the new file to the repository\n dict.__getitem__(dirInfoDict, \"files\")[name] = {\"dump\":dump,\n \"pull\":pull,\n \"timestamp\":datetime.utcnow(),\n \"id\":str(uuid.uuid1()),\n \"class\": klass,\n \"description\":description}\n # save repository\n self.save()"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef dump_file(self, value, relativePath, name=None,\n description=None, klass=None,\n dump=None, pull=None,\n replace=False, ACID=None, verbose=False):\n \"\"\"\n Dump a file using its value to the system and creates its\n attribute in the Repository with utc timestamp.\n\n :Parameters:\n #. value (object): The value of a file to dump and add to the repository. It is any python object or file.\n #. relativePath (str): The relative to the repository path of the directory where the file should be dumped.\n If relativePath does not exist, it will be created automatically.\n #. name (string): The file name.\n If None is given, name will be split from relativePath.\n #. description (None, string, pickable object): Any random description about the file.\n #. klass (None, class): The dumped object class. If None is given\n klass will be automatically set to the following value.__class__\n #. dump (None, string): The dumping method.\n If None it will be set automatically to pickle and therefore the object must be pickleable.\n If a string is given, the string should include all the necessary imports\n and a '$FILE_PATH' that replaces the absolute file path when the dumping will be performed.\\n\n e.g. \"import numpy as np; np.savetxt(fname='$FILE_PATH', X=value, fmt='%.6e')\"\n #. pull (None, string): The pulling method.\n If None it will be set automatically to pickle and therefore the object must be pickleable.\n If a string is given, the string should include all the necessary imports,\n a '$FILE_PATH' that replaces the absolute file path when the dumping will be performed\n and finally a PULLED_DATA variable.\\n\n e.g \"import numpy as np; PULLED_DATA=np.loadtxt(fname='$FILE_PATH')\"\n #. replace (boolean): Whether to replace any existing file with the same name if existing.\n #. ACID (None, boolean): Whether to ensure the ACID (Atomicity, Consistency, Isolation, Durability)\n properties of the repository upon dumping a file. This is ensured by dumping the file in\n a temporary path first and then moving it to the desired path.\n If None is given, repository ACID property will be used.\n #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n \"\"\"\n # check ACID\n if ACID is None:\n ACID = self.__ACID\n assert isinstance(ACID, bool), \"ACID must be boolean\"\n # check name and path\n relativePath = os.path.normpath(relativePath)\n if relativePath == '.':\n relativePath = ''\n assert name != '.pyrepinfo', \"'.pyrepinfo' is not allowed as file name in main repository directory\"\n assert name != '.pyrepstate', \"'.pyrepstate' is not allowed as file name in main repository directory\"\n assert name != '.pyreplock', \"'.pyreplock' is not allowed as file name in main repository directory\"\n if name is None:\n assert len(relativePath), \"name must be given when relative path is given as empty string or as a simple dot '.'\"\n relativePath,name = os.path.split(relativePath)\n # ensure directory added\n self.add_directory(relativePath)\n # get real path\n realPath = os.path.join(self.__path, relativePath)\n # get directory info dict\n dirInfoDict, errorMessage = self.get_directory_info(relativePath)\n assert dirInfoDict is not None, errorMessage\n if name in dict.__getitem__(dirInfoDict, \"files\"):\n if not replace:\n if verbose:\n warnings.warn(\"a file with the name '%s' is already defined in repository dictionary info. Set replace flag to True if you want to replace the existing file\"%(name))\n return\n # convert dump and pull methods to strings\n if dump is None:\n dump=DEFAULT_DUMP\n if pull is None:\n pull=DEFAULT_PULL\n # get savePath\n if ACID:\n savePath = os.path.join(tempfile.gettempdir(), str(uuid.uuid1()))\n else:\n savePath = os.path.join(realPath,name)\n # dump file\n try:\n exec( dump.replace(\"$FILE_PATH\", str(savePath)) )\n except Exception as e:\n message = \"unable to dump the file (%s)\"%e\n if 'pickle.dump(' in dump:\n message += '\\nmore info: %s'%str(get_pickling_errors(value))\n raise Exception( message )\n # copy if ACID\n if ACID:\n try:\n shutil.copyfile(savePath, os.path.join(realPath,name))\n except Exception as e:\n os.remove(savePath)\n if verbose:\n warnings.warn(e)\n return\n os.remove(savePath)\n # set info\n if klass is None and value is not None:\n klass = value.__class__\n if klass is not None:\n assert inspect.isclass(klass), \"klass must be a class definition\"\n # MUST TRY PICLKING KLASS TEMPORARILY FIRST\n # save the new file to the repository\n dict.__getitem__(dirInfoDict, \"files\")[name] = {\"dump\":dump,\n \"pull\":pull,\n \"timestamp\":datetime.utcnow(),\n \"id\":str(uuid.uuid1()),\n \"class\": klass,\n \"description\":description}\n # save repository\n self.save()", "response": "Dump a file into the repository."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nupdates the value and the utc timestamp of a file in the repository.", "response": "def update_file(self, value, relativePath, name=None,\n description=False, klass=False,\n dump=False, pull=False,\n ACID=None, verbose=False):\n \"\"\"\n Update the value and the utc timestamp of a file that is already in the Repository.\\n\n If file is not registered in repository, and error will be thrown.\\n\n If file is missing in the system, it will be regenerated as dump method is called.\n\n :Parameters:\n #. value (object): The value of the file to update. It is any python object or a file.\n #. relativePath (str): The relative to the repository path of the directory where the file should be dumped.\n #. name (None, string): The file name.\n If None is given, name will be split from relativePath.\n #. description (False, string, pickable object): Any random description about the file.\n If False is given, the description info won't be updated,\n otherwise it will be update to what description argument value is.\n #. klass (False, class): The dumped object class. If False is given,\n the class info won't be updated, otherwise it will be update to what klass argument value is.\n #. dump (False, string): The new dump method. If False is given, the old one will be used.\n #. pull (False, string): The new pull method. If False is given, the old one will be used.\n #. ACID (boolean): Whether to ensure the ACID (Atomicity, Consistency, Isolation, Durability)\n properties of the repository upon dumping a file. This is ensured by dumping the file in\n a temporary path first and then moving it to the desired path.\n If None is given, repository ACID property will be used.\n #. verbose (boolean): Whether to be warn and informed about any abnormalities.\n \"\"\"\n # check ACID\n if ACID is None:\n ACID = self.__ACID\n assert isinstance(ACID, bool), \"ACID must be boolean\"\n # get relative path normalized\n relativePath = os.path.normpath(relativePath)\n if relativePath == '.':\n relativePath = ''\n assert name != '.pyrepinfo', \"'.pyrepinfo' is not allowed as file name in main repository directory\"\n assert name != '.pyrepstate', \"'.pyrepstate' is not allowed as file name in main repository directory\"\n assert name != '.pyreplock', \"'.pyreplock' is not allowed as file name in main repository directory\"\n if name is None:\n assert len(relativePath), \"name must be given when relative path is given as empty string or as a simple dot '.'\"\n relativePath,name = os.path.split(relativePath)\n # get file info dict\n fileInfoDict, errorMessage = self.get_file_info(relativePath, name)\n assert fileInfoDict is not None, errorMessage\n # get real path\n realPath = os.path.join(self.__path, relativePath)\n # check if file exists\n if verbose:\n if not os.path.isfile( os.path.join(realPath, name) ):\n warnings.warn(\"file '%s' is in repository but does not exist in the system. It is therefore being recreated.\"%os.path.join(realPath, name))\n # convert dump and pull methods to strings\n if not dump:\n dump = fileInfoDict[\"dump\"]\n if not pull:\n pull = fileInfoDict[\"pull\"]\n # get savePath\n if ACID:\n savePath = os.path.join(tempfile.gettempdir(), name)\n else:\n savePath = os.path.join(realPath,name)\n # dump file\n try:\n exec( dump.replace(\"$FILE_PATH\", str(savePath)) )\n except Exception as e:\n message = \"unable to dump the file (%s)\"%e\n if 'pickle.dump(' in dump:\n message += '\\nmore info: %s'%str(get_pickling_errors(value))\n raise Exception( message )\n # copy if ACID\n if ACID:\n try:\n shutil.copyfile(savePath, os.path.join(realPath,name))\n except Exception as e:\n os.remove(savePath)\n if verbose:\n warnings.warn(e)\n return\n os.remove(savePath)\n # update timestamp\n fileInfoDict[\"timestamp\"] = datetime.utcnow()\n if description is not False:\n fileInfoDict[\"description\"] = description\n if klass is not False:\n assert inspect.isclass(klass), \"klass must be a class definition\"\n fileInfoDict[\"class\"] = klass\n # save repository\n self.save()"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef pull_file(self, relativePath, name=None, pull=None, update=True):\n # get relative path normalized\n relativePath = os.path.normpath(relativePath)\n if relativePath == '.':\n relativePath = ''\n assert name != '.pyrepinfo', \"pulling '.pyrepinfo' from main repository directory is not allowed.\"\n assert name != '.pyrepstate', \"pulling '.pyrepstate' from main repository directory is not allowed.\"\n assert name != '.pyreplock', \"pulling '.pyreplock' from main repository directory is not allowed.\"\n if name is None:\n assert len(relativePath), \"name must be given when relative path is given as empty string or as a simple dot '.'\"\n relativePath,name = os.path.split(relativePath)\n # get file info\n fileInfo, errorMessage = self.get_file_info(relativePath, name)\n assert fileInfo is not None, errorMessage\n # get absolute path\n realPath = os.path.join(self.__path, relativePath)\n assert os.path.exists(realPath), \"relative path '%s'within repository '%s' does not exist\"%(relativePath, self.__path)\n # file path\n fileAbsPath = os.path.join(realPath, name)\n assert os.path.isfile(fileAbsPath), \"file '%s' does not exist in absolute path '%s'\"%(name,realPath)\n if pull is None:\n pull = fileInfo[\"pull\"]\n # try to pull file\n try:\n namespace = {}\n namespace.update( globals() )\n exec( pull.replace(\"$FILE_PATH\", str(os.path.join(realPath,name)) ), namespace )\n except Exception as e:\n m = pull.replace(\"$FILE_PATH\", str(os.path.join(realPath,name)) )\n raise Exception( \"unable to pull data using '%s' from file (%s)\"%(m,e) )\n # update\n if update:\n fileInfo[\"pull\"] = pull\n # return data\n return namespace['PULLED_DATA']", "response": "Pulls a file from the repository."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef ensure_str(value):\n if isinstance(value, six.string_types):\n return value\n else:\n return six.text_type(value)", "response": "Ensure value is string."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef ensure_list(path_or_path_list):\n if isinstance(path_or_path_list, (tuple, list, set)):\n return [ensure_str(path) for path in path_or_path_list]\n else:\n return [ensure_str(path_or_path_list), ]", "response": "Ensures that the input argument is a list of paths."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef stream(self, report):\n with self.ClientSession() as session:\n lines = []\n for job in report['traces']:\n key = '%s:%s' % (self.name, job)\n for minute in report['traces'][job]:\n for k, v in report['traces'][job][minute].items():\n lines.append('# TYPE %s_%s gauge' % (key, k))\n lines.append('%s_%s %0.2f' % (key, k, v))\n\n # Empty is required at the end of the payload\n lines.append(\"\")\n data = \"\\n\".join(lines)\n logger.info(data)\n yield from session.post(self.url, data=bytes(data.encode('utf-8')))", "response": "Stream reports to application logs"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef stream(self, report):\n\n payload = {\n \"agent\": {\n \"host\": report['instance']['hostname'],\n \"version\": \"1.0.0\"\n },\n \"components\": [\n {\n \"name\": self.name,\n \"guid\": \"com.darwinmonroy.aiometrics\",\n \"duration\": 60,\n \"metrics\": {\n 'Component/{}'.format(key): {\n \"total\": metric['count'] * metric['avg'],\n \"count\": metric['count'],\n \"min\": metric['min'],\n \"max\": metric['max'],\n \"sum_of_squares\": metric['min']**2 + metric['max']**2,\n } for key, metric in report['traces'].items()\n }\n }\n ]\n }\n\n with self.ClientSession() as session:\n\n try:\n r = yield from session.post(\n 'https://platform-api.newrelic.com/platform/v1/metrics',\n data=json.dumps(payload),\n headers=(\n ('X-License-Key', self.license_key),\n ('Content-Type', 'application/json'),\n ('Accept', 'application/json'),\n )\n )\n r.close()\n except Exception as e:\n # Any exception should affect the execution of the main\n # program, so we must explicitly silence any error caused by\n # by the streaming of metrics\n # TODO: consider the implementation of a retry logic\n logger.exception(e)", "response": "Stream reports to application logs"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nbuilds per minute stats for each key", "response": "def stats(cls, traces):\n \"\"\"Build per minute stats for each key\"\"\"\n\n data = {}\n stats = {}\n # Group traces by key and minute\n for trace in traces:\n key = trace['key']\n if key not in data:\n data[key] = []\n stats[key] = {}\n\n data[key].append(trace['total_time'])\n cls._traces.pop(trace['id'])\n\n for key in data:\n times = data[key]\n stats[key] = dict(\n count=len(times),\n max=max(times),\n min=min(times),\n avg=sum(times)/len(times)\n )\n\n return stats"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef no_error_extract_data_from_file(self, file_path: str) -> Iterable[DataSourceType]:\n try:\n return self.extract_data_from_file(file_path)\n except Exception as e:\n logging.warning(e)\n return []", "response": "Proxy for extract_data_from_file that suppresses any errors and instead just returning an empty list."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nloading all of the data from the files in directory location.", "response": "def _load_all_in_directory(self) -> Dict[str, Iterable[DataSourceType]]:\n \"\"\"\n Loads all of the data from the files in directory location.\n :return: a origin map of all the loaded data\n \"\"\"\n origin_mapped_data = dict() # type: Dict[str, Iterable[DataSourceType]]\n for file_path in glob.iglob(\"%s/**/*\" % self._directory_location, recursive=True):\n if self.is_data_file(file_path):\n origin_mapped_data[file_path] = self.no_error_extract_data_from_file(file_path)\n return origin_mapped_data"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _extract_data_from_origin_map(origin_mapped_data: Dict[str, Iterable[DataSourceType]]) \\\n -> Iterable[DataSourceType]:\n \"\"\"\n Extracts the data from a data origin map.\n :param origin_mapped_data: a map containing the origin of the data as the key string and the data as the value\n :return: the data contained within the map\n \"\"\"\n data = []\n for _, data_item in origin_mapped_data.items():\n data.extend(data_item)\n return data", "response": "Extracts the data from an origin map."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nstarts monitoring data kept in files in the predefined directory.", "response": "def start(self):\n \"\"\"\n Monitors data kept in files in the predefined directory in a new thread.\n\n Note: Due to the underlying library, it may take a few milliseconds after this method is started for changes to\n start to being noticed.\n \"\"\"\n with self._status_lock:\n if self._running:\n raise RuntimeError(\"Already running\")\n self._running = True\n\n # Cannot re-use Observer after stopped\n self._observer = Observer()\n self._observer.schedule(self._event_handler, self._directory_location, recursive=True)\n self._observer.start()\n\n # Load all in directory afterwards to ensure no undetected changes between loading all and observing\n self._origin_mapped_data = self._load_all_in_directory()"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nstops monitoring the predefined directory.", "response": "def stop(self):\n \"\"\"\n Stops monitoring the predefined directory.\n \"\"\"\n with self._status_lock:\n if self._running:\n assert self._observer is not None\n self._observer.stop()\n self._running = False\n self._origin_mapped_data = dict()"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ncall when a file in the monitored directory has been created.", "response": "def _on_file_created(self, event: FileSystemEvent):\n \"\"\"\n Called when a file in the monitored directory has been created.\n :param event: the file system event\n \"\"\"\n if not event.is_directory and self.is_data_file(event.src_path):\n assert event.src_path not in self._origin_mapped_data\n self._origin_mapped_data[event.src_path] = self.no_error_extract_data_from_file(event.src_path)\n self.notify_listeners(FileSystemChange.CREATE)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncall when a file in the monitored directory has been modified.", "response": "def _on_file_modified(self, event: FileSystemEvent):\n \"\"\"\n Called when a file in the monitored directory has been modified.\n :param event: the file system event\n \"\"\"\n if not event.is_directory and self.is_data_file(event.src_path):\n assert event.src_path in self._origin_mapped_data\n self._origin_mapped_data[event.src_path] = self.no_error_extract_data_from_file(event.src_path)\n self.notify_listeners(FileSystemChange.MODIFY)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _on_file_deleted(self, event: FileSystemEvent):\n if not event.is_directory and self.is_data_file(event.src_path):\n assert event.src_path in self._origin_mapped_data\n del(self._origin_mapped_data[event.src_path])\n self.notify_listeners(FileSystemChange.DELETE)", "response": "Called when a file in the monitored directory has been deleted."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _on_file_moved(self, event: FileSystemMovedEvent):\n if not event.is_directory and self.is_data_file(event.src_path):\n delete_event = FileSystemEvent(event.src_path)\n delete_event.event_type = EVENT_TYPE_DELETED\n self._on_file_deleted(delete_event)\n\n create_event = FileSystemEvent(event.dest_path)\n create_event.event_type = EVENT_TYPE_CREATED\n self._on_file_created(create_event)", "response": "Called when a file in the monitored directory has been moved."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef tear_down(self):\n while len(self._temp_directories) > 0:\n directory = self._temp_directories.pop()\n shutil.rmtree(directory, ignore_errors=True)\n while len(self._temp_files) > 0:\n file = self._temp_files.pop()\n try:\n os.remove(file)\n except OSError:\n pass", "response": "Tear down all temp files and directories."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef create_temp_directory(self, **mkdtemp_kwargs) -> str:\n kwargs = {**self.default_mkdtemp_kwargs, **mkdtemp_kwargs}\n location = tempfile.mkdtemp(**kwargs)\n self._temp_directories.add(location)\n return location", "response": "Creates a temp directory."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef create_temp_file(self, **mkstemp_kwargs) -> Tuple[int, str]:\n kwargs = {**self.default_mkstemp_kwargs, **mkstemp_kwargs}\n handle, location = tempfile.mkstemp(**kwargs)\n self._temp_files.add(location)\n return handle, location", "response": "Creates a temp file."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef change(self,\n new_abspath=None,\n new_dirpath=None,\n new_dirname=None,\n new_basename=None,\n new_fname=None,\n new_ext=None):\n \"\"\"\n Return a new :class:`pathlib_mate.pathlib2.Path` object with updated information.\n \"\"\"\n if new_abspath is not None:\n p = self.__class__(new_abspath)\n return p\n\n if (new_dirpath is None) and (new_dirname is not None):\n new_dirpath = os.path.join(self.parent.dirpath, new_dirname)\n\n elif (new_dirpath is not None) and (new_dirname is None):\n new_dirpath = new_dirpath\n\n elif (new_dirpath is None) and (new_dirname is None):\n new_dirpath = self.dirpath\n\n elif (new_dirpath is not None) and (new_dirname is not None):\n raise ValueError(\"Cannot having both new_dirpath and new_dirname!\")\n\n if new_basename is None:\n if new_fname is None:\n new_fname = self.fname\n if new_ext is None:\n new_ext = self.ext\n new_basename = new_fname + new_ext\n else:\n if new_fname is not None or new_ext is not None:\n raise ValueError(\"Cannot having both new_basename, \"\n \"new_fname, new_ext!\")\n\n return self.__class__(new_dirpath, new_basename)", "response": "Change the contents of the current pathlib_mate. pathlib2. Path object."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ntesting whether a file target is not exists or allow overwrite.", "response": "def is_not_exist_or_allow_overwrite(self, overwrite=False):\n \"\"\"\n Test whether a file target is not exists or it exists but allow\n overwrite.\n \"\"\"\n if self.exists() and overwrite is False:\n return False\n else: # pragma: no cover\n return True"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nmove the path to another location.", "response": "def moveto(self,\n new_abspath=None,\n new_dirpath=None,\n new_dirname=None,\n new_basename=None,\n new_fname=None,\n new_ext=None,\n overwrite=False,\n makedirs=False):\n \"\"\"\n An advanced :meth:`pathlib_mate.pathlib2.Path.rename` method provide ability to rename by\n each components of a path. A new ``Path`` instance will returns.\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u9ad8\u7ea7\u91cd\u547d\u540d\u51fd\u6570, \u5141\u8bb8\u7528\u4e8e\u6839\u636e\u8def\u5f84\u7684\u5404\u4e2a\u7ec4\u6210\u90e8\u5206\u8fdb\u884c\u91cd\u547d\u540d\u3002\u4f46\u548cos.rename\n \u65b9\u6cd5\u4e00\u6837, \u9700\u8981\u4fdd\u8bc1\u6bcd\u6587\u4ef6\u5939\u5b58\u5728\u3002\n \"\"\"\n self.assert_exists()\n\n p = self.change(\n new_abspath=new_abspath,\n new_dirpath=new_dirpath,\n new_dirname=new_dirname,\n new_basename=new_basename,\n new_fname=new_fname,\n new_ext=new_ext,\n )\n\n if p.is_not_exist_or_allow_overwrite(overwrite=overwrite):\n # \u5982\u679c\u4e24\u4e2a\u8def\u5f84\u4e0d\u540c, \u624d\u8fdb\u884cmove\n if self.abspath != p.abspath:\n if makedirs:\n parent = p.parent\n if not parent.exists():\n os.makedirs(parent.abspath)\n self.rename(p)\n return p"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ncopies this file to another place.", "response": "def copyto(self,\n new_abspath=None,\n new_dirpath=None,\n new_dirname=None,\n new_basename=None,\n new_fname=None,\n new_ext=None,\n overwrite=False,\n makedirs=False):\n \"\"\"\n Copy this file to other place.\n \"\"\"\n self.assert_exists()\n\n p = self.change(\n new_abspath=new_abspath,\n new_dirpath=new_dirpath,\n new_dirname=new_dirname,\n new_basename=new_basename,\n new_fname=new_fname,\n new_ext=new_ext,\n )\n\n if p.is_not_exist_or_allow_overwrite(overwrite=overwrite):\n # \u5982\u679c\u4e24\u4e2a\u8def\u5f84\u4e0d\u540c, \u624d\u8fdb\u884ccopy\n if self.abspath != p.abspath:\n try:\n shutil.copy(self.abspath, p.abspath)\n except IOError as e:\n if makedirs:\n os.makedirs(p.parent.abspath)\n shutil.copy(self.abspath, p.abspath)\n else:\n raise e\n return p"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _create_client(base_url: str, tls: TLSConfig=False) -> Optional[APIClient]:\n try:\n client = APIClient(base_url=base_url, tls=tls, version=\"auto\")\n return client if client.ping() else None\n except:\n return None", "response": "Creates a Docker client with the given details."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncreate a Docker client.", "response": "def create_client() -> APIClient:\n \"\"\"\n Clients a Docker client.\n\n Will raise a `ConnectionError` if the Docker daemon is not accessible.\n :return: the Docker client\n \"\"\"\n global _client\n client = _client()\n if client is None:\n # First try looking at the environment variables for specification of the daemon's location\n docker_environment = kwargs_from_env(assert_hostname=False)\n if \"base_url\" in docker_environment:\n client = _create_client(docker_environment.get(\"base_url\"), docker_environment.get(\"tls\"))\n if client is None:\n raise ConnectionError(\n \"Could not connect to the Docker daemon specified by the `DOCKER_X` environment variables: %s\"\n % docker_environment)\n else:\n logging.info(\"Connected to Docker daemon specified by the environment variables\")\n else:\n # Let's see if the Docker daemon is accessible via the UNIX socket\n client = _create_client(\"unix://var/run/docker.sock\")\n if client is not None:\n logging.info(\"Connected to Docker daemon running on UNIX socket\")\n else:\n raise ConnectionError(\n \"Cannot connect to Docker - is the Docker daemon running? `$DOCKER_HOST` should be set or the \"\n \"daemon should be accessible via the standard UNIX socket.\")\n _client = weakref.ref(client)\n assert isinstance(client, APIClient)\n return client"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef get_dump_method(dump, protocol=-1):\n if dump is None:\n dump = 'pickle'\n if dump.startswith('pickle'):\n if dump == 'pickle':\n proto = protocol\n else:\n proto = dump.strip('pickle')\n try:\n proto = int(proto)\n assert proto>=-1\n except:\n raise Exception(\"protocol must be an integer >=-1\")\n code = \"\"\"\ntry:\n import cPickle as pickle\nexcept:\n import pickle\nwith open('$FILE_PATH', 'wb') as fd:\n pickle.dump( value, fd, protocol=%i )\n fd.flush()\n os.fsync(fd.fileno())\n\"\"\"%proto\n elif dump.startswith('dill'):\n if dump == 'dill':\n proto = 2\n else:\n proto = dump.strip('dill')\n try:\n proto = int(proto)\n assert proto>=-1\n except:\n raise Exception(\"protocol must be an integer >=-1\")\n code = \"\"\"\nimport dill\nwith open('$FILE_PATH', 'wb') as fd:\n dill.dump( value, fd, protocol=%i )\n fd.flush()\n os.fsync(fd.fileno())\n\"\"\"%proto\n elif dump == 'json':\n code = \"\"\"\nimport json\nwith open('$FILE_PATH', 'wb') as fd:\n json.dump( value,fd, ensure_ascii=True, indent=4 )\n fd.flush()\n os.fsync(fd.fileno())\n\"\"\"\n elif dump == 'numpy':\n code = \"\"\"\nimport numpy\nwith open('$FILE_PATH', 'wb') as fd:\n numpy.save(file=fd, arr=value)\n fd.flush()\n os.fsync(fd.fileno())\n\"\"\"\n elif dump == 'numpy_text':\n code = \"\"\"\nimport numpy\nnumpy.savetxt(fname='$FILE_PATH', X=value, fmt='%.6e')\n\"\"\"\n else:\n assert isinstance(dump, basestring), \"dump must be None or a string\"\n assert '$FILE_PATH' in dump, \"string dump code must inlcude '$FILE_PATH'\"\n code = dump\n # return\n return code", "response": "Get dump function code string"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nget pull function code string", "response": "def get_pull_method(pull):\n \"\"\"Get pull function code string\"\"\"\n if pull is None or pull.startswith('pickle'):\n code = \"\"\"\nimport os\ntry:\n import cPickle as pickle\nexcept:\n import pickle\nwith open('$FILE_PATH', 'rb') as fd:\n PULLED_DATA = pickle.load( fd )\n\"\"\"\n elif pull.startswith('dill'):\n code = \"\"\"\nimport dill\nwith open('$FILE_PATH', 'rb') as fd:\n PULLED_DATA = dill.load( fd )\n\"\"\"\n elif pull == 'json':\n code = \"\"\"\nimport json\nwith open('$FILE_PATH', 'rb') as fd:\n PULLED_DATA = json.load(fd)\n\"\"\"\n elif pull == 'numpy':\n code = \"\"\"\nimport numpy\nwith open('$FILE_PATH', 'rb') as fd:\n PULLED_DATA=numpy.load(file=fd)\n\n\"\"\"\n elif pull == 'numpy_text':\n code = \"\"\"\nimport numpy\nwith open('$FILE_PATH', 'rb') as fd:\n PULLED_DATA=numpy.loadtxt(fname=fd)\n\"\"\"\n else:\n assert isinstance(pull, basestring), \"pull must be None or a string\"\n assert 'PULLED_DATA' in pull, \"string pull code must inlcude 'PULLED_DATA'\"\n assert '$FILE_PATH' in pull, \"string pull code must inlcude '$FILE_PATH'\"\n code = pull\n # return\n return code"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef path_required(func):\n @wraps(func)\n def wrapper(self, *args, **kwargs):\n if self.path is None:\n warnings.warn('Must load (Repository.load_repository) or initialize (Repository.create_repository) the repository first !')\n return\n return func(self, *args, **kwargs)\n return wrapper", "response": "Decorate methods when repository path is required."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ncleaning repository given before and after states", "response": "def __clean_before_after(self, stateBefore, stateAfter, keepNoneEmptyDirectory=True):\n \"\"\"clean repository given before and after states\"\"\"\n # prepare after for faster search\n errors = []\n afterDict = {}\n [afterDict.setdefault(list(aitem)[0],[]).append(aitem) for aitem in stateAfter]\n # loop before\n for bitem in reversed(stateBefore):\n relaPath = list(bitem)[0]\n basename = os.path.basename(relaPath)\n btype = bitem[relaPath]['type']\n alist = afterDict.get(relaPath, [])\n aitem = [a for a in alist if a[relaPath]['type']==btype]\n if len(aitem)>1:\n errors.append(\"Multiple '%s' of type '%s' where found in '%s', this should never had happened. Please report issue\"%(basename,btype,relaPath))\n continue\n if not len(aitem):\n removeDirs = []\n removeFiles = []\n if btype == 'dir':\n if not len(relaPath):\n errors.append(\"Removing main repository directory is not allowed\")\n continue\n removeDirs.append(os.path.join(self.__path,relaPath))\n removeFiles.append(os.path.join(self.__path,relaPath,self.__dirInfo))\n removeFiles.append(os.path.join(self.__path,relaPath,self.__dirLock))\n elif btype == 'file':\n removeFiles.append(os.path.join(self.__path,relaPath))\n removeFiles.append(os.path.join(self.__path,relaPath,self.__fileInfo%basename))\n removeFiles.append(os.path.join(self.__path,relaPath,self.__fileLock%basename))\n else:\n ### MUST VERIFY THAT ONCE pyrepobjectdir IS IMPLEMENTED\n removeDirs.append(os.path.join(self.__path,relaPath))\n removeFiles.append(os.path.join(self.__path,relaPath,self.__fileInfo%basename))\n # remove files\n for fpath in removeFiles:\n if os.path.isfile(fpath):\n try:\n os.remove(fpath)\n except Exception as err:\n errors.append(\"Unable to clean file '%s' (%s)\"%(fpath, str(err)))\n # remove directories\n for dpath in removeDirs:\n if os.path.isdir(dpath):\n if keepNoneEmptyDirectory or not len(os.listdir(dpath)):\n try:\n shutil.rmtree(dpath)\n except Exception as err:\n errors.append(\"Unable to clean directory '%s' (%s)\"%(fpath, str(err)))\n # return result and errors list\n return len(errors)==0, errors"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngetting repository descriptive stats", "response": "def get_stats(self):\n \"\"\"\n Get repository descriptive stats\n\n :Returns:\n #. numberOfDirectories (integer): Number of diretories in repository\n #. numberOfFiles (integer): Number of files in repository\n \"\"\"\n if self.__path is None:\n return 0,0\n nfiles = 0\n ndirs = 0\n for fdict in self.get_repository_state():\n fdname = list(fdict)[0]\n if fdname == '':\n continue\n if fdict[fdname].get('pyrepfileinfo', False):\n nfiles += 1\n elif fdict[fdname].get('pyrepdirinfo', False):\n ndirs += 1\n else:\n raise Exception('Not sure what to do next. Please report issue')\n return ndirs,nfiles"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreset the internal state of the object.", "response": "def reset(self):\n \"\"\"Reset repository instance.\n \"\"\"\n self.__path = None\n self.__repo = {'repository_unique_name': str(uuid.uuid1()),\n 'create_utctime': time.time(),\n 'last_update_utctime': None,\n 'pyrep_version': str(__version__),\n 'repository_information': '',\n 'walk_repo': []}"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef is_repository(self, path):\n if path.strip() in ('','.'):\n path = os.getcwd()\n repoPath = os.path.realpath( os.path.expanduser(path) )\n if os.path.isfile( os.path.join(repoPath,self.__repoFile) ):\n return True\n else:\n try:\n from .OldRepository import Repository\n REP = Repository()\n result = REP.is_repository(repoPath)\n except:\n return False\n else:\n if result:\n warnings.warn(\"This is an old repository version 2.x.y! Make sure to start using repositories 3.x.y \")\n return result", "response": "Check if there is a repository in path."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef load_repository(self, path, verbose=True, ntrials=3):\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n repo = None\n for _trial in range(ntrials):\n try:\n self.__load_repository(path=path, verbose=True)\n except Exception as err1:\n try:\n from .OldRepository import Repository\n REP = Repository(path)\n except Exception as err2:\n #traceback.print_exc()\n error = \"Unable to load repository using neiher new style (%s) nor old style (%s)\"%(err1, err2)\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n error = None\n repo = REP\n break\n else:\n error = None\n repo = self\n break\n # check and return\n assert error is None, error\n return repo", "response": "Load a repository from a directory path and update the current instance with the loaded data."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncreating a new repository in a directory.", "response": "def create_repository(self, path, info=None, description=None, replace=True, allowNoneEmpty=True, raiseError=True):\n \"\"\"\n create a repository in a directory. This method insures the creation of\n the directory in the system if it is missing.\\n\n\n **N.B. If replace is True and existing repository is found in path, create_repository erases all existing files and directories in path.**\n\n :Parameters:\n #. path (string): The real absolute path where to create the Repository.\n If '.' or an empty string is passed, the current working directory will be used.\n #. description (None, str): Repository main directory information.\n #. info (None, object): Repository information. It can\n be None or any pickle writable type of data.\n #. replace (boolean): Whether to replace existing repository.\n #. allowNoneEmpty (boolean): Allow creating repository in none-empty\n directory.\n #. raiseError (boolean): Whether to raise encountered error instead\n of returning failure.\n\n :Returns:\n #. success (boolean): Whether creating repository was successful\n #. message (None, str): Any returned message.\n \"\"\"\n assert isinstance(raiseError, bool), \"raiseError must be boolean\"\n assert isinstance(allowNoneEmpty, bool), \"allowNoneEmpty must be boolean\"\n assert isinstance(replace, bool), \"replace must be boolean\"\n assert isinstance(path, basestring), \"path must be string\"\n if info is None:\n info = ''\n try:\n pickle.dumps(info)\n except Exception as err:\n raise Exception(\"info must be None or any pickle writable type of data (%s)\"%str(err))\n #assert isinstance(info, basestring), \"info must be None or a string\"\n if description is None:\n description = ''\n assert isinstance(description, basestring), \"description must be None or a string\"\n # get real path\n if path.strip() in ('','.'):\n path = os.getcwd()\n realPath = os.path.realpath( os.path.expanduser(path) )\n # reset if replace is set to True\n message = []\n if self.is_repository(realPath):\n if not replace:\n message.append(\"A pyrep Repository already exists in the given path '%s' set replace to True if you need to proceed.\"%path)\n return False, message\n else:\n message.append(\"Old existing pyrep repository existing in the given path '%s' has been replaced.\"%path)\n try:\n for _df in os.listdir(realPath):\n _p = os.path.join(realPath, _df)\n if os.path.isdir(_p):\n shutil.rmtree( _p )\n else:\n os.remove(_p)\n except Exception as err:\n message.append(\"Unable to clean remove repository before create (%s)\"%(str(err)))\n return False, '\\n'.join(message)\n if not os.path.isdir(realPath):\n os.makedirs(realPath)\n elif len(os.listdir(realPath)) and not allowNoneEmpty:\n return False, \"Not allowed to create repository in a non empty directory\"\n # reset repository\n oldRepo = self.__repo\n self.reset()\n self.__path = realPath.rstrip(os.sep)\n self.__repo['repository_information'] = info\n # save repository\n saved = self.save(description=description)\n if not saved:\n self.__repo = oldRepo\n message.append(\"Absolute path and directories might be created but no pyrep Repository is created.\")\n return False, '\\n'.join(message)\n # return\n return True, '\\n'.join(message)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef remove_repository(self, path=None, removeEmptyDirs=True):\n assert isinstance(removeEmptyDirs, bool), \"removeEmptyDirs must be boolean\"\n if path is not None:\n if path != self.__path:\n repo = Repository()\n repo.load_repository(path)\n else:\n repo = self\n else:\n repo = self\n assert repo.path is not None, \"path is not given and repository is not initialized\"\n # remove repo files and directories\n for fdict in reversed(repo.get_repository_state()):\n relaPath = list(fdict)[0]\n realPath = os.path.join(repo.path, relaPath)\n path, name = os.path.split(realPath)\n if fdict[relaPath]['type'] == 'file':\n if os.path.isfile(realPath):\n os.remove(realPath)\n if os.path.isfile(os.path.join(repo.path,path,self.__fileInfo%name)):\n os.remove(os.path.join(repo.path,path,self.__fileInfo%name))\n if os.path.isfile(os.path.join(repo.path,path,self.__fileLock%name)):\n os.remove(os.path.join(repo.path,path,self.__fileLock%name))\n if os.path.isfile(os.path.join(repo.path,path,self.__fileClass%name)):\n os.remove(os.path.join(repo.path,path,self.__fileClass%name))\n elif fdict[relaPath]['type'] == 'dir':\n if os.path.isfile(os.path.join(realPath,self.__dirInfo)):\n os.remove(os.path.join(realPath,self.__dirInfo))\n if os.path.isfile(os.path.join(realPath,self.__dirLock)):\n os.remove(os.path.join(realPath,self.__dirLock))\n if not len(os.listdir(realPath)) and removeEmptyDirs:\n shutil.rmtree( realPath )\n # remove repo information file\n if os.path.isfile(os.path.join(repo.path,self.__repoFile)):\n os.remove(os.path.join(repo.path,self.__repoFile))\n if os.path.isfile(os.path.join(repo.path,self.__repoLock)):\n os.remove(os.path.join(repo.path,self.__repoLock))", "response": "Removes all files and directories in the repository at the given path along with all repository tracked files and directories."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nsave the current repository. pyreprepo file to disk and create a new lock.", "response": "def save(self, description=None, raiseError=True, ntrials=3):\n \"\"\"\n Save repository '.pyreprepo' to disk and create (if missing) or\n update (if description is not None) '.pyrepdirinfo'.\n\n :Parameters:\n #. description (None, str): Repository main directory information.\n If given will be replaced.\n #. raiseError (boolean): Whether to raise encountered error instead\n of returning failure.\n #. ntrials (int): After aquiring all locks, ntrials is the maximum\n number of trials allowed before failing.\n In rare cases, when multiple processes\n are accessing the same repository components, different processes\n can alter repository components between successive lock releases\n of some other process. Bigger number of trials lowers the\n likelyhood of failure due to multiple processes same time\n alteration.\n\n :Returns:\n #. success (bool): Whether saving was successful.\n #. error (None, string): Fail to save repository message in case\n saving is not successful. If success is True, error will be None.\n \"\"\"\n assert isinstance(raiseError, bool), \"raiseError must be boolean\"\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n # get description\n if description is not None:\n assert isinstance(description, basestring), \"description must be None or a string\"\n dirInfoPath = os.path.join(self.__path, self.__dirInfo)\n if description is None and not os.path.isfile(dirInfoPath):\n description = ''\n # create and acquire lock\n LR = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(self.__path, self.__repoLock))\n acquired, code = LR.acquire_lock()\n # check if acquired.\n m = \"code %s. Unable to aquire the lock when calling 'save'. You may try again!\"%(code,)\n if not acquired:\n assert not raiseError, Exception(m)\n return False, m\n # save repository\n for _trial in range(ntrials):\n try:\n # open file\n repoInfoPath = os.path.join(self.__path, self.__repoFile)\n error = None\n self.__save_dirinfo(description=description, dirInfoPath=dirInfoPath)\n # load and update repository info if existing\n if os.path.isfile(repoInfoPath):\n with open(repoInfoPath, 'rb') as fd:\n repo = self.__load_repository_pickle_file(os.path.join(self.__path, self.__repoFile))\n self.__repo['walk_repo'] = repo['walk_repo']\n # create repository\n with open(repoInfoPath, 'wb') as fd:\n self.__repo[\"last_update_utctime\"] = time.time()\n pickle.dump( self.__repo,fd, protocol=self._DEFAULT_PICKLE_PROTOCOL )\n fd.flush()\n os.fsync(fd.fileno())\n except Exception as err:\n error = \"Unable to save repository (%s)\"%err\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n break\n # release lock\n LR.release_lock()\n # return\n assert error is None or not raiseError, error\n return error is None, error"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef is_name_allowed(self, path):\n assert isinstance(path, basestring), \"given path must be a string\"\n name = os.path.basename(path)\n if not len(name):\n return False, \"empty name is not allowed\"\n # exact match\n for em in [self.__repoLock,self.__repoFile,self.__dirInfo,self.__dirLock]:\n if name == em:\n return False, \"name '%s' is reserved for pyrep internal usage\"%em\n # pattern match\n for pm in [self.__fileInfo,self.__fileLock]:#,self.__objectDir]:\n if name == pm or (name.endswith(pm[3:]) and name.startswith('.')):\n return False, \"name pattern '%s' is not allowed as result may be reserved for pyrep internal usage\"%pm\n # name is ok\n return True, None", "response": "Checks whether the given path is allowed for the given file or a directory."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef to_repo_relative_path(self, path, split=False):\n path = os.path.normpath(path)\n if path == '.':\n path = ''\n path = path.split(self.__path)[-1].strip(os.sep)\n if split:\n return path.split(os.sep)\n else:\n return path", "response": "Given a path return relative path to diretory"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning a list representation of the repository state along with useful AttributeNames information.", "response": "def get_repository_state(self, relaPath=None):\n \"\"\"\n Get a list representation of repository state along with useful\n information. List state is ordered relativeley to directories level\n\n :Parameters:\n #. relaPath (None, str): relative directory path from where to\n start. If None all repository representation is returned.\n\n :Returns:\n #. state (list): List representation of the repository.\n List items are all dictionaries. Every dictionary has a single\n key which is the file or the directory name and the value is a\n dictionary of information including:\n\n * 'type': the type of the tracked whether it's file, dir, or objectdir\n * 'exists': whether file or directory actually exists on disk\n * 'pyrepfileinfo': In case of a file or an objectdir whether .%s_pyrepfileinfo exists\n * 'pyrepdirinfo': In case of a directory whether .pyrepdirinfo exists\n \"\"\"\n state = []\n def _walk_dir(relaPath, dirList):\n dirDict = {'type':'dir',\n 'exists':os.path.isdir(os.path.join(self.__path,relaPath)),\n 'pyrepdirinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__dirInfo)),\n }\n state.append({relaPath:dirDict})\n # loop files and dirobjects\n for fname in sorted([f for f in dirList if isinstance(f, basestring)]):\n relaFilePath = os.path.join(relaPath,fname)\n realFilePath = os.path.join(self.__path,relaFilePath)\n #if os.path.isdir(realFilePath) and df.startswith('.') and df.endswith(self.__objectDir[3:]):\n # fileDict = {'type':'objectdir',\n # 'exists':True,\n # 'pyrepfileinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__fileInfo%fname)),\n # }\n #else:\n # fileDict = {'type':'file',\n # 'exists':os.path.isfile(realFilePath),\n # 'pyrepfileinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__fileInfo%fname)),\n # }\n fileDict = {'type':'file',\n 'exists':os.path.isfile(realFilePath),\n 'pyrepfileinfo':os.path.isfile(os.path.join(self.__path,relaPath,self.__fileInfo%fname)),\n }\n state.append({relaFilePath:fileDict})\n # loop directories\n #for ddict in sorted([d for d in dirList if isinstance(d, dict) and len(d)], key=lambda k: list(k)[0]):\n for ddict in sorted([d for d in dirList if isinstance(d, dict)], key=lambda k: list(k)[0]):\n dirname = list(ddict)[0]\n _walk_dir(relaPath=os.path.join(relaPath,dirname), dirList=ddict[dirname])\n # call recursive _walk_dir\n if relaPath is None:\n _walk_dir(relaPath='', dirList=self.__repo['walk_repo'])\n else:\n assert isinstance(relaPath, basestring), \"relaPath must be None or a str\"\n relaPath = self.to_repo_relative_path(path=relaPath, split=False)\n spath = relaPath.split(os.sep)\n dirList = self.__repo['walk_repo']\n while len(spath):\n dirname = spath.pop(0)\n dList = [d for d in dirList if isinstance(d, dict)]\n if not len(dList):\n dirList = None\n break\n cDict = [d for d in dList if dirname in d]\n if not len(cDict):\n dirList = None\n break\n dirList = cDict[0][dirname]\n if dirList is not None:\n _walk_dir(relaPath=relaPath, dirList=dirList)\n # return state list\n return state"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_file_info(self, relativePath):\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n fileName = os.path.basename(relativePath)\n isRepoFile,fileOnDisk, infoOnDisk, classOnDisk = self.is_repository_file(relativePath)\n if not isRepoFile:\n return None, \"file is not a registered repository file.\"\n if not infoOnDisk:\n return None, \"file is a registered repository file but info file missing\"\n fileInfoPath = os.path.join(self.__path,os.path.dirname(relativePath),self.__fileInfo%fileName)\n try:\n with open(fileInfoPath, 'rb') as fd:\n info = pickle.load(fd)\n except Exception as err:\n return None, \"Unable to read file info from disk (%s)\"%str(err)\n return info, ''", "response": "Get file information dictionary from the repository given its relative path."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef is_repository_file(self, relativePath):\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n if relativePath == '':\n return False, False, False, False\n relaDir, name = os.path.split(relativePath)\n fileOnDisk = os.path.isfile(os.path.join(self.__path, relativePath))\n infoOnDisk = os.path.isfile(os.path.join(self.__path,os.path.dirname(relativePath),self.__fileInfo%name))\n classOnDisk = os.path.isfile(os.path.join(self.__path,os.path.dirname(relativePath),self.__fileClass%name))\n cDir = self.__repo['walk_repo']\n if len(relaDir):\n for dirname in relaDir.split(os.sep):\n dList = [d for d in cDir if isinstance(d, dict)]\n if not len(dList):\n cDir = None\n break\n cDict = [d for d in dList if dirname in d]\n if not len(cDict):\n cDir = None\n break\n cDir = cDict[0][dirname]\n if cDir is None:\n return False, fileOnDisk, infoOnDisk, classOnDisk\n #if name not in cDir:\n if str(name) not in [str(i) for i in cDir]:\n return False, fileOnDisk, infoOnDisk, classOnDisk\n # this is a repository registered file. check whether all is on disk\n return True, fileOnDisk, infoOnDisk, classOnDisk", "response": "Check whether a given relative path is a repository file."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef walk_files_path(self, relativePath=\"\", fullPath=False, recursive=False):\n assert isinstance(fullPath, bool), \"fullPath must be boolean\"\n assert isinstance(recursive, bool), \"recursive must be boolean\"\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n dirList = self.__get_repository_directory(relativePath=relativePath)\n assert dirList is not None, \"given relative path '%s' is not a repository directory\"%relativePath\n # walk recursive function\n def _walk(rpath, dlist,recursive):\n # walk files\n for fname in dlist:\n if isinstance(fname, basestring):\n if fullPath:\n yield os.path.join(self.__path, rpath, fname)\n else:\n yield os.path.join(rpath, fname)\n if recursive:\n for ddict in dlist:\n if isinstance(ddict, dict):\n dname = list(ddict)[0]\n for p in _walk(rpath=os.path.join(rpath,dname), dlist=ddict[dname],recursive=recursive):\n yield p\n # walk all files\n return _walk(rpath=relativePath, dlist=dirList, recursive=recursive)", "response": "Walk the files directory and yield the file relative or full path."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nwalking the repository relative path and yield tuple of two items where first item is file relative path second item is file info.", "response": "def walk_files_info(self, relativePath=\"\", fullPath=False, recursive=False):\n \"\"\"\n Walk the repository relative path and yield tuple of two items where\n first item is file relative/full path and second item is file info.\n If file info is not found on disk, second item will be None.\n\n :parameters:\n #. relativePath (string): The relative path from which start the walk.\n #. fullPath (boolean): Whether to return full or relative path.\n #. recursive (boolean): Whether walk all directories files recursively\n \"\"\"\n assert isinstance(fullPath, bool), \"fullPath must be boolean\"\n assert isinstance(recursive, bool), \"recursive must be boolean\"\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n for relaPath in self.walk_files_path(relativePath=relativePath, fullPath=False, recursive=recursive):\n fpath, fname = os.path.split(relaPath)\n fileInfoPath = os.path.join(self.__path,fpath,self.__fileInfo%fname)\n if os.path.isfile(fileInfoPath):\n with open(fileInfoPath, 'rb') as fd:\n info = pickle.load(fd)\n else:\n info = None\n if fullPath:\n yield (os.path.join(self.__path, relaPath), info)\n else:\n yield (relaPath, info)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef walk_directories_info(self, relativePath=\"\", fullPath=False, recursive=False):\n assert isinstance(fullPath, bool), \"fullPath must be boolean\"\n assert isinstance(recursive, bool), \"recursive must be boolean\"\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n # walk directories\n for dpath in self.walk_directories_path(relativePath=relativePath, fullPath=False, recursive=recursive):\n dirInfoPath = os.path.join(self.__path,dpath,self.__dirInfo)\n if os.path.isfile(dirInfoPath):\n with open(dirInfoPath, 'rb') as fd:\n info = pickle.load(fd)\n else:\n info = None\n if fullPath:\n yield (os.path.join(self.__path, dpath), info)\n else:\n yield (dpath, info)", "response": "Walk the repository relative path and yield tuple of two items where first item is directory relative path second item is directory file info."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncreates a tar file package of all the files and directories in the repository.", "response": "def create_package(self, path=None, name=None, mode=None):\n \"\"\"\n Create a tar file package of all the repository files and directories.\n Only files and directories that are tracked in the repository\n are stored in the package tar file.\n\n **N.B. On some systems packaging requires root permissions.**\n\n :Parameters:\n #. path (None, string): The real absolute path where to create the\n package. If None, it will be created in the same directory as\n the repository. If '.' or an empty string is passed, the current\n working directory will be used.\n #. name (None, string): The name to give to the package file\n If None, the package directory name will be used with the\n appropriate extension added.\n #. mode (None, string): The writing mode of the tarfile.\n If None, automatically the best compression mode will be chose.\n Available modes are ('w', 'w:', 'w:gz', 'w:bz2')\n \"\"\"\n # check mode\n assert mode in (None, 'w', 'w:', 'w:gz', 'w:bz2'), 'unkown archive mode %s'%str(mode)\n if mode is None:\n #mode = 'w:bz2'\n mode = 'w:'\n # get root\n if path is None:\n root = os.path.split(self.__path)[0]\n elif path.strip() in ('','.'):\n root = os.getcwd()\n else:\n root = os.path.realpath( os.path.expanduser(path) )\n assert os.path.isdir(root), 'absolute path %s is not a valid directory'%path\n # get name\n if name is None:\n ext = mode.split(\":\")\n if len(ext) == 2:\n if len(ext[1]):\n ext = \".\"+ext[1]\n else:\n ext = '.tar'\n else:\n ext = '.tar'\n name = os.path.split(self.__path)[1]+ext\n # create tar file\n tarfilePath = os.path.join(root, name)\n try:\n tarHandler = tarfile.TarFile.open(tarfilePath, mode=mode)\n except Exception as e:\n raise Exception(\"Unable to create package (%s)\"%e)\n # walk directory and create empty directories\n for dpath in sorted(list(self.walk_directories_path(recursive=True))):\n t = tarfile.TarInfo( dpath )\n t.type = tarfile.DIRTYPE\n tarHandler.addfile(t)\n tarHandler.add(os.path.join(self.__path,dpath,self.__dirInfo), arcname=self.__dirInfo)\n # walk files and add to tar\n for fpath in self.walk_files_path(recursive=True):\n relaPath, fname = os.path.split(fpath)\n tarHandler.add(os.path.join(self.__path,fpath), arcname=fname)\n tarHandler.add(os.path.join(self.__path,relaPath,self.__fileInfo%fname), arcname=self.__fileInfo%fname)\n tarHandler.add(os.path.join(self.__path,relaPath,self.__fileClass%fname), arcname=self.__fileClass%fname)\n # save repository .pyrepinfo\n tarHandler.add(os.path.join(self.__path,self.__repoFile), arcname=\".pyrepinfo\")\n # close tar file\n tarHandler.close()"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef add_directory(self, relativePath, description=None, clean=False,\n raiseError=True, ntrials=3):\n \"\"\"\n Add a directory in the repository and creates its attribute in the\n Repository with utc timestamp. It insures adding all the missing\n directories in the path.\n\n :Parameters:\n #. relativePath (string): The relative to the repository path to\n where directory must be added.\n #. description (None, string): Any random description about the\n added directory.\n #. clean (boolean): Whether to remove existing non repository\n tracked files and folders in all created directory chain tree.\n #. raiseError (boolean): Whether to raise encountered error instead\n of returning failure.\n #. ntrials (int): After aquiring all locks, ntrials is the maximum\n number of trials allowed before failing.\n In rare cases, when multiple processes\n are accessing the same repository components, different processes\n can alter repository components between successive lock releases\n of some other process. Bigger number of trials lowers the\n likelyhood of failure due to multiple processes same time\n alteration.\n\n :Returns:\n #. success (boolean): Whether adding the directory was successful.\n #. message (None, string): Reason why directory was not added or\n random information.\n \"\"\"\n assert isinstance(raiseError, bool), \"raiseError must be boolean\"\n assert isinstance(relativePath, basestring), \"relativePath must be a string\"\n if description is not None:\n assert isinstance(description, basestring), \"description must be None or a string\"\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n # normalise path\n path = self.to_repo_relative_path(path=relativePath, split=False)\n # whether to replace\n if self.is_repository_directory(path):\n return True, \"Directory is already tracked in repository\"\n # check whether name is allowed\n allowed, reason = self.is_name_allowed(path)\n if not allowed:\n if raiseError:\n raise Exception(reason)\n return False, reason\n # lock repository and get __repo updated from disk\n LR = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(self.__path, self.__repoLock))\n acquired, code = LR.acquire_lock()\n if not acquired:\n m = \"code %s. Unable to aquire the lock to add directory. You may try again!\"%(code,)\n if raiseError:\n raise Exception(m)\n return False,m\n # load repository info\n for _trial in range(ntrials):\n try:\n repo = self.__load_repository_pickle_file(os.path.join(self.__path, self.__repoFile))\n self.__repo['walk_repo'] = repo['walk_repo']\n except Exception as err:\n error = str(err)\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n error = None\n break\n if error is not None:\n _ = LR.release_lock()\n assert not raiseError, Exception(error)\n return False, error\n # create directories\n error = None\n posList = self.__repo['walk_repo']\n dirPath = self.__path\n spath = path.split(os.sep)\n for idx, name in enumerate(spath):\n # create and acquire lock.\n LD = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(dirPath, self.__dirLock))\n acquired, code = LD.acquire_lock()\n if not acquired:\n error = \"Code %s. Unable to aquire the lock when adding '%s'. All prior directories were added. You may try again, to finish adding directory\"%(code,dirPath)\n break\n # add to directory\n for _trial in range(ntrials):\n try:\n dirPath = os.path.join(dirPath, name)\n riPath = os.path.join(dirPath, self.__dirInfo)\n dList = [d for d in posList if isinstance(d, dict)]\n dList = [d for d in dList if name in d]\n # clean directory\n if not len(dList) and clean and os.path.exists(dirPath):\n try:\n shutil.rmtree( dirPath, ignore_errors=True )\n except Exception as err:\n error = \"Unable to clean directory '%s' (%s)\"%(dirPath, err)\n break\n # create directory\n if not os.path.exists(dirPath):\n try:\n os.mkdir(dirPath)\n except Exception as err:\n error = \"Unable to create directory '%s' (%s)\"%(dirPath, err)\n break\n # create and dump dirinfo\n self.__save_dirinfo(description=[None, description][idx==len(spath)-1],\n dirInfoPath=riPath, create=True)\n # update directory list\n if not len(dList):\n rsd = {name:[]}\n posList.append(rsd)\n posList = rsd[name]\n else:\n assert len(dList) == 1, \"Same directory name dict is found twice. This should'n have happened. Report issue\"\n posList = dList[0][name]\n except Exception as err:\n LD.release_lock()\n error = \"Unable to create directory '%s' info file (%s)\"%(dirPath, str(err))\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n LD.release_lock()\n break\n if error is not None:\n break\n # save __repo\n if error is None:\n try:\n _, error = self.__save_repository_pickle_file(lockFirst=False, raiseError=False)\n except Exception as err:\n error = str(err)\n pass\n try:\n LD.release_lock()\n except:\n pass\n try:\n LR.release_lock()\n except:\n pass\n # check and return\n assert error is None or not raiseError, error\n return error is None, error", "response": "This function adds a directory to the repository and creates its attribute in the repository with utc timestamp."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nremoves a directory from the repository.", "response": "def remove_directory(self, relativePath, clean=False, raiseError=True, ntrials=3):\n \"\"\"\n Remove directory from repository tracking.\n\n :Parameters:\n #. relativePath (string): The relative to the repository path of the\n directory to remove from the repository.\n #. clean (boolean): Whether to os remove directory. If False only\n tracked files will be removed along with left empty directories.\n #. raiseError (boolean): Whether to raise encountered error instead\n of returning failure.\n #. ntrials (int): After aquiring all locks, ntrials is the maximum\n number of trials allowed before failing.\n In rare cases, when multiple processes\n are accessing the same repository components, different processes\n can alter repository components between successive lock releases\n of some other process. Bigger number of trials lowers the\n likelyhood of failure due to multiple processes same time\n alteration.\n\n :Returns:\n #. success (boolean): Whether removing the directory was successful.\n #. reason (None, string): Reason why directory was not removed.\n \"\"\"\n assert isinstance(raiseError, bool), \"raiseError must be boolean\"\n assert isinstance(clean, bool), \"clean must be boolean\"\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n # normalise path\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n parentPath, dirName = os.path.split(relativePath)\n # check if this is main repository directory\n if relativePath == '':\n return False, \"Removing main repository directory is not allowed\"\n # check if this is a repository directory\n if not self.is_repository_directory(relativePath):\n return False, \"Given relative path '%s' is not a repository path\"%relativePath\n # check if directory actually exists on disk\n realPath = os.path.join(self.__path,relativePath)\n if not os.path.isdir(realPath):\n error = \"Repository relative directory '%s' seems to be missing. call maintain_repository to fix all issues\"\n assert not raiseError, error\n return False, error\n # get and acquire lock\n LD = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(self.__path,parentPath,self.__dirLock))\n acquired, code = LD.acquire_lock()\n if not acquired:\n error = \"Code %s. Unable to aquire the lock when adding '%s'. All prior directories were added. You may try again, to finish adding directory\"%(code,realPath)\n assert not raiseError, error\n return False, error\n # lock repository and get __repo updated from disk\n LR = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(self.__path, self.__repoLock))\n acquired, code = LR.acquire_lock()\n if not acquired:\n LD.release_lock()\n m = \"code %s. Unable to aquire the repository lock. You may try again!\"%(code,)\n assert raiseError, Exception(m)\n return False,m\n # remove directory\n for _trial in range(ntrials):\n error = None\n try:\n dirList = self.__get_repository_parent_directory(relativePath=relativePath)\n assert dirList is not None, \"Given relative path '%s' is not a repository directory\"%(relativePath,)\n stateBefore = self.get_repository_state(relaPath=parentPath)\n _files = [f for f in dirList if isinstance(f, basestring)]\n _dirs = [d for d in dirList if isinstance(d, dict)]\n _dirs = [d for d in dirList if dirName not in d]\n _ = [dirList.pop(0) for _ in range(len(dirList))]\n dirList.extend(_files)\n dirList.extend(_dirs)\n if clean:\n shutil.rmtree(realPath)\n else:\n stateAfter = self.get_repository_state(relaPath=parentPath)\n success, errors = self.__clean_before_after(stateBefore=stateBefore, stateAfter=stateAfter, keepNoneEmptyDirectory=True)\n assert success, \"\\n\".join(errors)\n except Exception as err:\n error = str(err)\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n break\n # return\n if error is None:\n _, error = self.__save_repository_pickle_file(lockFirst=False, raiseError=False)\n LD.release_lock()\n LR.release_lock()\n # check and return\n assert error is None or not raiseError, \"Unable to remove directory after %i trials '%s' (%s)\"%(relativePath, ntrials, error,)\n return error is None, error"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef rename_directory(self, relativePath, newName, raiseError=True, ntrials=3):\n assert isinstance(raiseError, bool), \"raiseError must be boolean\"\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n parentPath, dirName = os.path.split(relativePath)\n if relativePath == '':\n error = \"Renaming main repository directory is not allowed\"\n assert not raiseError, error\n return False, error\n realPath = os.path.join(self.__path,relativePath)\n newRealPath = os.path.join(os.path.dirname(realPath), newName)\n if os.path.isdir(newRealPath):\n error = \"New directory path '%s' already exist\"%(newRealPath,)\n assert not raiseError, error\n return False, error\n # get directory parent list\n LD = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(self.__path,parentPath, self.__dirLock))\n acquired, code = LD.acquire_lock()\n if not acquired:\n error = \"Code %s. Unable to aquire repository lock when renaming '%s'. All prior directories were added. You may try again, to finish adding the directory\"%(code,dirPath)\n assert not raiseError, error\n return False, error\n error = None\n\n # lock repository and get __repo updated from disk\n LR = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(self.__path, self.__repoLock))\n acquired, code = LR.acquire_lock()\n if not acquired:\n LD.release_lock()\n m = \"Code %s. Unable to aquire directory lock when renaming '%s'. All prior directories were added. You may try again, to finish adding the directory\"%(code,dirPath)\n assert raiseError, Exception(m)\n return False,m\n # load repository info\n for _trial in range(ntrials):\n try:\n repo = self.__load_repository_pickle_file(os.path.join(self.__path, self.__repoFile))\n self.__repo['walk_repo'] = repo['walk_repo']\n except Exception as err:\n error = str(err)\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n error = None\n break\n if error is not None:\n LD.release_lock()\n LR.release_lock()\n assert not raiseError, Exception(error)\n return False, error\n # rename directory\n for _trial in range(ntrials):\n error = None\n try:\n dirList = self.__get_repository_parent_directory(relativePath=relativePath)\n assert dirList is not None, \"Given relative path '%s' is not a repository directory\"%(relativePath,)\n # change dirName in dirList\n _dirDict = [nd for nd in dirList if isinstance(nd,dict)]\n _dirDict = [nd for nd in _dirDict if dirName in nd]\n assert len(_dirDict) == 1, \"This should not have happened. Directory not found in repository. Please report issue\"\n # rename directory\n os.rename(realPath, newRealPath)\n # update dirList\n _dirDict[0][newName] = _dirDict[0][dirName]\n _dirDict[0].pop(dirName)\n # update and dump dirinfo\n self.__save_dirinfo(description=None, dirInfoPath=parentPath, create=False)\n except Exception as err:\n error = str(err)\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n error = None\n break\n if error is None:\n _, error = self.__save_repository_pickle_file(lockFirst=False, raiseError=False)\n LR.release_lock()\n LD.release_lock()\n # check and return\n assert error is None or not raiseError, \"Unable to rename directory '%s' to '%s' after %i trials (%s)\"%(relativePath, newName, ntrials, error,)\n return error is None, error", "response": "This function renames a directory in the system."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ncopy a directory in the repository.", "response": "def copy_directory(self, relativePath, newRelativePath,\n overwrite=False, raiseError=True, ntrials=3):\n \"\"\"\n Copy a directory in the repository. New directory must not exist.\n\n :Parameters:\n #. relativePath (string): The relative to the repository path of\n the directory to be copied.\n #. newRelativePath (string): The new directory relative path.\n #. overwrite (boolean): Whether to overwrite existing but not tracked\n directory in repository.\n #. raiseError (boolean): Whether to raise encountered error instead\n of returning failure.\n #. ntrials (int): After aquiring all locks, ntrials is the maximum\n number of trials allowed before failing.\n In rare cases, when multiple processes\n are accessing the same repository components, different processes\n can alter repository components between successive lock releases\n of some other process. Bigger number of trials lowers the\n likelyhood of failure due to multiple processes same time\n alteration.\n\n :Returns:\n #. success (boolean): Whether renaming the directory was successful.\n #. message (None, string): Some explanatory message or error reason\n why directory was not renamed.\n \"\"\"\n #from distutils.dir_util import copy_tree\n assert isinstance(raiseError, bool), \"raiseError must be boolean\"\n assert isinstance(overwrite, bool), \"overwrite must be boolean\"\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n if relativePath == '':\n m = \"Copying to repository main directory is not possible\"\n assert not raiseError, m\n return False, m\n realPath = os.path.join(self.__path,relativePath)\n parentRealPath, dirName = os.path.split(realPath)\n parentRelativePath = os.path.dirname(relativePath)\n if not self.is_repository_directory(relativePath):\n m = \"Directory '%s' is not a tracked repository directory\"%(relativePath)\n assert not raiseError, m\n return False, m\n newRelativePath = self.to_repo_relative_path(path=newRelativePath, split=False)\n newRealPath = os.path.join(self.__path,newRelativePath)\n newParentRealPath, newDirName = os.path.split(newRealPath)\n newParentRelativePath = os.path.dirname(newRelativePath)\n if realPath == newRealPath:\n m = \"Copying to the same directory is not possible\"\n assert not raiseError, m\n return False, m\n if self.is_repository_directory(newRelativePath):\n m = \"Directory '%s' is a tracked repository directory\"%(newRelativePath)\n assert not raiseError, m\n return False, m\n if os.path.isdir(newRealPath):\n if overwrite:\n try:\n shutil.rmtree(newRealPath)\n except Exception as err:\n assert not raiseError, str(err)\n return False, str(err)\n else:\n error = \"New directory path '%s' already exist on disk. Set overwrite to True\"%(newRealPath,)\n assert not raiseError, error\n return False, error\n # add directory\n try:\n success, reason = self.add_directory(newParentRelativePath, raiseError=False, ntrials=ntrials)\n except Exception as err:\n reason = \"Unable to add directory (%s)\"%(str(err))\n success = False\n if not success:\n assert not raiseError, reason\n return False, reason\n # lock repository and get __repo updated from disk\n LR = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(self.__path, self.__repoLock))\n acquired, code = LR.acquire_lock()\n if not acquired:\n m = \"code %s. Unable to aquire the repository lock. You may try again!\"%(code,)\n assert raiseError, Exception(m)\n return False,m\n try:\n repo = self.__load_repository_pickle_file(os.path.join(self.__path, self.__repoFile))\n self.__repo['walk_repo'] = repo['walk_repo']\n except Exception as err:\n LR.release_lock()\n assert not raiseError, Exception(str(err))\n return False,m\n # create locks\n L0 = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(parentRealPath, self.__dirLock))\n acquired, code = L0.acquire_lock()\n if not acquired:\n LR.release_lock()\n error = \"Code %s. Unable to aquire the lock when adding '%s'. All prior directories were added. You may try again, to finish adding directory\"%(code,dirPath)\n assert not raiseError, error\n return False, error\n L1 = None\n if parentRealPath != newParentRealPath:\n L1 = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(newParentRealPath, self.__dirLock))\n acquired, code = L1.acquire_lock()\n if not acquired:\n L0.release_lock()\n LR.release_lock()\n error = \"Code %s. Unable to aquire the lock when adding '%s'. All prior directories were added. You may try again, to finish adding directory\"%(code,dirPath)\n assert not raiseError, error\n return False, error\n # get directory parent list\n error = None\n for _trial in range(ntrials):\n try:\n # make sure again because sometimes, when multiple processes are working on the same repo things can happen in between\n assert self.is_repository_directory(relativePath), \"Directory '%s' is not anymore a tracked repository directory\"%(relativePath)\n assert not self.is_repository_directory(newRelativePath), \"Directory '%s' has become a tracked repository directory\"%(relativePath)\n dirList = self.__get_repository_parent_directory(relativePath=relativePath)\n assert dirList is not None, \"Given relative path '%s' is not a repository directory\"%(relativePath,)\n newDirList = self.__get_repository_parent_directory(relativePath=newRelativePath)\n assert newDirList is not None, \"Given new relative path '%s' parent directory is not a repository directory\"%(newRelativePath,)\n # change dirName in dirList\n _dirDict = [nd for nd in dirList if isinstance(nd,dict)]\n _dirDict = [nd for nd in _dirDict if dirName in nd]\n assert len(_dirDict) == 1, \"This should not have happened. Directory not found in repository. Please report issue\"\n _newDirDict = [nd for nd in newDirList if isinstance(nd,dict)]\n _newDirDict = [nd for nd in _newDirDict if newDirName in nd]\n assert len(_newDirDict) == 0, \"This should not have happened. New directory is found in repository. Please report issue\"\n # try to copy directory\n _newDirDict = copy.deepcopy(_dirDict[0])\n if dirName != newDirName:\n _newDirDict[newDirName] = _newDirDict.pop(dirName)\n copy_tree(realPath, newRealPath)\n # update newDirList\n newDirList.append(_newDirDict)\n # update and dump dirinfo\n self.__save_dirinfo(description=None, dirInfoPath=newParentRelativePath, create=False)\n except Exception as err:\n error = str(err)\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n error = None\n break\n if error is None:\n _, error = self.__save_repository_pickle_file(lockFirst=False, raiseError=False)\n LR.release_lock()\n L0.release_lock()\n if L1 is not None:\n L1.release_lock()\n # check and return\n assert error is None or not raiseError, \"Unable to copy directory '%s' to '%s' after %i trials (%s)\"%(relativePath, newRelativePath, ntrials, error,)\n return error is None, error"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ndumping a file into the repository.", "response": "def dump_file(self, value, relativePath,\n description=None,\n dump=None, pull=None,\n replace=False, raiseError=True, ntrials=3):\n \"\"\"\n Dump a file using its value to the system and creates its\n attribute in the Repository with utc timestamp.\n\n :Parameters:\n #. value (object): The value of a file to dump and add to the\n repository. It is any python object or file.\n #. relativePath (str): The relative to the repository path to where\n to dump the file.\n #. description (None, string): Any description about the file.\n #. dump (None, string): The dumping method.\n If None it will be set automatically to pickle and therefore the\n object must be pickleable. If a string is given, it can be a\n keyword ('json','pickle','dill') or a string compileable code to\n dump the data. The string code must include all the necessary\n imports and a '$FILE_PATH' that replaces the absolute file path\n when the dumping will be performed.\\n\n e.g. \"import numpy as np; np.savetxt(fname='$FILE_PATH', X=value, fmt='%.6e')\"\n #. pull (None, string): The pulling method. If None it will be set\n automatically to pickle and therefore the object must be\n pickleable. If a string is given, it can be a keyword\n ('json','pickle','dill') or a string compileable code to pull\n the data. The string code must include all the necessary imports,\n a '$FILE_PATH' that replaces the absolute file path when the\n dumping will be performed and finally a PULLED_DATA variable.\\n\n e.g \"import numpy as np; PULLED_DATA=np.loadtxt(fname='$FILE_PATH')\"\n #. replace (boolean): Whether to replace any existing file.\n #. raiseError (boolean): Whether to raise encountered error instead\n of returning failure.\n #. ntrials (int): After aquiring all locks, ntrials is the maximum\n number of trials allowed before failing.\n In rare cases, when multiple processes\n are accessing the same repository components, different processes\n can alter repository components between successive lock releases\n of some other process. Bigger number of trials lowers the\n likelyhood of failure due to multiple processes same time\n alteration.\n\n :Returns:\n #. success (boolean): Whether renaming the directory was successful.\n #. message (None, string): Some explanatory message or error reason\n why directory was not dumped.\n \"\"\"\n # check arguments\n assert isinstance(raiseError, bool), \"raiseError must be boolean\"\n assert isinstance(replace, bool), \"replace must be boolean\"\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n if description is None:\n description = ''\n assert isinstance(description, basestring), \"description must be None or a string\"\n # convert dump and pull methods to strings\n if pull is None and dump is not None:\n if dump.startswith('pickle') or dump.startswith('dill') or dump.startswith('numpy') or dump =='json':\n pull = dump\n dump = get_dump_method(dump, protocol=self._DEFAULT_PICKLE_PROTOCOL)\n pull = get_pull_method(pull)\n # check name and path\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n savePath = os.path.join(self.__path,relativePath)\n fPath, fName = os.path.split(savePath)\n # check if name is allowed\n success, reason = self.is_name_allowed(savePath)\n if not success:\n assert not raiseError, reason\n return False, reason\n # ensure directory added\n try:\n success, reason = self.add_directory(fPath, raiseError=False, ntrials=ntrials)\n except Exception as err:\n reason = \"Unable to add directory (%s)\"%(str(err))\n success = False\n if not success:\n assert not raiseError, reason\n return False, reason\n # lock repository\n LR = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(self.__path, self.__repoLock))\n acquired, code = LR.acquire_lock()\n if not acquired:\n m = \"code %s. Unable to aquire the repository lock. You may try again!\"%(code,)\n assert raiseError, Exception(m)\n return False,m\n # lock file\n LF = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(fPath,self.__fileLock%fName))\n acquired, code = LF.acquire_lock()\n if not acquired:\n LR.release_lock()\n error = \"Code %s. Unable to aquire the lock when adding '%s'\"%(code,relativePath)\n assert not raiseError, error\n return False, error\n # load repository info\n for _trial in range(ntrials):\n try:\n repo = self.__load_repository_pickle_file(os.path.join(self.__path, self.__repoFile))\n self.__repo['walk_repo'] = repo['walk_repo']\n except Exception as err:\n error = str(err)\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n error = None\n break\n if error is not None:\n LR.release_lock()\n LF.release_lock()\n assert not raiseError, Exception(error)\n return False, error\n # dump file\n for _trial in range(ntrials):\n error = None\n try:\n isRepoFile, fileOnDisk, infoOnDisk, classOnDisk = self.is_repository_file(relativePath)\n if isRepoFile:\n assert replace, \"file is a registered repository file. set replace to True to replace\"\n fileInfoPath = os.path.join(self.__path,os.path.dirname(relativePath),self.__fileInfo%fName)\n if isRepoFile and fileOnDisk:\n with open(fileInfoPath, 'rb') as fd:\n info = pickle.load(fd)\n assert info['repository_unique_name'] == self.__repo['repository_unique_name'], \"it seems that file was created by another repository\"\n info['last_update_utctime'] = time.time()\n else:\n info = {'repository_unique_name':self.__repo['repository_unique_name']}\n info['create_utctime'] = info['last_update_utctime'] = time.time()\n info['dump'] = dump\n info['pull'] = pull\n info['description'] = description\n # get parent directory list if file is new and not being replaced\n if not isRepoFile:\n dirList = self.__get_repository_directory(fPath)\n # dump file\n #exec( dump.replace(\"$FILE_PATH\", str(savePath)) )\n my_exec( dump.replace(\"$FILE_PATH\", str(savePath)), locals=locals(), globals=globals(), description='dump' )\n # update info\n with open(fileInfoPath, 'wb') as fd:\n pickle.dump( info,fd, protocol=self._DEFAULT_PICKLE_PROTOCOL)\n fd.flush()\n os.fsync(fd.fileno())\n # update class file\n fileClassPath = os.path.join(self.__path,os.path.dirname(relativePath),self.__fileClass%fName)\n with open(fileClassPath, 'wb') as fd:\n if value is None:\n klass = None\n else:\n klass = value.__class__\n pickle.dump(klass , fd, protocol=self._DEFAULT_PICKLE_PROTOCOL )\n fd.flush()\n os.fsync(fd.fileno())\n # add to repo if file is new and not being replaced\n if not isRepoFile:\n dirList.append(fName)\n except Exception as err:\n error = \"unable to dump the file (%s)\"%(str(err),)\n try:\n if 'pickle.dump(' in dump:\n mi = get_pickling_errors(value)\n if mi is not None:\n error += '\\nmore info: %s'%str(mi)\n except:\n pass\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n error = None\n break\n # save repository\n if error is None:\n _, error = self.__save_repository_pickle_file(lockFirst=False, raiseError=False)\n # release locks\n LR.release_lock()\n LF.release_lock()\n assert not raiseError or error is None, \"unable to dump file '%s' after %i trials (%s)\"%(relativePath, ntrials, error,)\n return success, error"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nupdates the value of a file in the repository.", "response": "def update_file(self, value, relativePath, description=False,\n dump=False, pull=False, raiseError=True, ntrials=3):\n \"\"\"\n Update the value of a file that is already in the Repository.\\n\n If file is not registered in repository, and error will be thrown.\\n\n If file is missing in the system, it will be regenerated as dump method\n is called.\n Unlike dump_file, update_file won't block the whole repository but only\n the file being updated.\n\n :Parameters:\n #. value (object): The value of a file to update.\n #. relativePath (str): The relative to the repository path of the\n file to be updated.\n #. description (False, string): Any random description about the file.\n If False is given, the description info won't be updated,\n otherwise it will be update to what description argument value is.\n #. dump (False, string): The new dump method. If False is given,\n the old one will be used.\n #. pull (False, string): The new pull method. If False is given,\n the old one will be used.\n #. raiseError (boolean): Whether to raise encountered error instead\n of returning failure.\n #. ntrials (int): After aquiring all locks, ntrials is the maximum\n number of trials allowed before failing.\n In rare cases, when multiple processes\n are accessing the same repository components, different processes\n can alter repository components between successive lock releases\n of some other process. Bigger number of trials lowers the\n likelyhood of failure due to multiple processes same time\n alteration.\n\n :Returns:\n #. success (boolean): Whether renaming the directory was successful.\n #. message (None, string): Some explanatory message or error reason\n why directory was not updated.\n \"\"\"\n # check arguments\n assert isinstance(raiseError, bool), \"raiseError must be boolean\"\n assert description is False or description is None or isinstance(description, basestring), \"description must be False, None or a string\"\n assert dump is False or dump is None or isinstance(dump, basestring), \"dump must be False, None or a string\"\n assert pull is False or pull is None or isinstance(pull, basestring), \"pull must be False, None or a string\"\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n # get name and path\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n savePath = os.path.join(self.__path,relativePath)\n fPath, fName = os.path.split(savePath)\n # get locker\n LF = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(fPath,self.__fileLock%fName))\n acquired, code = LF.acquire_lock()\n if not acquired:\n error = \"Code %s. Unable to aquire the lock to update '%s'\"%(code,relativePath)\n assert not raiseError, error\n return False, error\n # update file\n for _trial in range(ntrials):\n message = []\n updated = False\n try:\n # check file in repository\n isRepoFile, fileOnDisk, infoOnDisk, classOnDisk = self.is_repository_file(relativePath)\n assert isRepoFile, \"file '%s' is not registered in repository, no update can be performed.\"%(relativePath,)\n # get file info\n if not fileOnDisk:\n assert description is not False, \"file '%s' is found on disk, description must be provided\"%(relativePath,)\n assert dump is not False, \"file '%s' is found on disk, dump must be provided\"%(relativePath,)\n assert pull is not False, \"file '%s' is found on disk, pull must be provided\"%(relativePath,)\n info = {}\n info['repository_unique_name'] = self.__repo['repository_unique_name']\n info['create_utctime'] = info['last_update_utctime'] = time.time()\n else:\n with open(os.path.join(fPath,self.__fileInfo%fName), 'rb') as fd:\n info = pickle.load(fd)\n info['last_update_utctime'] = time.time()\n if not fileOnDisk:\n message.append(\"file %s is registered in repository but it was found on disk prior to updating\"%relativePath)\n if not infoOnDisk:\n message.append(\"%s is not found on disk prior to updating\"%self.__fileInfo%fName)\n if not classOnDisk:\n message.append(\"%s is not found on disk prior to updating\"%self.__fileClass%fName)\n # get dump and pull\n if (description is False) or (dump is False) or (pull is False):\n if description is False:\n description = info['description']\n elif description is None:\n description = ''\n if dump is False:\n dump = info['dump']\n elif dump is None:\n dump = get_dump_method(dump, protocol=self._DEFAULT_PICKLE_PROTOCOL)\n if pull is False:\n pull = info['pull']\n elif pull is None:\n pull = get_pull_method(pull)\n # update dump, pull and description\n info['dump'] = dump\n info['pull'] = pull\n info['description'] = description\n # dump file\n my_exec( dump.replace(\"$FILE_PATH\", str(savePath)), locals=locals(), globals=globals(), description='update' )\n #exec( dump.replace(\"$FILE_PATH\", str(savePath)) )\n # remove file if exists\n _path = os.path.join(fPath,self.__fileInfo%fName)\n # update info\n with open(_path, 'wb') as fd:\n pickle.dump( info,fd, protocol=self._DEFAULT_PICKLE_PROTOCOL )\n fd.flush()\n os.fsync(fd.fileno())\n # update class file\n fileClassPath = os.path.join(self.__path,os.path.dirname(relativePath),self.__fileClass%fName)\n with open(fileClassPath, 'wb') as fd:\n if value is None:\n klass = None\n else:\n klass = value.__class__\n pickle.dump(klass , fd, protocol=self._DEFAULT_PICKLE_PROTOCOL )\n fd.flush()\n os.fsync(fd.fileno())\n except Exception as err:\n message.append(str(err))\n updated = False\n try:\n if 'pickle.dump(' in dump:\n mi = get_pickling_errors(value)\n if mi is not None:\n message.append('more info: %s'%str(mi))\n except:\n pass\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], '\\n'.join(message)))\n else:\n updated = True\n break\n # release lock\n LF.release_lock()\n # check and return\n assert updated or not raiseError, \"Unable to update file '%s' (%s)\"%(relativePath, '\\n'.join(message),)\n return updated, '\\n'.join(message)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\npull a file from the repository.", "response": "def pull_file(self, relativePath, pull=None, update=True, ntrials=3):\n \"\"\"\n Pull a file's data from the Repository.\n\n :Parameters:\n #. relativePath (string): The relative to the repository path from\n where to pull the file.\n #. pull (None, string): The pulling method.\n If None, the pull method saved in the file info will be used.\n If a string is given, the string should include all the necessary\n imports, a '$FILE_PATH' that replaces the absolute file path when\n the dumping will be performed and finally a PULLED_DATA variable.\n e.g \"import numpy as np; PULLED_DATA=np.loadtxt(fname='$FILE_PATH')\"\n #. update (boolean): If pull is not None, Whether to update the pull\n method stored in the file info by the given pull method.\n #. ntrials (int): After aquiring all locks, ntrials is the maximum\n number of trials allowed before failing.\n In rare cases, when multiple processes\n are accessing the same repository components, different processes\n can alter repository components between successive lock releases\n of some other process. Bigger number of trials lowers the\n likelyhood of failure due to multiple processes same time\n alteration.\n\n :Returns:\n #. data (object): The pulled data from the file.\n \"\"\"\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n # check name and path\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n realPath = os.path.join(self.__path,relativePath)\n fPath, fName = os.path.split(realPath)\n # check whether it's a repository file\n isRepoFile,fileOnDisk, infoOnDisk, classOnDisk = self.is_repository_file(relativePath)\n if not isRepoFile:\n fileOnDisk = [\"\",\". File itself is found on disk\"][fileOnDisk]\n infoOnDisk = [\"\",\". %s is found on disk\"%self.__fileInfo%fName][infoOnDisk]\n classOnDisk = [\"\",\". %s is found on disk\"%self.__fileClass%fName][classOnDisk]\n assert False, \"File '%s' is not a repository file%s%s%s\"%(relativePath,fileOnDisk,infoOnDisk,classOnDisk)\n assert fileOnDisk, \"File '%s' is registered in repository but the file itself was not found on disk\"%(relativePath,)\n if not infoOnDisk:\n if pull is not None:\n warnings.warn(\"'%s' was not found on disk but pull method is given\"%(self.__fileInfo%fName))\n else:\n raise Exception(\"File '%s' is registered in repository but the '%s' was not found on disk and pull method is not specified\"%(relativePath,(self.__fileInfo%fName)))\n # lock repository\n LF = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(fPath,self.__fileLock%fName))\n acquired, code = LF.acquire_lock()\n if not acquired:\n error = \"Code %s. Unable to aquire the lock when adding '%s'\"%(code,relativePath)\n return False, error\n # pull file\n for _trial in range(ntrials):\n error = None\n try:\n # get pull method\n if pull is not None:\n pull = get_pull_method(pull)\n else:\n with open(os.path.join(fPath,self.__fileInfo%fName), 'rb') as fd:\n info = pickle.load(fd)\n pull = info['pull']\n # try to pull file\n #namespace = {}\n #namespace.update( globals() )\n #exec( pull.replace(\"$FILE_PATH\", str(realPath) ), namespace )\n my_exec( pull.replace(\"$FILE_PATH\", str(realPath) ), locals=locals(), globals=globals(), description='pull' )\n except Exception as err:\n LF.release_lock()\n m = str(pull).replace(\"$FILE_PATH\", str(realPath) )\n error = \"Unable to pull data using '%s' from file (%s)\"%(m,err)\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n break\n LF.release_lock()\n assert error is None, \"After %i trials, %s\"%(ntrials, error)\n # return data\n return locals()['PULLED_DATA']"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef rename_file(self, relativePath, newRelativePath,\n force=False, raiseError=True, ntrials=3):\n \"\"\"\n Rename a file in the repository. It insures renaming the file in the system.\n\n :Parameters:\n #. relativePath (string): The relative to the repository path of\n the file that needst to be renamed.\n #. newRelativePath (string): The new relative to the repository path\n of where to move and rename the file.\n #. force (boolean): Whether to force renaming even when another\n repository file exists. In this case old repository file\n will be removed from the repository and the system as well.\n #. raiseError (boolean): Whether to raise encountered error instead\n of returning failure.\n #. ntrials (int): After aquiring all locks, ntrials is the maximum\n number of trials allowed before failing.\n In rare cases, when multiple processes\n are accessing the same repository components, different processes\n can alter repository components between successive lock releases\n of some other process. Bigger number of trials lowers the\n likelyhood of failure due to multiple processes same time\n alteration.\n\n :Returns:\n #. success (boolean): Whether renaming the file was successful.\n #. message (None, string): Some explanatory message or error reason\n why directory was not updated.\n \"\"\"\n assert isinstance(raiseError, bool), \"raiseError must be boolean\"\n assert isinstance(force, bool), \"force must be boolean\"\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n # check old name and path\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n realPath = os.path.join(self.__path,relativePath)\n fPath, fName = os.path.split(realPath)\n # check new name and path\n newRelativePath = self.to_repo_relative_path(path=newRelativePath, split=False)\n newRealPath = os.path.join(self.__path,newRelativePath)\n nfPath, nfName = os.path.split(newRealPath)\n # lock old file\n LO = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(fPath,self.__fileLock%fName))\n acquired, code = LO.acquire_lock()\n if not acquired:\n error = \"Code %s. Unable to aquire the lock for old file '%s'\"%(code,relativePath)\n assert not raiseError, error\n return False, error\n # add directory\n try:\n success, reason = self.add_directory(nfPath, raiseError=False, ntrials=ntrials)\n except Exception as err:\n reason = \"Unable to add directory (%s)\"%(str(err))\n success = False\n if not success:\n LO.release_lock()\n assert not raiseError, reason\n return False, reason\n # create new file lock\n LN = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(nfPath,self.__fileLock%nfName))\n acquired, code = LN.acquire_lock()\n if not acquired:\n LO.release_lock()\n error = \"Code %s. Unable to aquire the lock for new file path '%s'\"%(code,newRelativePath)\n assert not raiseError, error\n return False, error\n # rename file\n for _trial in range(ntrials):\n renamed = False\n error = None\n try:\n # check whether it's a repository file\n isRepoFile,fileOnDisk, infoOnDisk, classOnDisk = self.is_repository_file(relativePath)\n assert isRepoFile, \"file '%s' is not a repository file\"%(relativePath,)\n assert fileOnDisk, \"file '%s' is found on disk\"%(relativePath,)\n assert infoOnDisk, \"%s is found on disk\"%self.__fileInfo%fName\n assert classOnDisk, \"%s is found on disk\"%self.__fileClass%fName\n # get new file path\n nisRepoFile,nfileOnDisk,ninfoOnDisk,nclassOnDisk = self.is_repository_file(newRelativePath)\n assert not nisRepoFile or force, \"New file path is a registered repository file, set force to True to proceed regardless\"\n # get parent directories list\n oDirList = self.__get_repository_directory(fPath)\n nDirList = self.__get_repository_directory(nfPath)\n # remove new file and all repository files from disk\n if os.path.isfile(newRealPath):\n os.remove(newRealPath)\n if os.path.isfile(os.path.join(nfPath,self.__fileInfo%nfName)):\n os.remove(os.path.join(nfPath,self.__fileInfo%nfName))\n if os.path.isfile(os.path.join(nfPath,self.__fileClass%nfName)):\n os.remove(os.path.join(nfPath,self.__fileClass%nfName))\n # move old file to new path\n os.rename(realPath, newRealPath)\n os.rename(os.path.join(fPath,self.__fileInfo%fName), os.path.join(nfPath,self.__fileInfo%nfName))\n os.rename(os.path.join(fPath,self.__fileClass%fName), os.path.join(nfPath,self.__fileClass%nfName))\n # update list\n findex = oDirList.index(fName)\n oDirList.pop(findex)\n # update new list\n if nfName not in nDirList:\n nDirList.append(nfName)\n except Exception as err:\n renamed = False\n error = str(err)\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], str(error)))\n else:\n renamed = True\n break\n # release locks\n LO.release_lock()\n LN.release_lock()\n # always clean old file lock\n try:\n if os.path.isfile(os.path.join(fPath,self.__fileLock%fName)):\n os.remove(os.path.join(fPath,self.__fileLock%fName))\n except:\n pass\n # return\n assert renamed or not raiseError, \"Unable to rename file '%s' to '%s' after %i trials (%s)\"%(relativePath, newRelativePath, ntrials, error,)\n #assert renamed or not raiseError, '\\n'.join(message)\n return renamed, error", "response": "This function rename a file in the repository."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nremove a file from the repository.", "response": "def remove_file(self, relativePath, removeFromSystem=False,\n raiseError=True, ntrials=3):\n \"\"\"\n Remove file from repository.\n\n :Parameters:\n #. relativePath (string): The relative to the repository path of the\n file to remove.\n #. removeFromSystem (boolean): Whether to remove file from disk as\n well.\n #. raiseError (boolean): Whether to raise encountered error instead\n of returning failure.\n #. ntrials (int): After aquiring all locks, ntrials is the maximum\n number of trials allowed before failing.\n In rare cases, when multiple processes\n are accessing the same repository components, different processes\n can alter repository components between successive lock releases\n of some other process. Bigger number of trials lowers the\n likelyhood of failure due to multiple processes same time\n alteration.\n \"\"\"\n assert isinstance(raiseError, bool), \"removeFromSystem must be boolean\"\n assert isinstance(removeFromSystem, bool), \"removeFromSystem must be boolean\"\n assert isinstance(ntrials, int), \"ntrials must be integer\"\n assert ntrials>0, \"ntrials must be >0\"\n # check name and path\n relativePath = self.to_repo_relative_path(path=relativePath, split=False)\n realPath = os.path.join(self.__path,relativePath)\n fPath, fName = os.path.split(realPath)\n # lock repository\n LF = Locker(filePath=None, lockPass=str(uuid.uuid1()), lockPath=os.path.join(fPath,self.__fileLock%fName))\n acquired, code = LF.acquire_lock()\n if not acquired:\n error = \"Code %s. Unable to aquire the lock when adding '%s'\"%(code,relativePath)\n assert not raiseError, error\n return False, error\n # remove file\n for _trial in range(ntrials):\n removed = False\n message = []\n try:\n # check whether it's a repository file\n isRepoFile,fileOnDisk, infoOnDisk, classOnDisk = self.is_repository_file(relativePath)\n if not isRepoFile:\n message(\"File '%s' is not a repository file\"%(relativePath,))\n if fileOnDisk:\n message.append(\"File itself is found on disk\")\n if infoOnDisk:\n message.append(\"%s is found on disk\"%self.__fileInfo%fName)\n if classOnDisk:\n message.append(\"%s is found on disk\"%self.__fileClass%fName)\n else:\n dirList = self.__get_repository_directory(fPath)\n findex = dirList.index(fName)\n dirList.pop(findex)\n if os.path.isfile(realPath):\n os.remove(realPath)\n if os.path.isfile(os.path.join(fPath,self.__fileInfo%fName)):\n os.remove(os.path.join(fPath,self.__fileInfo%fName))\n if os.path.isfile(os.path.join(fPath,self.__fileClass%fName)):\n os.remove(os.path.join(fPath,self.__fileClass%fName))\n except Exception as err:\n removed = False\n message.append(str(err))\n if self.DEBUG_PRINT_FAILED_TRIALS: print(\"Trial %i failed in Repository.%s (%s). Set Repository.DEBUG_PRINT_FAILED_TRIALS to False to mute\"%(_trial, inspect.stack()[1][3], '\\n'.join(message)))\n else:\n removed = True\n break\n # release lock\n LF.release_lock()\n # always clean\n try:\n if os.path.isfile(os.path.join(fPath,self.__fileLock%fName)):\n os.remove(os.path.join(fPath,self.__fileLock%fName))\n except:\n pass\n # check and return\n assert removed or not raiseError, \"Unable to remove file '%s' after %i trials (%s)\"%(relativePath, ntrials, '\\n'.join(message),)\n return removed, '\\n'.join(message)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef rename(self, key: Any, new_key: Any):\n if new_key == key:\n return\n\n required_locks = [self._key_locks[key], self._key_locks[new_key]]\n ordered_required_locks = sorted(required_locks, key=lambda x: id(x))\n for lock in ordered_required_locks:\n lock.acquire()\n\n try:\n if key not in self._data:\n raise KeyError(\"Attribute to rename \\\"%s\\\" does not exist\" % key)\n self._data[new_key] = self[key]\n del self._data[key]\n finally:\n for lock in required_locks:\n lock.release()", "response": "Renames an item in this collection as a transaction."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_text_fingerprint(text, hash_meth, encoding=\"utf-8\"): # pragma: no cover\n m = hash_meth()\n m.update(text.encode(encoding))\n return m.hexdigest()", "response": "Get a fingerprint of a piece of text."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn md5 hash value of a file", "response": "def md5file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE):\n \"\"\"\n Return md5 hash value of a piece of a file\n\n Estimate processing time on:\n\n :param abspath: the absolute path to the file\n :param nbytes: only has first N bytes of the file. if 0 or None,\n hash all file\n\n CPU = i7-4600U 2.10GHz - 2.70GHz, RAM = 8.00 GB\n 1 second can process 0.25GB data\n\n - 0.59G - 2.43 sec\n - 1.3G - 5.68 sec\n - 1.9G - 7.72 sec\n - 2.5G - 10.32 sec\n - 3.9G - 16.0 sec\n \"\"\"\n return get_file_fingerprint(abspath, hashlib.md5, nbytes=nbytes, chunk_size=chunk_size)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef sha256file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE):\n return get_file_fingerprint(abspath, hashlib.sha256, nbytes=nbytes, chunk_size=chunk_size)", "response": "Return the sha256 hash value of a file"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef sha512file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE):\n return get_file_fingerprint(abspath, hashlib.sha512, nbytes=nbytes, chunk_size=chunk_size)", "response": "Return the sha512 hash value of a file"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef register(registerable: Any):\n listenable = registration_event_listenable_map[type(registerable)]\n event = RegistrationEvent(registerable, RegistrationEvent.Type.REGISTERED)\n listenable.notify_listeners(event)", "response": "Registers an object notifying any listeners that may be interested in it."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef unregister(registerable: Any):\n listenable = registration_event_listenable_map[type(registerable)]\n event = RegistrationEvent(registerable, RegistrationEvent.Type.UNREGISTERED)\n listenable.notify_listeners(event)", "response": "Unregisters an object from the sequence of registered objects."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _load_module(path: str):\n spec = spec_from_file_location(os.path.basename(path), path)\n module = module_from_spec(spec)\n spec.loader.exec_module(module)", "response": "Dynamically loads the python module at the given path."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncheck if the object is empty.", "response": "def is_empty(self, strict=True):\n \"\"\"\n - If it's a file, check if it is a empty file. (0 bytes content)\n - If it's a directory, check if there's no file and dir in it.\n But if ``strict = False``, then only check if there's no file in it.\n\n :param strict: only useful when it is a directory. if True, only\n return True if this dir has no dir and file. if False, return True\n if it doesn't have any file.\n \"\"\"\n if self.exists():\n if self.is_file():\n return self.size == 0\n elif self.is_dir():\n if strict:\n return len(list(self.select(recursive=True))) == 0\n else: # pragma: no cover\n return len(list(self.select_file(recursive=True))) == 0\n else: # pragma: no cover\n msg = \"'%s' is not either file or directory! (maybe simlink)\" % self\n raise EnvironmentError(msg)\n else:\n raise EnvironmentError(\"'%s' not exists!\" % self)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef auto_complete_choices(self, case_sensitive=False):\n self_basename = self.basename\n self_basename_lower = self.basename.lower()\n if case_sensitive: # pragma: no cover\n def match(basename):\n return basename.startswith(self_basename)\n else:\n def match(basename):\n return basename.lower().startswith(self_basename_lower)\n\n choices = list()\n if self.is_dir():\n choices.append(self)\n for p in self.sort_by_abspath(self.select(recursive=False)):\n choices.append(p)\n else:\n p_parent = self.parent\n if p_parent.is_dir():\n for p in self.sort_by_abspath(p_parent.select(recursive=False)):\n if match(p.basename):\n choices.append(p)\n else: # pragma: no cover\n raise ValueError(\"'%s' directory does not exist!\" % p_parent)\n return choices", "response": "A command line auto complete similar behavior. Find all items with same\n prefix of this one."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef print_big_dir(self, top_n=5):\n self.assert_is_dir_and_exists()\n\n size_table = sorted(\n [(p, p.dirsize) for p in self.select_dir(recursive=False)],\n key=lambda x: x[1],\n reverse=True,\n )\n for p, size in size_table[:top_n]:\n print(\"{:<9} {:<9}\".format(repr_data_size(size), p.abspath))", "response": "Print top_n big dir in this dir."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef print_big_file(self, top_n=5):\n self.assert_is_dir_and_exists()\n\n size_table = sorted(\n [(p, p.size) for p in self.select_file(recursive=True)],\n key=lambda x: x[1],\n reverse=True,\n )\n for p, size in size_table[:top_n]:\n print(\"{:<9} {:<9}\".format(repr_data_size(size), p.abspath))", "response": "Print the top n big files in this dir."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef print_big_dir_and_big_file(self, top_n=5):\n self.assert_is_dir_and_exists()\n\n size_table1 = sorted(\n [(p, p.dirsize) for p in self.select_dir(recursive=False)],\n key=lambda x: x[1],\n reverse=True,\n )\n for p1, size1 in size_table1[:top_n]:\n print(\"{:<9} {:<9}\".format(repr_data_size(size1), p1.abspath))\n size_table2 = sorted(\n [(p, p.size) for p in p1.select_file(recursive=True)],\n key=lambda x: x[1],\n reverse=True,\n )\n for p2, size2 in size_table2[:top_n]:\n print(\" {:<9} {:<9}\".format(\n repr_data_size(size2), p2.abspath))", "response": "Print top_n big dir and big file in each dir."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn a dict of stat information for all files directories and total size.", "response": "def file_stat_for_all(self, filters=all_true): # pragma: no cover\n \"\"\"\n Find out how many files, directories and total size (Include file in\n it's sub-folder) it has for each folder and sub-folder.\n\n :returns: stat, a dict like ``{\"directory path\": {\n \"file\": number of files, \"dir\": number of directories,\n \"size\": total size in bytes}}``\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u8fd4\u56de\u4e00\u4e2a\u76ee\u5f55\u4e2d\u7684\u6bcf\u4e2a\u5b50\u76ee\u5f55\u7684, \u6587\u4ef6, \u6587\u4ef6\u5939, \u5927\u5c0f\u7684\u7edf\u8ba1\u6570\u636e\u3002\n \"\"\"\n self.assert_is_dir_and_exists()\n\n from collections import OrderedDict\n\n stat = OrderedDict()\n stat[self.abspath] = {\"file\": 0, \"dir\": 0, \"size\": 0}\n\n for p in self.select(filters=filters, recursive=True):\n if p.is_file():\n size = p.size\n while 1:\n parent = p.parent\n\n stat[parent.abspath][\"file\"] += 1\n stat[parent.abspath][\"size\"] += size\n\n if parent.abspath == self.abspath:\n break\n\n p = parent\n\n elif p.is_dir():\n stat[p.abspath] = {\"file\": 0, \"dir\": 0, \"size\": 0}\n\n while 1:\n parent = p.parent\n stat[parent.abspath][\"dir\"] += 1\n\n if parent.abspath == self.abspath:\n break\n\n p = parent\n\n return stat"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nfinding out how many files directorys and total size.", "response": "def file_stat(self, filters=all_true):\n \"\"\"Find out how many files, directorys and total size (Include file in\n it's sub-folder).\n\n :returns: stat, a dict like ``{\"file\": number of files,\n \"dir\": number of directorys, \"size\": total size in bytes}``\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u8fd4\u56de\u4e00\u4e2a\u76ee\u5f55\u4e2d\u7684\u6587\u4ef6, \u6587\u4ef6\u5939, \u5927\u5c0f\u7684\u7edf\u8ba1\u6570\u636e\u3002\n \"\"\"\n self.assert_is_dir_and_exists()\n\n stat = {\"file\": 0, \"dir\": 0, \"size\": 0}\n\n for p in self.select(filters=filters, recursive=True):\n if p.is_file():\n stat[\"file\"] += 1\n stat[\"size\"] += p.size\n elif p.is_dir():\n stat[\"dir\"] += 1\n\n return stat"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef mirror_to(self, dst): # pragma: no cover\n self.assert_is_dir_and_exists()\n\n src = self.abspath\n dst = os.path.abspath(dst)\n if os.path.exists(dst): # pragma: no cover\n raise Exception(\"distination already exist!\")\n\n folder_to_create = list()\n file_to_create = list()\n\n for current_folder, _, file_list in os.walk(self.abspath):\n current_folder = current_folder.replace(src, dst)\n try:\n os.mkdir(current_folder)\n except: # pragma: no cover\n pass\n for basename in file_list:\n abspath = os.path.join(current_folder, basename)\n with open(abspath, \"wb\") as _:\n pass", "response": "Mirrors the contents of this directory to another directory."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nexecuting every. py file as main script.", "response": "def execute_pyfile(self, py_exe=None): # pragma: no cover\n \"\"\"\n Execute every ``.py`` file as main script.\n\n :param py_exe: str, python command or python executable path.\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709Python\u6587\u4ef6\u4f5c\u4e3a\u4e3b\u811a\u672c\u7528\u5f53\u524d\u89e3\u91ca\u5668\u8fd0\u884c\u3002\n \"\"\"\n import subprocess\n\n self.assert_is_dir_and_exists()\n\n if py_exe is None:\n if six.PY2:\n py_exe = \"python2\"\n elif six.PY3:\n py_exe = \"python3\"\n\n for p in self.select_by_ext(\".py\"):\n subprocess.Popen('%s \"%s\"' % (py_exe, p.abspath))"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ntrailing white space at end of each line for every. py file.", "response": "def trail_space(self, filters=lambda p: p.ext == \".py\"): # pragma: no cover\n \"\"\"\n Trail white space at end of each line for every ``.py`` file.\n\n **\u4e2d\u6587\u6587\u6863**\n\n \u5c06\u76ee\u5f55\u4e0b\u7684\u6240\u6709\u88ab\u9009\u62e9\u7684\u6587\u4ef6\u4e2d\u884c\u672b\u7684\u7a7a\u683c\u5220\u9664\u3002\n \"\"\"\n self.assert_is_dir_and_exists()\n\n for p in self.select_file(filters):\n try:\n with open(p.abspath, \"rb\") as f:\n lines = list()\n for line in f:\n lines.append(line.decode(\"utf-8\").rstrip())\n\n with open(p.abspath, \"wb\") as f:\n f.write(\"\\n\".join(lines).encode(\"utf-8\"))\n\n except Exception as e: # pragma: no cover\n raise e"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef autopep8(self, **kwargs): # pragma: no cover\n self.assert_is_dir_and_exists()\n\n for p in self.select_by_ext(\".py\"):\n with open(p.abspath, \"rb\") as f:\n code = f.read().decode(\"utf-8\")\n\n formatted_code = autopep8.fix_code(code, **kwargs)\n\n with open(p.abspath, \"wb\") as f:\n f.write(formatted_code.encode(\"utf-8\"))", "response": "Auto convert your python code in a directory to pep8 styled code."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nnotifying all event listeners that the data has been passed to the event listeners.", "response": "def notify_listeners(self, data: Optional[_ListenableDataType]=_NO_DATA_MARKER):\n \"\"\"\n Notify event listeners, passing them the given data (if any).\n :param data: the data to pass to the event listeners\n \"\"\"\n for listener in self._listeners:\n if data is not Listenable._NO_DATA_MARKER:\n listener(data)\n else:\n listener()"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the size of the file in bytes.", "response": "def size(self):\n \"\"\"\n File size in bytes.\n \"\"\"\n try:\n return self._stat.st_size\n except: # pragma: no cover\n self._stat = self.stat()\n return self.size"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nget most recent modify time in timestamp.", "response": "def mtime(self):\n \"\"\"\n Get most recent modify time in timestamp.\n \"\"\"\n try:\n return self._stat.st_mtime\n except: # pragma: no cover\n self._stat = self.stat()\n return self.mtime"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngetting most recent access time in timestamp.", "response": "def atime(self):\n \"\"\"\n Get most recent access time in timestamp.\n \"\"\"\n try:\n return self._stat.st_atime\n except: # pragma: no cover\n self._stat = self.stat()\n return self.atime"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef ctime(self):\n try:\n return self._stat.st_ctime\n except: # pragma: no cover\n self._stat = self.stat()\n return self.ctime", "response": "Get most recent create time in timestamp."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning current terminal size or a default if detect fails.", "response": "def get_terminal_size(default_cols=80, default_rows=25):\n \"\"\"Return current terminal size (cols, rows) or a default if detect fails.\n\n This snippet comes from color ls by Chuck Blake:\n http://pdos.csail.mit.edu/~cblake/cls/cls.py\n\n \"\"\"\n def ioctl_GWINSZ(fd):\n \"\"\"Get (cols, rows) from a putative fd to a tty.\"\"\"\n try: \n rows_cols = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) \n return tuple(reversed(rows_cols))\n except:\n return None\n # Try std in/out/err...\n cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)\n # ...or ctty...\n if not cr:\n try:\n fd = os.open(os.ctermid(), os.O_RDONLY)\n cr = ioctl_GWINSZ(fd)\n os.close(fd)\n except:\n # ...or fall back to defaults\n cr = (int(os.environ.get('COLUMNS', default_cols)), \n int(os.environ.get('LINES', default_rows)))\n return cr"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_metainfo(scriptfile,\n keywords=['author', 'contact', 'copyright', 'download', 'git', 'subversion', 'version', 'website'],\n special={},\n first_line_pattern=r'^(?P.+)(\\s+v(?P\\S+))?',\n keyword_pattern_template=r'^\\s*%(pretty)s:\\s*(?P<%(keyword)s>\\S.+?)\\s*$',\n prettify = lambda kw: kw.capitalize().replace('_', ' ')):\n \"\"\"Dumb helper for pulling metainfo from a script __doc__ string.\n \n Returns a metainfo dict with command, description, progname and the given \n keywords (if present). \n \n This function will only make minimal efforts to succeed. If you need \n anything else: roll your own.\n \n The docstring needs to be multiline and the closing quotes need to be first \n on a line, optionally preceeded by whitespace. \n \n The first non-whitespace line is re.search'ed using first_line_pattern, \n default e.g (version optional, contains no whitespace): PROGNAME [vVERSION]\n \n The next non-whitespace, non-keyword line is expected to be the program \n description.\n\n The following lines are re.search'ed against a keyword:pattern dict which\n is constructed using \n keyword_pattern % dict(pretty=prettify(keyword), keyword=keyword)\n Default prettify is keyword.capitalize().replace('_', ' '). Example,\n for the keyword \"licence\" will match the following line:\n License: The MIT license.\n and set the license metainfo to \"The MIT license.\".\n \n Any keyword:pattern pairs that need special treatment can be supplied with \n special.\n \"\"\"\n patterns = dict((kw, re.compile(keyword_pattern_template % dict(pretty=prettify(kw), keyword=kw))) for kw in keywords)\n patterns.update(special)\n metainfo = dict()\n \n if scriptfile[-4:] in ['.pyc', '.pyo']: \n scriptfile = scriptfile[:-1]\n script = open(scriptfile)\n closer = ''\n for line in script:\n line = line.strip()\n if not line or line.startswith('#'):\n continue\n if line[:3] in ('\"\"\"', \"'''\"):\n closer = line[:3] \n break\n raise ValueError('file contains no docstring')\n if not line:\n for line in script:\n line = line.strip()\n if line:\n break\n g = re.search(first_line_pattern, line[3:]).groupdict()\n metainfo['progname'] = g['progname']\n if g['version']:\n metainfo['version'] = g['version']\n for line in script:\n if line.strip().startswith(closer):\n break\n for keyword, pattern in patterns.items():\n m = pattern.search(line)\n if m:\n metainfo[keyword] = m.group(keyword)\n break\n if line.strip() and not 'description' in metainfo:\n metainfo['description'] = line.strip()\n return metainfo", "response": "This function takes a script file and returns a dictionary with command description progname and keywords."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nlisting options that have not been used to format other values in their sections.", "response": "def unusedoptions(self, sections):\n \"\"\"Lists options that have not been used to format other values in \n their sections. \n \n Good for finding out if the user has misspelled any of the options.\n \"\"\"\n unused = set([])\n for section in _list(sections):\n if not self.has_section(section):\n continue\n options = self.options(section)\n raw_values = [self.get(section, option, raw=True) for option in options]\n for option in options:\n formatter = \"%(\" + option + \")s\"\n for raw_value in raw_values:\n if formatter in raw_value:\n break\n else:\n unused.add(option) \n return list(unused)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nconsume and process arguments and store the result in self. value.", "response": "def parse(self, argv, usedname, location):\n \"\"\"Consume and process arguments and store the result.\n ARGS:\n argv :\n The argument list to parse.\n usedname :\n The string used by the user to invoke the option.\n location :\n A user friendly sring describing where the parser got this\n data from.\n\n \"\"\"\n try:\n value = self.format.parse(argv)\n except formats.BadNumberOfArguments, e:\n raise BadNumberOfArguments(usedname, e.required, e.supplied)\n except formats.BadArgument, e:\n raise BadArgument(usedname, e.argument, e.message)\n if self.recurring:\n self.value.append(value)\n else:\n self.value = value\n self.location = location"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nparsing a string lexically and stores the result in the internal object.", "response": "def parsestr(self, argsstr, usedname, location):\n \"\"\"Parse a string lexically and store the result.\n ARGS:\n argsstr :\n The string to parse.\n usedname :\n The string used by the user to invoke the option.\n location :\n A user friendly sring describing where the parser got this\n data from.\n\n \"\"\"\n try:\n value = self.format.parsestr(argsstr)\n except formats.BadNumberOfArguments, e:\n raise BadNumberOfArguments(usedname, e.required, e.supplied)\n except formats.BadArgument, e:\n raise BadArgument(usedname, e.argument, e.message)\n if self.recurring:\n self.value.append(value)\n else:\n self.value = value\n self.location = location"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef parse(self, argv):\n if not argv and self.optional:\n self.value = [] if self.recurring else None\n return\n try:\n value = self.format.parse(argv)\n if not self.recurring:\n self.value = value\n return\n self.value = [value]\n while argv:\n self.value.append(self.format.parse(argv))\n except formats.BadNumberOfArguments, e:\n raise BadNumberOfArguments(self.displayname, e.required, e.given)\n except formats.BadArgument, e:\n raise BadArgument(self.displayname, e.argument, e.details)", "response": "Consume and process arguments and store the result in self. value."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef keys(self):\n return self.options.keys() + [p.name for p in self.positional_args]", "response": "List names of options and positional arguments."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef values(self):\n return self.options.values() + [p.value for p in self.positional_args]", "response": "List values of options and positional arguments."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef items(self):\n return [(p.name, p.value) for p in self.options.values() + self.positional_args]", "response": "List values of options and positional arguments."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef getparam(self, key):\n try:\n return self.options[key]\n except:\n pass\n for posarg in self.positional_args:\n if posarg.name == key:\n return posarg\n try:\n return self.abbreviations[key[1:]]\n except:\n raise KeyError('no such option or positional argument')", "response": "Get option or positional argument by name index or abbreviation."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nadd an Option object to the user interface.", "response": "def _add_option(self, option):\n \"\"\"Add an Option object to the user interface.\"\"\"\n if option.name in self.options:\n raise ValueError('name already in use')\n if option.abbreviation in self.abbreviations:\n raise ValueError('abbreviation already in use')\n if option.name in [arg.name for arg in self.positional_args]:\n raise ValueError('name already in use by a positional argument')\n self.options[option.name] = option\n if option.abbreviation:\n self.abbreviations[option.abbreviation] = option\n self.option_order.append(option.name)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _add_positional_argument(self, posarg):\n if self.positional_args:\n if self.positional_args[-1].recurring:\n raise ValueError(\"recurring positional arguments must be last\")\n if self.positional_args[-1].optional and not posarg.optional:\n raise ValueError(\"required positional arguments must precede optional ones\")\n self.positional_args.append(posarg)", "response": "Append a positional argument to the user interface."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef read_docs(self, docsfiles):\n updates = DocParser()\n for docsfile in _list(docsfiles):\n if os.path.isfile(docsfile):\n updates.parse(docsfile)\n self.docs.update((k, _docs(updates[k], self.docvars)) for k in self.docs if updates.blocks[k])\n for name, text in updates['parameters'].items():\n if name in self:\n self.getparam(name).docs = text[0] % self.docvars\n elif name not in self.ignore:\n raise ValueError(\"parameter %r does not exist\" % name)", "response": "Read program documentation from a list of paths to potential docsfiles."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nparsing configfiles. INDRA API.", "response": "def parse_files(self, files=None, sections=None):\n \"\"\"Parse configfiles. \n files , or None:\n What files to parse. None means use self.configfiles. New\n values override old ones. A string value will be interpreted\n as a list of one item.\n sections , or None:\n Which sections to parse from the files. None means use\n self.sections. A string value will be interpreted as a list\n of one item. The [DEFAULT]\n section is always read, and it is read as if its contents were\n copied to the beginning of all other sections.\n \n \"\"\"\n files = _list(files, self.configfiles)\n sections = _list(sections, self.sections)\n for file in files:\n parser = StrictConfigParser()\n parser.read(file)\n for section in sections:\n if not parser.has_section(section):\n continue\n for unused in parser.unusedoptions(section):\n if unused not in self.options and unused not in self.ignore: \n templ = \"The option %r in section [%s] of file %s does not exist.\"\n raise InvalidOption(unused, message=templ % (unused, section, file))\n for name in parser.options(section): \n if name in self.options:\n if self.options[name].reserved:\n templ = \"The option %s in section [%s] of file %s is reserved for command line use.\"\n raise ReservedOptionError(message=templ % (unused, section, file))\n value = parser.get(section, name)\n self.options[name].parsestr(value, name, '%s [%s]' % (file, section))"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _parse_options(self, argv, location):\n observed = []\n while argv:\n if argv[0].startswith('--'):\n name = argv.pop(0)[2:]\n # '--' means end of options.\n if not name:\n break\n if name not in self.options:\n raise InvalidOption(name)\n option = self.options[name]\n if not option.recurring:\n if option in observed:\n raise OptionRecurrenceError(name)\n observed.append(option)\n option.parse(argv, name, location)\n elif argv[0].startswith('-'):\n # A single - is not an abbreviation block, but the first positional arg.\n if argv[0] == '-':\n break\n block = argv.pop(0)[1:]\n # Abbrevs for options that take values go last in the block.\n for abbreviation in block[:-1]:\n if self.abbreviations[abbreviation].nargs != 0:\n raise BadAbbreviationBlock(abbreviation, block, \"options that require value arguments must be last in abbreviation blocks\")\n # Parse individual options.\n for abbreviation in block:\n option = self.abbreviations[abbreviation]\n if not option.recurring:\n if option in observed:\n raise OptionRecurrenceError(option.name)\n observed.append(option)\n option.parse(argv, '-' + abbreviation, location)\n # only arguments that start with -- or - can be Options.\n else:\n break", "response": "Parse the options part of an argument list."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _parse_positional_arguments(self, argv):\n for posarg in self.positional_args:\n posarg.parse(argv)\n if argv:\n if None in [p.nargs for p in self.positional_args]:\n msg = '%s too many argument%s given'\n plural_s = len(argv) > 1 and 's' or ''\n raise BadNumberOfArguments(message=msg % (len(argv), plural_s))\n msg = 'This program accepts exactly %s positional arguments (%s given).'\n required = len([p.nargs for p in self.positional_args])\n raise BadNumberOfArguments(message=msg % (required, required + len(argv)))", "response": "Parse the positional arguments part of an argument list. Will be altered."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nparsing command line arguments.", "response": "def parse_argv(self, argv=None, location='Command line.'):\n \"\"\"Parse command line arguments.\n \n args or None:\n The argument list to parse. None means use a copy of sys.argv. argv[0] is\n ignored.\n location = '' :\n A user friendly string describing where the parser got this\n data from. '' means use \"Command line.\" if args == None, and\n \"Builtin default.\" otherwise.\n \n \"\"\"\n if argv is None:\n argv = list(sys.argv)\n argv.pop(0)\n self._parse_options(argv, location)\n self._parse_positional_arguments(argv)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning user friendly help on program options.", "response": "def optionhelp(self, indent=0, maxindent=25, width=79):\n \"\"\"Return user friendly help on program options.\"\"\"\n def makelabels(option):\n labels = '%*s--%s' % (indent, ' ', option.name)\n if option.abbreviation:\n labels += ', -' + option.abbreviation\n return labels + ': '\n docs = []\n helpindent = _autoindent([makelabels(o) for o in self.options.values()], indent, maxindent)\n for name in self.option_order:\n option = self.options[name]\n labels = makelabels(option)\n helpstring = \"%s(%s). %s\" % (option.formatname, option.strvalue, option.docs)\n wrapped = self._wrap_labelled(labels, helpstring, helpindent, width)\n docs.extend(wrapped)\n return '\\n'.join(docs)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef posarghelp(self, indent=0, maxindent=25, width=79):\n docs = []\n makelabel = lambda posarg: ' ' * indent + posarg.displayname + ': '\n helpindent = _autoindent([makelabel(p) for p in self.positional_args], indent, maxindent)\n for posarg in self.positional_args:\n label = makelabel(posarg)\n text = posarg.formatname + '. ' + posarg.docs\n wrapped = self._wrap_labelled(label, text, helpindent, width)\n docs.extend(wrapped)\n return '\\n'.join(docs)", "response": "Return user friendly help on positional arguments in the program."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef format_usage(self, usage=None):\n if usage is None:\n usage = self.docs['usage']\n if usage is not None:\n return usage[0] % self.docvars\n usage = self.docvars['command']\n if self.basic_option_names.get('help'):\n usage += ' [--%s]' % self.basic_option_names.get('help')\n if self.options:\n usage += ' '\n optional = 0\n for posarg in self.positional_args:\n usage += ' '\n if posarg.optional:\n usage += \"[\" \n optional += 1\n usage += posarg.displayname\n if posarg.recurring:\n usage += ' [%s2 [...]]' % posarg.displayname\n usage += ']' * optional\n return usage", "response": "Return a formatted usage string."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _wraptext(self, text, indent=0, width=0):\n return '\\n'.join(self._wrap(par, indent, width) for par in text)", "response": "Wrap text with the given indent and width."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning brief help containing Title and usage instructions.", "response": "def shorthelp(self, width=0):\n \"\"\"Return brief help containing Title and usage instructions.\n ARGS:\n width = 0 :\n Maximum allowed page width. 0 means use default from\n self.iMaxHelpWidth.\n\n \"\"\"\n out = []\n out.append(self._wrap(self.docs['title'], width=width))\n if self.docs['description']:\n out.append(self._wrap(self.docs['description'], indent=2, width=width))\n out.append('')\n out.append(self._wrapusage(width=width))\n out.append('')\n return '\\n'.join(out)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef strsettings(self, indent=0, maxindent=25, width=0):\n out = []\n makelabel = lambda name: ' ' * indent + name + ': '\n settingsindent = _autoindent([makelabel(s) for s in self.options], indent, maxindent)\n for name in self.option_order:\n option = self.options[name]\n label = makelabel(name)\n settingshelp = \"%s(%s): %s\" % (option.formatname, option.strvalue, option.location)\n wrapped = self._wrap_labelled(label, settingshelp, settingsindent, width)\n out.extend(wrapped)\n return '\\n'.join(out)", "response": "Return a string representation of the options for the current object."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef settingshelp(self, width=0):\n out = []\n out.append(self._wrap(self.docs['title'], width=width))\n if self.docs['description']:\n out.append(self._wrap(self.docs['description'], indent=2, width=width))\n out.append('')\n out.append('SETTINGS:')\n out.append(self.strsettings(indent=2, width=width))\n out.append('')\n return '\\n'.join(out)", "response": "Return a summary of program options their values and origins."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef launch(self,\n argv=None,\n showusageonnoargs=False,\n width=0,\n helphint=\"Use with --help for more information.\\n\",\n debug_parser=False):\n \"\"\"Do the usual stuff to initiallize the program.\n \n Read config files and parse arguments, and if the user has used any \n of the help/version/settings options, display help and exit.\n \n If debug_parser is false, don't catch ParseErrors and exit with user\n friendly help. Crash with traceback instead.\n \n configfiles is a list of config files. None means use self.configfiles.\n \n sections is a list of configfile section names to read. None means use\n self.sections.\n \n argv is a list of arguments to parse. Will be modified. None means use\n copy of sys.argv. argv[0] is ignored.\n \n If showusageonnoargs is true, show usage and exit if the user didn't \n give any args. Should be False if there are no required PositionalArgs.\n \n width is the maximum allowed page width. 0 means use self.width.\n \n helphint is a string that hints on how to get more help which is \n displayed at the end of usage help messages. \n \"\"\"\n if showusageonnoargs and len(argv) == 1:\n print self.shorthelp(width=width)\n if helphint:\n print self._wrap(helphint, indent=2, width=width)\n sys.exit(0)\n parsing_error = None\n try:\n self.parse_files()\n self.parse_argv(argv)\n except ParseError, parsing_error:\n if debug_parser:\n raise\n for optiontype in ['help', 'longhelp', 'settings', 'version']:\n name = self.basic_option_names.get(optiontype)\n if name and self[name]:\n methodname = optiontype.rstrip('help') + 'help'\n print getattr(self, methodname)(width)\n sys.exit()\n if parsing_error:\n self.graceful_exit(parsing_error, width)", "response": "Do the usual stuff to initiallize the program.\n \n Read config files and parse arguments, and if the user has used any \n of the help/version/settings options, display help and exit.\n \n If debug_parser is false, don't catch ParseErrors and exit with user\n friendly help. Crash with traceback instead.\n \n configfiles is a list of config files. None means use self.configfiles.\n \n sections is a list of configfile section names to read. None means use\n self.sections.\n \n argv is a list of arguments to parse. Will be modified. None means use\n copy of sys.argv. argv[0] is ignored.\n \n If showusageonnoargs is true, show usage and exit if the user didn't \n give any args. Should be False if there are no required PositionalArgs.\n \n width is the maximum allowed page width. 0 means use self.width.\n \n helphint is a string that hints on how to get more help which is \n displayed at the end of usage help messages."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nparsing text blocks from a file.", "response": "def parse(self, file):\n \"\"\"Parse text blocks from a file.\"\"\"\n if isinstance(file, basestring):\n file = open(file)\n line_number = 0\n label = None\n block = self.untagged\n for line in file:\n line_number += 1\n line = line.rstrip('\\n')\n if self.tabsize > 0:\n line = line.replace('\\t', ' ' * self.tabsize)\n if self.decommenter:\n line = self.decommenter.decomment(line)\n if line is None:\n continue\n tag = line.split(':', 1)[0].strip()\n # Still in the same block?\n if tag not in self.names:\n if block is None:\n if line and not line.isspace():\n raise ParseError(file.name, line, \"garbage before first block: %r\" % line)\n continue\n block.addline(line)\n continue\n # Open a new block.\n name = self.names[tag]\n label = line.split(':',1)[1].strip()\n if name in self.labelled_classes:\n if not label:\n raise ParseError(file.name, line, \"missing label for %r block\" % name)\n block = self.blocks[name].setdefault(label, self.labelled_classes[name]())\n else:\n if label:\n msg = \"label %r present for unlabelled block %r\" % (label, name)\n raise ParseError(file.name, line_number, msg)\n block = self.blocks[name]\n block.startblock()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_format(format):\n if isinstance(format, BaseFormat):\n return format\n if isinstance(format, basestring):\n for name, formatclass in globals().items():\n if name.lower() == format.lower():\n if not issubclass(formatclass, BaseFormat):\n raise ValueError('%s is not the name of a format class' % format)\n return formatclass()\n try:\n return format()\n except:\n raise ValueError('no such format')", "response": "Get a format object."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef parsestr(self, argstr):\n argv = shlex.split(argstr, comments=True)\n if len(argv) != self.nargs:\n raise BadNumberOfArguments(self.nargs, len(argv))\n return self.parse(argv)", "response": "Parse arguments found in settings files."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef parse_argument(self, arg):\n lookup = self.casesensitive and arg or arg.lower()\n if lookup in self.special:\n return self.special[lookup]\n try:\n return self.to_python(arg, *self.args, **self.kw)\n except Exception, e:\n raise BadArgument(arg, str(e))", "response": "Parse a single argument."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\npopping parse and return the first self. nargs items from args. Raise BadNumberOfArguments or BadArgument on errors.", "response": "def parse(self, argv):\n \"\"\"Pop, parse and return the first self.nargs items from args.\n\n if self.nargs > 1 a list of parsed values will be returned.\n \n Raise BadNumberOfArguments or BadArgument on errors.\n \n NOTE: argv may be modified in place by this method.\n \"\"\"\n if len(argv) < self.nargs:\n raise BadNumberOfArguments(self.nargs, len(argv))\n if self.nargs == 1:\n return self.parse_argument(argv.pop(0))\n return [self.parse_argument(argv.pop(0)) for tmp in range(self.nargs)]"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns a user - friendly representation of a value.", "response": "def present(self, value):\n \"\"\"Return a user-friendly representation of a value.\n \n Lookup value in self.specials, or call .to_literal() if absent.\n \"\"\"\n for k, v in self.special.items():\n if v == value:\n return k\n return self.to_literal(value, *self.args, **self.kw)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nparse the arguments found in settings files.", "response": "def parsestr(self, argstr):\n \"\"\"Parse arguments found in settings files.\n \n Use the values in self.true for True in settings files, or those in \n self.false for False, case insensitive.\n \"\"\"\n argv = shlex.split(argstr, comments=True)\n if len(argv) != 1:\n raise BadNumberOfArguments(1, len(argv))\n arg = argv[0]\n lower = arg.lower()\n if lower in self.true:\n return True\n if lower in self.false:\n return False\n raise BadArgument(arg, \"Allowed values are \" + self.allowed + '.')"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\npops parse and return the first arg from argv.", "response": "def parse(self, argv):\n \"\"\"Pop, parse and return the first arg from argv.\n \n The arg will be .split() based on self.separator and the (optionally \n stripped) items will be parsed by self.format and returned as a list. \n\n Raise BadNumberOfArguments or BadArgument on errors.\n \n NOTE: args will be modified.\n \"\"\"\n if not argv:\n raise BadNumberOfArguments(1, 0)\n argument = argv.pop(0)\n lookup = self.casesensitive and argument or argument.lower()\n if lookup in self.special:\n return self.special[lookup]\n argv = [(self.strip and s.strip() or s) for s in argument.split(self.separator)]\n values = []\n while argv:\n values.append(self.format.parse(argv))\n return values"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn a user - friendly representation of a value.", "response": "def present(self, value):\n \"\"\"Return a user-friendly representation of a value.\n \n Lookup value in self.specials, or call .to_literal() if absent.\n \"\"\"\n for k, v in self.special.items():\n if v == value:\n return k\n return self.separator.join(self.format.present(v) for v in value)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning the separator that preceding format i or an empty string for i == 0.", "response": "def get_separator(self, i):\n \"\"\"Return the separator that preceding format i, or '' for i == 0.\"\"\"\n return i and self.separator[min(i - 1, len(self.separator) - 1)] or ''"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef parse(self, argv):\n if not argv:\n raise BadNumberOfArguments(1, 0)\n remainder = argv.pop(0)\n lookup = self.casesensitive and remainder or remainder.lower()\n if lookup in self.special:\n return self.special[lookup]\n values = []\n for i, format in enumerate(self.format[:-1]):\n print i, self.get_separator(i)\n try:\n arg, remainder = remainder.split(self.get_separator(i + 1), 1)\n except:\n raise BadArgument(remainder, 'does not contain required separator ' + repr(self.get_separator(i + 1)))\n if self.strip:\n arg = arg.strip()\n values.append(format.parse([arg]))\n if self.strip:\n remainder = remainder.strip()\n values.append(format.parse([remainder]))\n return values", "response": "Pop parse and return the first arg from argv."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef present(self, value):\n for k, v in self.special.items():\n if v == value:\n return k\n return ''.join(self.get_separator(i) + self.format[i].present(v) for i, v in enumerate(value))", "response": "Return a user - friendly representation of a value."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef authorize_url(self):\n auth_url = OAUTH_ROOT + '/authorize'\n params = {\n 'client_id': self.client_id,\n 'redirect_uri': self.redirect_uri,\n }\n return \"{}?{}\".format(auth_url, urlencode(params))", "response": "Return a URL to redirect the user to for OAuth authentication."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nexchange the authorization code for an access token.", "response": "def exchange_token(self, code):\n \"\"\"\n Exchange the authorization code for an access token.\n \"\"\"\n access_token_url = OAUTH_ROOT + '/access_token'\n params = {\n 'client_id': self.client_id,\n 'client_secret': self.client_secret,\n 'redirect_uri': self.redirect_uri,\n 'code': code,\n }\n resp = requests.get(access_token_url, params=params)\n if not resp.ok:\n raise MixcloudOauthError(\"Could not get access token.\")\n return resp.json()['access_token']"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngets a PORT that will be available on the machine.", "response": "def get_open_port() -> int:\n \"\"\"\n Gets a PORT that will (probably) be available on the machine.\n It is possible that in-between the time in which the open PORT of found and when it is used, another process may\n bind to it instead.\n :return: the (probably) available PORT\n \"\"\"\n free_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n free_socket.bind((\"\", 0))\n free_socket.listen(1)\n port = free_socket.getsockname()[1]\n free_socket.close()\n return port"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef release(self):\n self._lock.release()\n\n with self._stat_lock:\n self._locked = False\n self._last_released = datetime.now()", "response": "Removes the lock and resets the last acquired time."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nhandle a dict that might contain a wrapped state for a custom type.", "response": "def default_decoder(self, obj):\n \"\"\"Handle a dict that might contain a wrapped state for a custom type.\"\"\"\n typename, marshalled_state = self.unwrap_callback(obj)\n if typename is None:\n return obj\n\n try:\n cls, unmarshaller = self.serializer.unmarshallers[typename]\n except KeyError:\n raise LookupError('no unmarshaller found for type \"{}\"'.format(typename)) from None\n\n if cls is not None:\n instance = cls.__new__(cls)\n unmarshaller(instance, marshalled_state)\n return instance\n else:\n return unmarshaller(marshalled_state)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nwraps the marshalled state in a dictionary.", "response": "def wrap_state_dict(self, typename: str, state) -> Dict[str, Any]:\n \"\"\"\n Wrap the marshalled state in a dictionary.\n\n The returned dictionary has two keys, corresponding to the ``type_key`` and ``state_key``\n options. The former holds the type name and the latter holds the marshalled state.\n\n :param typename: registered name of the custom type\n :param state: the marshalled state of the object\n :return: an object serializable by the serializer\n\n \"\"\"\n return {self.type_key: typename, self.state_key: state}"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef unwrap_state_dict(self, obj: Dict[str, Any]) -> Union[Tuple[str, Any], Tuple[None, None]]:\n if len(obj) == 2:\n typename = obj.get(self.type_key)\n state = obj.get(self.state_key)\n if typename is not None:\n return typename, state\n\n return None, None", "response": "Unwraps a marshalled state dictionary into a tuple of the type and state."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nenabling HTTP access to a dataset.", "response": "def publish(quiet, dataset_uri):\n \"\"\"Enable HTTP access to a dataset.\n\n This only works on datasets in some systems. For example, datasets stored\n in AWS S3 object storage and Microsoft Azure Storage can be published as\n datasets accessible over HTTP. A published dataset is world readable.\n \"\"\"\n access_uri = http_publish(dataset_uri)\n if not quiet:\n click.secho(\"Dataset accessible at \", nl=False, fg=\"green\")\n click.secho(access_uri)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef register_custom_type(\n self, cls: type, marshaller: Optional[Callable[[Any], Any]] = default_marshaller,\n unmarshaller: Union[Callable[[Any, Any], None],\n Callable[[Any], Any], None] = default_unmarshaller, *,\n typename: str = None, wrap_state: bool = True) -> None:\n \"\"\"\n Register a marshaller and/or unmarshaller for the given class.\n\n The state object returned by the marshaller and passed to the unmarshaller can be any\n serializable type. Usually a dictionary mapping of attribute names to values is used.\n\n .. warning:: Registering marshallers/unmarshallers for any custom type will override any\n serializer specific encoding/decoding hooks (respectively) already in place!\n\n :param cls: the class to register\n :param marshaller: a callable that takes the object to be marshalled as the argument and\n returns a state object\n :param unmarshaller: a callable that either:\n\n * takes an uninitialized instance of ``cls`` and its state object as arguments and\n restores the state of the object\n * takes a state object and returns a new instance of ``cls``\n :param typename: a unique identifier for the type (defaults to the ``module:varname``\n reference to the class)\n :param wrap_state: ``True`` to wrap the marshalled state before serialization so that it\n can be recognized later for unmarshalling, ``False`` to serialize it as is\n\n \"\"\"\n assert check_argument_types()\n typename = typename or qualified_name(cls)\n\n if marshaller:\n self.marshallers[cls] = typename, marshaller, wrap_state\n self.custom_type_codec.register_object_encoder_hook(self)\n\n if unmarshaller and self.custom_type_codec is not None:\n target_cls = cls # type: Optional[type]\n if len(signature(unmarshaller).parameters) == 1:\n target_cls = None\n\n self.unmarshallers[typename] = target_cls, unmarshaller\n self.custom_type_codec.register_object_decoder_hook(self)", "response": "Registers a custom type for the given class."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nupdates the descriptive metadata interactively.", "response": "def _prompt_for_values(d):\n \"\"\"Update the descriptive metadata interactively.\n\n Uses values entered by the user. Note that the function keeps recursing\n whenever a value is another ``CommentedMap`` or a ``list``. The\n function works as passing dictionaries and lists into a function edits\n the values in place.\n \"\"\"\n for key, value in d.items():\n if isinstance(value, CommentedMap):\n _prompt_for_values(value)\n elif isinstance(value, list):\n for item in value:\n _prompt_for_values(item)\n else:\n typ = type(value)\n\n if isinstance(value, ScalarFloat): # Deal with ruamel.yaml floats.\n typ = float\n\n new_value = click.prompt(key, type=typ, default=value)\n d[key] = new_value\n return d"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef create(quiet, name, base_uri, symlink_path):\n _validate_name(name)\n\n admin_metadata = dtoolcore.generate_admin_metadata(name)\n parsed_base_uri = dtoolcore.utils.generous_parse_uri(base_uri)\n\n if parsed_base_uri.scheme == \"symlink\":\n if symlink_path is None:\n raise click.UsageError(\"Need to specify symlink path using the -s/--symlink-path option\") # NOQA\n\n if symlink_path:\n base_uri = dtoolcore.utils.sanitise_uri(\n \"symlink:\" + parsed_base_uri.path\n )\n parsed_base_uri = dtoolcore.utils.generous_parse_uri(base_uri)\n\n # Create the dataset.\n proto_dataset = dtoolcore.generate_proto_dataset(\n admin_metadata=admin_metadata,\n base_uri=dtoolcore.utils.urlunparse(parsed_base_uri),\n config_path=CONFIG_PATH)\n\n # If we are creating a symlink dataset we need to set the symlink_path\n # attribute on the storage broker.\n if symlink_path:\n symlink_abspath = os.path.abspath(symlink_path)\n proto_dataset._storage_broker.symlink_path = symlink_abspath\n try:\n proto_dataset.create()\n except dtoolcore.storagebroker.StorageBrokerOSError as err:\n raise click.UsageError(str(err))\n\n proto_dataset.put_readme(\"\")\n\n if quiet:\n click.secho(proto_dataset.uri)\n else:\n # Give the user some feedback and hints on what to do next.\n click.secho(\"Created proto dataset \", nl=False, fg=\"green\")\n click.secho(proto_dataset.uri)\n click.secho(\"Next steps: \")\n\n step = 1\n\n if parsed_base_uri.scheme != \"symlink\":\n click.secho(\"{}. Add raw data, eg:\".format(step))\n click.secho(\n \" dtool add item my_file.txt {}\".format(proto_dataset.uri),\n fg=\"cyan\")\n\n if parsed_base_uri.scheme == \"file\":\n # Find the abspath of the data directory for user feedback.\n data_path = proto_dataset._storage_broker._data_abspath\n click.secho(\" Or use your system commands, e.g: \")\n click.secho(\n \" mv my_data_directory {}/\".format(data_path),\n fg=\"cyan\"\n )\n step = step + 1\n\n click.secho(\"{}. Add descriptive metadata, e.g: \".format(step))\n click.secho(\n \" dtool readme interactive {}\".format(proto_dataset.uri),\n fg=\"cyan\")\n step = step + 1\n\n click.secho(\n \"{}. Convert the proto dataset into a dataset: \".format(step)\n )\n click.secho(\" dtool freeze {}\".format(proto_dataset.uri), fg=\"cyan\")", "response": "Create a new proto dataset."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef name(dataset_uri, new_name):\n if new_name != \"\":\n _validate_name(new_name)\n\n try:\n dataset = dtoolcore.ProtoDataSet.from_uri(\n uri=dataset_uri,\n config_path=CONFIG_PATH\n )\n except dtoolcore.DtoolCoreTypeError:\n dataset = dtoolcore.DataSet.from_uri(\n uri=dataset_uri,\n config_path=CONFIG_PATH\n )\n\n dataset.update_name(new_name)\n\n admin_metadata = dtoolcore._admin_metadata_from_uri(\n uri=dataset_uri,\n config_path=CONFIG_PATH\n )\n click.secho(admin_metadata[\"name\"])", "response": "Update the name of the dataset."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nprompts to populate the readme.", "response": "def interactive(proto_dataset_uri):\n \"\"\"Interactive prompting to populate the readme.\"\"\"\n proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n uri=proto_dataset_uri,\n config_path=CONFIG_PATH)\n\n # Create an CommentedMap representation of the yaml readme template.\n readme_template = _get_readme_template()\n yaml = YAML()\n yaml.explicit_start = True\n yaml.indent(mapping=2, sequence=4, offset=2)\n descriptive_metadata = yaml.load(readme_template)\n\n descriptive_metadata = _prompt_for_values(descriptive_metadata)\n\n # Write out the descriptive metadata to the readme file.\n stream = StringIO()\n\n yaml.dump(descriptive_metadata, stream)\n\n proto_dataset.put_readme(stream.getvalue())\n\n click.secho(\"Updated readme \", fg=\"green\")\n click.secho(\"To edit the readme using your default editor:\")\n click.secho(\n \"dtool readme edit {}\".format(proto_dataset_uri),\n fg=\"cyan\")"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef edit(dataset_uri):\n try:\n dataset = dtoolcore.ProtoDataSet.from_uri(\n uri=dataset_uri,\n config_path=CONFIG_PATH\n )\n except dtoolcore.DtoolCoreTypeError:\n dataset = dtoolcore.DataSet.from_uri(\n uri=dataset_uri,\n config_path=CONFIG_PATH\n )\n readme_content = dataset.get_readme_content()\n\n try:\n # Python2 compatibility.\n readme_content = unicode(readme_content, \"utf-8\")\n except NameError:\n pass\n\n edited_content = click.edit(readme_content)\n if edited_content is not None:\n _validate_and_put_readme(dataset, edited_content)\n click.secho(\"Updated readme \", nl=False, fg=\"green\")\n else:\n click.secho(\"Did not update readme \", nl=False, fg=\"red\")\n click.secho(dataset_uri)", "response": "Default editor updating of readme content."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef show(dataset_uri):\n try:\n dataset = dtoolcore.ProtoDataSet.from_uri(\n uri=dataset_uri,\n config_path=CONFIG_PATH\n )\n except dtoolcore.DtoolCoreTypeError:\n dataset = dtoolcore.DataSet.from_uri(\n uri=dataset_uri,\n config_path=CONFIG_PATH\n )\n readme_content = dataset.get_readme_content()\n click.secho(readme_content)", "response": "Show the descriptive metadata in the readme."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef write(proto_dataset_uri, input):\n proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n uri=proto_dataset_uri\n )\n _validate_and_put_readme(proto_dataset, input.read())", "response": "Write the content of a file or stdin to the README."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nadds a file to the proto dataset.", "response": "def item(proto_dataset_uri, input_file, relpath_in_dataset):\n \"\"\"Add a file to the proto dataset.\"\"\"\n proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n proto_dataset_uri,\n config_path=CONFIG_PATH)\n if relpath_in_dataset == \"\":\n relpath_in_dataset = os.path.basename(input_file)\n proto_dataset.put_item(input_file, relpath_in_dataset)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nadd metadata to a file in the proto dataset.", "response": "def metadata(proto_dataset_uri, relpath_in_dataset, key, value):\n \"\"\"Add metadata to a file in the proto dataset.\"\"\"\n proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n uri=proto_dataset_uri,\n config_path=CONFIG_PATH)\n proto_dataset.add_item_metadata(\n handle=relpath_in_dataset,\n key=key,\n value=value)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef freeze(proto_dataset_uri):\n proto_dataset = dtoolcore.ProtoDataSet.from_uri(\n uri=proto_dataset_uri,\n config_path=CONFIG_PATH\n )\n\n num_items = len(list(proto_dataset._identifiers()))\n max_files_limit = int(dtoolcore.utils.get_config_value(\n \"DTOOL_MAX_FILES_LIMIT\",\n CONFIG_PATH,\n 10000\n ))\n assert isinstance(max_files_limit, int)\n if num_items > max_files_limit:\n click.secho(\n \"Too many items ({} > {}) in proto dataset\".format(\n num_items,\n max_files_limit\n ),\n fg=\"red\"\n )\n click.secho(\"1. Consider splitting the dataset into smaller datasets\")\n click.secho(\"2. Consider packaging small files using tar\")\n click.secho(\"3. Increase the limit using the DTOOL_MAX_FILES_LIMIT\")\n click.secho(\" environment variable\")\n sys.exit(2)\n\n handles = [h for h in proto_dataset._storage_broker.iter_item_handles()]\n for h in handles:\n if not valid_handle(h):\n click.secho(\n \"Invalid item name: {}\".format(h),\n fg=\"red\"\n )\n click.secho(\"1. Consider renaming the item\")\n click.secho(\"2. Consider removing the item\")\n sys.exit(3)\n\n with click.progressbar(length=len(list(proto_dataset._identifiers())),\n label=\"Generating manifest\") as progressbar:\n try:\n proto_dataset.freeze(progressbar=progressbar)\n except dtoolcore.storagebroker.DiskStorageBrokerValidationWarning as e:\n click.secho(\"\")\n click.secho(str(e), fg=\"red\", nl=False)\n sys.exit(4)\n\n click.secho(\"Dataset frozen \", nl=False, fg=\"green\")\n click.secho(proto_dataset_uri)", "response": "Convert a proto dataset into a dataset."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef copy(resume, quiet, dataset_uri, dest_base_uri):\n click.secho(\n \"The ``dtool copy`` command is deprecated\",\n fg=\"red\",\n err=True\n )\n click.secho(\n \"Use ``dtool cp`` instead\",\n fg=\"red\",\n err=True\n )\n _copy(resume, quiet, dataset_uri, dest_base_uri)", "response": "DEPRECATED - Copy a dataset to a different location."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef cp(resume, quiet, dataset_uri, dest_base_uri):\n _copy(resume, quiet, dataset_uri, dest_base_uri)", "response": "Copy a dataset to a different location."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef compress(obj, level=6, return_type=\"bytes\"):\n if isinstance(obj, binary_type):\n b = zlib.compress(obj, level)\n elif isinstance(obj, string_types):\n b = zlib.compress(obj.encode(\"utf-8\"), level)\n else:\n b = zlib.compress(pickle.dumps(obj, protocol=2), level)\n\n if return_type == \"bytes\":\n return b\n elif return_type == \"str\":\n return base64.b64encode(b).decode(\"utf-8\")\n else:\n raise ValueError(\"'return_type' has to be one of 'bytes', 'str'!\")", "response": "Compress a single object to bytes or base64."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _parsems(value):\n if \".\" not in value:\n return int(value), 0\n else:\n i, f = value.split(\".\")\n return int(i), int(f.ljust(6, \"0\")[:6])", "response": "Parse a I [. F ] seconds value into ( seconds microseconds )."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef find_probable_year_index(self, tokens):\n for index, token in enumerate(self):\n potential_year_tokens = _ymd.find_potential_year_tokens(\n token, tokens)\n if len(potential_year_tokens) == 1 and len(potential_year_tokens[0]) > 2:\n return index", "response": "Find the index of the first occurrence of a token in the list that is not longer than 100 year."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nparsing the date or time string into a naive datetime object.", "response": "def parse(self, timestr, default=None, ignoretz=False, tzinfos=None, **kwargs):\n \"\"\"\n Parse the date/time string into a :class:`datetime.datetime` object.\n\n :param timestr:\n Any date/time string using the supported formats.\n\n :param default:\n The default datetime object, if this is a datetime object and not\n ``None``, elements specified in ``timestr`` replace elements in the\n default object.\n\n :param ignoretz:\n If set ``True``, time zones in parsed strings are ignored and a\n naive :class:`datetime.datetime` object is returned.\n\n :param tzinfos:\n Additional time zone names / aliases which may be present in the\n string. This argument maps time zone names (and optionally offsets\n from those time zones) to time zones. This parameter can be a\n dictionary with timezone aliases mapping time zone names to time\n zones or a function taking two parameters (``tzname`` and\n ``tzoffset``) and returning a time zone.\n\n The timezones to which the names are mapped can be an integer\n offset from UTC in minutes or a :class:`tzinfo` object.\n\n .. doctest::\n :options: +NORMALIZE_WHITESPACE\n\n >>> from dateutil.parser import parse\n >>> from dateutil.tz import gettz\n >>> tzinfos = {\"BRST\": -10800, \"CST\": gettz(\"America/Chicago\")}\n >>> parse(\"2012-01-19 17:21:00 BRST\", tzinfos=tzinfos)\n datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -10800))\n >>> parse(\"2012-01-19 17:21:00 CST\", tzinfos=tzinfos)\n datetime.datetime(2012, 1, 19, 17, 21,\n tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago'))\n\n This parameter is ignored if ``ignoretz`` is set.\n\n :param **kwargs:\n Keyword arguments as passed to ``_parse()``.\n\n :return:\n Returns a :class:`datetime.datetime` object or, if the\n ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the\n first element being a :class:`datetime.datetime` object, the second\n a tuple containing the fuzzy tokens.\n\n :raises ValueError:\n Raised for invalid or unknown string format, if the provided\n :class:`tzinfo` is not in a valid format, or if an invalid date\n would be created.\n\n :raises TypeError:\n Raised for non-string or character stream input.\n\n :raises OverflowError:\n Raised if the parsed date exceeds the largest valid C integer on\n your system.\n \"\"\"\n\n if default is None:\n default = datetime.datetime.now().replace(hour=0, minute=0,\n second=0, microsecond=0)\n\n res, skipped_tokens = self._parse(timestr, **kwargs)\n\n if res is None:\n raise ValueError(\"Unknown string format\")\n\n if len(res) == 0:\n raise ValueError(\"String does not contain a date.\")\n\n repl = {}\n for attr in (\"year\", \"month\", \"day\", \"hour\",\n \"minute\", \"second\", \"microsecond\"):\n value = getattr(res, attr)\n if value is not None:\n repl[attr] = value\n\n if 'day' not in repl:\n # If the default day exceeds the last day of the month, fall back to\n # the end of the month.\n cyear = default.year if res.year is None else res.year\n cmonth = default.month if res.month is None else res.month\n cday = default.day if res.day is None else res.day\n\n if cday > monthrange(cyear, cmonth)[1]:\n repl['day'] = monthrange(cyear, cmonth)[1]\n\n ret = default.replace(**repl)\n\n if res.weekday is not None and not res.day:\n ret = ret + relativedelta.relativedelta(weekday=res.weekday)\n\n if not ignoretz:\n if (isinstance(tzinfos, collections.Callable) or\n tzinfos and res.tzname in tzinfos):\n\n if isinstance(tzinfos, collections.Callable):\n tzdata = tzinfos(res.tzname, res.tzoffset)\n else:\n tzdata = tzinfos.get(res.tzname)\n\n if isinstance(tzdata, datetime.tzinfo):\n tzinfo = tzdata\n elif isinstance(tzdata, text_type):\n tzinfo = tz.tzstr(tzdata)\n elif isinstance(tzdata, integer_types):\n tzinfo = tz.tzoffset(res.tzname, tzdata)\n else:\n raise ValueError(\"Offset must be tzinfo subclass, \"\n \"tz string, or int offset.\")\n ret = ret.replace(tzinfo=tzinfo)\n elif res.tzname and res.tzname in time.tzname:\n ret = ret.replace(tzinfo=tz.tzlocal())\n elif res.tzoffset == 0:\n ret = ret.replace(tzinfo=tz.tzutc())\n elif res.tzoffset:\n ret = ret.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset))\n\n if kwargs.get('fuzzy_with_tokens', False):\n return ret, skipped_tokens\n else:\n return ret"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef tzname_in_python2(namefunc):\n def adjust_encoding(*args, **kwargs):\n name = namefunc(*args, **kwargs)\n if name is not None and not PY3:\n name = name.encode()\n\n return name\n\n return adjust_encoding", "response": "Change unicode output into bytestrings in Python 2 and Python 3 changed in Python 3."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns True if the wall time of a given datetime is ambiguous in thisCOOKIE zone.", "response": "def is_ambiguous(self, dt):\n \"\"\"\n Whether or not the \"wall time\" of a given datetime is ambiguous in this\n zone.\n\n :param dt:\n A :py:class:`datetime.datetime`, naive or time zone aware.\n\n\n :return:\n Returns ``True`` if ambiguous, ``False`` otherwise.\n\n .. versionadded:: 2.6.0\n \"\"\"\n\n dt = dt.replace(tzinfo=self)\n\n wall_0 = enfold(dt, fold=0)\n wall_1 = enfold(dt, fold=1)\n\n same_offset = wall_0.utcoffset() == wall_1.utcoffset()\n same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None)\n\n return same_dt and not same_offset"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _fold_status(self, dt_utc, dt_wall):\n if self.is_ambiguous(dt_wall):\n delta_wall = dt_wall - dt_utc\n _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst()))\n else:\n _fold = 0\n\n return _fold", "response": "Determines the fold status of a given UTC datetime."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngives a timezone - aware datetime in a given timezone calculates a new object containing the unambiguous entry - set entry for that datetime.", "response": "def _fromutc(self, dt):\n \"\"\"\n Given a timezone-aware datetime in a given timezone, calculates a\n timezone-aware datetime in a new timezone.\n\n Since this is the one time that we *know* we have an unambiguous\n datetime object, we take this opportunity to determine whether the\n datetime is ambiguous and in a \"fold\" state (e.g. if it's the first\n occurence, chronologically, of the ambiguous datetime).\n\n :param dt:\n A timezone-aware :class:`datetime.datetime` object.\n \"\"\"\n\n # Re-implement the algorithm from Python's datetime.py\n dtoff = dt.utcoffset()\n if dtoff is None:\n raise ValueError(\"fromutc() requires a non-None utcoffset() \"\n \"result\")\n\n # The original datetime.py code assumes that `dst()` defaults to\n # zero during ambiguous times. PEP 495 inverts this presumption, so\n # for pre-PEP 495 versions of python, we need to tweak the algorithm.\n dtdst = dt.dst()\n if dtdst is None:\n raise ValueError(\"fromutc() requires a non-None dst() result\")\n delta = dtoff - dtdst\n\n dt += delta\n # Set fold=1 so we can default to being in the fold for\n # ambiguous dates.\n dtdst = enfold(dt, fold=1).dst()\n if dtdst is None:\n raise ValueError(\"fromutc(): dt.dst gave inconsistent \"\n \"results; cannot convert\")\n return dt + dtdst"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncalculating a from a timezone - aware datetime in a given timezone.", "response": "def fromutc(self, dt):\n \"\"\"\n Given a timezone-aware datetime in a given timezone, calculates a\n timezone-aware datetime in a new timezone.\n\n Since this is the one time that we *know* we have an unambiguous\n datetime object, we take this opportunity to determine whether the\n datetime is ambiguous and in a \"fold\" state (e.g. if it's the first\n occurance, chronologically, of the ambiguous datetime).\n\n :param dt:\n A timezone-aware :class:`datetime.datetime` object.\n \"\"\"\n dt_wall = self._fromutc(dt)\n\n # Calculate the fold status given the two datetimes.\n _fold = self._fold_status(dt, dt_wall)\n\n # Set the default fold value for ambiguous dates\n return enfold(dt_wall, fold=_fold)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef fromutc(self, dt):\n if not isinstance(dt, datetime):\n raise TypeError(\"fromutc() requires a datetime argument\")\n\n if dt.tzinfo is not self:\n raise ValueError(\"dt.tzinfo is not self\")\n\n # Get transitions - if there are none, fixed offset\n transitions = self.transitions(dt.year)\n if transitions is None:\n return dt + self.utcoffset(dt)\n\n # Get the transition times in UTC\n dston, dstoff = transitions\n\n dston -= self._std_offset\n dstoff -= self._std_offset\n\n utc_transitions = (dston, dstoff)\n dt_utc = dt.replace(tzinfo=None)\n\n isdst = self._naive_isdst(dt_utc, utc_transitions)\n\n if isdst:\n dt_wall = dt + self._dst_offset\n else:\n dt_wall = dt + self._std_offset\n\n _fold = int(not isdst and self.is_ambiguous(dt_wall))\n\n return enfold(dt_wall, fold=_fold)", "response": "Given a datetime in UTC return a new time object."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn True if the wall time of a given datetime is ambiguous in thisCOOKIE zone.", "response": "def is_ambiguous(self, dt):\n \"\"\"\n Whether or not the \"wall time\" of a given datetime is ambiguous in this\n zone.\n\n :param dt:\n A :py:class:`datetime.datetime`, naive or time zone aware.\n\n\n :return:\n Returns ``True`` if ambiguous, ``False`` otherwise.\n\n .. versionadded:: 2.6.0\n \"\"\"\n if not self.hasdst:\n return False\n\n start, end = self.transitions(dt.year)\n\n dt = dt.replace(tzinfo=None)\n return (end <= dt < end + self._dst_base_offset)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef strip_comment_line_with_symbol(line, start):\n parts = line.split(start)\n counts = [len(findall(r'(?:^|[^\"\\\\]|(?:\\\\\\\\|\\\\\")+)(\")', part))\n for part in parts]\n total = 0\n for nr, count in enumerate(counts):\n total += count\n if total % 2 == 0:\n return start.join(parts[:nr + 1]).rstrip()\n else: # pragma: no cover\n return line.rstrip()", "response": "Strip comments from line string."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nstrip comments from json string.", "response": "def strip_comments(string, comment_symbols=frozenset(('#', '//'))):\n \"\"\"Strip comments from json string.\n\n :param string: A string containing json with comments started by comment_symbols.\n :param comment_symbols: Iterable of symbols that start a line comment (default # or //).\n :return: The string with the comments removed.\n \"\"\"\n lines = string.splitlines()\n for k in range(len(lines)):\n for symbol in comment_symbols:\n lines[k] = strip_comment_line_with_symbol(lines[k], start=symbol)\n return '\\n'.join(lines)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nrebuilding the internal timezone info in dateutil / zoneinfo * tar * file", "response": "def rebuild(filename, tag=None, format=\"gz\", zonegroups=[], metadata=None):\n \"\"\"Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*\n\n filename is the timezone tarball from ftp.iana.org/tz.\n\n \"\"\"\n tmpdir = tempfile.mkdtemp()\n zonedir = os.path.join(tmpdir, \"zoneinfo\")\n moduledir = os.path.dirname(__file__)\n try:\n with tar_open(filename) as tf:\n for name in zonegroups:\n tf.extract(name, tmpdir)\n filepaths = [os.path.join(tmpdir, n) for n in zonegroups]\n try:\n check_call([\"zic\", \"-d\", zonedir] + filepaths)\n except OSError as e:\n _print_on_nosuchfile(e)\n raise\n # write metadata file\n with open(os.path.join(zonedir, METADATA_FN), 'w') as f:\n json.dump(metadata, f, indent=4, sort_keys=True)\n target = os.path.join(moduledir, ZONEFILENAME)\n with tar_open(target, \"w:%s\" % format) as tf:\n for entry in os.listdir(zonedir):\n entrypath = os.path.join(zonedir, entry)\n tf.add(entrypath, entry)\n finally:\n shutil.rmtree(tmpdir)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\npicking the nth weekday of the given dayofweek.", "response": "def picknthweekday(year, month, dayofweek, hour, minute, whichweek):\n \"\"\" dayofweek == 0 means Sunday, whichweek 5 means last instance \"\"\"\n first = datetime.datetime(year, month, 1, hour, minute)\n\n # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6),\n # Because 7 % 7 = 0\n weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1)\n wd = weekdayone + ((whichweek - 1) * ONEWEEK)\n if (wd.month != month):\n wd -= ONEWEEK\n\n return wd"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef valuestodict(key):\n dout = {}\n size = winreg.QueryInfoKey(key)[1]\n tz_res = None\n\n for i in range(size):\n key_name, value, dtype = winreg.EnumValue(key, i)\n if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN:\n # If it's a DWORD (32-bit integer), it's stored as unsigned - convert\n # that to a proper signed integer\n if value & (1 << 31):\n value = value - (1 << 32)\n elif dtype == winreg.REG_SZ:\n # If it's a reference to the tzres DLL, load the actual string\n if value.startswith('@tzres'):\n tz_res = tz_res or tzres()\n value = tz_res.name_from_string(value)\n\n value = value.rstrip('\\x00') # Remove trailing nulls\n\n dout[key_name] = value\n\n return dout", "response": "Convert a registry key s values to a dictionary."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef load_name(self, offset):\n resource = self.p_wchar()\n lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR)\n nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0)\n return resource[:nchar]", "response": "Load a timezone name from a DLL offset."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef name_from_string(self, tzname_str):\n if not tzname_str.startswith('@'):\n return tzname_str\n\n name_splt = tzname_str.split(',-')\n try:\n offset = int(name_splt[1])\n except:\n raise ValueError(\"Malformed timezone string.\")\n\n return self.load_name(offset)", "response": "Parse a string into a localized time zone name."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef transitions(self, year):\n\n if not self.hasdst:\n return None\n\n dston = picknthweekday(year, self._dstmonth, self._dstdayofweek,\n self._dsthour, self._dstminute,\n self._dstweeknumber)\n\n dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek,\n self._stdhour, self._stdminute,\n self._stdweeknumber)\n\n # Ambiguous dates default to the STD side\n dstoff -= self._dst_base_offset\n\n return dston, dstoff", "response": "Returns the DST on and off transition times expressed\n always on the standard time side."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_zonefile_instance(new_instance=False):\n if new_instance:\n zif = None\n else:\n zif = getattr(get_zonefile_instance, '_cached_instance', None)\n\n if zif is None:\n zif = ZoneInfoFile(getzoneinfofile_stream())\n\n get_zonefile_instance._cached_instance = zif\n\n return zif", "response": "Returns a new instance of the ZoneInfoFile class."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a time zone object for the given name.", "response": "def gettz(name):\n \"\"\"\n This retrieves a time zone from the local zoneinfo tarball that is packaged\n with dateutil.\n\n :param name:\n An IANA-style time zone name, as found in the zoneinfo file.\n\n :return:\n Returns a :class:`dateutil.tz.tzfile` time zone object.\n\n .. warning::\n It is generally inadvisable to use this function, and it is only\n provided for API compatibility with earlier versions. This is *not*\n equivalent to ``dateutil.tz.gettz()``, which selects an appropriate\n time zone based on the inputs, favoring system zoneinfo. This is ONLY\n for accessing the dateutil-specific zoneinfo (which may be out of\n date compared to the system zoneinfo).\n\n .. deprecated:: 2.6\n If you need to use a specific zoneinfofile over the system zoneinfo,\n instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call\n :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead.\n\n Use :func:`get_zonefile_instance` to retrieve an instance of the\n dateutil-provided zoneinfo.\n \"\"\"\n warnings.warn(\"zoneinfo.gettz() will be removed in future versions, \"\n \"to use the dateutil-provided zoneinfo files, instantiate a \"\n \"ZoneInfoFile object and use ZoneInfoFile.zones.get() \"\n \"instead. See the documentation for details.\",\n DeprecationWarning)\n\n if len(_CLASS_ZONE_INSTANCE) == 0:\n _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))\n return _CLASS_ZONE_INSTANCE[0].zones.get(name)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef gettz_db_metadata():\n warnings.warn(\"zoneinfo.gettz_db_metadata() will be removed in future \"\n \"versions, to use the dateutil-provided zoneinfo files, \"\n \"ZoneInfoFile object and query the 'metadata' attribute \"\n \"instead. See the documentation for details.\",\n DeprecationWarning)\n\n if len(_CLASS_ZONE_INSTANCE) == 0:\n _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))\n return _CLASS_ZONE_INSTANCE[0].metadata", "response": "Get the zonefile metadata from the database."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngetting the configuration for the given JID based on XMPP_HTTP_UPLOAD_ACCESS.", "response": "def get_config(jid):\n \"\"\"Get the configuration for the given JID based on XMPP_HTTP_UPLOAD_ACCESS.\n\n If the JID does not match any rule, ``False`` is returned.\n \"\"\"\n\n acls = getattr(settings, 'XMPP_HTTP_UPLOAD_ACCESS', (('.*', False), ))\n\n for regex, config in acls:\n if isinstance(regex, six.string_types):\n regex = [regex]\n\n for subex in regex:\n if re.search(subex, jid):\n return config\n\n return False"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngiving a datetime and a time zone determine whether or not a given datetime is in a gap.", "response": "def datetime_exists(dt, tz=None):\n \"\"\"\n Given a datetime and a time zone, determine whether or not a given datetime\n would fall in a gap.\n\n :param dt:\n A :class:`datetime.datetime` (whose time zone will be ignored if ``tz``\n is provided.)\n\n :param tz:\n A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If\n ``None`` or not provided, the datetime's own time zone will be used.\n\n :return:\n Returns a boolean value whether or not the \"wall time\" exists in ``tz``.\n \"\"\"\n if tz is None:\n if dt.tzinfo is None:\n raise ValueError('Datetime is naive and no time zone provided.')\n tz = dt.tzinfo\n\n dt = dt.replace(tzinfo=None)\n\n # This is essentially a test of whether or not the datetime can survive\n # a round trip to UTC.\n dt_rt = dt.replace(tzinfo=tz).astimezone(tzutc()).astimezone(tz)\n dt_rt = dt_rt.replace(tzinfo=None)\n\n return dt == dt_rt"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef datetime_ambiguous(dt, tz=None):\n if tz is None:\n if dt.tzinfo is None:\n raise ValueError('Datetime is naive and no time zone provided.')\n\n tz = dt.tzinfo\n\n # If a time zone defines its own \"is_ambiguous\" function, we'll use that.\n is_ambiguous_fn = getattr(tz, 'is_ambiguous', None)\n if is_ambiguous_fn is not None:\n try:\n return tz.is_ambiguous(dt)\n except:\n pass\n\n # If it doesn't come out and tell us it's ambiguous, we'll just check if\n # the fold attribute has any effect on this particular date and time.\n dt = dt.replace(tzinfo=tz)\n wall_0 = enfold(dt, fold=0)\n wall_1 = enfold(dt, fold=1)\n\n same_offset = wall_0.utcoffset() == wall_1.utcoffset()\n same_dst = wall_0.dst() == wall_1.dst()\n\n return not (same_offset and same_dst)", "response": "Given a datetime and a time zone determine whether or not the wall time of the given datetime is ambiguous."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef is_ambiguous(self, dt):\n naive_dst = self._naive_is_dst(dt)\n return (not naive_dst and\n (naive_dst != self._naive_is_dst(dt - self._dst_saved)))", "response": "Returns True if the wall time of a given datetime is ambiguous in thisCOOKIE zone."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _set_tzdata(self, tzobj):\n # Copy the relevant attributes over as private attributes\n for attr in _tzfile.attrs:\n setattr(self, '_' + attr, getattr(tzobj, attr))", "response": "Set the time zone data of this object from a _tzfile object"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef fromutc(self, dt):\n # These isinstance checks are in datetime.tzinfo, so we'll preserve\n # them, even if we don't care about duck typing.\n if not isinstance(dt, datetime.datetime):\n raise TypeError(\"fromutc() requires a datetime argument\")\n\n if dt.tzinfo is not self:\n raise ValueError(\"dt.tzinfo is not self\")\n\n # First treat UTC as wall time and get the transition we're in.\n idx = self._find_last_transition(dt, in_utc=True)\n tti = self._get_ttinfo(idx)\n\n dt_out = dt + datetime.timedelta(seconds=tti.offset)\n\n fold = self.is_ambiguous(dt_out, idx=idx)\n\n return enfold(dt_out, fold=int(fold))", "response": "Returns a new object representing the object in the time zone from the given datetime."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef is_ambiguous(self, dt, idx=None):\n if idx is None:\n idx = self._find_last_transition(dt)\n\n # Calculate the difference in offsets from current to previous\n timestamp = _datetime_to_timestamp(dt)\n tti = self._get_ttinfo(idx)\n\n if idx is None or idx <= 0:\n return False\n\n od = self._get_ttinfo(idx - 1).offset - tti.offset\n tt = self._trans_list[idx] # Transition time\n\n return timestamp < tt + od", "response": "Returns True if the wall time of a given datetime is ambiguous in thisCOOKIE zone."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef transitions(self, year):\n if not self.hasdst:\n return None\n\n base_year = datetime.datetime(year, 1, 1)\n\n start = base_year + self._start_delta\n end = base_year + self._end_delta\n\n return (start, end)", "response": "Returns the DST on and off transition times expressed\n always on the standard time side."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get(self, tzid=None):\n if tzid is None:\n if len(self._vtz) == 0:\n raise ValueError(\"no timezones defined\")\n elif len(self._vtz) > 1:\n raise ValueError(\"more than one timezone available\")\n tzid = next(iter(self._vtz))\n\n return self._vtz.get(tzid)", "response": "Retrieves a time zone object by its tzid."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef normalized(self):\n # Cascade remainders down (rounding each to roughly nearest\n # microsecond)\n days = int(self.days)\n\n hours_f = round(self.hours + 24 * (self.days - days), 11)\n hours = int(hours_f)\n\n minutes_f = round(self.minutes + 60 * (hours_f - hours), 10)\n minutes = int(minutes_f)\n\n seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8)\n seconds = int(seconds_f)\n\n microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds))\n\n # Constructor carries overflow back up with call to _fix()\n return self.__class__(years=self.years, months=self.months,\n days=days, hours=hours, minutes=minutes,\n seconds=seconds, microseconds=microseconds,\n leapdays=self.leapdays, year=self.year,\n month=self.month, day=self.day,\n weekday=self.weekday, hour=self.hour,\n minute=self.minute, second=self.second,\n microsecond=self.microsecond)", "response": "Return a version of this object represented entirely using integer\n values for the relative attributes."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_algorithm(alg: str) -> Callable:\n if alg not in algorithms:\n raise ValueError('Invalid algorithm: {:s}'.format(alg))\n return algorithms[alg]", "response": "Returns a function that returns the requested algorithm."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _hash(secret: bytes, data: bytes, alg: str) -> bytes:\n algorithm = get_algorithm(alg)\n return hmac \\\n .new(secret, msg=data, digestmod=algorithm) \\\n .digest()", "response": "Create a new HMAC hash."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nencode the payload and header in a new token.", "response": "def encode(secret: Union[str, bytes], payload: dict = None,\n alg: str = default_alg, header: dict = None) -> str:\n \"\"\"\n :param secret: The secret used to encode the token.\n :type secret: Union[str, bytes]\n :param payload: The payload to be encoded in the token.\n :type payload: dict\n :param alg: The algorithm used to hash the token.\n :type alg: str\n :param header: The header to be encoded in the token.\n :type header: dict\n :return: A new token\n :rtype: str\n \"\"\"\n secret = util.to_bytes(secret)\n\n payload = payload or {}\n header = header or {}\n\n header_json = util.to_bytes(json.dumps(header))\n header_b64 = util.b64_encode(header_json)\n payload_json = util.to_bytes(json.dumps(payload))\n payload_b64 = util.b64_encode(payload_json)\n\n pre_signature = util.join(header_b64, payload_b64)\n signature = _hash(secret, pre_signature, alg)\n signature_b64 = util.b64_encode(signature)\n\n token = util.join(pre_signature, signature_b64)\n return util.from_bytes(token)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ndecoding the given token and validates the signature.", "response": "def decode(secret: Union[str, bytes], token: Union[str, bytes],\n alg: str = default_alg) -> Tuple[dict, dict]:\n \"\"\"\n Decodes the given token's header and payload and validates the signature.\n\n :param secret: The secret used to decode the token. Must match the\n secret used when creating the token.\n :type secret: Union[str, bytes]\n :param token: The token to decode.\n :type token: Union[str, bytes]\n :param alg: The algorithm used to decode the token. Must match the\n algorithm used when creating the token.\n :type alg: str\n :return: The decoded header and payload.\n :rtype: Tuple[dict, dict]\n \"\"\"\n secret = util.to_bytes(secret)\n token = util.to_bytes(token)\n pre_signature, signature_segment = token.rsplit(b'.', 1)\n header_b64, payload_b64 = pre_signature.split(b'.')\n try:\n header_json = util.b64_decode(header_b64)\n header = json.loads(util.from_bytes(header_json))\n except (json.decoder.JSONDecodeError, UnicodeDecodeError, ValueError):\n raise InvalidHeaderError('Invalid header')\n try:\n payload_json = util.b64_decode(payload_b64)\n payload = json.loads(util.from_bytes(payload_json))\n except (json.decoder.JSONDecodeError, UnicodeDecodeError, ValueError):\n raise InvalidPayloadError('Invalid payload')\n\n if not isinstance(header, dict):\n raise InvalidHeaderError('Invalid header: {}'.format(header))\n if not isinstance(payload, dict):\n raise InvalidPayloadError('Invalid payload: {}'.format(payload))\n\n signature = util.b64_decode(signature_segment)\n calculated_signature = _hash(secret, pre_signature, alg)\n\n if not compare_signature(signature, calculated_signature):\n raise InvalidSignatureError('Invalid signature')\n return header, payload"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ncompares the given signature and returns True if the signature matches.", "response": "def compare_signature(expected: Union[str, bytes],\n actual: Union[str, bytes]) -> bool:\n \"\"\"\n Compares the given signatures.\n\n :param expected: The expected signature.\n :type expected: Union[str, bytes]\n :param actual: The actual signature.\n :type actual: Union[str, bytes]\n :return: Do the signatures match?\n :rtype: bool\n \"\"\"\n expected = util.to_bytes(expected)\n actual = util.to_bytes(actual)\n return hmac.compare_digest(expected, actual)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ncompare the given tokens. :param expected: The expected token. :type expected: Union[str, bytes] :param actual: The actual token. :type actual: Union[str, bytes] :return: Do the tokens match? :rtype: bool", "response": "def compare_token(expected: Union[str, bytes],\n actual: Union[str, bytes]) -> bool:\n \"\"\"\n Compares the given tokens.\n\n :param expected: The expected token.\n :type expected: Union[str, bytes]\n :param actual: The actual token.\n :type actual: Union[str, bytes]\n :return: Do the tokens match?\n :rtype: bool\n \"\"\"\n expected = util.to_bytes(expected)\n actual = util.to_bytes(actual)\n _, expected_sig_seg = expected.rsplit(b'.', 1)\n _, actual_sig_seg = actual.rsplit(b'.', 1)\n expected_sig = util.b64_decode(expected_sig_seg)\n actual_sig = util.b64_decode(actual_sig_seg)\n return compare_signature(expected_sig, actual_sig)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn the token header.", "response": "def header(self) -> dict:\n \"\"\"\n :return: Token header.\n :rtype: dict\n \"\"\"\n header = {}\n if isinstance(self._header, dict):\n header = self._header.copy()\n header.update(self._header)\n header.update({\n 'type': 'JWT',\n 'alg': self.alg\n })\n return header"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn True if the token is valid.", "response": "def valid(self, time: int = None) -> bool:\n \"\"\"\n Is the token valid? This method only checks the timestamps within the\n token and compares them against the current time if none is provided.\n\n :param time: The timestamp to validate against\n :type time: Union[int, None]\n :return: The validity of the token.\n :rtype: bool\n \"\"\"\n if time is None:\n epoch = datetime(1970, 1, 1, 0, 0, 0)\n now = datetime.utcnow()\n time = int((now - epoch).total_seconds())\n if isinstance(self.valid_from, int) and time < self.valid_from:\n return False\n if isinstance(self.valid_to, int) and time > self.valid_to:\n return False\n return True"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _pop_claims_from_payload(self):\n claims_in_payload = [k for k in self.payload.keys() if\n k in registered_claims.values()]\n for name in claims_in_payload:\n self.registered_claims[name] = self.payload.pop(name)", "response": "Pop claims from the payload and update the self. registered_claims property."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef encode(self) -> str:\n payload = {}\n payload.update(self.registered_claims)\n payload.update(self.payload)\n return encode(self.secret, payload, self.alg, self.header)", "response": "Encode the data held in the class into a token."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef decode(secret: Union[str, bytes], token: Union[str, bytes],\n alg: str = default_alg) -> 'Jwt':\n \"\"\"\n Decodes the given token into an instance of `Jwt`.\n\n :param secret: The secret used to decode the token. Must match the\n secret used when creating the token.\n :type secret: Union[str, bytes]\n :param token: The token to decode.\n :type token: Union[str, bytes]\n :param alg: The algorithm used to decode the token. Must match the\n algorithm used when creating the token.\n :type alg: str\n :return: The decoded token.\n :rtype: `Jwt`\n \"\"\"\n header, payload = decode(secret, token, alg)\n return Jwt(secret, payload, alg, header)", "response": "Decodes the given token into an instance of Jwt."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncompare this Jwt with another Jwt.", "response": "def compare(self, jwt: 'Jwt', compare_dates: bool = False) -> bool:\n \"\"\"\n Compare against another `Jwt`.\n\n :param jwt: The token to compare against.\n :type jwt: Jwt\n :param compare_dates: Should the comparision take dates into account?\n :type compare_dates: bool\n :return: Are the two Jwt's the same?\n :rtype: bool\n \"\"\"\n if self.secret != jwt.secret:\n return False\n if self.payload != jwt.payload:\n return False\n if self.alg != jwt.alg:\n return False\n if self.header != jwt.header:\n return False\n expected_claims = self.registered_claims\n actual_claims = jwt.registered_claims\n if not compare_dates:\n strip = ['exp', 'nbf', 'iat']\n expected_claims = {k: {v if k not in strip else None} for k, v in\n expected_claims.items()}\n actual_claims = {k: {v if k not in strip else None} for k, v in\n actual_claims.items()}\n if expected_claims != actual_claims:\n return False\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nbase 64 encode data.", "response": "def b64_encode(data: bytes) -> bytes:\n \"\"\"\n :param data: Data the encode.\n :type data: bytes\n :return: Base 64 encoded data with padding removed.\n :rtype: bytes\n \"\"\"\n encoded = urlsafe_b64encode(data)\n return encoded.replace(b'=', b'')"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef b64_decode(data: bytes) -> bytes:\n missing_padding = len(data) % 4\n if missing_padding != 0:\n data += b'=' * (4 - missing_padding)\n return urlsafe_b64decode(data)", "response": "Decode base 64 encoded data."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nconvert data to bytes.", "response": "def to_bytes(data: Union[str, bytes]) -> bytes:\n \"\"\"\n :param data: Data to convert to bytes.\n :type data: Union[str, bytes]\n :return: `data` encoded to UTF8.\n :rtype: bytes\n \"\"\"\n if isinstance(data, bytes):\n return data\n return data.encode('utf-8')"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ndecoding a UTF8 byte string into a base64 - encoded version of the object.", "response": "def from_bytes(data: Union[str, bytes]) -> str:\n \"\"\"\n :param data: A UTF8 byte string.\n :type data: Union[str, bytes]\n :return: `data` decoded from UTF8.\n :rtype: str\n \"\"\"\n if isinstance(data, str):\n return data\n return str(data, 'utf-8')"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef camelize_classname(base, tablename, table):\n \"Produce a 'camelized' class name, e.g. \"\n \"'words_and_underscores' -> 'WordsAndUnderscores'\"\n return str(tablename[0].upper() +\n re.sub(r'_([a-z])', lambda m: m.group(1).upper(),\n tablename[1:]))", "response": "Produce a camelized class name e. g. words_and_underscores -> words_and_underscores"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nproduce an uncamelized pluralized class name e. g.", "response": "def pluralize_collection(base, local_cls, referred_cls, constraint):\n \"Produce an 'uncamelized', 'pluralized' class name, e.g. \"\n \"'SomeTerm' -> 'some_terms'\"\n referred_name = referred_cls.__name__\n uncamelized = re.sub(r'[A-Z]',\n lambda m: \"_%s\" % m.group(0).lower(),\n referred_name)[1:]\n pluralized = _pluralizer.plural(uncamelized)\n return pluralized"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef is_compressed_json_file(abspath):\n abspath = abspath.lower()\n fname, ext = os.path.splitext(abspath)\n if ext in [\".json\", \".js\"]:\n is_compressed = False\n elif ext == \".gz\":\n is_compressed = True\n else:\n raise ValueError(\n \"'%s' is not a valid json file. \"\n \"extension has to be '.json' or '.js' for uncompressed, '.gz' \"\n \"for compressed.\" % abspath)\n return is_compressed", "response": "Test a file is a valid json file."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ndumps a set into a dictionary.", "response": "def dump_set(self, obj, class_name=set_class_name):\n \"\"\"\n ``set`` dumper.\n \"\"\"\n return {\"$\" + class_name: [self._json_convert(item) for item in obj]}"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef dump_deque(self, obj, class_name=\"collections.deque\"):\n return {\"$\" + class_name: [self._json_convert(item) for item in obj]}", "response": "Dump a deque into a JSON - compatible dict."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndumping an OrderedDict into a dictionary.", "response": "def dump_OrderedDict(self, obj, class_name=\"collections.OrderedDict\"):\n \"\"\"\n ``collections.OrderedDict`` dumper.\n \"\"\"\n return {\n \"$\" + class_name: [\n (key, self._json_convert(value)) for key, value in iteritems(obj)\n ]\n }"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef dump_nparray(self, obj, class_name=numpy_ndarray_class_name):\n return {\"$\" + class_name: self._json_convert(obj.tolist())}", "response": "Dump a numpy. ndarray into a dictionary."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _invalidates_cache(f):\n\n def inner_func(self, *args, **kwargs):\n rv = f(self, *args, **kwargs)\n self._invalidate_cache()\n return rv\n\n return inner_func", "response": "Decorator for rruleset methods which may invalidate the cached length."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef before(self, dt, inc=False):\n if self._cache_complete:\n gen = self._cache\n else:\n gen = self\n last = None\n if inc:\n for i in gen:\n if i > dt:\n break\n last = i\n else:\n for i in gen:\n if i >= dt:\n break\n last = i\n return last", "response": "Returns the last recurrence before the given datetime instance."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef after(self, dt, inc=False):\n if self._cache_complete:\n gen = self._cache\n else:\n gen = self\n if inc:\n for i in gen:\n if i >= dt:\n return i\n else:\n for i in gen:\n if i > dt:\n return i\n return None", "response": "Returns the first recurrence after the given datetime instance."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef xafter(self, dt, count=None, inc=False):\n\n if self._cache_complete:\n gen = self._cache\n else:\n gen = self\n\n # Select the comparison function\n if inc:\n def comp(dc, dtc): return dc >= dtc\n else:\n def comp(dc, dtc): return dc > dtc\n\n # Generate dates\n n = 0\n for d in gen:\n if comp(d, dt):\n if count is not None:\n n += 1\n if n > count:\n break\n\n yield d", "response": "Generator which yields up to count recurrences after the given datetime instance."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef replace(self, **kwargs):\n new_kwargs = {\"interval\": self._interval,\n \"count\": self._count,\n \"dtstart\": self._dtstart,\n \"freq\": self._freq,\n \"until\": self._until,\n \"wkst\": self._wkst,\n \"cache\": False if self._cache is None else True}\n new_kwargs.update(self._original_rule)\n new_kwargs.update(kwargs)\n return rrule(**new_kwargs)", "response": "Return a new rrule with same attributes except for those attributes given new\n values by whichever keyword arguments are specified."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nconstructs a set of all possible values for a given frequency range.", "response": "def __construct_byset(self, start, byxxx, base):\n \"\"\"\n If a `BYXXX` sequence is passed to the constructor at the same level as\n `FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some\n specifications which cannot be reached given some starting conditions.\n\n This occurs whenever the interval is not coprime with the base of a\n given unit and the difference between the starting position and the\n ending position is not coprime with the greatest common denominator\n between the interval and the base. For example, with a FREQ of hourly\n starting at 17:00 and an interval of 4, the only valid values for\n BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not\n coprime.\n\n :param start:\n Specifies the starting position.\n :param byxxx:\n An iterable containing the list of allowed values.\n :param base:\n The largest allowable value for the specified frequency (e.g.\n 24 hours, 60 minutes).\n\n This does not preserve the type of the iterable, returning a set, since\n the values should be unique and the order is irrelevant, this will\n speed up later lookups.\n\n In the event of an empty set, raises a :exception:`ValueError`, as this\n results in an empty rrule.\n \"\"\"\n\n cset = set()\n\n # Support a single byxxx value.\n if isinstance(byxxx, integer_types):\n byxxx = (byxxx, )\n\n for num in byxxx:\n i_gcd = gcd(self._interval, base)\n # Use divmod rather than % because we need to wrap negative nums.\n if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0:\n cset.add(num)\n\n if len(cset) == 0:\n raise ValueError(\"Invalid rrule byxxx generates an empty set.\")\n\n return cset"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef __mod_distance(self, value, byxxx, base):\n accumulator = 0\n for ii in range(1, base + 1):\n # Using divmod() over % to account for negative intervals\n div, value = divmod(value + self._interval, base)\n accumulator += div\n if value in byxxx:\n return (accumulator, value)", "response": "Calculates the distance between the value and the next specified value in byxxx."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs):\n l = []\n for wday in value.split(','):\n if '(' in wday:\n # If it's of the form TH(+1), etc.\n splt = wday.split('(')\n w = splt[0]\n n = int(splt[1][:-1])\n elif len(wday):\n # If it's of the form +1MO\n for i in range(len(wday)):\n if wday[i] not in '+-0123456789':\n break\n n = wday[:i] or None\n w = wday[i:]\n if n:\n n = int(n)\n else:\n raise ValueError(\"Invalid (empty) BYDAY specification.\")\n\n l.append(weekdays[self._weekday_map[w]](n))\n rrkwargs[\"byweekday\"] = l", "response": "Handle BYDAY keyword arguments."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncalculating what percentage a given number is of another, e.g. 50 is 50% of 100.", "response": "def run_get_percentage():\n \"\"\"\n Calculate what percentage a given number is of another,\n e.g. 50 is 50% of 100.\n \"\"\"\n description = run_get_percentage.__doc__\n parser = argparse.ArgumentParser(\n prog='get_percentage',\n description=description,\n epilog=\"Example use: get_percentage 25 100\",\n )\n parser.add_argument(\n 'a', help='Integer or floating point number that is a percent of another number'\n )\n parser.add_argument(\n 'b',\n help='Integer or floating point number of which the first number is a percent',\n )\n args = parser.parse_args()\n print(sm.get_percentage(float(args.a), float(args.b)))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nrun the excel_to_html function from the command - line.", "response": "def run_excel_to_html():\n \"\"\"\n Run the excel_to_html function from the\n command-line.\n\n Args:\n -p path to file\n -s name of the sheet to convert\n -css classes to apply\n -m attempt to combine merged cells\n -c caption for accessibility\n -su summary for accessibility\n -d details for accessibility\n\n Example use:\n\n excel_to_html -p myfile.xlsx -s SheetName -css diablo-python -m true\n \"\"\"\n # Capture commandline arguments. prog='' argument must\n # match the command name in setup.py entry_points\n parser = argparse.ArgumentParser(prog='excel_to_html')\n parser.add_argument('-p', nargs='?', help='Path to an excel file for conversion.')\n parser.add_argument(\n '-s',\n nargs='?',\n help='The name of a sheet in our excel file. Defaults to \"Sheet1\".',\n )\n parser.add_argument(\n '-css', nargs='?', help='Space separated css classes to append to the table.'\n )\n parser.add_argument(\n '-m', action='store_true', help='Merge, attempt to combine merged cells.'\n )\n parser.add_argument(\n '-c', nargs='?', help='Caption for creating an accessible table.'\n )\n parser.add_argument(\n '-d',\n nargs='?',\n help='Two strings separated by a | character. The first string \\\n is for the html \"summary\" attribute and the second string is for the html \"details\" attribute. \\\n both values must be provided and nothing more.',\n )\n parser.add_argument(\n '-r', action='store_true', help='Row headers. Does the table have row headers?'\n )\n\n args = parser.parse_args()\n inputs = {\n 'p': args.p,\n 's': args.s,\n 'css': args.css,\n 'm': args.m,\n 'c': args.c,\n 'd': args.d,\n 'r': args.r,\n }\n\n p = inputs['p']\n s = inputs['s'] if inputs['s'] else 'Sheet1'\n css = inputs['css'] if inputs['css'] else ''\n m = inputs['m'] if inputs['m'] else False\n c = inputs['c'] if inputs['c'] else ''\n d = inputs['d'].split('|') if inputs['d'] else []\n r = inputs['r'] if inputs['r'] else False\n\n html = fp.excel_to_html(\n p, sheetname=s, css_classes=css, caption=c, details=d, row_headers=r, merge=m\n )\n\n print(html)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngetting the return string for a language that s supported by python.", "response": "def get_built_in(self, language, level, data):\n \"\"\"\n Gets the return string for a language that's supported by python.\n Used in cases when python provides support for the conversion.\n \n Args:\n language: string the langage to return for.\n\n level: integer, the indentation level.\n\n data: python data structure being converted (list of tuples)\n\n Returns:\n None, updates self.data_structure \n \"\"\"\n # Language is python\n pp = pprint.PrettyPrinter(indent=level)\n\n lookup = {'python' : pp.pformat(data),\n 'json' : str(json.dumps(data, sort_keys=True, indent=level, separators=(',', ': ')))}\n\n self.data_structure = lookup[language]"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the inner template for the given language and type.", "response": "def get_inner_template(self, language, template_type, indentation, key, val):\n \"\"\"\n Gets the requested template for the given language.\n\n Args:\n language: string, the language of the template to look for.\n\n template_type: string, 'iterable' or 'singular'. \n An iterable template is needed when the value is an iterable\n and needs more unpacking, e.g. list, tuple. A singular template \n is needed when unpacking is complete and the value is singular, \n e.g. string, int, float.\n\n indentation: int, the indentation level.\n \n key: multiple types, the array key.\n\n val: multiple types, the array values\n\n Returns:\n string, template formatting for arrays by language.\n \"\"\"\n #Language specific inner templates\n inner_templates = {'php' : {\n 'iterable' : '%s%s => array \\n%s( \\n%s%s),\\n' % (indentation, key, indentation, val, indentation),\n 'singular' : '%s%s => %s, \\n' % (indentation, key, val) },\n 'javascript' : {\n 'iterable' : '%s%s : {\\n%s\\n%s},\\n' % (indentation, key, val, indentation),\n 'singular' : '%s%s: %s,\\n' % (indentation, key, val)},\n 'ocaml' : { \n 'iterable' : '%s[| (%s, (\\n%s\\n%s))|] ;;\\n' % (indentation, key, val, indentation),\n 'singular' : '%s(%s, %s);\\n' % (indentation, key, val)}}\n\n return inner_templates[language][template_type]"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ntranslating a string representing a php array into a data structure in the specified language.", "response": "def translate_array(self, string, language, level=3, retdata=False):\n \"\"\"Unserializes a serialized php array and prints it to\n the console as a data structure in the specified language.\n Used to translate or convert a php array into a data structure \n in another language. Currently supports, PHP, Python, Javascript,\n and JSON. \n\n Args:\n string: a string of serialized php\n \n language: a string representing the desired output \n format for the array.\n\n level: integer, indentation level in spaces. \n Defaults to 3.\n\n retdata: boolean, the method will return the string\n in addition to printing it if set to True. Defaults \n to false.\n\n Returns:\n None but prints a string to the console if retdata is \n False, otherwise returns a string.\n \"\"\"\n language = language.lower()\n assert self.is_built_in(language) or language in self.outer_templates, \\\n \"Sorry, \" + language + \" is not a supported language.\"\n\n # Serialized data converted to a python data structure (list of tuples)\n data = phpserialize.loads(bytes(string, 'utf-8'), array_hook=list, decode_strings=True)\n\n # If language conversion is supported by python avoid recursion entirely\n # and use a built in library\n if self.is_built_in(language):\n self.get_built_in(language, level, data) \n print(self)\n return self.data_structure if retdata else None\n\n # The language is not supported. Use recursion to build a data structure.\n def loop_print(iterable, level=3):\n \"\"\"\n Loops over a python representation of a php array \n (list of tuples) and constructs a representation in another language.\n Translates a php array into another structure.\n\n Args:\n iterable: list or tuple to unpack.\n\n level: integer, number of spaces to use for indentation\n \"\"\"\n retval = ''\n indentation = ' ' * level\n\n # Base case - variable is not an iterable\n if not self.is_iterable(iterable) or isinstance(iterable, str):\n non_iterable = str(iterable)\n return str(non_iterable)\n \n # Recursive case\n for item in iterable:\n # If item is a tuple it should be a key, value pair\n if isinstance(item, tuple) and len(item) == 2:\n # Get the key value pair\n key = item[0]\n val = loop_print(item[1], level=level+3)\n \n # Translate special values\n val = self.translate_val(language, val) if language in self.lang_specific_values \\\n and val in self.lang_specific_values[language] else val\n \n # Convert keys to their properly formatted strings\n # Integers are not quoted as array keys\n key = str(key) if isinstance(key, int) else '\\'' + str(key) + '\\''\n\n # The first item is a key and the second item is an iterable, boolean\n needs_unpacking = hasattr(item[0],'__iter__') == False \\\n and hasattr(item[1],'__iter__') == True \n\n # The second item is an iterable\n if needs_unpacking:\n retval += self.get_inner_template(language, 'iterable', indentation, key, val)\n # The second item is not an iterable\n else:\n # Convert values to their properly formatted strings\n # Integers and booleans are not quoted as array values\n val = str(val) if val.isdigit() or val in self.lang_specific_values[language].values() else '\\'' + str(val) + '\\''\n\n retval += self.get_inner_template(language, 'singular', indentation, key, val) \n\n return retval\n \n # Execute the recursive call in language specific wrapper template\n self.data_structure = self.outer_templates[language] % (loop_print(data))\n print(self)\n return self.data_structure if retdata else None"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _validate(config):\n for mandatory_key in _mandatory_keys:\n if mandatory_key not in config:\n raise KeyError(mandatory_key)\n for key in config.keys():\n if key not in _mandatory_keys and key not in _optional_keys:\n raise SyntaxError(key)\n if not isinstance(config[key], _default_config[key].__class__):\n raise ValueError(key)", "response": "Validate the config dictionary for the key sequence."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _create_default_config():\n config_path = _get_config_path()\n with open(config_path, 'w+') as f:\n yaml.dump(_default_config, f, default_flow_style=False)", "response": "Writes the default configuration to the appropriate place."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef reusable(func):\n sig = signature(func)\n origin = func\n while hasattr(origin, '__wrapped__'):\n origin = origin.__wrapped__\n return type(\n origin.__name__,\n (ReusableGenerator, ),\n dict([\n ('__doc__', origin.__doc__),\n ('__module__', origin.__module__),\n ('__signature__', sig),\n ('__wrapped__', staticmethod(func)),\n ] + [\n (name, property(compose(itemgetter(name),\n attrgetter('_bound_args.arguments'))))\n for name in sig.parameters\n ] + ([\n ('__qualname__', origin.__qualname__),\n ] if sys.version_info > (3, ) else [])))", "response": "Create a reusable class from a generator function."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsending an item into a generator expecting a final return value", "response": "def sendreturn(gen, value):\n \"\"\"Send an item into a generator expecting a final return value\n\n Parameters\n ----------\n gen: ~typing.Generator[T_yield, T_send, T_return]\n the generator to send the value to\n value: T_send\n the value to send\n\n Raises\n ------\n RuntimeError\n if the generator did not return as expected\n\n Returns\n -------\n T_return\n the generator's return value\n \"\"\"\n try:\n gen.send(value)\n except StopIteration as e:\n return stopiter_value(e)\n else:\n raise RuntimeError('generator did not return as expected')"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef imap_send(func, gen):\n gen = iter(gen)\n assert _is_just_started(gen)\n yielder = yield_from(gen)\n for item in yielder:\n with yielder:\n yielder.send(func((yield item)))\n return_(yielder.result)", "response": "Apply a function to all send values of a generator."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ncreating a new generator by relaying yield and send interactions through another generator.", "response": "def irelay(gen, thru):\n \"\"\"Create a new generator by relaying yield/send interactions\n through another generator\n\n Parameters\n ----------\n gen: Generable[T_yield, T_send, T_return]\n the original generator\n thru: ~typing.Callable[[T_yield], ~typing.Generator]\n the generator callable through which each interaction is relayed\n\n Returns\n -------\n ~typing.Generator\n the relayed generator\n \"\"\"\n gen = iter(gen)\n assert _is_just_started(gen)\n\n yielder = yield_from(gen)\n for item in yielder:\n with yielder:\n\n subgen = thru(item)\n subyielder = yield_from(subgen)\n for subitem in subyielder:\n with subyielder:\n subyielder.send((yield subitem))\n\n yielder.send(subyielder.result)\n\n return_(yielder.result)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncheck if all command dependencies refers to and existing command. If not raises an error. ProjectfileError will be raised with the problematic dependency and it s command.", "response": "def _data_integrity_check(data):\r\n \"\"\"Checks if all command dependencies refers to and existing command. If not, a ProjectfileError\r\n will be raised with the problematic dependency and it's command.\r\n\r\n :param data: parsed raw data set.\r\n :return: None\r\n \"\"\"\r\n deps = []\r\n for command in data['commands']:\r\n if 'dependencies' in data['commands'][command]:\r\n for d in data['commands'][command]['dependencies']:\r\n deps.append({\r\n 'd': d,\r\n 'c': command\r\n })\r\n for d in deps:\r\n if d['d'] not in data['commands']:\r\n raise error.ProjectfileError({\r\n 'error': error.PROJECTFILE_INVALID_DEPENDENCY.format(d['d'], d['c'])\r\n })"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\npopulate any database related fields that have _getters to populate them with", "response": "def _link_rels(obj, fields=None, save=False, overwrite=False):\n \"\"\"Populate any database related fields (ForeignKeyField, OneToOneField) that have `_get`ters to populate them with\"\"\"\n if not fields:\n meta = obj._meta\n fields = [f.name for f in meta.fields if hasattr(f, 'do_related_class') and not f.primary_key and hasattr(meta, '_get_' + f.name) and hasattr(meta, '_' + f.name)]\n for field in fields:\n # skip fields if they contain non-null data and `overwrite` option wasn't set\n if not overwrite and not isinstance(getattr(obj, field, None), NoneType):\n # print 'skipping %s which already has a value of %s' % (field, getattr(obj, field, None))\n continue\n if hasattr(obj, field):\n setattr(obj, field, getattr(obj, '_' + field, None))\n if save:\n obj.save()\n return obj"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nupdates any database fields that have _getters to populate them with", "response": "def _update(obj, fields=None, save=False, overwrite=False):\n \"\"\"Update/populate any database fields that have `_get`ters to populate them with, regardless of whether they are data fields or related fields\"\"\"\n if not fields:\n meta = obj._meta\n fields = [f.name for f in meta.fields if not f.primary_key and hasattr(meta, '_get_' + f.name) and hasattr(meta, '_' + f.name)]\n # print fields\n fields_updated = []\n for field in fields:\n # skip fields if they contain non-null data and `overwrite` option wasn't set\n if not overwrite and not getattr(obj, field, None) == None:\n # print 'skipping %s which already has a value of %s' % (field, getattr(obj, field, None))\n continue\n # print field\n if hasattr(obj, field):\n # print field, getattr(obj, '_' + field, None)\n setattr(obj, field, getattr(obj, '_' + field, None))\n if getattr(obj, field, None) != None:\n fields_updated += [field]\n if save:\n obj.save()\n return fields_updated"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nprint the traceback and invokes the ipython debugger on any exception in the order they were passed.", "response": "def bug_info(exc_type, exc_value, exc_trace):\n \"\"\"Prints the traceback and invokes the ipython debugger on any exception\n\n Only invokes ipydb if you are outside ipython or python interactive session.\n So scripts must be called from OS shell in order for exceptions to ipy-shell-out.\n\n Dependencies:\n Needs `pip install ipdb`\n\n Arguments:\n exc_type (type): The exception type/class (e.g. RuntimeError)\n exc_value (Exception): The exception instance (e.g. the error message passed to the Exception constructor)\n exc_trace (Traceback): The traceback instance\n \n References:\n http://stackoverflow.com/a/242531/623735\n\n Example Usage:\n $ python -c 'from pug import debug;x=[];x[0]'\n Traceback (most recent call last):\n File \"\", line 1, in \n IndexError: list index out of range\n\n > (1)()\n\n ipdb> x\n []\n ipdb> locals()\n {'__builtins__': , '__package__': None, 'x': [], 'debug': , '__name__': '__main__', '__doc__': None}\n ipdb> \n \"\"\"\n if hasattr(sys, 'ps1') or not sys.stderr.isatty():\n # We are in interactive mode or don't have a tty-like device, so we call the default hook\n sys.__excepthook__(exc_type, exc_value, exc_trace)\n else:\n # Need to import non-built-ins here, so if dependencies haven't been installed, both tracebacks will print\n # (e.g. the ImportError and the Exception that got you here)\n import ipdb\n # We are NOT in interactive mode, print the exception\n traceback.print_exception(exc_type, exc_value, exc_trace)\n print\n # Start the debugger in post-mortem mode.\n ipdb.post_mortem(exc_trace)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncopying a file from its location on the web to a designated place on the local machine.", "response": "def copy_web_file_to_local(file_path, target_path):\n \"\"\"Copies a file from its location on the web to a designated \n place on the local machine.\n\n Args:\n file_path: Complete url of the file to copy, string (e.g. http://fool.com/input.css).\n\n target_path: Path and name of file on the local machine, string. (e.g. /directory/output.css)\n\n Returns:\n None.\n\n \"\"\"\n response = urllib.request.urlopen(file_path)\n f = open(target_path, 'w')\n f.write(response.read()) \n f.close()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get_line_count(fname):\n i = 0\n with open(fname) as f:\n for i, l in enumerate(f):\n pass\n return i + 1", "response": "Counts the number of lines in a file."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef indent_css(f, output):\n line_count = get_line_count(f)\n f = open(f, 'r+')\n output = open(output, 'r+')\n for line in range(line_count):\n string = f.readline().rstrip()\n if len(string) > 0:\n if string[-1] == \";\":\n output.write(\" \" + string + \"\\n\")\n else:\n output.write(string + \"\\n\")\n output.close()\n f.close()", "response": "Indentes css that has not been indented and saves it to a new file."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef add_newlines(f, output, char):\n line_count = get_line_count(f)\n f = open(f, 'r+')\n output = open(output, 'r+')\n for line in range(line_count):\n string = f.readline()\n string = re.sub(char, char + '\\n', string)\n output.write(string)", "response": "Adds line breaks after every occurance of a given character in a file."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nadds a space before a character.", "response": "def add_whitespace_before(char, input_file, output_file):\n \"\"\"Adds a space before a character if there's isn't one already.\n \n Args:\n char: string, character that needs a space before it.\n\n input_file: string, path to file to parse.\n\n output_file: string, path to destination file.\n \n Returns:\n None.\n \"\"\"\n line_count = get_line_count(input_file)\n input_file = open(input_file, 'r')\n output_file = open(output_file, 'r+')\n for line in range(line_count):\n string = input_file.readline()\n # If there's not already a space before the character, add one\n if re.search(r'[a-zA-Z0-9]' + char, string) != None:\n string = re.sub(char, ' ' + char, string)\n output_file.write(string)\n input_file.close()"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreformats poorly written css.", "response": "def reformat_css(input_file, output_file):\n \"\"\"Reformats poorly written css. This function does not validate or fix errors in the code.\n It only gives code the proper indentation. \n\n Args:\n input_file: string, path to the input file.\n\n output_file: string, path to where the reformatted css should be saved. If the target file\n doesn't exist, a new file is created.\n\n Returns:\n None.\n \"\"\"\n # Number of lines in the file.\n line_count = get_line_count(input_file)\n\n # Open source and target files.\n f = open(input_file, 'r+')\n output = open(output_file, 'w')\n\n # Loop over every line in the file.\n for line in range(line_count):\n # Eliminate whitespace at the beginning and end of lines.\n string = f.readline().strip()\n # New lines after { \n string = re.sub('\\{', '{\\n', string)\n # New lines after ; \n string = re.sub('; ', ';', string)\n string = re.sub(';', ';\\n', string)\n # Eliminate whitespace before comments\n string = re.sub('} /*', '}/*', string)\n # New lines after } \n string = re.sub('\\}', '}\\n', string)\n # New lines at the end of comments\n string = re.sub('\\*/', '*/\\n', string)\n # Write to the output file.\n output.write(string)\n\n # Close the files.\n output.close()\n f.close()\n\n # Indent the css.\n indent_css(output_file, output_file)\n\n # Make sure there's a space before every {\n add_whitespace_before(\"{\", output_file, output_file)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef is_int(string):\n try:\n a = float(string)\n b = int(a)\n except ValueError:\n return False\n else:\n return a == b", "response": "Checks if a string is an integer."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef total_hours(input_files):\n hours = 0 \n # Look for singular and plural forms of the word\n # and allow typos.\n allow = set(['hours', 'hour', 'huors', 'huor'])\n for input_file in input_files:\n doc = open(input_file, 'r')\n for line in doc:\n line = line.rstrip()\n data = line.split(' ')\n if (len(data) == 2) and (is_numeric(data[0])) and (data[1].lower() in allow):\n hours += float(data[0])\n doc.close()\n return hours", "response": "Returns the total number of hours spent on a given project."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef clean_strings(iterable):\n retval = []\n for val in iterable:\n try:\n retval.append(val.strip())\n except(AttributeError):\n retval.append(val)\n return retval", "response": "Takes a list of strings and clear whitespace \n on each one."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nconvert an Excel spreadsheet to an html table.", "response": "def excel_to_html(path, sheetname='Sheet1', css_classes='', \\\n caption='', details=[], row_headers=False, merge=False):\n \"\"\"\n Convert an excel spreadsheet to an html table.\n This function supports the conversion of merged \n cells. It can be used in code or run from the \n command-line. If passed the correct arguments\n it can generate fully accessible html.\n\n Args:\n path: string, path to the spreadsheet.\n\n sheetname: string, name of the sheet\n to convert. \n\n css_classes: string, space separated\n classnames to append to the table.\n\n caption: string, a short heading-like \n description of the table.\n\n details: list of strings, where the first\n item in the list is a string for the html \n summary element and the second item is\n a string for the details element. The \n summary should be very short, e.g. \"Help\",\n where as the details element should be a \n long description regarding the purpose or \n how to navigate the table.\n\n row_headers: boolean, defaults to False.\n Does the table have row headers? If set\n to True, the first element in each row\n will be a
element \n instead of a
element.\n \n merge: boolean, whether or not to \n combine cells that were merged in the \n spreadsheet.\n\n Returns:\n string, html table \n \"\"\"\n\n def get_data_on_merged_cells():\n \"\"\"\n Build a datastructure with data \n on merged cells.\n \"\"\"\n # Use this to build support for merged columns and rows???? \n merged_cells = xls.book.sheet_by_name(sheetname).merged_cells\n ds = {}\n for crange in merged_cells:\n rlo, rhi, clo, chi = crange\n for rowx in range(rlo, rhi):\n for colx in range(clo, chi):\n # Cell (rlo, clo) (the top left one) will carry the data and \n # formatting info. The remainder will be recorded as blank cells, \n # but a renderer will apply the formatting info for the top left \n # cell (e.g. border, pattern) to all cells in the range.\n #print(str(rlo) + ' ' + str(clo))\n #print(str(rowx) + ' ' + str(colx))\n parent_cell = (rlo,clo)\n child_cell = (rowx,colx)\n if not parent_cell in ds:\n # Return data structure is a dictionary with numeric tuples \n # as keys. Each tuple holds the x, y coordinates of the cell.\n # The dictionary holds two values:\n # 1. A list with two numbers which represent the x/y count \n # starting at 1 for the current cell.\n # 2. A set describing which direction the cells are merged.\n ds[parent_cell] = [[1,1], set([])]\n else:\n if parent_cell != child_cell and child_cell[0] == parent_cell[0]:\n ds[parent_cell][0][0] += 1\n ds[parent_cell][1].add('right')\n elif parent_cell != child_cell and child_cell[0] > parent_cell[0]:\n if child_cell[1] == parent_cell[1]:\n ds[parent_cell][0][1] += 1\n ds[parent_cell][1].add('down')\n else:\n raise RuntimeError('Something went wrong')\n return ds\n\n\n def mark_cells_going_right(cell, curr_cell, merged_cells):\n \"\"\"\n Add a \"colspan\" attribute and mark empty table \n columns for deletion if they are part of a \n merged cell going right.\n\n Args:\n cell: BeautifulSoup element tag object \n representation of the current cell.\n\n curr_cell: tuple, numeric representation \n of the current cell.\n\n merged_cells: dictionary of of data about \n merged cells.\n \"\"\"\n #if curr_cell in merged_cells and merged_cells[curr_cell][1] == set(['right']):\n try:\n xcount = merged_cells[curr_cell][0][0]\n if xcount > 1: # No colspans on 1\n cell['colspan'] = xcount\n col_count = xcount - 1 \n while col_count > 0:\n cell = cell.find_next_sibling()\n cell['class'] = 'delete'\n col_count -= 1\n except:\n pass\n\n def mark_cells_going_down(cell, curr_cell, merged_cells):\n \"\"\"\n Add a \"rowspan\" attribute and mark empty table \n columns for deletion if they are part of a \n merged cell going down.\n\n Args:\n cell: BeautifulSoup element tag object \n representation of the current cell.\n\n curr_cell: tuple, numeric representation \n of the current cell.\n\n merged_cells: dictionary of of data about \n merged cells.\n \"\"\"\n if curr_cell in merged_cells and merged_cells[curr_cell][1] == set(['down']):\n ycount = merged_cells[curr_cell][0][1]\n cell['rowspan'] = ycount\n row_count = ycount\n for child_row in cell.parent.find_next_siblings(limit=row_count - 1):\n i = 0\n for child in child_row.find_all('td'):\n if i == curr_cell[1]:\n child['class'] = 'delete'\n i += 1\n\n def mark_cells_going_down_and_right(cell, curr_cell, merged_cells):\n \"\"\"\n Add \"rowspan\" and \"colspan\" attributes and mark \n empty columns for deletion if they are part of a \n merged cell going down and to the right diagonally.\n\n Args:\n cell: BeautifulSoup element tag object \n representation of the current cell.\n\n curr_cell: tuple, numeric representation \n of the current cell.\n\n merged_cells: dictionary of of data about \n merged cells.\n \"\"\"\n if curr_cell in merged_cells and \\\n ('down' in merged_cells[curr_cell][1] and \\\n 'right' in merged_cells[curr_cell][1]):\n xcount = merged_cells[curr_cell][0][0]\n ycount = merged_cells[curr_cell][0][1]\n row_count = ycount\n col_count = xcount\n mark_cells_going_right(cell, curr_cell, merged_cells)\n \n flag = False\n for child_row in [cell.parent] + cell.parent.find_all_next('tr', limit=row_count - 1):\n i = 0\n for child in child_row.find_all('td'):\n if i == curr_cell[1]:\n mark_cells_going_right(child, curr_cell, merged_cells)\n if not flag:\n child['colspan'] = col_count\n child['rowspan'] = row_count\n flag = True\n else:\n child['class'] = 'delete'\n i += 1\n\n\n def is_empty_th(string):\n \"\"\"\n Detects if a table cell is left\n empty (is a merged cell).\n\n Args:\n string: string\n \"\"\"\n if string[:8] == 'Unnamed:':\n data = string.split(' ')\n if is_numeric(data[1]):\n return True\n return False\n\n\n def mark_header_cells(html):\n \"\"\"\n Mark header cells for deletion if they \n need to be merged. Also, add colspan\n and scope attributes.\n\n Args: \n html: string\n \"\"\"\n th = html.find_all('th')\n for header in th:\n txt = header.string\n if not is_empty_th(txt):\n header['scope'] = 'col'\n count = 1\n for sibling in header.find_next_siblings():\n if is_empty_th(sibling.string):\n count += 1\n sibling['class'] = 'delete'\n else:\n break\n if count > 1:\n header['colspan'] = count\n header['scope'] = 'colgroup'\n\n\n def create_caption(html, caption):\n \"\"\"\n Create a caption element for an \n accessible table and append it\n to the right part of the tree.\n \n Args:\n html: string\n\n caption: string\n \"\"\"\n ctag = html.new_tag('caption')\n ctag.insert(0, caption)\n html.table.insert(0, ctag)\n\n\n def create_summary_and_details(html, details):\n \"\"\"\n Create a summary and details element\n for an accessible table and insert \n it into the right part of the tree.\n\n Args:\n html: string\n\n details: string\n \"\"\"\n if len(details) != 2:\n msg = 'The \"details\" argument should be a list with two items. ' \\\n + 'The first item should be a string for the html summary ' \\\n + 'and the second should be a long description for the details ' \\\n + 'element. Both of those must be included and nothing else.'\n raise RuntimeError(msg)\n\n summary = details[0]\n details = details[1]\n\n if not caption:\n create_caption(html, caption)\n\n dtag = html.new_tag('details')\n stag = html.new_tag('summary')\n ptag = html.new_tag('p')\n stag.insert(0, summary)\n ptag.insert(0, details)\n dtag.insert(0, stag)\n dtag.append(ptag) \n html.table.caption.insert(1, dtag) \n\n\n def format_properly(html):\n \"\"\"\n Fix bad formatting from beautifulsoup.\n\n Args:\n html: string of html representing \n a table.\n \"\"\"\n return html.replace('\\n ', '').replace('\\n
s if row_headers\n is set to True.\n\n Args:\n html: string, table.\n \"\"\"\n for row in html.tbody.find_all('tr'):\n spans_rows = 'rowspan' in row.td.attrs\n spans_columns = 'colspan' in row.td.attrs\n new_tag = html.new_tag('th')\n new_tag['scope'] = 'row'\n new_tag.string = row.td.string\n if spans_rows:\n new_tag['rowspan'] = row.td.attrs['rowspan']\n new_tag['scope'] = 'rowgroup'\n if spans_columns:\n new_tag['colspan'] = row.td.attrs['colspan']\n row.td.replace_with(new_tag)\n\n\n def beautify(html):\n \"\"\"\n Beautify the html from pandas.\n\n Args:\n html: table markup from pandas.\n \"\"\"\n table = html.find('table')\n first_tr = table.find('tr')\n del table['border']\n del first_tr['style']\n\n return format_properly(html.prettify(formatter='minimal'))\n\n\n def parse_html(html, caption, details):\n \"\"\"\n Use BeautifulSoup to correct the \n html for merged columns and rows.\n What could possibly go wrong?\n\n Args:\n html: string\n\n caption: string\n\n details: list of strings lenght of two\n\n Returns:\n string, modified html\n \"\"\"\n new_html = BeautifulSoup(html, 'html.parser')\n if merge:\n row_num = 1\n # e.g. {(4, 3): [1, 'right'], (2, 1): [1, 'down']}\n merged_cells = get_data_on_merged_cells()\n rows = new_html.find('table').find('tbody').find_all('tr')\n for row in rows:\n cell_num = 0 # Why are we off by 1? Maybe because we set index to False in to_html?\n cells = row.find_all('td')\n for cell in cells:\n #cell['class'] = str(row_num) + ' ' + str(cell_num) # DEBUG\n curr_cell = (row_num, cell_num)\n\n # Mark merged cells for deletion\n mark_cells_going_right(cell, curr_cell, merged_cells) \n mark_cells_going_down(cell, curr_cell, merged_cells)\n mark_cells_going_down_and_right(cell, curr_cell, merged_cells)\n \n cell_num += 1\n row_num += 1\n\n # Mark header cells for deletion\n mark_header_cells(new_html)\n\n # Delete all the renegade cells at once\n destroy = new_html.find_all(attrs={'class' : 'delete' })\n for item in destroy:\n item.extract()\n\n # Convert
s to
s if needed.\n if row_headers:\n add_row_headers(new_html)\n\n # Add caption if applicable\n if caption:\n create_caption(new_html, caption)\n\n # Add summary and details if possible\n if details:\n create_summary_and_details(new_html, details)\n \n return beautify(new_html)\n\n # Set options for pandas and load the excel file\n pd.options.display.max_colwidth = -1\n xls = pd.ExcelFile(path)\n\n # Parse the sheet you're interested in, results in a Dataframe\n df = xls.parse(sheetname)\n\n # Convert the dataframe to html\n panda_html = df.to_html(classes=css_classes, index=False, na_rep='')\n \n # Parse the panda html to merge cells and beautify the markup \n return parse_html(panda_html, caption, details)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ncalculates the future value of the current value of the aracartor for a given number of years.", "response": "def future_value(present_value, annual_rate, periods_per_year, years):\n \"\"\"\n Calculates the future value of money invested at an anual interest rate,\n x times per year, for a given number of years.\n\n Args:\n present_value: int or float, the current value of the money (principal).\n\n annual_rate: float 0 to 1 e.g., .5 = 50%), the interest rate paid out.\n\n periods_per_year: int, the number of times money is invested per year.\n\n years: int, the number of years invested.\n\n Returns:\n Float, the future value of the money invested with compound interest.\n \"\"\"\n\n # The nominal interest rate per period (rate) is how much interest you earn during a\n # particular length of time, before accounting for compounding. This is typically\n # expressed as a percentage.\n rate_per_period = annual_rate / float(periods_per_year)\n\n # How many periods in the future the calculation is for.\n periods = periods_per_year * years\n\n return present_value * (1 + rate_per_period) ** periods"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef triangle_area(point1, point2, point3):\n\n \"\"\"Lengths of the three sides of the triangle\"\"\"\n a = point_distance(point1, point2)\n b = point_distance(point1, point3)\n c = point_distance(point2, point3)\n\n \"\"\"Where s is the semiperimeter\"\"\"\n s = (a + b + c) / 2.0\n\n \"\"\"Return the area of the triangle (using Heron's formula)\"\"\"\n return math.sqrt(s * (s - a) * (s - b) * (s - c))", "response": "Calculates the area of a triangle."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef regular_polygon_area(number_of_sides, length_of_sides):\n return (0.25 * number_of_sides * length_of_sides ** 2) / math.tan(\n math.pi / number_of_sides\n )", "response": "Calculates the area of a regular polygon"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncalculate the median of a list of integers or floating point numbers.", "response": "def median(data):\n \"\"\"\n Calculates the median of a list of integers or floating point numbers.\n\n Args:\n data: A list of integers or floating point numbers\n\n Returns:\n Sorts the list numerically and returns the middle number if the list has an odd number\n of items. If the list contains an even number of items the mean of the two middle numbers\n is returned.\n \"\"\"\n ordered = sorted(data)\n length = len(ordered)\n if length % 2 == 0:\n return (\n ordered[math.floor(length / 2) - 1] + ordered[math.floor(length / 2)]\n ) / 2.0\n\n elif length % 2 != 0:\n return ordered[math.floor(length / 2)]"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncalculate the average or mean of a list of numbers or a Decimal object.", "response": "def average(numbers, numtype='float'):\n \"\"\"\n Calculates the average or mean of a list of numbers\n\n Args:\n numbers: a list of integers or floating point numbers.\n\n numtype: string, 'decimal' or 'float'; the type of number to return.\n\n Returns:\n The average (mean) of the numbers as a floating point number\n or a Decimal object.\n\n Requires:\n The math module\n \"\"\"\n if type == 'decimal':\n return Decimal(sum(numbers)) / len(numbers)\n else:\n return float(sum(numbers)) / len(numbers)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef variance(numbers, type='population'):\n mean = average(numbers)\n variance = 0\n for number in numbers:\n variance += (mean - number) ** 2\n\n if type == 'population':\n return variance / len(numbers)\n else:\n return variance / (len(numbers) - 1)", "response": "Calculates the population or sample variance of a list of numbers."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_percentage(a, b, i=False, r=False):\n # Round to the second decimal\n if i is False and r is True:\n percentage = round(100.0 * (float(a) / b), 2)\n\n # Round to the nearest whole number\n elif (i is True and r is True) or (i is True and r is False):\n percentage = int(round(100 * (float(a) / b)))\n\n # A rounded number and an integer were requested\n if r is False:\n warnings.warn(\n \"If integer is set to True and Round is set to False, you will still get a rounded number if you pass floating point numbers as arguments.\"\n )\n\n # A precise unrounded decimal\n else:\n percentage = 100.0 * (float(a) / b)\n\n return percentage", "response": "Returns the percentage of one number over another."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncalculate the net take - home pay including employer retirement savings", "response": "def take_home_pay(gross_pay, employer_match, taxes_and_fees, numtype='float'):\n \"\"\"\n Calculate net take-home pay including employer retirement savings match\n using the formula laid out by Mr. Money Mustache:\n http://www.mrmoneymustache.com/2015/01/26/calculating-net-worth/\n\n Args:\n gross_pay: float or int, gross monthly pay.\n\n employer_match: float or int, the 401(k) match from your employer.\n\n taxes_and_fees: list, taxes and fees that are deducted from your paycheck.\n\n numtype: string, 'decimal' or 'float'; the type of number to return.\n\n Returns:\n your monthly take-home pay.\n \"\"\"\n if numtype == 'decimal':\n return (Decimal(gross_pay) + Decimal(employer_match)) - Decimal(\n sum(taxes_and_fees)\n )\n else:\n return (float(gross_pay) + float(employer_match)) - sum(taxes_and_fees)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef savings_rate(take_home_pay, spending, numtype='float'):\n\n if numtype == 'decimal':\n try:\n return (\n (Decimal(take_home_pay) - Decimal(spending)) / (Decimal(take_home_pay))\n ) * Decimal(100.0)\n # Leave InvalidOperation for backwards compatibility\n except (InvalidOperation, DivisionByZero):\n return Decimal(0.0)\n else:\n try:\n return (\n (float(take_home_pay) - float(spending)) / (float(take_home_pay))\n ) * 100.0\n except (ZeroDivisionError):\n return 0.0", "response": "Calculate monthly savings rate for a given monthly take - home pay and spending."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_variable(relpath, keyword='__version__'):\n for line in open(os.path.join(os.path.dirname(__file__), relpath), encoding='cp437'):\n if keyword in line:\n if '\"' in line:\n return line.split('\"')[1]\n elif \"'\" in line:\n return line.split(\"'\")[1]", "response": "Read the variable from a python file without importing it \n from gist. github. com."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nconverts a datetime string to a unix timestamp", "response": "def datetime_str_to_timestamp(datetime_str):\n '''\n '2018-01-01 00:00:00' (str) --> 1514736000\n\n :param str datetime_str: datetime string\n :return: unix timestamp (int) or None\n :rtype: int or None\n '''\n\n try:\n dtf = DTFormat()\n struct_time = time.strptime(datetime_str, dtf.datetime_format)\n return time.mktime(struct_time)\n except:\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngets datetime string from datetime object", "response": "def get_datetime_string(datetime_obj):\n '''\n Get datetime string from datetime object\n\n :param datetime datetime_obj: datetime object\n :return: datetime string\n :rtype: str\n '''\n\n if isinstance(datetime_obj, datetime):\n dft = DTFormat()\n return datetime_obj.strftime(dft.datetime_format)\n\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef timestamp_to_datetime(timestamp):\n '''\n 1514736000 --> datetime object\n\n :param int timestamp: unix timestamp (int)\n :return: datetime object or None\n :rtype: datetime or None\n '''\n\n if isinstance(timestamp, (int, float, str)):\n try:\n timestamp = float(timestamp)\n if timestamp.is_integer():\n timestamp = int(timestamp)\n except:\n return None\n\n temp = str(timestamp).split('.')[0]\n if len(temp) == 13:\n timestamp = timestamp / 1000.0\n\n if len(temp) < 10:\n return None\n\n else:\n return None\n\n return datetime.fromtimestamp(timestamp)", "response": "converts unix timestamp to datetime object"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef attrdict(prev, attr_names):\n if isinstance(attr_names, dict):\n for obj in prev:\n attr_values = dict()\n for name in attr_names.keys():\n if hasattr(obj, name):\n attr_values[name] = getattr(obj, name)\n else:\n attr_values[name] = attr_names[name]\n yield attr_values\n else:\n for obj in prev:\n attr_values = dict()\n for name in attr_names:\n if hasattr(obj, name):\n attr_values[name] = getattr(obj, name)\n yield attr_values", "response": "This function returns a generator that yields the attribute values of the object in the object that is in the pipe."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef flatten(prev, depth=sys.maxsize):\n def inner_flatten(iterable, curr_level, max_levels):\n for i in iterable:\n if hasattr(i, '__iter__') and curr_level < max_levels:\n for j in inner_flatten(i, curr_level + 1, max_levels):\n yield j\n else:\n yield i\n\n for d in prev:\n if hasattr(d, '__iter__') and depth > 0:\n for inner_d in inner_flatten(d, 1, depth):\n yield inner_d\n else:\n yield d", "response": "This function flattens the given pipe into a single nested item."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nvaluing pipe extract value from previous pipe.", "response": "def values(prev, *keys, **kw):\n \"\"\"values pipe extract value from previous pipe.\n\n If previous pipe send a dictionary to values pipe, keys should contains\n the key of dictionary which you want to get. If previous pipe send list or\n tuple,\n\n :param prev: The previous iterator of pipe.\n :type prev: Pipe\n :returns: generator\n \"\"\"\n d = next(prev)\n if isinstance(d, dict):\n yield [d[k] for k in keys if k in d]\n for d in prev:\n yield [d[k] for k in keys if k in d]\n else:\n yield [d[i] for i in keys if 0 <= i < len(d)]\n for d in prev:\n yield [d[i] for i in keys if 0 <= i < len(d)]"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\npack pipe takes n elements from previous generator and yield one list to next. :param prev: The previous iterator of pipe. :type prev: Pipe :param rest: Set True to allow to output the rest part of last elements. :type prev: boolean :param padding: Specify the padding element for the rest part of last elements. :type prev: boolean :returns: generator :Example: >>> result([1,2,3,4,5,6,7] | pack(3)) [[1, 2, 3], [4, 5, 6]] >>> result([1,2,3,4,5,6,7] | pack(3, rest=True)) [[1, 2, 3], [4, 5, 6], [7,]] >>> result([1,2,3,4,5,6,7] | pack(3, padding=None)) [[1, 2, 3], [4, 5, 6], [7, None, None]]", "response": "def pack(prev, n, rest=False, **kw):\n \"\"\"pack pipe takes n elements from previous generator and yield one\n list to next.\n\n :param prev: The previous iterator of pipe.\n :type prev: Pipe\n :param rest: Set True to allow to output the rest part of last elements.\n :type prev: boolean\n :param padding: Specify the padding element for the rest part of last elements.\n :type prev: boolean\n :returns: generator\n\n :Example:\n >>> result([1,2,3,4,5,6,7] | pack(3))\n [[1, 2, 3], [4, 5, 6]]\n\n >>> result([1,2,3,4,5,6,7] | pack(3, rest=True))\n [[1, 2, 3], [4, 5, 6], [7,]]\n\n >>> result([1,2,3,4,5,6,7] | pack(3, padding=None))\n [[1, 2, 3], [4, 5, 6], [7, None, None]]\n \"\"\"\n\n if 'padding' in kw:\n use_padding = True\n padding = kw['padding']\n else:\n use_padding = False\n padding = None\n\n items = []\n for i, data in enumerate(prev, 1):\n items.append(data)\n if (i % n) == 0:\n yield items\n items = []\n if len(items) != 0 and rest:\n if use_padding:\n items.extend([padding, ] * (n - (i % n)))\n yield items"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef grep(prev, pattern, *args, **kw):\n inv = False if 'inv' not in kw else kw.pop('inv')\n pattern_obj = re.compile(pattern, *args, **kw)\n\n for data in prev:\n if bool(inv) ^ bool(pattern_obj.match(data)):\n yield data", "response": "The grep function for the given pattern in the given pipe."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef match(prev, pattern, *args, **kw):\n to = 'to' in kw and kw.pop('to')\n pattern_obj = re.compile(pattern, *args, **kw)\n\n if to is dict:\n for data in prev:\n match = pattern_obj.match(data)\n if match is not None:\n yield match.groupdict()\n elif to is tuple:\n for data in prev:\n match = pattern_obj.match(data)\n if match is not None:\n yield match.groups()\n elif to is list:\n for data in prev:\n match = pattern_obj.match(data)\n if match is not None:\n yield list(match.groups())\n else:\n for data in prev:\n match = pattern_obj.match(data)\n if match is not None:\n yield match", "response": "The pattern is a regular expression which can be used to filter the data."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef resplit(prev, pattern, *args, **kw):\n maxsplit = 0 if 'maxsplit' not in kw else kw.pop('maxsplit')\n pattern_obj = re.compile(pattern, *args, **kw)\n for s in prev:\n yield pattern_obj.split(s, maxsplit=maxsplit)", "response": "The resplit pipe split previous string by regular expression."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef sub(prev, pattern, repl, *args, **kw):\n count = 0 if 'count' not in kw else kw.pop('count')\n pattern_obj = re.compile(pattern, *args, **kw)\n for s in prev:\n yield pattern_obj.sub(repl, s, count=count)", "response": "A wrapper around re. sub method."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nyields all data that matches pattern in the previous generator of natalatalatalels", "response": "def wildcard(prev, pattern, *args, **kw):\n \"\"\"wildcard pipe greps data passed from previous generator\n according to given regular expression.\n\n :param prev: The previous iterator of pipe.\n :type prev: Pipe\n :param pattern: The wildcard string which used to filter data.\n :type pattern: str|unicode|re pattern object\n :param inv: If true, invert the match condition.\n :type inv: boolean\n :returns: generator\n \"\"\"\n import fnmatch\n\n inv = 'inv' in kw and kw.pop('inv')\n pattern_obj = re.compile(fnmatch.translate(pattern), *args, **kw)\n\n if not inv:\n for data in prev:\n if pattern_obj.match(data):\n yield data\n else:\n for data in prev:\n if not pattern_obj.match(data):\n yield data"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef stdout(prev, endl='\\n', thru=False):\n for i in prev:\n sys.stdout.write(str(i) + endl)\n if thru:\n yield i", "response": "This pipe writes data from previous iterator to stdout."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nexecutes a shell command.", "response": "def sh(prev, *args, **kw):\n \"\"\"sh pipe execute shell command specified by args. If previous pipe exists,\n read data from it and write it to stdin of shell process. The stdout of\n shell process will be passed to next pipe object line by line.\n\n A optional keyword argument 'trim' can pass a function into sh pipe. It is\n used to trim the output from shell process. The default trim function is\n str.rstrip. Therefore, any space characters in tail of\n shell process output line will be removed.\n\n For example:\n\n py_files = result(sh('ls') | strip | wildcard('*.py'))\n\n :param prev: The previous iterator of pipe.\n :type prev: Pipe\n :param args: The command line arguments. It will be joined by space character.\n :type args: list of string.\n :param kw: arguments for subprocess.Popen.\n :type kw: dictionary of options.\n :returns: generator\n \"\"\"\n endl = '\\n' if 'endl' not in kw else kw.pop('endl')\n trim = None if 'trim' not in kw else kw.pop('trim')\n if trim is None:\n trim = bytes.rstrip if is_py3 else str.rstrip\n\n cmdline = ' '.join(args)\n if not cmdline:\n if prev is not None:\n for i in prev:\n yield i\n else:\n while True:\n yield None\n\n process = subprocess.Popen(cmdline, shell=True,\n stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n **kw)\n if prev is not None:\n stdin_buffer = StringIO()\n for i in prev:\n stdin_buffer.write(i)\n if endl:\n stdin_buffer.write(endl)\n if is_py3:\n process.stdin.write(stdin_buffer.getvalue().encode('utf-8'))\n else:\n process.stdin.write(stdin_buffer.getvalue())\n process.stdin.flush()\n process.stdin.close()\n stdin_buffer.close()\n\n for line in process.stdout:\n yield trim(line)\n\n process.wait()"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef join(prev, sep, *args, **kw):\n '''alias of str.join'''\n yield sep.join(prev, *args, **kw)", "response": "alias of str. join"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\naliases of string. Template. substitute", "response": "def substitute(prev, *args, **kw):\n '''alias of string.Template.substitute'''\n template_obj = string.Template(*args, **kw)\n for data in prev:\n yield template_obj.substitute(data)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\naliases of string. Template. safe_substitute", "response": "def safe_substitute(prev, *args, **kw):\n '''alias of string.Template.safe_substitute'''\n template_obj = string.Template(*args, **kw)\n for data in prev:\n yield template_obj.safe_substitute(data)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef to_str(prev, encoding=None):\n first = next(prev)\n if isinstance(first, str):\n if encoding is None:\n yield first\n for s in prev:\n yield s\n else:\n yield first.encode(encoding)\n for s in prev:\n yield s.encode(encoding)\n else:\n if encoding is None:\n encoding = sys.stdout.encoding or 'utf-8'\n yield first.decode(encoding)\n for s in prev:\n yield s.decode(encoding)", "response": "Convert data from previous pipe with specified encoding."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef register_default_types():\n register_type(type, pipe.map)\n register_type(types.FunctionType, pipe.map)\n register_type(types.MethodType, pipe.map)\n register_type(tuple, seq)\n register_type(list, seq)\n register_type(types.GeneratorType, seq)\n register_type(string_type, sh)\n register_type(unicode_type, sh)\n register_type(file_type, fileobj)\n\n if is_py3:\n register_type(range, seq)\n register_type(map, seq)", "response": "Regiser all default type - to - pipe convertors."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nconvert Paginator instance to dict", "response": "def get_dict(self):\n '''\n Convert Paginator instance to dict\n\n :return: Paging data\n :rtype: dict\n '''\n\n return dict(\n current_page=self.current_page,\n total_page_count=self.total_page_count,\n items=self.items,\n total_item_count=self.total_item_count,\n page_size=self.page_size\n )"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef write_log(log_directory, log_filename, header, logline, debug,\n require_latest, latest_directory, latest_filename):\n \"\"\"This function logs a line of data to both a 'log' file, and a 'latest'\n file The 'latest' file is optional, and is sent to this function as a\n boolean value via the variable 'require_latest'.\n So the 2 log directories and filenames are:\n a. (REQUIRED): log_directory + log_filename\n b. (OPTIONAL): latest_directory + latest_filename\n\n The 'latest' directory and filename is provided so as to have a consistent\n file of the latest events This is usually the latest day of events.\n The way this function works with the 'latest' log_dir is as follows:\n a. It checks for the existance of log_directory + log_filename\n b. If (a) doesn't exist, then any 'latest' file is removed and a new one created\n c. If (a) already exists, logs are written to any existing 'latest' file\n If one doesn't exist, it will be created\n\n For both the 'log' and 'latest' files, a header line will be written if a new\n file is created Please note that a header must start with the '#' symbol, so\n the Ardexa agent can interpret this line as a header , and will not send it to\n the cloud\n \"\"\"\n create_new_file = False\n\n # Make sure the logging directory exists. The following will create all the necessary subdirs,\n # if the subdirs exist in part or in full\n if not os.path.exists(log_directory):\n os.makedirs(log_directory)\n full_path_log = os.path.join(log_directory, log_filename)\n if debug > 1:\n print(\"Full path of log directory: \", full_path_log)\n # If the file doesn't exist, annotate that a new 'latest' file is to be created\n # and that a header is to be created\n if not os.path.isfile(full_path_log):\n if debug > 1:\n print(\"Log file doesn't exist: \", full_path_log)\n create_new_file = True\n\n # Repeat for the 'latest', if it doesn't exist\n if require_latest:\n if not os.path.exists(latest_directory):\n os.makedirs(latest_directory)\n full_path_latest = os.path.join(latest_directory, latest_filename)\n if debug > 1:\n print(\"Full path of latest directory: \", full_path_latest)\n # If the 'create_new_file' tag is set AND the file exists, then remove it\n if create_new_file and os.path.isfile(full_path_latest):\n # then remove the file\n os.remove(full_path_latest)\n\n # Now create both (or open both) and write to them\n if debug > 1:\n print(\"##########################################\")\n print(\"Writing the line to\", full_path_latest)\n print(logline)\n print(\"##########################################\")\n\n # Write the logline to the log file\n output_file = open(full_path_log, \"a\")\n if create_new_file:\n output_file.write(header)\n output_file.write(logline)\n output_file.close()\n\n # And write it to the 'latest' if required\n if require_latest:\n write_latest = open(full_path_latest, \"a\")\n if create_new_file:\n write_latest.write(header)\n write_latest.write(logline)\n write_latest.close()", "response": "This function writes a line of data to a log file."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef check_pidfile(pidfile, debug):\n # Check PID exists and see if the PID is running\n if os.path.isfile(pidfile):\n pidfile_handle = open(pidfile, 'r')\n # try and read the PID file. If no luck, remove it\n try:\n pid = int(pidfile_handle.read())\n pidfile_handle.close()\n if check_pid(pid, debug):\n return True\n except:\n pass\n\n # PID is not active, remove the PID file\n os.unlink(pidfile)\n\n # Create a PID file, to ensure this is script is only run once (at a time)\n pid = str(os.getpid())\n open(pidfile, 'w').write(pid)\n return False", "response": "Check that a process is not running more than once using PIDFILE"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef check_pid(pid, debug):\n try:\n # A Kill of 0 is to check if the PID is active. It won't kill the process\n os.kill(pid, 0)\n if debug > 1:\n print(\"Script has a PIDFILE where the process is still running\")\n return True\n except OSError:\n if debug > 1:\n print(\"Script does not appear to be running\")\n return False", "response": "This function will check whether a process is currently running."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef convert_words_to_uint(high_word, low_word):\n try:\n low_num = int(low_word)\n # low_word might arrive as a signed number. Convert to unsigned\n if low_num < 0:\n low_num = abs(low_num) + 2**15\n number = (int(high_word) << 16) | low_num\n return number, True\n except:\n return 0, False", "response": "Convert two words to a floating point number"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nconverts two words to a floating point number", "response": "def convert_words_to_float(high_word, low_word):\n \"\"\"Convert two words to a floating point\"\"\"\n number, retval = convert_words_to_uint(high_word, low_word)\n if not retval:\n return 0.0, False\n\n try:\n packed_float = struct.pack('>l', number)\n return struct.unpack('>f', packed_float)[0], True\n except:\n return 0.0, False"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef disown(debug):\n # Get the current PID\n pid = os.getpid()\n cgroup_file = \"/proc/\" + str(pid) + \"/cgroup\"\n try:\n infile = open(cgroup_file, \"r\")\n except IOError:\n print(\"Could not open cgroup file: \", cgroup_file)\n return False\n\n # Read each line\n for line in infile:\n # Check if the line contains \"ardexa.service\"\n if line.find(\"ardexa.service\") == -1:\n continue\n\n # if the lines contains \"name=\", replace it with nothing\n line = line.replace(\"name=\", \"\")\n # Split the line by commas\n items_list = line.split(':')\n accounts = items_list[1]\n dir_str = accounts + \"/ardexa.disown\"\n # If accounts is empty, continue\n if not accounts:\n continue\n\n # Create the dir and all subdirs\n full_dir = \"/sys/fs/cgroup/\" + dir_str\n if not os.path.exists(full_dir):\n os.makedirs(full_dir)\n if debug >= 1:\n print(\"Making directory: \", full_dir)\n else:\n if debug >= 1:\n print(\"Directory already exists: \", full_dir)\n\n # Add the PID to the file\n full_path = full_dir + \"/cgroup.procs\"\n prog_list = [\"echo\", str(pid), \">\", full_path]\n run_program(prog_list, debug, True)\n\n # If this item contains a comma, then separate it, and reverse\n # some OSes will need cpuacct,cpu reversed to actually work\n if accounts.find(\",\") != -1:\n acct_list = accounts.split(',')\n accounts = acct_list[1] + \",\" + acct_list[0]\n dir_str = accounts + \"/ardexa.disown\"\n # Create the dir and all subdirs. But it may not work. So use a TRY\n full_dir = \"/sys/fs/cgroup/\" + dir_str\n try:\n if not os.path.exists(full_dir):\n os.makedirs(full_dir)\n except:\n continue\n\n # Add the PID to the file\n full_path = full_dir + \"/cgroup.procs\"\n prog_list = [\"echo\", str(pid), \">\", full_path]\n run_program(prog_list, debug, True)\n\n infile.close()\n\n # For debug purposes only\n if debug >= 1:\n prog_list = [\"cat\", cgroup_file]\n run_program(prog_list, debug, False)\n\n # If there are any \"ardexa.service\" in the proc file. If so, exit with error\n prog_list = [\"grep\", \"-q\", \"ardexa.service\", cgroup_file]\n if run_program(prog_list, debug, False):\n # There are entries still left in the file\n return False\n\n return True", "response": "This function will disown the Ardexa service and all of its sub - directories and the Ardexa service."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef run_program(prog_list, debug, shell):\n try:\n if not shell:\n process = Popen(prog_list, stdout=PIPE, stderr=PIPE)\n stdout, stderr = process.communicate()\n retcode = process.returncode\n if debug >= 1:\n print(\"Program : \", \" \".join(prog_list))\n print(\"Return Code: \", retcode)\n print(\"Stdout: \", stdout)\n print(\"Stderr: \", stderr)\n return bool(retcode)\n else:\n command = \" \".join(prog_list)\n os.system(command)\n return True\n except:\n return False", "response": "Run a program and check return code"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef parse_address_list(addrs):\n for addr in addrs.split(','):\n elem = addr.split('-')\n if len(elem) == 1: # a number\n yield int(elem[0])\n elif len(elem) == 2: # a range inclusive\n start, end = list(map(int, elem))\n for i in range(start, end+1):\n yield i\n else: # more than one hyphen\n raise ValueError('format error in %s' % addr)", "response": "Yield each integer from a complex range string like 1 - 9 12 15 - 20 23"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ndoes url - encode resource ids", "response": "def _encode_ids(*args):\n \"\"\"\n Do url-encode resource ids\n \"\"\"\n\n ids = []\n for v in args:\n if isinstance(v, basestring):\n qv = v.encode('utf-8') if isinstance(v, unicode) else v\n ids.append(urllib.quote(qv))\n else:\n qv = str(v)\n ids.append(urllib.quote(qv))\n\n return ';'.join(ids)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef random_string(length):\n '''\n Generate random string with parameter length.\n Example:\n\n >>> from eggit.egg_string import random_string\n >>> random_string(8)\n 'q4f2eaT4'\n >>>\n\n '''\n\n str_list = [random.choice(string.digits + string.ascii_letters) for i in range(length)]\n return ''.join(str_list)", "response": "Generate random string with parameter length."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_item_creator(item_type):\n if item_type not in Pipe.pipe_item_types:\n for registered_type in Pipe.pipe_item_types:\n if issubclass(item_type, registered_type):\n return Pipe.pipe_item_types[registered_type]\n return None\n else:\n return Pipe.pipe_item_types[item_type]", "response": "Get item creator function according registered item type."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef clone(self):\n new_object = copy.copy(self)\n if new_object.next:\n new_object.next = new_object.next.clone()\n return new_object", "response": "Self - cloning. All its next Pipe objects are cloned too."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nappending next object to the end of the pipe.", "response": "def append(self, next):\n \"\"\"Append next object to pipe tail.\n\n :param next: The Pipe object to be appended to tail.\n :type next: Pipe object.\n \"\"\"\n next.chained = True\n if self.next:\n self.next.append(next)\n else:\n self.next = next"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef iter(self, prev=None):\n\n if self.next:\n generator = self.next.iter(self.func(prev, *self.args, **self.kw))\n else:\n generator = self.func(prev, *self.args, **self.kw)\n return generator", "response": "Return an iterator object which yields the data from the next pipe."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef reduce(func):\n def wrapper(prev, *argv, **kw):\n accum_value = None if 'init' not in kw else kw.pop('init')\n if prev is None:\n raise TypeError('A reducer must have input.')\n for i in prev:\n accum_value = func(accum_value, i, *argv, **kw)\n yield accum_value\n return Pipe(wrapper)", "response": "Wrap a function to reduce the data from a list of entries."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef stopper(func):\n def wrapper(prev, *argv, **kw):\n if prev is None:\n raise TypeError('A stopper must have input.')\n for i in prev:\n if func(i, *argv, **kw):\n break\n yield i\n return Pipe(wrapper)", "response": "Wrap a conditoinal function to a pipe object."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning a dictionary of network name to active status bools.", "response": "def _list_networks():\n \"\"\"Return a dictionary of network name to active status bools.\n\n Sample virsh net-list output::\n\n Name State Autostart\n -----------------------------------------\n default active yes\n juju-test inactive no\n foobar inactive no\n\n Parsing the above would return::\n {\"default\": True, \"juju-test\": False, \"foobar\": False}\n\n See: http://goo.gl/kXwfC\n \"\"\"\n output = core.run(\"virsh net-list --all\")\n networks = {}\n\n # Take the header off and normalize whitespace.\n net_lines = [n.strip() for n in output.splitlines()[2:]]\n for line in net_lines:\n if not line:\n continue\n name, state, auto = line.split()\n networks[name] = state == \"active\"\n return networks"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef flush(self, line):\n # TODO -- maybe use echo?\n sys.stdout.write(line)\n sys.stdout.flush()", "response": "flush the line to stdout"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nrun the passed in arguments and returns an iterator on the output of the running command", "response": "def execute(self, arg_str='', **kwargs):\n \"\"\"runs the passed in arguments and returns an iterator on the output of\n running command\"\"\"\n cmd = \"{} {} {}\".format(self.cmd_prefix, self.script, arg_str)\n expected_ret_code = kwargs.pop('code', 0)\n\n # any kwargs with all capital letters should be considered environment\n # variables\n environ = self.environ\n for k in list(kwargs.keys()):\n if k.isupper():\n environ[k] = kwargs.pop(k)\n\n # we will allow overriding of these values\n kwargs.setdefault(\"stderr\", subprocess.STDOUT)\n\n # we will not allow these to be overridden via kwargs\n kwargs[\"shell\"] = True\n kwargs[\"stdout\"] = subprocess.PIPE\n kwargs[\"cwd\"] = self.cwd\n kwargs[\"env\"] = environ\n\n process = None\n self.buf = deque(maxlen=self.bufsize)\n\n try:\n process = subprocess.Popen(\n cmd,\n **kwargs\n )\n\n # another round of links\n # http://stackoverflow.com/a/17413045/5006 (what I used)\n # http://stackoverflow.com/questions/2715847/\n for line in iter(process.stdout.readline, b\"\"):\n line = line.decode(self.encoding)\n self.buf.append(line.rstrip())\n yield line\n\n process.wait()\n if process.returncode != expected_ret_code:\n if process.returncode > 0:\n raise RuntimeError(\"{} returned {} with output: {}\".format(\n cmd,\n process.returncode,\n self.output\n ))\n\n except subprocess.CalledProcessError as e:\n if e.returncode != expected_ret_code:\n raise RuntimeError(\"{} returned {} with output: {}\".format(\n cmd,\n e.returncode,\n self.output\n ))\n\n finally:\n if process:\n process.stdout.close()"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nbuilds a basic 035 subfield with basic information from the OAI - PMH request.", "response": "def get_request_subfields(root):\n \"\"\"Build a basic 035 subfield with basic information from the OAI-PMH request.\n\n :param root: ElementTree root node\n\n :return: list of subfield tuples [(..),(..)]\n \"\"\"\n request = root.find('request')\n responsedate = root.find('responseDate')\n\n subs = [(\"9\", request.text),\n (\"h\", responsedate.text),\n (\"m\", request.attrib[\"metadataPrefix\"])]\n return subs"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef strip_xml_namespace(root):\n try:\n root.tag = root.tag.split('}')[1]\n except IndexError:\n pass\n\n for element in root.getchildren():\n strip_xml_namespace(element)", "response": "This function removes out namespace data from an ElementTree."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef element_tree_collection_to_records(tree):\n from .bibrecord import create_record\n\n records = []\n collection = tree.getroot()\n for record_element in collection.getchildren():\n marcxml = ET.tostring(record_element, encoding=\"utf-8\")\n record, status, errors = create_record(marcxml)\n if errors:\n print(str(status))\n records.append(record)\n return records", "response": "Take an ElementTree and converts the nodes into BibRecord records."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ntaking an ElementTree object and converts the nodes into BibRecord records.", "response": "def element_tree_oai_records(tree, header_subs=None):\n \"\"\"Take an ElementTree and converts the nodes into BibRecord records.\n\n This expects a clean OAI response with the tree root as ListRecords\n or GetRecord and record as the subtag like so:\n \n \n \n \n \n \n \n \n \n \n \n ... \n \n\n :param tree: ElementTree object corresponding to GetRecord node from\n OAI request\n :param header_subs: OAI header subfields, if any\n\n :yield: (record, is_deleted) A tuple, with first a BibRecord found and\n second a boolean value saying if this is a deleted record or not.\n \"\"\"\n from .bibrecord import record_add_field, create_record\n\n if not header_subs:\n header_subs = []\n # Make it a tuple, this information should not be changed\n header_subs = tuple(header_subs)\n\n oai_records = tree.getroot()\n for record_element in oai_records.getchildren():\n header = record_element.find('header')\n\n # Add to OAI subfield\n datestamp = header.find('datestamp')\n identifier = header.find('identifier')\n identifier = identifier.text\n\n # The record's subfield is based on header information\n subs = list(header_subs)\n subs.append((\"a\", identifier))\n subs.append((\"d\", datestamp.text))\n\n if \"status\" in header.attrib and header.attrib[\"status\"] == \"deleted\":\n # Record was deleted - create delete record\n deleted_record = {}\n record_add_field(deleted_record, \"037\", subfields=subs)\n yield deleted_record, True\n else:\n marc_root = record_element.find('metadata').find('record')\n marcxml = ET.tostring(marc_root, encoding=\"utf-8\")\n record, status, errors = create_record(marcxml)\n if status == 1:\n # Add OAI request information\n record_add_field(record, \"035\", subfields=subs)\n yield record, False"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nstarting a server instance.", "response": "def run(app=None,\n server='wsgiref',\n host='127.0.0.1',\n port=8080,\n interval=1,\n reloader=False,\n quiet=False,\n plugins=None,\n debug=None, **kargs):\n \"\"\" Start a server instance. This method blocks until the server terminates.\n\n :param app: WSGI application or target string supported by\n :func:`load_app`. (default: :func:`default_app`)\n :param server: Server adapter to use. See :data:`server_names` keys\n for valid names or pass a :class:`ServerAdapter` subclass.\n (default: `wsgiref`)\n :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on\n all interfaces including the external one. (default: 127.0.0.1)\n :param port: Server port to bind to. Values below 1024 require root\n privileges. (default: 8080)\n :param reloader: Start auto-reloading server? (default: False)\n :param interval: Auto-reloader interval in seconds (default: 1)\n :param quiet: Suppress output to stdout and stderr? (default: False)\n :param options: Options passed to the server adapter.\n \"\"\"\n if NORUN: return\n if reloader and not os.environ.get('BOTTLE_CHILD'):\n import subprocess\n lockfile = None\n try:\n fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock')\n os.close(fd) # We only need this file to exist. We never write to it\n while os.path.exists(lockfile):\n args = [sys.executable] + sys.argv\n environ = os.environ.copy()\n environ['BOTTLE_CHILD'] = 'true'\n environ['BOTTLE_LOCKFILE'] = lockfile\n p = subprocess.Popen(args, env=environ)\n while p.poll() is None: # Busy wait...\n os.utime(lockfile, None) # I am alive!\n time.sleep(interval)\n if p.poll() != 3:\n if os.path.exists(lockfile): os.unlink(lockfile)\n sys.exit(p.poll())\n except KeyboardInterrupt:\n pass\n finally:\n if os.path.exists(lockfile):\n os.unlink(lockfile)\n return\n\n try:\n if debug is not None: _debug(debug)\n app = app or default_app()\n if isinstance(app, basestring):\n app = load_app(app)\n if not callable(app):\n raise ValueError(\"Application is not callable: %r\" % app)\n\n for plugin in plugins or []:\n if isinstance(plugin, basestring):\n plugin = load(plugin)\n app.install(plugin)\n\n if server in server_names:\n server = server_names.get(server)\n if isinstance(server, basestring):\n server = load(server)\n if isinstance(server, type):\n server = server(host=host, port=port, **kargs)\n if not isinstance(server, ServerAdapter):\n raise ValueError(\"Unknown or unsupported server: %r\" % server)\n\n server.quiet = server.quiet or quiet\n if not server.quiet:\n _stderr(\"Bottle v%s server starting up (using %s)...\\n\" %\n (__version__, repr(server)))\n _stderr(\"Listening on http://%s:%d/\\n\" %\n (server.host, server.port))\n _stderr(\"Hit Ctrl-C to quit.\\n\\n\")\n\n if reloader:\n lockfile = os.environ.get('BOTTLE_LOCKFILE')\n bgcheck = FileCheckerThread(lockfile, interval)\n with bgcheck:\n server.run(app)\n if bgcheck.status == 'reload':\n sys.exit(3)\n else:\n server.run(app)\n except KeyboardInterrupt:\n pass\n except (SystemExit, MemoryError):\n raise\n except:\n if not reloader: raise\n if not getattr(server, 'quiet', quiet):\n print_exc()\n time.sleep(interval)\n sys.exit(3)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nloading values from a dictionary structure.", "response": "def load_dict(self, source, namespace=''):\n \"\"\" Load values from a dictionary structure. Nesting can be used to\n represent namespaces.\n\n >>> c = ConfigDict()\n >>> c.load_dict({'some': {'namespace': {'key': 'value'} } })\n {'some.namespace.key': 'value'}\n \"\"\"\n for key, value in source.items():\n if isinstance(key, str):\n nskey = (namespace + '.' + key).strip('.')\n if isinstance(value, dict):\n self.load_dict(value, namespace=nskey)\n else:\n self[nskey] = value\n else:\n raise TypeError('Key has type %r (not a string)' % type(key))\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef json(request, *args, **kwargs):\n # coerce to dictionary\n params = dict(request.GET.items())\n \n callback = params.pop('callback', None)\n url = params.pop('url', None)\n \n if not url:\n return HttpResponseBadRequest('Required parameter missing: URL')\n \n try:\n provider = oembed.site.provider_for_url(url)\n if not provider.provides:\n raise OEmbedMissingEndpoint()\n except OEmbedMissingEndpoint:\n raise Http404('No provider found for %s' % url)\n \n query = dict([(smart_str(k), smart_str(v)) for k, v in params.items() if v])\n \n try:\n resource = oembed.site.embed(url, **query)\n except OEmbedException, e:\n raise Http404('Error embedding %s: %s' % (url, str(e)))\n\n response = HttpResponse(mimetype='application/json')\n json = resource.json\n \n if callback:\n response.write('%s(%s)' % (defaultfilters.force_escape(callback), json))\n else:\n response.write(json)\n \n return response", "response": "Return a JSON representation of the site s metadata."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nextracting and return oembed content for given urls", "response": "def consume_json(request):\n \"\"\"\n Extract and return oembed content for given urls.\n\n Required GET params:\n urls - list of urls to consume\n\n Optional GET params:\n width - maxwidth attribute for oembed content\n height - maxheight attribute for oembed content\n template_dir - template_dir to use when rendering oembed\n\n Returns:\n list of dictionaries with oembed metadata and renderings, json encoded\n \"\"\"\n client = OEmbedConsumer()\n \n urls = request.GET.getlist('urls')\n width = request.GET.get('width')\n height = request.GET.get('height')\n template_dir = request.GET.get('template_dir')\n\n output = {}\n ctx = RequestContext(request)\n\n for url in urls:\n try:\n provider = oembed.site.provider_for_url(url)\n except OEmbedMissingEndpoint:\n oembeds = None\n rendered = None\n else:\n oembeds = url\n rendered = client.parse_text(url, width, height, context=ctx, template_dir=template_dir)\n\n output[url] = {\n 'oembeds': oembeds,\n 'rendered': rendered,\n }\n\n return HttpResponse(simplejson.dumps(output), mimetype='application/json')"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef oembed_schema(request):\n current_domain = Site.objects.get_current().domain\n url_schemes = [] # a list of dictionaries for all the urls we can match\n endpoint = reverse('oembed_json') # the public endpoint for our oembeds\n providers = oembed.site.get_providers()\n\n for provider in providers:\n # first make sure this provider class is exposed at the public endpoint\n if not provider.provides:\n continue\n \n match = None\n if isinstance(provider, DjangoProvider):\n # django providers define their regex_list by using urlreversing\n url_pattern = resolver.reverse_dict.get(provider._meta.named_view)\n\n # this regex replacement is set to be non-greedy, which results\n # in things like /news/*/*/*/*/ -- this is more explicit\n if url_pattern:\n regex = re.sub(r'%\\(.+?\\)s', '*', url_pattern[0][0][0])\n match = 'http://%s/%s' % (current_domain, regex)\n elif isinstance(provider, HTTPProvider):\n match = provider.url_scheme\n else:\n match = provider.regex\n\n if match:\n url_schemes.append({\n 'type': provider.resource_type,\n 'matches': match,\n 'endpoint': endpoint\n })\n \n url_schemes.sort(key=lambda item: item['matches'])\n \n response = HttpResponse(mimetype='application/json')\n response.write(simplejson.dumps(url_schemes))\n return response", "response": "A basic schema for OEmbed - able content."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef find_meta(*meta_file_parts, meta_key):\n meta_file = read(*meta_file_parts)\n meta_match = re.search(r\"^__{}__ = ['\\\"]([^'\\\"]*)['\\\"]\".format(meta_key),\n meta_file, re.M)\n if meta_match:\n return meta_match.group(1)\n raise RuntimeError(\"Unable to find __{}__ string.\".format(meta_key))", "response": "Extract __*meta__ from meta_file."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef main(path):\n '''scan path directory and any subdirectories for valid captain scripts'''\n basepath = os.path.abspath(os.path.expanduser(str(path)))\n\n echo.h2(\"Available scripts in {}\".format(basepath))\n echo.br()\n for root_dir, dirs, files in os.walk(basepath, topdown=True):\n for f in fnmatch.filter(files, '*.py'):\n try:\n filepath = os.path.join(root_dir, f)\n\n # super edge case, this makes sure the python script won't start\n # an interactive console session which would cause the session\n # to start and not allow the for loop to complete\n with open(filepath, encoding=\"UTF-8\") as fp:\n body = fp.read()\n is_console = \"InteractiveConsole\" in body\n is_console = is_console or \"code\" in body\n is_console = is_console and \"interact(\" in body\n if is_console:\n continue\n\n s = captain.Script(filepath)\n if s.can_run_from_cli():\n rel_filepath = s.call_path(basepath)\n p = s.parser\n\n echo.h3(rel_filepath)\n\n desc = p.description\n if desc:\n echo.indent(desc, indent=(\" \" * 4))\n\n subcommands = s.subcommands\n if subcommands:\n echo.br()\n echo.indent(\"Subcommands:\", indent=(\" \" * 4))\n for sc in subcommands.keys():\n echo.indent(sc, indent=(\" \" * 6))\n\n echo.br()\n\n except captain.ParseError:\n pass\n\n except Exception as e:\n #echo.exception(e)\n #echo.err(\"Failed to parse {} because {}\", f, e.message)\n echo.err(\"Failed to parse {}\", f)\n echo.verbose(e.message)\n echo.br()", "response": "scan path directory and any subdirectories for valid captain scripts"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn Decimal of the tax rate for given info.", "response": "def get_rate(self, zipcode, city=None, state=None, multiple_rates=False):\n \"\"\"\n Finds sales tax for given info.\n Returns Decimal of the tax rate, e.g. 8.750.\n \"\"\"\n data = self.make_request_data(zipcode, city, state)\n\n r = requests.get(self.url, params=data)\n resp = r.json()\n\n return self.process_response(resp, multiple_rates)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef make_request_data(self, zipcode, city, state):\n data = {'key': self.api_key,\n 'postalcode': str(zipcode),\n 'city': city,\n 'state': state\n }\n data = ZipTaxClient._clean_request_data(data)\n return data", "response": "Make the request params given location data"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nprocesses the response from the ZipTax API and return the tax rates", "response": "def process_response(self, resp, multiple_rates):\n \"\"\" Get the tax rate from the ZipTax response \"\"\"\n self._check_for_exceptions(resp, multiple_rates)\n\n rates = {}\n for result in resp['results']:\n rate = ZipTaxClient._cast_tax_rate(result['taxSales'])\n rates[result['geoCity']] = rate\n if not multiple_rates:\n return rates[list(rates.keys())[0]]\n return rates"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nchecks if there are exceptions that should be raised", "response": "def _check_for_exceptions(self, resp, multiple_rates):\n \"\"\" Check if there are exceptions that should be raised \"\"\"\n if resp['rCode'] != 100:\n raise exceptions.get_exception_for_code(resp['rCode'])(resp)\n\n results = resp['results']\n if len(results) == 0:\n raise exceptions.ZipTaxNoResults('No results found')\n if len(results) > 1 and not multiple_rates:\n # It's fine if all the taxes are the same\n rates = [result['taxSales'] for result in results]\n if len(set(rates)) != 1:\n raise exceptions.ZipTaxMultipleResults('Multiple results found but requested only one')"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_all_text(node):\n if node.nodeType == node.TEXT_NODE:\n return node.data\n else:\n text_string = \"\"\n for child_node in node.childNodes:\n text_string += get_all_text(child_node)\n return text_string", "response": "Recursively extract all text from node."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nextract a package in a new temporary directory.", "response": "def _extract_packages(self):\n \"\"\"\n Extract a package in a new temporary directory.\n \"\"\"\n self.path_unpacked = mkdtemp(prefix=\"scoap3_package_\",\n dir=CFG_TMPSHAREDDIR)\n for path in self.retrieved_packages_unpacked:\n scoap3utils_extract_package(path, self.path_unpacked, self.logger)\n\n return self.path_unpacked"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef register(self, provider_class):\n if not issubclass(provider_class, BaseProvider):\n raise TypeError('%s is not a subclass of BaseProvider' % provider_class.__name__)\n \n if provider_class in self._registered_providers:\n raise AlreadyRegistered('%s is already registered' % provider_class.__name__)\n \n if issubclass(provider_class, DjangoProvider):\n # set up signal handler for cache invalidation\n signals.post_save.connect(\n self.invalidate_stored_oembeds,\n sender=provider_class._meta.model\n )\n \n # don't build the regex yet - if not all urlconfs have been loaded\n # and processed at this point, the DjangoProvider instances will fail\n # when attempting to reverse urlpatterns that haven't been created.\n # Rather, the regex-list will be populated once, on-demand.\n self._registered_providers.append(provider_class)\n \n # flag for re-population\n self.invalidate_providers()", "response": "Registers a provider with the site."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef unregister(self, provider_class):\n if not issubclass(provider_class, BaseProvider):\n raise TypeError('%s must be a subclass of BaseProvider' % provider_class.__name__)\n \n if provider_class not in self._registered_providers:\n raise NotRegistered('%s is not registered' % provider_class.__name__)\n \n self._registered_providers.remove(provider_class)\n \n # flag for repopulation\n self.invalidate_providers()", "response": "Unregisters a provider from the site."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef populate(self):\n self._registry = {}\n \n for provider_class in self._registered_providers:\n instance = provider_class()\n self._registry[instance] = instance.regex\n \n for stored_provider in StoredProvider.objects.active():\n self._registry[stored_provider] = stored_provider.regex\n \n self._populated = True", "response": "Populate the internal registry with the regexes for each\n provider instance"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nfinding the right provider for a URL", "response": "def provider_for_url(self, url):\n \"\"\"\n Find the right provider for a URL\n \"\"\"\n for provider, regex in self.get_registry().items():\n if re.match(regex, url) is not None:\n return provider\n \n raise OEmbedMissingEndpoint('No endpoint matches URL: %s' % url)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef embed(self, url, **kwargs):\n try:\n # first figure out the provider\n provider = self.provider_for_url(url)\n except OEmbedMissingEndpoint:\n raise\n else:\n try:\n # check the database for a cached response, because of certain\n # race conditions that exist with get_or_create(), do a filter\n # lookup and just grab the first item\n stored_match = StoredOEmbed.objects.filter(\n match=url, \n maxwidth=kwargs.get('maxwidth', None), \n maxheight=kwargs.get('maxheight', None),\n date_expires__gte=datetime.datetime.now())[0]\n return OEmbedResource.create_json(stored_match.response_json)\n except IndexError:\n # query the endpoint and cache response in db\n # prevent None from being passed in as a GET param\n params = dict([(k, v) for k, v in kwargs.items() if v])\n \n # request an oembed resource for the url\n resource = provider.request_resource(url, **params)\n \n try:\n cache_age = int(resource.cache_age)\n if cache_age < MIN_OEMBED_TTL:\n cache_age = MIN_OEMBED_TTL\n except:\n cache_age = DEFAULT_OEMBED_TTL\n \n date_expires = datetime.datetime.now() + datetime.timedelta(seconds=cache_age)\n \n stored_oembed, created = StoredOEmbed.objects.get_or_create(\n match=url,\n maxwidth=kwargs.get('maxwidth', None),\n maxheight=kwargs.get('maxheight', None))\n \n stored_oembed.response_json = resource.json\n stored_oembed.resource_type = resource.type\n stored_oembed.date_expires = date_expires\n \n if resource.content_object:\n stored_oembed.content_object = resource.content_object\n \n stored_oembed.save()\n return resource", "response": "Get a resource from the database and return it."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nloads up StoredProviders from url if it is an oembed scheme", "response": "def autodiscover(self, url):\n \"\"\"\n Load up StoredProviders from url if it is an oembed scheme\n \"\"\"\n headers, response = fetch_url(url)\n if headers['content-type'].split(';')[0] in ('application/json', 'text/javascript'):\n provider_data = json.loads(response)\n return self.store_providers(provider_data)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nstoring all providers in the database.", "response": "def store_providers(self, provider_data):\n \"\"\"\n Iterate over the returned json and try to sort out any new providers\n \"\"\"\n if not hasattr(provider_data, '__iter__'):\n raise OEmbedException('Autodiscovered response not iterable')\n \n provider_pks = []\n \n for provider in provider_data:\n if 'endpoint' not in provider or \\\n 'matches' not in provider:\n continue\n \n resource_type = provider.get('type')\n if resource_type not in RESOURCE_TYPES:\n continue\n \n stored_provider, created = StoredProvider.objects.get_or_create(\n wildcard_regex=provider['matches']\n )\n \n if created:\n stored_provider.endpoint_url = relative_to_full( \n provider['endpoint'],\n provider['matches']\n )\n stored_provider.resource_type = resource_type\n stored_provider.save()\n \n provider_pks.append(stored_provider.pk)\n \n return StoredProvider.objects.filter(pk__in=provider_pks)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nrequests an OEmbedResource for a given url.", "response": "def request_resource(self, url, **kwargs):\n \"\"\"\n Request an OEmbedResource for a given url. Some valid keyword args:\n - format\n - maxwidth\n - maxheight\n \"\"\"\n params = kwargs\n \n params['url'] = url\n params['format'] = 'json'\n \n if '?' in self.endpoint_url:\n url_with_qs = '%s&%s' % (self.endpoint_url.rstrip('&'), urlencode(params))\n else:\n url_with_qs = \"%s?%s\" % (self.endpoint_url, urlencode(params))\n \n headers, raw_response = self._fetch(url_with_qs)\n resource = self.convert_to_resource(headers, raw_response, params)\n \n return resource"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _image_field(self):\n for field in self.model._meta.fields:\n if isinstance(field, ImageField):\n return field.name", "response": "Try to automatically detect an image field"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _date_field(self):\n for field in self.model._meta.fields:\n if isinstance(field, (DateTimeField, DateField)):\n return field.name", "response": "Try to automatically detect an image field\n "}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nbuilds a regex that matches the object_id of the object.", "response": "def _build_regex(self):\n \"\"\"\n Performs a reverse lookup on a named view and generates\n a list of regexes that match that object. It generates\n regexes with the domain name included, using sites provided\n by the get_sites() method.\n \n >>> regex = provider.regex\n >>> regex.pattern\n 'http://(www2.kusports.com|www2.ljworld.com|www.lawrence.com)/photos/(?P\\\\d{4})/(?P\\\\w{3})/(?P\\\\d{1,2})/(?P\\\\d+)/$'\n \"\"\"\n # get the regexes from the urlconf\n url_patterns = resolver.reverse_dict.get(self._meta.named_view)\n \n try:\n regex = url_patterns[1]\n except TypeError:\n raise OEmbedException('Error looking up %s' % self._meta.named_view)\n \n # get a list of normalized domains\n cleaned_sites = self.get_cleaned_sites()\n \n site_regexes = []\n \n for site in self.get_sites():\n site_regexes.append(cleaned_sites[site.pk][0])\n \n # join the sites together with the regex 'or'\n sites = '|'.join(site_regexes)\n \n # create URL-matching regexes for sites\n regex = re.compile('(%s)/%s' % (sites, regex))\n \n return regex"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ngives a URL for any of our sites try and match it to one and return the domain & name of the match. If no match is found return the current. nacute_name.", "response": "def provider_from_url(self, url):\n \"\"\"\n Given a URL for any of our sites, try and match it to one, returning\n the domain & name of the match. If no match is found, return current.\n \n Returns a tuple of domain, site name -- used to determine 'provider'\n \"\"\"\n domain = get_domain(url)\n site_tuples = self.get_cleaned_sites().values()\n for domain_re, name, normalized_domain in site_tuples:\n if re.match(domain_re, domain):\n return normalized_domain, name\n site = Site.objects.get_current()\n return site.domain, site.name"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nextract the named parameters from a url regex.", "response": "def get_params(self, url):\n \"\"\"\n Extract the named parameters from a url regex. If the url regex does not contain\n named parameters, they will be keyed _0, _1, ...\n \n * Named parameters\n Regex:\n /photos/^(?P\\d{4})/(?P\\w{3})/(?P\\d{1,2})/(?P\\d+)/\n \n URL:\n http://www2.ljworld.com/photos/2009/oct/11/12345/\n \n Return Value:\n {u'day': '11', u'month': 'oct', u'object_id': '12345', u'year': '2009'}\n \n * Unnamed parameters\n Regex:\n /blah/([\\w-]+)/(\\d+)/\n \n URL:\n http://www.example.com/blah/hello/123/\n \n Return Value:\n {u'_0': 'hello', u'_1': '123'}\n \"\"\"\n match = re.match(self.regex, url)\n if match is not None:\n params = match.groupdict()\n if not params:\n params = {}\n for i, group in enumerate(match.groups()[1:]):\n params['_%s' % i] = group\n return params\n \n raise OEmbedException('No regex matched the url %s' % (url))"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nget an object from the database", "response": "def get_object(self, url):\n \"\"\"\n Fields to match is a mapping of url params to fields, so for\n the photos example above, it would be:\n \n fields_to_match = { 'object_id': 'id' }\n \n This procedure parses out named params from a URL and then uses\n the fields_to_match dictionary to generate a query.\n \"\"\"\n params = self.get_params(url)\n query = {}\n for key, value in self._meta.fields_to_match.iteritems():\n try:\n query[value] = params[key]\n except KeyError:\n raise OEmbedException('%s was not found in the urlpattern parameters. Valid names are: %s' % (key, ', '.join(params.keys())))\n \n try:\n obj = self.get_queryset().get(**query)\n except self._meta.model.DoesNotExist:\n raise OEmbedException('Requested object not found')\n \n return obj"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngenerates the html attribute of an oembed resource using a template.", "response": "def render_html(self, obj, context=None):\n \"\"\"\n Generate the 'html' attribute of an oembed resource using a template.\n Sort of a corollary to the parser's render_oembed method. By default,\n the current mapping will be passed in as the context.\n \n OEmbed templates are stored in:\n \n oembed/provider/[app_label]_[model].html\n \n -- or --\n \n oembed/provider/media_video.html\n \"\"\" \n provided_context = context or Context()\n context = RequestContext(mock_request())\n context.update(provided_context)\n \n context.push()\n context[self._meta.context_varname] = obj\n rendered = render_to_string(self._meta.template_name, context)\n context.pop()\n return rendered"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nmapping an attribute to the object.", "response": "def map_attr(self, mapping, attr, obj):\n \"\"\"\n A kind of cheesy method that allows for callables or attributes to\n be used interchangably\n \"\"\"\n if attr not in mapping and hasattr(self, attr):\n if not callable(getattr(self, attr)):\n mapping[attr] = getattr(self, attr)\n else:\n mapping[attr] = getattr(self, attr)(obj)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns an ImageFileField instance", "response": "def get_image(self, obj):\n \"\"\"\n Return an ImageFileField instance\n \"\"\"\n if self._meta.image_field:\n return getattr(obj, self._meta.image_field)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef map_to_dictionary(self, url, obj, **kwargs):\n maxwidth = kwargs.get('maxwidth', None)\n maxheight = kwargs.get('maxheight', None)\n \n provider_url, provider_name = self.provider_from_url(url)\n \n mapping = {\n 'version': '1.0',\n 'url': url,\n 'provider_name': provider_name,\n 'provider_url': provider_url,\n 'type': self.resource_type\n }\n \n # a hook\n self.preprocess(obj, mapping, **kwargs)\n \n # resize image if we have a photo, otherwise use the given maximums\n if self.resource_type == 'photo' and self.get_image(obj):\n self.resize_photo(obj, mapping, maxwidth, maxheight)\n elif self.resource_type in ('video', 'rich', 'photo'):\n width, height = size_to_nearest(\n maxwidth,\n maxheight,\n self._meta.valid_sizes,\n self._meta.force_fit\n )\n mapping.update(width=width, height=height)\n \n # create a thumbnail\n if self.get_image(obj):\n self.thumbnail(obj, mapping)\n \n # map attributes to the mapping dictionary. if the attribute is\n # a callable, it must have an argument signature of\n # (self, obj)\n for attr in ('title', 'author_name', 'author_url', 'html'):\n self.map_attr(mapping, attr, obj)\n \n # fix any urls\n if 'url' in mapping:\n mapping['url'] = relative_to_full(mapping['url'], url)\n \n if 'thumbnail_url' in mapping:\n mapping['thumbnail_url'] = relative_to_full(mapping['thumbnail_url'], url)\n \n if 'html' not in mapping and mapping['type'] in ('video', 'rich'):\n mapping['html'] = self.render_html(obj, context=Context(mapping))\n \n # a hook\n self.postprocess(obj, mapping, **kwargs)\n \n return mapping", "response": "Map the object to a dictionary."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nrequests an OEmbedResource for a given url.", "response": "def request_resource(self, url, **kwargs):\n \"\"\"\n Request an OEmbedResource for a given url. Some valid keyword args:\n - format\n - maxwidth\n - maxheight\n \"\"\"\n obj = self.get_object(url)\n \n mapping = self.map_to_dictionary(url, obj, **kwargs)\n \n resource = OEmbedResource.create(mapping)\n resource.content_object = obj\n \n return resource"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_object(self, url, month_format='%b', day_format='%d'):\n params = self.get_params(url)\n try:\n year = params[self._meta.year_part]\n month = params[self._meta.month_part]\n day = params[self._meta.day_part]\n except KeyError:\n try:\n # named lookups failed, so try to get the date using the first\n # three parameters\n year, month, day = params['_0'], params['_1'], params['_2']\n except KeyError:\n raise OEmbedException('Error extracting date from url parameters')\n \n try:\n tt = time.strptime('%s-%s-%s' % (year, month, day),\n '%s-%s-%s' % ('%Y', month_format, day_format))\n date = datetime.date(*tt[:3])\n except ValueError:\n raise OEmbedException('Error parsing date from: %s' % url)\n\n # apply the date-specific lookups\n if isinstance(self._meta.model._meta.get_field(self._meta.date_field), DateTimeField):\n min_date = datetime.datetime.combine(date, datetime.time.min)\n max_date = datetime.datetime.combine(date, datetime.time.max)\n query = {'%s__range' % self._meta.date_field: (min_date, max_date)}\n else:\n query = {self._meta.date_field: date}\n \n # apply the regular search lookups\n for key, value in self._meta.fields_to_match.iteritems():\n try:\n query[value] = params[key]\n except KeyError:\n raise OEmbedException('%s was not found in the urlpattern parameters. Valid names are: %s' % (key, ', '.join(params.keys())))\n \n try:\n obj = self.get_queryset().get(**query)\n except self._meta.model.DoesNotExist:\n raise OEmbedException('Requested object not found')\n \n return obj", "response": "Parses the date from a url and uses it in the query."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_record(self):\n self.recid = self.get_recid()\n self.remove_controlfields()\n self.update_system_numbers()\n self.add_systemnumber(\"Inspire\", recid=self.recid)\n self.add_control_number(\"003\", \"SzGeCERN\")\n self.update_collections()\n self.update_languages()\n self.update_reportnumbers()\n self.update_authors()\n self.update_journals()\n self.update_subject_categories(\"INSPIRE\", \"SzGeCERN\", \"categories_cds\")\n self.update_pagenumber()\n self.update_notes()\n self.update_experiments()\n self.update_isbn()\n self.update_dois()\n self.update_links_and_ffts()\n self.update_date()\n self.update_date_year()\n self.update_hidden_notes()\n self.update_oai_info()\n self.update_cnum()\n self.update_conference_info()\n\n self.fields_list = [\n \"909\", \"541\", \"961\",\n \"970\", \"690\", \"695\",\n \"981\",\n ]\n self.strip_fields()\n\n if \"ANNOUNCEMENT\" in self.collections:\n self.update_conference_111()\n self.update_conference_links()\n record_add_field(self.record, \"690\", ind1=\"C\", subfields=[(\"a\", \"CONFERENCE\")])\n\n if \"THESIS\" in self.collections:\n self.update_thesis_information()\n self.update_thesis_supervisors()\n\n if \"PROCEEDINGS\" in self.collections:\n # Special proceeding syntax\n self.update_title_to_proceeding()\n self.update_author_to_proceeding()\n record_add_field(self.record, \"690\", ind1=\"C\", subfields=[(\"a\", \"CONFERENCE\")])\n\n # 690 tags\n if self.tag_as_cern:\n record_add_field(self.record, \"690\", ind1=\"C\", subfields=[(\"a\", \"CERN\")])\n\n return self.record", "response": "Override the base method to get the record."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef update_oai_info(self):\n for field in record_get_field_instances(self.record, '909', ind1=\"C\", ind2=\"O\"):\n new_subs = []\n for tag, value in field[0]:\n if tag == \"o\":\n new_subs.append((\"a\", value))\n else:\n new_subs.append((tag, value))\n if value in [\"CERN\", \"CDS\", \"ForCDS\"]:\n self.tag_as_cern = True\n record_add_field(self.record, '024', ind1=\"8\", subfields=new_subs)\n record_delete_fields(self.record, '909')", "response": "Update the 909 OAI info to 035."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef update_cnum(self):\n if \"ConferencePaper\" not in self.collections:\n cnums = record_get_field_values(self.record, '773', code=\"w\")\n for cnum in cnums:\n cnum_subs = [\n (\"9\", \"INSPIRE-CNUM\"),\n (\"a\", cnum)\n ]\n record_add_field(self.record, \"035\", subfields=cnum_subs)", "response": "Check if we shall add cnum in 035."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef update_hidden_notes(self):\n if not self.tag_as_cern:\n notes = record_get_field_instances(self.record,\n tag=\"595\")\n for field in notes:\n for dummy, value in field[0]:\n if value == \"CDS\":\n self.tag_as_cern = True\n record_delete_fields(self.record, tag=\"595\")", "response": "Remove hidden notes and tag a CERN if detected."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef update_system_numbers(self):\n scn_035_fields = record_get_field_instances(self.record, '035')\n new_fields = []\n for field in scn_035_fields:\n subs = field_get_subfields(field)\n if '9' in subs:\n if subs['9'][0].lower() == \"cds\" and subs.get('a'):\n self.add_control_number(\"001\", subs.get('a')[0])\n if subs['9'][0].lower() in [\"inspire\", \"spirestex\", \"inspiretex\", \"desy\", \"cds\"]:\n continue\n new_fields.append(field_get_subfield_instances(field))\n record_delete_fields(self.record, tag=\"035\")\n for field in new_fields:\n record_add_field(self.record, tag=\"035\", subfields=field)", "response": "Update the system numbers of the 3035 records."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nupdate the list of collections that this record belongs to.", "response": "def update_collections(self):\n \"\"\"Try to determine which collections this record should belong to.\"\"\"\n for value in record_get_field_values(self.record, '980', code='a'):\n if 'NOTE' in value.upper():\n self.collections.add('NOTE')\n if 'THESIS' in value.upper():\n self.collections.add('THESIS')\n\n if 'PUBLISHED' in value.upper():\n self.collections.add('ARTICLE')\n\n if 'CONFERENCES' in value.upper():\n self.collections.add('ANNOUNCEMENT')\n\n if 'PROCEEDINGS' in value.upper():\n self.collections.add('PROCEEDINGS')\n elif 'CONFERENCEPAPER' in value.upper() and \\\n \"ConferencePaper\" not in self.collections:\n self.collections.add('ConferencePaper')\n if self.is_published() and \"ARTICLE\" not in self.collections:\n self.collections.add('ARTICLE')\n else:\n self.collections.add('PREPRINT')\n\n if \"HIDDEN\" in value.upper():\n self.hidden = True\n\n # Clear out any existing ones.\n record_delete_fields(self.record, \"980\")\n\n if not self.collections:\n self.collections.add('PREPRINT')\n\n for collection in self.collections:\n record_add_field(self.record,\n tag='980',\n subfields=[('a', collection)])\n if collection in self.collection_base:\n subs = [('a', self.collection_base[collection])]\n record_add_field(self.record,\n tag='960',\n subfields=subs)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nremove INSPIRE specific notes.", "response": "def update_notes(self):\n \"\"\"Remove INSPIRE specific notes.\"\"\"\n fields = record_get_field_instances(self.record, '500')\n for field in fields:\n subs = field_get_subfields(field)\n for sub in subs.get('a', []):\n sub = sub.strip() # remove any spaces before/after\n if sub.startswith(\"*\") and sub.endswith(\"*\"):\n record_delete_field(self.record, tag=\"500\",\n field_position_global=field[4])"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nmove title info from 245 to 111 proceeding style.", "response": "def update_title_to_proceeding(self):\n \"\"\"Move title info from 245 to 111 proceeding style.\"\"\"\n titles = record_get_field_instances(self.record,\n tag=\"245\")\n for title in titles:\n subs = field_get_subfields(title)\n new_subs = []\n if \"a\" in subs:\n new_subs.append((\"a\", subs['a'][0]))\n if \"b\" in subs:\n new_subs.append((\"c\", subs['b'][0]))\n record_add_field(self.record,\n tag=\"111\",\n subfields=new_subs)\n record_delete_fields(self.record, tag=\"245\")\n record_delete_fields(self.record, tag=\"246\")"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef update_experiments(self):\n # 693 Remove if 'not applicable'\n for field in record_get_field_instances(self.record, '693'):\n subs = field_get_subfields(field)\n acc_experiment = subs.get(\"e\", [])\n if not acc_experiment:\n acc_experiment = subs.get(\"a\", [])\n if not acc_experiment:\n continue\n experiment = acc_experiment[-1]\n\n # Handle special case of leading experiments numbers NA-050 -> NA 50\n e_suffix = \"\"\n if \"-NA-\" in experiment or \\\n \"-RD-\" in experiment or \\\n \"-WA-\" in experiment:\n splitted_experiment = experiment.split(\"-\")\n e_suffix = \"-\".join(splitted_experiment[2:])\n if e_suffix.startswith(\"0\"):\n e_suffix = e_suffix[1:]\n experiment = \"-\".join(splitted_experiment[:2]) # only CERN-NA\n\n translated_experiment = self.get_config_item(experiment,\n \"experiments\")\n if not translated_experiment:\n continue\n new_subs = []\n if \"---\" in translated_experiment:\n experiment_a, experiment_e = translated_experiment.split(\"---\")\n new_subs.append((\"a\", experiment_a.replace(\"-\", \" \")))\n else:\n experiment_e = translated_experiment\n new_subs.append((\"e\", experiment_e.replace(\"-\", \" \") + e_suffix))\n record_delete_field(self.record, tag=\"693\",\n field_position_global=field[4])\n record_add_field(self.record, \"693\", subfields=new_subs)", "response": "Update the experiments of the CERN record."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef update_authors(self):\n author_names = record_get_field_instances(self.record, '100')\n author_names.extend(record_get_field_instances(self.record, '700'))\n for field in author_names:\n subs = field_get_subfields(field)\n for idx, (key, value) in enumerate(field[0]):\n if key == 'a':\n field[0][idx] = ('a', value.replace(\".\", \" \").strip())\n elif key == 'v':\n del field[0][idx]\n if subs.get(\"u\", None) == \"CERN\":\n self.tag_as_cern = True", "response": "Update the author names of the archive."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef update_isbn(self):\n isbns = record_get_field_instances(self.record, '020')\n for field in isbns:\n for idx, (key, value) in enumerate(field[0]):\n if key == 'a':\n field[0][idx] = ('a', value.replace(\"-\", \"\").strip())", "response": "Remove dashes from ISBN."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef update_dois(self):\n dois = record_get_field_instances(self.record, '024', ind1=\"7\")\n all_dois = {}\n for field in dois:\n subs = field_get_subfield_instances(field)\n subs_dict = dict(subs)\n if subs_dict.get('a'):\n if subs_dict['a'] in all_dois:\n record_delete_field(self.record, tag='024', ind1='7', field_position_global=field[4])\n continue\n all_dois[subs_dict['a']] = field", "response": "Update all BibMatch DOIs."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef update_journals(self):\n for field in record_get_field_instances(self.record, '773'):\n subs = field_get_subfield_instances(field)\n new_subs = []\n volume_letter = \"\"\n journal_name = \"\"\n for idx, (key, value) in enumerate(subs):\n if key == 'p':\n journal_name = self.get_config_item(value, \"journals\", allow_substring=False)\n # Make sure journal names have the form (dot)(space) (I know it's horrible)\n journal_name = journal_name.replace('. ', '.').replace('.', '. ').replace('. ,', '.,').strip()\n elif key == 'v':\n volume_letter = value\n else:\n new_subs.append((key, value))\n\n if not journal_name == \"PoS\":\n # Special handling of journal name and volumes, except PoS\n letter = return_letters_from_string(volume_letter)\n if letter:\n journal_name = \"{0} {1}\".format(journal_name, letter)\n volume_letter = volume_letter.strip(letter)\n\n if journal_name:\n new_subs.append((\"p\", journal_name))\n if volume_letter:\n new_subs.append((\"v\", volume_letter))\n record_delete_field(self.record, tag=\"773\",\n field_position_global=field[4])\n record_add_field(self.record, \"773\", subfields=new_subs)", "response": "Update the journals field in the record."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef update_thesis_supervisors(self):\n for field in record_get_field_instances(self.record, '701'):\n subs = list(field[0])\n subs.append((\"e\", \"dir.\"))\n record_add_field(self.record, '700', subfields=subs)\n record_delete_fields(self.record, '701')", "response": "700 -> 701 Thesis supervisors."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nupdates the page number of the records.", "response": "def update_pagenumber(self):\n \"\"\"300 page number.\"\"\"\n pages = record_get_field_instances(self.record, '300')\n for field in pages:\n for idx, (key, value) in enumerate(field[0]):\n if key == 'a':\n field[0][idx] = ('a', \"{0} p\".format(value))"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nchecks if the record has already been published.", "response": "def is_published(self):\n \"\"\"Check fields 980 and 773 to see if the record has already been published.\n\n :return: True is published, else False\n \"\"\"\n field773 = record_get_field_instances(self.record, '773')\n for f773 in field773:\n if 'c' in field_get_subfields(f773):\n return True\n return False"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nupdate links and FFTs for the current ISO.", "response": "def update_links_and_ffts(self):\n \"\"\"FFT (856) Dealing with files.\"\"\"\n for field in record_get_field_instances(self.record,\n tag='856',\n ind1='4'):\n subs = field_get_subfields(field)\n newsubs = []\n url = subs.get(\"u\", [])\n\n if not url:\n record_delete_field(self.record, '856', ind1='4',\n field_position_global=field[4])\n continue\n url = url[0]\n if \"inspirehep.net/record\" in url and url.endswith(\"pdf\"):\n # We have an FFT from INSPIRE\n newsubs.append(('a', url))\n description = subs.get(\"y\", [])\n if description:\n newsubs.append(('d', description[0]))\n if newsubs:\n record_add_field(self.record, 'FFT', subfields=newsubs)\n record_delete_field(self.record, '856', ind1='4',\n field_position_global=field[4])\n else:\n # Remove $w\n for idx, (key, value) in enumerate(field[0]):\n if key == 'w':\n del field[0][idx]"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef update_languages(self):\n language_fields = record_get_field_instances(self.record, '041')\n language = \"eng\"\n record_delete_fields(self.record, \"041\")\n for field in language_fields:\n subs = field_get_subfields(field)\n if 'a' in subs:\n language = self.get_config_item(subs['a'][0], \"languages\")\n break\n new_subs = [('a', language)]\n record_add_field(self.record, \"041\", subfields=new_subs)", "response": "Update the languages field in the record."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef pathjoin(*args, **kwargs):\n log.debug('pathjoin: %r' % list(args))\n\n def _pathjoin(*args, **kwargs):\n len_ = len(args) - 1\n if len_ < 0:\n raise Exception('no args specified')\n elif len_ == 0:\n if not isinstance(args, basestring):\n if hasattr(args, '__iter__'):\n _args = args\n _args\n args = args[0]\n for i, arg in enumerate(args):\n if not i:\n yield arg.rstrip('/')\n elif i == len_:\n yield arg.lstrip('/')\n else:\n yield arg.strip('/')\n joined_path = u'/'.join(_pathjoin(*args))\n return sanitize_path(joined_path)", "response": "Join the paths of a single object with the key - value pairs."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ngenerate the HTML directory listing for the given directory.", "response": "def generate_dirlist_html(FS, filepath):\n \"\"\"\n Generate directory listing HTML\n\n Arguments:\n FS (FS): filesystem object to read files from\n filepath (str): path to generate directory listings for\n\n Keyword Arguments:\n list_dir (callable: list[str]): list file names in a directory\n isdir (callable: bool): os.path.isdir\n\n Yields:\n str: lines of an HTML table\n \"\"\"\n yield '
'\n if filepath == '/':\n filepath = ''\n for name in FS.listdir(filepath):\n full_path = pathjoin(filepath, name)\n if FS.isdir(full_path):\n full_path = full_path + '/'\n yield u'
'\n ]\n if table_row_count == IMAGES_PER_ROW:\n table_row_count = 0\n html.append('
')\n table_row_count += 1\n html += ['', '
']\n html += [\n '
',\n ' ',\n ''\n ]\n # Actually create the file, now we've put together the HTML content\n index_file_path = _get_index_file_path(location)\n print('Creating index file %s' % index_file_path)\n index_file = open(index_file_path, 'w')\n index_file.write('\\n'.join(html))\n index_file.close()\n # Return the path for cleaning up later\n return index_file_path"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _create_index_files(root_dir, force_no_processing=False):\n # Initialise list of created file paths to build up as we make them\n created_files = []\n # Walk the root dir downwards, creating index files as we go\n for here, dirs, files in os.walk(root_dir):\n print('Processing %s' % here)\n # Sort the subdirectories by name\n dirs = sorted(dirs)\n # Get image files - all files in the directory matching IMAGE_FILE_REGEX\n image_files = [f for f in files if re.match(IMAGE_FILE_REGEX, f)]\n # Sort the image files by name\n image_files = sorted(image_files)\n # Create this directory's index file and add its name to the created\n # files list\n created_files.append(\n _create_index_file(\n root_dir, here, image_files, dirs, force_no_processing\n )\n )\n # Return the list of created files\n return created_files", "response": "Create the index files in each node in the directory root_dir and return the list of created files."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngets an instance of PIL. Image from the given file.", "response": "def _get_image_from_file(dir_path, image_file):\n \"\"\"\n Get an instance of PIL.Image from the given file.\n @param {String} dir_path - The directory containing the image file\n @param {String} image_file - The filename of the image file within dir_path\n @return {PIL.Image} An instance of the image file as a PIL Image, or None\n if the functionality is not available. This could be because PIL is not\n present, or because it can't process the given file type.\n \"\"\"\n # Save ourselves the effort if PIL is not present, and return None now\n if not PIL_ENABLED:\n return None\n # Put together full path\n path = os.path.join(dir_path, image_file)\n # Try to read the image\n img = None\n try:\n img = Image.open(path)\n except IOError as exptn:\n print('Error loading image file %s: %s' % (path, exptn))\n # Return image or None\n return img"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nget the value to be used as the href for links from thumbnail images.", "response": "def _get_image_link_target_from_file(dir_path, image_file, force_no_processing=False):\n \"\"\"\n Get the value to be used as the href for links from thumbnail images. For\n most image formats this will simply be the image file name itself. However,\n some image formats (tif) are not natively displayable by many browsers and\n therefore we must link to image data in another format.\n @param {String} dir_path - The directory containing the image file\n @param {String} image_file - The filename of the image file within dir_path\n @param {Boolean=False} force_no_processing - If True, do not attempt to\n actually process a thumbnail, PIL image or anything. Simply return the\n image filename as src.\n @return {String} The href to use.\n \"\"\"\n # If we've specified to force no processing, just return the image filename\n if force_no_processing:\n return image_file\n # First try to get an image\n img = _get_image_from_file(dir_path, image_file)\n # If format is directly displayable in-browser, just return the filename\n # Else, we need to return a full-sized chunk of displayable image data\n if img.format.lower() in ['tif', 'tiff']:\n return _get_image_src_from_file(\n dir_path, image_file, force_no_processing\n )\n return image_file"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _get_image_src_from_file(dir_path, image_file, force_no_processing=False):\n # If we've specified to force no processing, just return the image filename\n if force_no_processing:\n if image_file.endswith('tif') or image_file.endswith('tiff'):\n return UNSUPPORTED_IMAGE_TYPE_DATA\n return image_file\n # First try to get an image\n img = _get_image_from_file(dir_path, image_file)\n return _get_src_from_image(img, image_file)", "response": "Get the base - 64 encoded data for the given image file."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nget base - 64 encoded data as a string for the given image. Fallback to return fallback_image_file", "response": "def _get_src_from_image(img, fallback_image_file):\n \"\"\"\n Get base-64 encoded data as a string for the given image. Fallback to return\n fallback_image_file if cannot get the image data or img is None.\n @param {Image} img - The PIL Image to get src data for\n @param {String} fallback_image_file - The filename of the image file,\n to be used when image data capture fails\n @return {String} The base-64 encoded image data string, or path to the file\n itself if not supported.\n \"\"\"\n # If the image is None, then we can't process, so we should return the\n # path to the file itself\n if img is None:\n return fallback_image_file\n # Target format should be the same as the original image format, unless it's\n # a TIF/TIFF, which can't be displayed by most browsers; we convert these\n # to jpeg\n target_format = img.format\n if target_format.lower() in ['tif', 'tiff']:\n target_format = 'JPEG'\n # If we have an actual Image, great - put together the base64 image string\n try:\n bytesio = io.BytesIO()\n img.save(bytesio, target_format)\n byte_value = bytesio.getvalue()\n b64 = base64.b64encode(byte_value)\n return 'data:image/%s;base64,%s' % (target_format.lower(), b64)\n except IOError as exptn:\n print('IOError while saving image bytes: %s' % exptn)\n return fallback_image_file"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _get_thumbnail_image_from_file(dir_path, image_file):\n # Get image\n img = _get_image_from_file(dir_path, image_file)\n # If it's not supported, exit now\n if img is None:\n return None\n if img.format.lower() == 'gif':\n return None\n # Get image dimensions\n img_width, img_height = img.size\n # We need to perform a resize - first, work out the scale ratio to take the\n # image width to THUMBNAIL_WIDTH (THUMBNAIL_WIDTH:img_width ratio)\n scale_ratio = THUMBNAIL_WIDTH / float(img_width)\n # Work out target image height based on the scale ratio\n target_height = int(scale_ratio * img_height)\n # Perform the resize\n try:\n img.thumbnail((THUMBNAIL_WIDTH, target_height), resample=RESAMPLE)\n except IOError as exptn:\n print('WARNING: IOError when thumbnailing %s/%s: %s' % (\n dir_path, image_file, exptn\n ))\n return None\n # Return the resized image\n return img", "response": "Get a PIL. Image from the given image file which has been scaled down to\n THUMBNAIL_WIDTH wide."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _get_thumbnail_src_from_file(dir_path, image_file, force_no_processing=False):\n # If we've specified to force no processing, just return the image filename\n if force_no_processing:\n if image_file.endswith('tif') or image_file.endswith('tiff'):\n return UNSUPPORTED_IMAGE_TYPE_DATA\n return image_file\n # First try to get a thumbnail image\n img = _get_thumbnail_image_from_file(dir_path, image_file)\n return _get_src_from_image(img, image_file)", "response": "Get the base - 64 encoded data for the given image file s thumbnail and the image filename as src."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _run_server():\n # Get the port to run on\n port = _get_server_port()\n # Configure allow_reuse_address to make re-runs of the script less painful -\n # if this is not True then waiting for the address to be freed after the\n # last run can block a subsequent run\n SocketServer.TCPServer.allow_reuse_address = True\n # Create the server instance\n server = SocketServer.TCPServer(\n ('', port),\n SimpleHTTPServer.SimpleHTTPRequestHandler\n )\n # Print out before actually running the server (cheeky / optimistic, however\n # you want to look at it)\n print('Your images are at http://127.0.0.1:%d/%s' % (\n port,\n INDEX_FILE_NAME\n ))\n # Try to run the server\n try:\n # Run it - this call blocks until the server is killed\n server.serve_forever()\n except KeyboardInterrupt:\n # This is the expected way of the server being killed, since imageMe is\n # intended for ad-hoc running from command line\n print('User interrupted, stopping')\n except Exception as exptn:\n # Catch everything else - this will handle shutdowns via other signals\n # and faults actually starting the server in the first place\n print(exptn)\n print('Unhandled exception in server, stopping')", "response": "Runs the image server. This is blocking. Will handle user KeyboardInterrupt and other exceptions appropriately and return control once the server is stopped."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngenerating indexes and run server from the given directory downwards.", "response": "def serve_dir(dir_path):\n \"\"\"\n Generate indexes and run server from the given directory downwards.\n @param {String} dir_path - The directory path (absolute, or relative to CWD)\n @return {None}\n \"\"\"\n # Create index files, and store the list of their paths for cleanup later\n # This time, force no processing - this gives us a fast first-pass in terms\n # of page generation, but potentially slow serving for large image files\n print('Performing first pass index file generation')\n created_files = _create_index_files(dir_path, True)\n if (PIL_ENABLED):\n # If PIL is enabled, we'd like to process the HTML indexes to include\n # generated thumbnails - this slows down generation so we don't do it\n # first time around, but now we're serving it's good to do in the\n # background\n print('Performing PIL-enchanced optimised index file generation in background')\n background_indexer = BackgroundIndexFileGenerator(dir_path)\n background_indexer.run()\n # Run the server in the current location - this blocks until it's stopped\n _run_server()\n # Clean up the index files created earlier so we don't make a mess of\n # the image directories\n _clean_up(created_files)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngetting caller s modulename", "response": "def modulename(cls, depth=1):\n \"\"\"\n get caller's __name__\n \"\"\"\n depth += cls.extra_depth\n frame = sys._getframe(depth)\n return frame.f_globals['__name__']"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef deco_optional(decorator):\n\n @functools.wraps(decorator)\n def dispatcher(*args, **kwargs):\n one_arg = len(args) == 1 and not kwargs\n if one_arg and inspect.isfunction(args[0]):\n decor_obj = decorator()\n return decor_obj(args[0])\n else:\n return decorator(*args, **kwargs)\n\n return dispatcher", "response": "Decorator to be used as a decorator for optional arguments."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef optional(deco):\n @functools.wraps(deco)\n def dispatcher(*args, **kwargs):\n decorator = deco(**kwargs)\n if args:\n assert len(args) == 1\n return decorator(args[0])\n else:\n return decorator\n return dispatcher", "response": "A decorator that returns a function that takes a single argument and returns the first argument."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nbinds a function to a sequence of arguments", "response": "def bindargs(fun, *argsbind, **kwbind):\n \"\"\"\n _ = bind.placeholder # unbound placeholder (arg)\n f = bind(fun, _, _, arg3, kw=kw1, kw2=kw2), f(arg1, arg2)\n :param fun:\n :param argsbind:\n :param kwbind:\n :return:\n \"\"\"\n\n assert argsbind\n argsb = list(argsbind)\n iargs = [i for i in range(len(argsbind)) if argsbind[i] is bind.placeholder]\n # iargs = [a is bind.placeholder for a in argsbind]\n\n @functools.wraps(fun)\n def wrapped(*args, **kwargs):\n kws = kwbind.copy()\n\n args_this = [a for a in argsb]\n for i, arg in zip(iargs, args):\n args_this[i] = arg\n args_this.extend(args[len(iargs):])\n\n # kwargs.update(kwbind)\n kws.update(kwargs)\n # return fun(*argsb, **kws)\n return fun(*args_this, **kws)\n\n return wrapped"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef default(fun, **kwdefault):\n\n @functools.wraps(fun)\n def wrapped(*args, **kwargs):\n merge = wrapped.default.copy()\n merge.update(kwargs)\n return fun(*args, **merge)\n\n wrapped.default = kwdefault\n\n return wrapped", "response": "change default value for function\n ex"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef setup_once(initfn):\n def wrap(method):\n\n finit = initfn.__name__\n fnname = method.__name__\n\n @functools.wraps(method)\n def wrapped(self, *args, **kwargs):\n\n @functools.wraps(method)\n def aftersetup(*a, **kw):\n return method(self, *a, **kw)\n\n setupfn = getattr(self, finit)\n setupfn(*args, **kwargs)\n\n res = method(self, *args, **kwargs)\n setattr(self, fnname, aftersetup)\n return res\n return wrapped\n\n return wrap", "response": "A decorator that makes sure that the initfn is called only once."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef rand_crop(sz, *imagez):\n\n def _rand_crop(*imgz):\n imsz = imgz[0].shape[:2]\n\n assert imsz[0] >= sz[0] and imsz[1] >= sz[1]\n\n si = np.random.randint(imsz[0] - sz[0]) if imsz[0] > sz[0] else 0\n sj = np.random.randint(imsz[1] - sz[1]) if imsz[1] > sz[1] else 0\n\n slicei = slice(si, si+sz[0])\n slicej = slice(sj, sj+sz[1])\n\n outs = tuple(img[slicei, slicej] for img in imgz)\n return tuple_or_not(*outs)\n\n return _rand_crop(*imagez) if imagez else _rand_crop", "response": "random crop\n # assume imagez has same size (H, W)\n # assume sz is less or equal than size of image\n :param sz: cropped image sz\n :param imagez: imagez\n :return: rand cropped image pairs or function bound to sz"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef blend_discrete(images, depthmask, depth=None):\n imshape = images.shape\n depth = depth or images.shape[3]\n blend = np.empty(shape=(imshape[0], imshape[1], imshape[2]))\n for d in range(depth):\n imask = (depthmask == d)\n channel = images[..., d]\n blend[imask] = channel[imask]\n return np.expand_dims(blend, axis=-1)", "response": "Blend discrete images into one image at a time."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nvectoring parameters :param size: :param vz: :param vscale: :param voctave: :param vpersistence: :param vlacunarity: :return:", "response": "def snoise2dvec(size, *params, **kwargs): #, vlacunarity):\n \"\"\"\n vector parameters\n :param size:\n :param vz:\n :param vscale:\n :param voctave:\n :param vpersistence:\n :param vlacunarity:\n :return:\n \"\"\"\n data = (snoise2d(size, *p, **kwargs) for p in zip(*params)) # , vlacunarity))\n return np.stack(data, 0)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef snoise2d(size, z=0.0, scale=0.05, octaves=1, persistence=0.25, lacunarity=2.0):\n import noise\n data = np.empty(size, dtype='float32')\n for y in range(size[0]):\n for x in range(size[1]):\n v = noise.snoise3(x * scale, y * scale, z,\n octaves=octaves, persistence=persistence, lacunarity=lacunarity)\n data[x, y] = v\n data = data * 0.5 + 0.5\n if __debug__:\n assert data.min() >= 0. and data.max() <= 1.0\n return data", "response": "snoise2d - 2D function for the given size z - value as like a seed\n "}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef snoise2dz(size, z, scale=0.05, octaves=1, persistence=0.25, lacunarity=2.0):\n import noise\n z_l = len(z)\n\n data = np.empty((z_l, size[0], size[1]), dtype='float32')\n for iz in range(z_l):\n zvalue = z[iz]\n for y in range(size[0]):\n for x in range(size[1]):\n v = noise.snoise3(x * scale, y * scale, zvalue,\n octaves=octaves, persistence=persistence, lacunarity=lacunarity)\n data[iz, y, x] = v\n data = data * 0.5 + 0.5\n if __debug__:\n assert data.min() >= 0. and data.max() <= 1.0\n return data", "response": "snoise2dz - 2D z - > numpy array"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef rand_brightness(imagez, scale=1.0, randfun=rand.normal(0., .1), clamp=(0., 1.)):\n l, h = clamp\n r = randfun((imagez[0].shape[0], 1, 1, 1)) * scale\n\n def apply(im):\n im += r\n im[im < l] = l\n im[im > h] = h\n return im\n\n return tuple(map(apply, imagez))", "response": "Randomly select a set of images from the imagez array."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef elastic_transform(im, alpha=0.5, sigma=0.2, affine_sigma=1.):\n # fixme : not implemented for multi channel !\n import cv2\n\n islist = isinstance(im, (tuple, list))\n ima = im[0] if islist else im\n\n # image shape\n shape = ima.shape\n shape_size = shape[:2]\n\n # Random affine transform\n center_square = np.float32(shape_size) // 2\n square_size = min(shape_size) // 3\n pts1 = np.float32([center_square + square_size,\n [center_square[0] + square_size, center_square[1] - square_size],\n center_square - square_size])\n pts2 = pts1 + np.random.uniform(-affine_sigma, affine_sigma, size=pts1.shape).astype(np.float32)\n M = cv2.getAffineTransform(pts1, pts2)\n if islist:\n res = []\n for i, ima in enumerate(im):\n if i == 0:\n res.append(cv2.warpAffine(ima, M, shape_size[::-1], borderMode=cv2.BORDER_REFLECT_101))\n else:\n res.append(cv2.warpAffine(ima, M, shape_size[::-1]))\n im = res\n else:\n ima = cv2.warpAffine(ima, M, shape_size[::-1], borderMode=cv2.BORDER_REFLECT_101)\n # ima = cv2.warpAffine(ima, M, shape_size[::-1])\n\n # fast gaussian filter\n blur_size = int(4 * sigma) | 1\n dx = cv2.GaussianBlur((np.random.rand(*shape) * 2 - 1), ksize=(blur_size, blur_size), sigmaX=sigma) * alpha\n dy = cv2.GaussianBlur((np.random.rand(*shape) * 2 - 1), ksize=(blur_size, blur_size), sigmaX=sigma) * alpha\n\n # remap\n x, y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))\n map_x, map_y = (y + dy).astype('float32'), (x + dx).astype('float32')\n\n def remap(data):\n r = cv2.remap(data, map_y, map_x, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)\n return r[..., np.newaxis]\n\n if islist:\n return tuple([remap(ima) for ima in im])\n else:\n return remap(ima)", "response": "This function transforms an image into an elastic deformation of images."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nrotating and crop the image with the given centerij and angle", "response": "def rotate_crop(centerij, sz, angle, img=None, mode='constant', **kwargs):\n \"\"\"\n rotate and crop\n if no img, then return crop function\n :param centerij:\n :param sz:\n :param angle:\n :param img: [h,w,d]\n :param mode: padding option\n :return: cropped image or function\n \"\"\"\n # crop enough size ( 2 * sqrt(sum(sz^2) )\n # rotate\n from skimage import transform\n sz = np.array(sz)\n crop_half = int(np.ceil(np.sqrt(np.square(sz).sum())))\n\n if centerij[0] >= crop_half or centerij[1] >= crop_half:\n raise NotImplementedError\n\n slicei = slice(centerij[0] - crop_half, centerij[0] + crop_half)\n slicej = slice(centerij[1] - crop_half, centerij[1] + crop_half)\n\n # slicei = (centerij[0] - crop_half, centerij[0] + crop_half)\n # slicej = (centerij[1] - crop_half, centerij[1] + crop_half)\n\n # def _pad_if_need(im):\n # imshape = im.shape\n # pad_need = slicei[0] < 0 or slicej[0] < 0 or slice\n # padwidth = [(slicei[0], np.maximum(0, slicei[1] - imshape[0])),\n # (slicej[0], np.maximum(0, slicej[1] - imshape[1]))]\n\n def _rotate_cropcenter(im):\n enoughcrop = im[slicei, slicej]\n\n rotated = transform.rotate(enoughcrop, angle, resize=False, preserve_range=True, mode=mode, **kwargs)\n return cropcenter(sz, rotated)\n if img is not None:\n return _rotate_cropcenter(img)\n\n return _rotate_cropcenter"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef crop(img, center, sz, mode='constant'):\n center = np.array(center)\n sz = np.array(sz)\n istart = (center - sz / 2.).astype('int32')\n iend = istart + sz\n imsz = img.shape[:2]\n if np.any(istart < 0) or np.any(iend > imsz):\n # padding\n padwidth = [(np.minimum(0, istart[0]), np.maximum(0, iend[0]-imsz[0])),\n (np.minimum(0, istart[1]), np.maximum(0, iend[1]-imsz[1]))]\n padwidth += [(0, 0)] * (len(img.shape) - 2)\n img = np.pad(img, padwidth, mode=mode)\n istart = (np.maximum(0, istart[0]), np.maximum(0, istart[1]))\n\n return img[istart[0]:istart[0]+sz[0], istart[1]:istart[1]+sz[1]]\n\n return img[istart[0]:iend[0], istart[1]:iend[1]]", "response": "crop sz from ij as center"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn a function that crops the image with the given size.", "response": "def cropcenter(sz, img=None):\n \"\"\"\n if no img, then return crop function\n :param sz:\n :param img:\n :return:\n \"\"\"\n l = len(sz)\n sz = np.array(sz)\n\n def wrapped(im):\n imsz = np.array(im.shape)\n s = (imsz[:l] - sz) / 2 # start index\n to = s + sz # end index\n\n # img[s[0]:to[0], ... s[end]:to[end], ...]\n slices = [slice(s, e) for s, e in zip(s, to)]\n\n return im[slices]\n\n if img is not None:\n return wrapped(img)\n\n return wrapped"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\npads img if need to guarantee minumum size", "response": "def pad_if_need(sz_atleast, img, mode='constant'):\n # fixme : function or ....\n \"\"\"\n pad img if need to guarantee minumum size\n :param sz_atleast: [H,W] at least\n :param img: image np.array [H,W, ...]\n :param mode: str, padding mode\n :return: padded image or asis if enought size\n \"\"\"\n # sz_atleast = np.asarray(sz_atleast)\n imsz = img.shape[:2] # assume img [H,W, ...]\n padneed = np.asarray((sz_atleast[0] - imsz[0], sz_atleast[1] - imsz[1]))\n if np.any(padneed > 0):\n # need padding\n padding = np.zeros((img.ndim, 2), dtype='int16')\n padneed = np.maximum(padneed, 0)\n padding[:2, 0] = padneed/2\n padding[:2, 1] = padneed - padneed/2\n img = np.pad(img, padding, mode=mode)\n\n return img"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nguesses the package path for the given object.", "response": "def guess_package_path(searchfrom):\n \"\"\"\n package path. return None if failed to guess\n \"\"\"\n from snipy.io import fileutil\n\n current = searchfrom + '/'\n init_found = False\n pack_found = False\n while not init_found and current != '/':\n current = os.path.dirname(current)\n initfile = os.path.join(current, '__init__.py')\n init_found = os.path.exists(initfile)\n\n if not init_found:\n # search for breadth\n searchfrom = dirname(searchfrom)\n\n for folder in fileutil.listfolder(searchfrom):\n current = os.path.join(searchfrom, folder)\n initfile = os.path.join(current, '__init__.py')\n init_found = os.path.exists(initfile)\n if init_found:\n break\n\n while init_found:\n current = os.path.dirname(current)\n initfile = os.path.join(current, '__init__.py')\n init_found = os.path.exists(initfile)\n pack_found = not init_found\n\n return current if pack_found else None"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef find_package_path(searchfrom):\n\n current = searchfrom + '/'\n init_found = False\n pack_found = False\n while not init_found and current != '/':\n current = os.path.dirname(current)\n initfile = os.path.join(current, '__init__.py')\n init_found = os.path.exists(initfile)\n\n while init_found:\n current = os.path.dirname(current)\n initfile = os.path.join(current, '__init__.py')\n init_found = os.path.exists(initfile)\n pack_found = not init_found\n\n return current if pack_found else None", "response": "Find the package path of the\n ."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nappending sys path to this_package. py", "response": "def append_this_package_path(depth=1):\n \"\"\"\n this_package.py \uc5d0\uc11c \uc0ac\uc6a9\n import snipy.this_package\n \"\"\"\n from .caller import caller\n\n logg.debug('caller module %s', caller.modulename(depth + 1))\n c = caller.abspath(depth + 1)\n logg.debug('caller path %s', c)\n\n p = guess_package_path(dirname(c))\n if p:\n logg.debug('appending sys path %s', p)\n append_sys_path(p)\n else:\n # do some logging\n logg.debug('failed to guess package path for: %s', c)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef flows(args):\n\n def flow_if_not(fun):\n # t = type(fun)\n if isinstance(fun, iterator):\n return fun\n elif isinstance(fun, type) and 'itertools' in str(fun.__class__):\n return fun\n else:\n try:\n return flow(fun)\n except AttributeError:\n # generator object has no attribute '__module__'\n return fun\n\n return FlowList(map(flow_if_not, args))", "response": "return a FlowList of the passed in flows"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nadds example :param size: :param iterable: :param rest: :return:", "response": "def ibatch(size, iterable=None, rest=False):\n \"\"\"\n add example\n :param size:\n :param iterable:\n :param rest:\n :return:\n \"\"\"\n\n @iterflow\n def exact_size(it):\n it = iter(it)\n while True:\n yield [it.next() for _ in xrange(size)]\n\n @iterflow\n def at_most(it):\n it = iter(it)\n while True:\n data = []\n for _ in xrange(size):\n try:\n data.append(it.next())\n except StopIteration:\n if data:\n yield data\n raise StopIteration\n yield data\n\n ibatchit = at_most if rest else exact_size\n\n return ibatchit if iterable is None else ibatchit(iterable)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef batchzip(size, iterable=None, rest=False):\n fn = ibatch(size, rest=rest) >> zipflow\n\n return fn if iterable is None else fn(iterable)", "response": "batchzip - returns a sequence of size size"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ntaking a size in batches and returns a sequence of n - tuples", "response": "def batchstack(size, iterable=None, rest=False):\n \"\"\"\n todo : add example\n :param size:\n :param iterable:\n :param rest:\n :return:\n \"\"\"\n\n def stack(data):\n import numpy as np\n return map(np.vstack, data)\n\n fn = batchzip(size, rest=rest) >> flow(stack)\n\n return fn if iterable is None else fn(iterable)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef shuffle(qsize=1024, iterable=None):\n\n @iterflow\n def shuffleit(it):\n from random import randrange\n q = []\n\n for i, d in enumerate(it):\n q.insert(randrange(0, len(q) + 1), d)\n if i < qsize:\n continue\n yield q.pop(randrange(0, len(q)))\n\n while q:\n yield q.pop(randrange(0, len(q)))\n\n return shuffleit if iterable is None else shuffleit(iterable)", "response": "Returns an iterator that shuffle the given iterable."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nconverts a permutation into a permutation matrix.", "response": "def to_permutation_matrix(matches):\n \"\"\"Converts a permutation into a permutation matrix.\n\n `matches` is a dictionary whose keys are vertices and whose values are\n partners. For each vertex ``u`` and ``v``, entry (``u``, ``v``) in the\n returned matrix will be a ``1`` if and only if ``matches[u] == v``.\n\n Pre-condition: `matches` must be a permutation on an initial subset of the\n natural numbers.\n\n Returns a permutation matrix as a square NumPy array.\n\n \"\"\"\n n = len(matches)\n P = np.zeros((n, n))\n # This is a cleverer way of doing\n #\n # for (u, v) in matches.items():\n # P[u, v] = 1\n #\n P[list(zip(*(matches.items())))] = 1\n return P"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn the adjacency matrix of a bipartite graph whose biadjacency matrix is A.", "response": "def to_bipartite_matrix(A):\n \"\"\"Returns the adjacency matrix of a bipartite graph whose biadjacency\n matrix is `A`.\n\n `A` must be a NumPy array.\n\n If `A` has **m** rows and **n** columns, then the returned matrix has **m +\n n** rows and columns.\n\n \"\"\"\n m, n = A.shape\n return four_blocks(zeros(m, m), A, A.T, zeros(n, n))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef to_pattern_matrix(D):\n result = np.zeros_like(D)\n # This is a cleverer way of doing\n #\n # for (u, v) in zip(*(D.nonzero())):\n # result[u, v] = 1\n #\n result[D.nonzero()] = 1\n return result", "response": "Returns the Boolean matrix in the same shape as D with ones exactly\n where there are nonzero entries in D."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the Birkhoff - von Neumann decomposition of the given doubly - stochastic matrix D.", "response": "def birkhoff_von_neumann_decomposition(D):\n \"\"\"Returns the Birkhoff--von Neumann decomposition of the doubly\n stochastic matrix `D`.\n\n The input `D` must be a square NumPy array representing a doubly\n stochastic matrix (that is, a matrix whose entries are nonnegative\n reals and whose row sums and column sums are all 1). Each doubly\n stochastic matrix is a convex combination of at most ``n ** 2``\n permutation matrices, where ``n`` is the dimension of the input\n array.\n\n The returned value is a list of pairs whose length is at most ``n **\n 2``. In each pair, the first element is a real number in the interval **(0,\n 1]** and the second element is a NumPy array representing a permutation\n matrix. This represents the doubly stochastic matrix as a convex\n combination of the permutation matrices.\n\n The input matrix may also be a scalar multiple of a doubly\n stochastic matrix, in which case the row sums and column sums must\n each be *c*, for some positive real number *c*. This may be useful\n in avoiding precision issues: given a doubly stochastic matrix that\n will have many entries close to one, multiply it by a large positive\n integer. The returned permutation matrices will be the same\n regardless of whether the given matrix is a doubly stochastic matrix\n or a scalar multiple of a doubly stochastic matrix, but in the\n latter case, the coefficients will all be scaled by the appropriate\n scalar multiple, and their sum will be that scalar instead of one.\n\n For example::\n\n >>> import numpy as np\n >>> from birkhoff import birkhoff_von_neumann_decomposition as decomp\n >>> D = np.ones((2, 2))\n >>> zipped_pairs = decomp(D)\n >>> coefficients, permutations = zip(*zipped_pairs)\n >>> coefficients\n (1.0, 1.0)\n >>> permutations[0]\n array([[ 1., 0.],\n [ 0., 1.]])\n >>> permutations[1]\n array([[ 0., 1.],\n [ 1., 0.]])\n >>> zipped_pairs = decomp(D / 2) # halve each value in the matrix\n >>> coefficients, permutations = zip(*zipped_pairs)\n >>> coefficients # will be half as large as before\n (0.5, 0.5)\n >>> permutations[0] # will be the same as before\n array([[ 1., 0.],\n [ 0., 1.]])\n >>> permutations[1]\n array([[ 0., 1.],\n [ 1., 0.]])\n\n The returned list of pairs is given in the order computed by the algorithm\n (so in particular they are not sorted in any way).\n\n \"\"\"\n m, n = D.shape\n if m != n:\n raise ValueError('Input matrix must be square ({} x {})'.format(m, n))\n indices = list(itertools.product(range(m), range(n)))\n # These two lists will store the result as we build it up each iteration.\n coefficients = []\n permutations = []\n # Create a copy of D so that we don't modify it directly. Cast the\n # entries of the matrix to floating point numbers, regardless of\n # whether they were integers.\n S = D.astype('float')\n while not np.all(S == 0):\n # Create an undirected graph whose adjacency matrix contains a 1\n # exactly where the matrix S has a nonzero entry.\n W = to_pattern_matrix(S)\n # Construct the bipartite graph whose left and right vertices both\n # represent the vertex set of the pattern graph (whose adjacency matrix\n # is ``W``).\n X = to_bipartite_matrix(W)\n # Convert the matrix of a bipartite graph into a NetworkX graph object.\n G = from_numpy_matrix(X)\n # Compute a perfect matching for this graph. The dictionary `M` has one\n # entry for each matched vertex (in both the left and the right vertex\n # sets), and the corresponding value is its partner.\n #\n # The bipartite maximum matching algorithm requires specifying\n # the left set of nodes in the bipartite graph. By construction,\n # the left set of nodes is {0, ..., n - 1} and the right set is\n # {n, ..., 2n - 1}; see `to_bipartite_matrix()`.\n left_nodes = range(n)\n M = maximum_matching(G, left_nodes)\n # However, since we have both a left vertex set and a right vertex set,\n # each representing the original vertex set of the pattern graph\n # (``W``), we need to convert any vertex greater than ``n`` to its\n # original vertex number. To do this,\n #\n # - ignore any keys greater than ``n``, since they are already\n # covered by earlier key/value pairs,\n # - ensure that all values are less than ``n``.\n #\n M = {u: v % n for u, v in M.items() if u < n}\n # Convert that perfect matching to a permutation matrix.\n P = to_permutation_matrix(M)\n # Get the smallest entry of S corresponding to the 1 entries in the\n # permutation matrix.\n q = min(S[i, j] for (i, j) in indices if P[i, j] == 1)\n # Store the coefficient and the permutation matrix for later.\n coefficients.append(q)\n permutations.append(P)\n # Subtract P scaled by q. After this subtraction, S has a zero entry\n # where the value q used to live.\n S -= q * P\n # PRECISION ISSUE: There seems to be a problem with floating point\n # precision here, so we need to round down to 0 any entry that is very\n # small.\n S[np.abs(S) < TOLERANCE] = 0.0\n return list(zip(coefficients, permutations))"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the result of incrementing version.", "response": "def bump_version(version, which=None):\n \"\"\"Returns the result of incrementing `version`.\n\n If `which` is not specified, the \"patch\" part of the version number will be\n incremented. If `which` is specified, it must be ``'major'``, ``'minor'``,\n or ``'patch'``. If it is one of these three strings, the corresponding part\n of the version number will be incremented instead of the patch number.\n\n Returns a string representing the next version number.\n\n Example::\n\n >>> bump_version('2.7.1')\n '2.7.2'\n >>> bump_version('2.7.1', 'minor')\n '2.8.0'\n >>> bump_version('2.7.1', 'major')\n '3.0.0'\n\n \"\"\"\n try:\n parts = [int(n) for n in version.split('.')]\n except ValueError:\n fail('Current version is not numeric')\n if len(parts) != 3:\n fail('Current version is not semantic versioning')\n # Determine where to increment the version number\n PARTS = {'major': 0, 'minor': 1, 'patch': 2}\n index = PARTS[which] if which in PARTS else 2\n # Increment the version number at that index and set the subsequent parts\n # to 0.\n before, middle, after = parts[:index], parts[index], parts[index + 1:]\n middle += 1\n return '.'.join(str(n) for n in before + [middle] + after)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_version(filename, pattern):\n with open(filename) as f:\n match = re.search(r\"^(\\s*%s\\s*=\\s*')(.+?)(')(?sm)\" % pattern, f.read())\n if match:\n before, version, after = match.groups()\n return version\n fail('Could not find {} in {}'.format(pattern, filename))", "response": "Gets the current version from the specified file."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef fail(message=None, exit_status=None):\n print('Error:', message, file=sys.stderr)\n sys.exit(exit_status or 1)", "response": "Prints the specified message and exits the program with the specified exit status."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ntags the current version.", "response": "def git_tag(tag):\n \"\"\"Tags the current version.\"\"\"\n print('Tagging \"{}\"'.format(tag))\n msg = '\"Released version {}\"'.format(tag)\n Popen(['git', 'tag', '-s', '-m', msg, tag]).wait()"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ninitializing with templates path parameters templates_path str the position of templates directory global_dataSynchronize with global data", "response": "def initialize(self, templates_path, global_data):\n \"\"\"initialize with templates' path\n parameters\n templates_path str the position of templates directory\n global_data dict globa data can be got in any templates\"\"\"\n self.env = Environment(loader=FileSystemLoader(templates_path))\n self.env.trim_blocks = True\n self.global_data = global_data"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nrenders data with template return html unicodes.", "response": "def render(self, template, **data):\n \"\"\"Render data with template, return html unicodes.\n parameters\n template str the template's filename\n data dict the data to render\n \"\"\"\n # make a copy and update the copy\n dct = self.global_data.copy()\n dct.update(data)\n\n try:\n html = self.env.get_template(template).render(**dct)\n except TemplateNotFound:\n raise JinjaTemplateNotFound\n return html"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nrender data with template and then write to path", "response": "def render_to(self, path, template, **data):\n \"\"\"Render data with template and then write to path\"\"\"\n html = self.render(template, **data)\n with open(path, 'w') as f:\n f.write(html.encode(charset))"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef replace_relative_url_to_absolute(self, content):\n p = os.path.join(os.getcwd(), './src', '../')\n return content.replace('../', p)", "response": "Replace.. / leaded url with absolute uri."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_dataframe(self):\n assert self.dataframe is not None, (\n \"'%s' should either include a `dataframe` attribute, \"\n \"or override the `get_dataframe()` method.\"\n % self.__class__.__name__\n )\n\n dataframe = self.dataframe\n return dataframe", "response": "Get the DataFrame for this view."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef index_row(self, dataframe):\n return dataframe.loc[self.kwargs[self.lookup_url_kwarg]].to_frame().T", "response": "Index the row based on the request parameters."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_object(self):\n dataframe = self.filter_dataframe(self.get_dataframe())\n\n assert self.lookup_url_kwarg in self.kwargs, (\n 'Expected view %s to be called with a URL keyword argument '\n 'named \"%s\". Fix your URL conf, or set the `.lookup_field` '\n 'attribute on the view correctly.' %\n (self.__class__.__name__, self.lookup_url_kwarg)\n )\n\n try:\n obj = self.index_row(dataframe)\n except (IndexError, KeyError, ValueError):\n raise Http404\n\n # May raise a permission denied\n self.check_object_permissions(self.request, obj)\n\n return obj", "response": "Returns the row of the view is displaying."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns the paginator instance associated with the view or None if the view is not yet initialized.", "response": "def paginator(self):\n \"\"\"\n The paginator instance associated with the view, or `None`.\n \"\"\"\n if not hasattr(self, '_paginator'):\n if self.pagination_class is None:\n self._paginator = None\n else:\n self._paginator = self.pagination_class()\n return self._paginator"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef paginate_dataframe(self, dataframe):\n if self.paginator is None:\n return None\n return self.paginator.paginate_dataframe(dataframe, self.request, view=self)", "response": "Returns a single page of results."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef parse(self):\n\n if exists(self.filepath):\n content = open(self.filepath).read().decode(charset)\n else:\n content = \"\"\n\n try:\n config = toml.loads(content)\n except toml.TomlSyntaxError:\n raise ConfigSyntaxError\n\n return config", "response": "parse config return a dict"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef chunks(lst, number):\n lst_len = len(lst)\n\n for i in xrange(0, lst_len, number):\n yield lst[i: i+number]", "response": "A generator that yields a list of size number equal size parts."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nupdates nested dict a with another dict b", "response": "def update_nested_dict(a, b):\n \"\"\"\n update nested dict `a` with another dict b.\n usage::\n\n >>> a = {'x' : { 'y': 1}}\n >>> b = {'x' : {'z':2, 'y':3}, 'w': 4}\n >>> update_nested_dict(a,b)\n {'x': {'y': 3, 'z': 2}, 'w': 4}\n\n \"\"\"\n for k, v in b.iteritems():\n if isinstance(v, dict):\n d = a.setdefault(k, {})\n update_nested_dict(d, v)\n else:\n a[k] = v\n return a"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef render_to(path, template, **data):\n try:\n renderer.render_to(path, template, **data)\n except JinjaTemplateNotFound as e:\n logger.error(e.__doc__ + ', Template: %r' % template)\n sys.exit(e.exit_code)", "response": "shortcut to render data with template and then write to path"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nparses ascii post source return dict", "response": "def parse(self, source):\n \"\"\"Parse ascii post source, return dict\"\"\"\n\n rt, title, title_pic, markdown = libparser.parse(source)\n\n if rt == -1:\n raise SeparatorNotFound\n elif rt == -2:\n raise PostTitleNotFound\n\n # change to unicode\n title, title_pic, markdown = map(to_unicode, (title, title_pic,\n markdown))\n\n # render to html\n html = self.markdown.render(markdown)\n summary = self.markdown.render(markdown[:200])\n\n return {\n 'title': title,\n 'markdown': markdown,\n 'html': html,\n 'summary': summary,\n 'title_pic': title_pic\n }"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nparsing post source files name to datetime object", "response": "def parse_filename(self, filepath):\n \"\"\"parse post source files name to datetime object\"\"\"\n name = os.path.basename(filepath)[:-src_ext_len]\n try:\n dt = datetime.strptime(name, \"%Y-%m-%d-%H-%M\")\n except ValueError:\n raise PostNameInvalid\n return {'name': name, 'datetime': dt, 'filepath': filepath}"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef run_server(self, port):\n\n try:\n self.server = MultiThreadedHTTPServer(('0.0.0.0', port), Handler)\n except socket.error, e: # failed to bind port\n logger.error(str(e))\n sys.exit(1)\n\n logger.info(\"HTTP serve at http://0.0.0.0:%d (ctrl-c to stop) ...\"\n % port)\n\n try:\n self.server.serve_forever()\n except KeyboardInterrupt:\n logger.info(\"^C received, shutting down server\")\n self.shutdown_server()", "response": "run a server binding to port"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nget source files update time", "response": "def get_files_stat(self):\n \"\"\"get source files' update time\"\"\"\n\n if not exists(Post.src_dir):\n logger.error(SourceDirectoryNotFound.__doc__)\n sys.exit(SourceDirectoryNotFound.exit_code)\n\n paths = []\n\n for fn in ls(Post.src_dir):\n if fn.endswith(src_ext):\n paths.append(join(Post.src_dir, fn))\n\n # config.toml\n if exists(config.filepath):\n paths.append(config.filepath)\n\n # files: a dict\n files = dict((p, stat(p).st_mtime) for p in paths)\n return files"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef watch_files(self):\n\n try:\n while 1:\n sleep(1) # check every 1s\n\n try:\n files_stat = self.get_files_stat()\n except SystemExit:\n logger.error(\"Error occurred, server shut down\")\n self.shutdown_server()\n\n if self.files_stat != files_stat:\n logger.info(\"Changes detected, start rebuilding..\")\n\n try:\n generator.re_generate()\n global _root\n _root = generator.root\n except SystemExit: # catch sys.exit, it means fatal error\n logger.error(\"Error occurred, server shut down\")\n self.shutdown_server()\n\n self.files_stat = files_stat # update files' stat\n except KeyboardInterrupt:\n # I dont know why, but this exception won't be catched\n # because absolutly each KeyboardInterrupt is catched by\n # the server thread, which will terminate this thread the same time\n logger.info(\"^C received, shutting down watcher\")\n self.shutdown_watcher()", "response": "watch files for changes rebuild blog. this thread will quit if the main process ends"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nparsing a single post from src.", "response": "def parse(src):\n \"\"\"Note: src should be ascii string\"\"\"\n rt = libparser.parse(byref(post), src)\n return (\n rt,\n string_at(post.title, post.tsz),\n string_at(post.tpic, post.tpsz),\n post.body\n )"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ndeploys new blog to current directory", "response": "def deploy_blog():\n \"\"\"Deploy new blog to current directory\"\"\"\n logger.info(deploy_blog.__doc__)\n # `rsync -aqu path/to/res/* .`\n call(\n 'rsync -aqu ' + join(dirname(__file__), 'res', '*') + ' .',\n shell=True)\n logger.success('Done')\n logger.info('Please edit config.toml to meet your needs')"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ntouch a new post in src_dir", "response": "def new_post():\n \"\"\"Touch a new post in src/\"\"\"\n logger.info(new_post.__doc__)\n # make the new post's filename\n now = datetime.datetime.now()\n now_s = now.strftime('%Y-%m-%d-%H-%M')\n filepath = join(Post.src_dir, now_s + src_ext)\n # check if `src/` exists\n if not exists(Post.src_dir):\n logger.error(SourceDirectoryNotFound.__doc__)\n sys.exit(SourceDirectoryNotFound.exit_code)\n # write sample content to new post\n content = (\n 'Title\\n'\n 'Title Picture URL\\n'\n '---\\n'\n 'Markdown content ..'\n )\n f = open(filepath, 'w')\n f.write(content)\n f.close()\n logger.success('New post created: %s' % filepath)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef clean():\n logger.info(clean.__doc__)\n paths = ['post', 'page', 'index.html']\n call(['rm', '-rf'] + paths)\n logger.success('Done')", "response": "Clean htmls rux built"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef resolve_blocks(template, context):\n '''\n Return a BlockContext instance of all the {% block %} tags in the template.\n\n If template is a string, it will be resolved through get_template\n '''\n try:\n blocks = context.render_context[BLOCK_CONTEXT_KEY]\n except KeyError:\n blocks = context.render_context[BLOCK_CONTEXT_KEY] = BlockContext()\n\n # If it's just the name, resolve into template\n if isinstance(template, six.string_types):\n template = get_template(template)\n\n # For Django 1.8 compatibility\n template = getattr(template, 'template', template)\n\n # Add this templates blocks as the first\n local_blocks = {\n block.name: block\n for block in template.nodelist.get_nodes_by_type(BlockNode)\n }\n blocks.add_blocks(local_blocks)\n\n # Do we extend a parent template?\n extends = template.nodelist.get_nodes_by_type(ExtendsNode)\n if extends:\n # Can only have one extends in a template\n extends_node = extends[0]\n\n # Get the parent, and recurse\n parent_template = extends_node.get_parent(context)\n resolve_blocks(parent_template, context)\n\n return blocks", "response": "Resolves all the blocks in the template."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef parse_widget_name(widget):\n '''\n Parse a alias:block_name string into separate parts.\n '''\n try:\n alias, block_name = widget.split(':', 1)\n except ValueError:\n raise template.TemplateSyntaxError('widget name must be \"alias:block_name\" - %s' % widget)\n\n return alias, block_name", "response": "Parse a widget name into a alias and block name."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nfind the first matching block in the current block_context", "response": "def find_block(context, *names):\n '''\n Find the first matching block in the current block_context\n '''\n block_set = context.render_context[BLOCK_CONTEXT_KEY]\n for name in names:\n block = block_set.get_block(name)\n if block is not None:\n return block\n\n raise template.TemplateSyntaxError('No widget found for: %r' % (names,))"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef load_widgets(context, **kwargs):\n '''\n Load a series of widget libraries.\n '''\n _soft = kwargs.pop('_soft', False)\n\n try:\n widgets = context.render_context[WIDGET_CONTEXT_KEY]\n except KeyError:\n widgets = context.render_context[WIDGET_CONTEXT_KEY] = {}\n\n for alias, template_name in kwargs.items():\n if _soft and alias in widgets:\n continue\n\n with context.render_context.push({BLOCK_CONTEXT_KEY: BlockContext()}):\n blocks = resolve_blocks(template_name, context)\n widgets[alias] = blocks\n\n return ''", "response": "Load a series of widget libraries."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef auto_widget(field):\n '''Return a list of widget names for the provided field.'''\n # Auto-detect\n info = {\n 'widget': field.field.widget.__class__.__name__,\n 'field': field.field.__class__.__name__,\n 'name': field.name,\n }\n\n return [\n fmt.format(**info)\n for fmt in (\n '{field}_{widget}_{name}',\n '{field}_{name}',\n '{widget}_{name}',\n '{field}_{widget}',\n '{name}',\n '{widget}',\n '{field}',\n )\n ]", "response": "Return a list of widget names for the provided field."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nallowing reuse of a block within a template.", "response": "def reuse(context, block_list, **kwargs):\n '''\n Allow reuse of a block within a template.\n\n {% reuse '_myblock' foo=bar %}\n\n If passed a list of block names, will use the first that matches:\n\n {% reuse list_of_block_names .... %}\n '''\n try:\n block_context = context.render_context[BLOCK_CONTEXT_KEY]\n except KeyError:\n block_context = BlockContext()\n\n if not isinstance(block_list, (list, tuple)):\n block_list = [block_list]\n\n for block in block_list:\n block = block_context.get_block(block)\n if block:\n break\n else:\n return ''\n\n with context.push(kwargs):\n return block.render(context)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef display(self):\n if not self.is_group():\n return self._display\n return ((force_text(k), v) for k, v in self._display)", "response": "Return a list of key - value pairs that can be used to display the current value of the user."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nlisting the items in the cache with the given key.", "response": "def _list_key(self, key):\n \"\"\"\n boilerplate\n \"\"\"\n ret = []\n for msg_json in self.client.lrange(key, 0, -1):\n ret.append(self._fromJSON(msg_json))\n return ret"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef create_message(self, level, msg_text, extra_tags='', date=None, url=None):\n if not date:\n now = timezone.now()\n else:\n now = date\n r = now.isoformat()\n if now.microsecond:\n r = r[:23] + r[26:]\n if r.endswith('+00:00'):\n r = r[:-6] + 'Z'\n\n fingerprint = r + msg_text\n\n msg_id = hashlib.sha256(fingerprint.encode('ascii', 'ignore')).hexdigest()\n return Message(id=msg_id, message=msg_text, level=level, tags=extra_tags, date=r, url=url)", "response": "Create a new message object."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nsends a message to a list of users without passing through django. contrib. messages", "response": "def add_message_for(users, level, message_text, extra_tags='', date=None, url=None, fail_silently=False):\n \"\"\"\n Send a message to a list of users without passing through `django.contrib.messages`\n\n :param users: an iterable containing the recipients of the messages\n :param level: message level\n :param message_text: the string containing the message\n :param extra_tags: like the Django api, a string containing extra tags for the message\n :param date: a date, different than the default timezone.now\n :param url: an optional url\n :param fail_silently: not used at the moment\n \"\"\"\n BackendClass = stored_messages_settings.STORAGE_BACKEND\n backend = BackendClass()\n m = backend.create_message(level, message_text, extra_tags, date, url)\n backend.archive_store(users, m)\n backend.inbox_store(users, m)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nsending a message to all users aka broadcast.", "response": "def broadcast_message(level, message_text, extra_tags='', date=None, url=None, fail_silently=False):\n \"\"\"\n Send a message to all users aka broadcast.\n\n :param level: message level\n :param message_text: the string containing the message\n :param extra_tags: like the Django api, a string containing extra tags for the message\n :param date: a date, different than the default timezone.now\n :param url: an optional url\n :param fail_silently: not used at the moment\n \"\"\"\n from django.contrib.auth import get_user_model\n users = get_user_model().objects.all()\n add_message_for(users, level, message_text, extra_tags=extra_tags, date=date, url=url, fail_silently=fail_silently)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef mark_read(user, message):\n BackendClass = stored_messages_settings.STORAGE_BACKEND\n backend = BackendClass()\n backend.inbox_delete(user, message)", "response": "Mark a message as read for a user."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nmarks all message instances for a user as read.", "response": "def mark_all_read(user):\n \"\"\"\n Mark all message instances for a user as read.\n\n :param user: user instance for the recipient\n \"\"\"\n BackendClass = stored_messages_settings.STORAGE_BACKEND\n backend = BackendClass()\n backend.inbox_purge(user)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nmarking all messages as read", "response": "def mark_all_read(request):\n \"\"\"\n Mark all messages as read (i.e. delete from inbox) for current logged in user\n \"\"\"\n from .settings import stored_messages_settings\n backend = stored_messages_settings.STORAGE_BACKEND()\n backend.inbox_purge(request.user)\n return Response({\"message\": \"All messages read\"})"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nmark the message as read", "response": "def read(self, request, pk=None):\n \"\"\"\n Mark the message as read (i.e. delete from inbox)\n \"\"\"\n from .settings import stored_messages_settings\n backend = stored_messages_settings.STORAGE_BACKEND()\n\n try:\n backend.inbox_delete(request.user, pk)\n except MessageDoesNotExist as e:\n return Response(e.message, status='404')\n\n return Response({'status': 'message marked as read'})"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning a list of unread stored messages for the current user", "response": "def stored_messages_list(context, num_elements=10):\n \"\"\"\n Renders a list of unread stored messages for the current user\n \"\"\"\n if \"user\" in context:\n user = context[\"user\"]\n if user.is_authenticated():\n qs = Inbox.objects.select_related(\"message\").filter(user=user)\n return {\n \"messages\": qs[:num_elements],\n \"count\": qs.count(),\n }"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef stored_messages_count(context):\n if \"user\" in context:\n user = context[\"user\"]\n if user.is_authenticated():\n return Inbox.objects.select_related(\"message\").filter(user=user).count()", "response": "Returns a list of unread stored messages for the current user"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef stored_messages_archive(context, num_elements=10):\n if \"user\" in context:\n user = context[\"user\"]\n if user.is_authenticated():\n qs = MessageArchive.objects.select_related(\"message\").filter(user=user)\n return {\n \"messages\": qs[:num_elements],\n \"count\": qs.count(),\n }", "response": "Returns a list of archived messages for the current user"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _get(self, *args, **kwargs):\n messages, all_retrieved = super(StorageMixin, self)._get(*args, **kwargs)\n if self.user.is_authenticated():\n inbox_messages = self.backend.inbox_list(self.user)\n else:\n inbox_messages = []\n\n return messages + inbox_messages, all_retrieved", "response": "Retrieve unread messages for current user both from the inbox and\n from other storages"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef add(self, level, message, extra_tags=''):\n if not message:\n return\n # Check that the message level is not less than the recording level.\n level = int(level)\n if level < self.level:\n return\n # Check if the message doesn't have a level that needs to be persisted\n if level not in stored_messages_settings.STORE_LEVELS or self.user.is_anonymous():\n return super(StorageMixin, self).add(level, message, extra_tags)\n\n self.added_new = True\n m = self.backend.create_message(level, message, extra_tags)\n self.backend.archive_store([self.user], m)\n self._queued_messages.append(m)", "response": "Add a new message to the database."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nstoring the given messages in the database.", "response": "def _store(self, messages, response, *args, **kwargs):\n \"\"\"\n persistent messages are already in the database inside the 'archive',\n so we can say they're already \"stored\".\n Here we put them in the inbox, or remove from the inbox in case the\n messages were iterated.\n\n messages contains only new msgs if self.used==True\n else contains both new and unread messages\n \"\"\"\n contrib_messages = []\n if self.user.is_authenticated():\n if not messages:\n # erase inbox\n self.backend.inbox_purge(self.user)\n else:\n for m in messages:\n try:\n self.backend.inbox_store([self.user], m)\n except MessageTypeNotSupported:\n contrib_messages.append(m)\n\n super(StorageMixin, self)._store(contrib_messages, response, *args, **kwargs)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _prepare_messages(self, messages):\n for message in messages:\n if not self.backend.can_handle(message):\n message._prepare()", "response": "Prepare a list of messages for storage\n ."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ninitialize a base logger", "response": "def init(base_level=DEFAULT_BASE_LOGGING_LEVEL,\n verbose_level=DEFAULT_VERBOSE_LOGGING_LEVEL,\n logging_config=None):\n \"\"\"initializes a base logger\n\n you can use this to init a logger in any of your files.\n this will use config.py's LOGGER param and logging.dictConfig to configure\n the logger for you.\n\n :param int|logging.LEVEL base_level: desired base logging level\n :param int|logging.LEVEL verbose_level: desired verbose logging level\n :param dict logging_dict: dictConfig based configuration.\n used to override the default configuration from config.py\n :rtype: `python logger`\n \"\"\"\n if logging_config is None:\n logging_config = {}\n logging_config = logging_config or LOGGER\n # TODO: (IMPRV) only perform file related actions if file handler is\n # TODO: (IMPRV) defined.\n\n log_file = LOGGER['handlers']['file']['filename']\n log_dir = os.path.dirname(os.path.expanduser(log_file))\n if os.path.isfile(log_dir):\n sys.exit('file {0} exists - log directory cannot be created '\n 'there. please remove the file and try again.'\n .format(log_dir))\n try:\n if not os.path.exists(log_dir) and not len(log_dir) == 0:\n os.makedirs(log_dir)\n dictconfig.dictConfig(logging_config)\n lgr = logging.getLogger('user')\n lgr.setLevel(base_level)\n return lgr\n except ValueError as e:\n sys.exit('could not initialize logger.'\n ' verify your logger config'\n ' and permissions to write to {0} ({1})'\n .format(log_file, e))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndefaulting converter for the cfg:// protocol.", "response": "def cfg_convert(self, value):\n \"\"\"Default converter for the cfg:// protocol.\"\"\"\n rest = value\n m = self.WORD_PATTERN.match(rest)\n if m is None:\n raise ValueError(\"Unable to convert %r\" % value)\n else:\n rest = rest[m.end():]\n d = self.config[m.groups()[0]]\n # print d, rest\n while rest:\n m = self.DOT_PATTERN.match(rest)\n if m:\n d = d[m.groups()[0]]\n else:\n m = self.INDEX_PATTERN.match(rest)\n if m:\n idx = m.groups()[0]\n if not self.DIGIT_PATTERN.match(idx):\n d = d[idx]\n else:\n try:\n n = int(idx)\n d = d[n]\n except TypeError:\n d = d[idx]\n if m:\n rest = rest[m.end():]\n else:\n raise ValueError('Unable to convert '\n '%r at %r' % (value, rest))\n # rest should be empty\n return d"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef configure_custom(self, config):\n c = config.pop('()')\n if not hasattr(c, '__call__') and \\\n hasattr(types, 'ClassType') and isinstance(c, types.ClassType):\n c = self.resolve(c)\n props = config.pop('.', None)\n # Check for valid identifiers\n kwargs = dict((k, config[k]) for k in config if valid_ident(k))\n result = c(**kwargs)\n if props:\n for name, value in props.items():\n setattr(result, name, value)\n return result", "response": "Configure an object with a user - supplied factory."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsetting the global verbosity level for console and the jocker_lgr logger.", "response": "def _set_global_verbosity_level(is_verbose_output=False):\n \"\"\"sets the global verbosity level for console and the jocker_lgr logger.\n\n :param bool is_verbose_output: should be output be verbose\n \"\"\"\n global verbose_output\n # TODO: (IMPRV) only raise exceptions in verbose mode\n verbose_output = is_verbose_output\n if verbose_output:\n jocker_lgr.setLevel(logging.DEBUG)\n else:\n jocker_lgr.setLevel(logging.INFO)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _import_config(config_file):\n # get config file path\n jocker_lgr.debug('config file is: {0}'.format(config_file))\n # append to path for importing\n try:\n jocker_lgr.debug('importing config...')\n with open(config_file, 'r') as c:\n return yaml.safe_load(c.read())\n except IOError as ex:\n jocker_lgr.error(str(ex))\n raise RuntimeError('cannot access config file')\n except yaml.parser.ParserError as ex:\n jocker_lgr.error('invalid yaml file: {0}'.format(ex))\n raise RuntimeError('invalid yaml file')", "response": "returns a configuration object from a config file"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngenerating a Dockerfile and builds an image and pushes it to DockerHub.", "response": "def execute(varsfile, templatefile, outputfile=None, configfile=None,\n dryrun=False, build=False, push=False, verbose=False):\n \"\"\"generates a Dockerfile, builds an image and pushes it to DockerHub\n\n A `Dockerfile` will be generated by Jinja2 according to the `varsfile`\n imported. If build is true, an image will be generated from the\n `outputfile` which is the generated Dockerfile and committed to the\n image:tag string supplied to `build`.\n If push is true, a build will be triggered and the produced image\n will be pushed to DockerHub upon completion.\n\n :param string varsfile: path to file with variables.\n :param string templatefile: path to template file to use.\n :param string outputfile: path to output Dockerfile.\n :param string configfile: path to yaml file with docker-py config.\n :param bool dryrun: mock run.\n :param build: False or the image:tag to build to.\n :param push: False or the image:tag to build to. (triggers build)\n :param bool verbose: verbose output.\n \"\"\"\n if dryrun and (build or push):\n jocker_lgr.error('dryrun requested, cannot build.')\n sys.exit(100)\n\n _set_global_verbosity_level(verbose)\n j = Jocker(varsfile, templatefile, outputfile, configfile, dryrun,\n build, push)\n formatted_text = j.generate()\n if dryrun:\n g = j.dryrun(formatted_text)\n if build or push:\n j.build_image()\n if push:\n j.push_image()\n if dryrun:\n return g"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nparsing the output of a dumb push process", "response": "def _parse_dumb_push_output(self, string):\n \"\"\"since the push process outputs a single unicode string consisting of\n multiple JSON formatted \"status\" lines, we need to parse it so that it\n can be read as multiple strings.\n\n This will receive the string as an input, count curly braces and ignore\n any newlines. When the curly braces stack is 0, it will append the\n entire string it has read up until then to a list and so forth.\n\n :param string: the string to parse\n :rtype: list of JSON's\n \"\"\"\n stack = 0\n json_list = []\n tmp_json = ''\n for char in string:\n if not char == '\\r' and not char == '\\n':\n tmp_json += char\n if char == '{':\n stack += 1\n elif char == '}':\n stack -= 1\n if stack == 0:\n if not len(tmp_json) == 0:\n json_list.append(tmp_json)\n tmp_json = ''\n return json_list"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nuploading an image file to Imgur", "response": "def upload_gif(gif):\n \"\"\"Uploads an image file to Imgur\"\"\"\n\n client_id = os.environ.get('IMGUR_API_ID')\n client_secret = os.environ.get('IMGUR_API_SECRET')\n\n if client_id is None or client_secret is None:\n click.echo('Cannot upload - could not find IMGUR_API_ID or IMGUR_API_SECRET environment variables')\n return\n\n client = ImgurClient(client_id, client_secret)\n\n click.echo('Uploading file {}'.format(click.format_filename(gif)))\n\n response = client.upload_from_path(gif)\n\n click.echo('File uploaded - see your gif at {}'.format(response['link']))"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns True if the IP address is in dotted decimal notation.", "response": "def is_dot(ip):\n \"\"\"Return true if the IP address is in dotted decimal notation.\"\"\"\n octets = str(ip).split('.')\n if len(octets) != 4:\n return False\n for i in octets:\n try:\n val = int(i)\n except ValueError:\n return False\n if val > 255 or val < 0:\n return False\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef is_bin(ip):\n try:\n ip = str(ip)\n if len(ip) != 32:\n return False\n dec = int(ip, 2)\n except (TypeError, ValueError):\n return False\n if dec > 4294967295 or dec < 0:\n return False\n return True", "response": "Return True if the IP address is in binary notation."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns True if the IP address is in octal notation.", "response": "def is_oct(ip):\n \"\"\"Return true if the IP address is in octal notation.\"\"\"\n try:\n dec = int(str(ip), 8)\n except (TypeError, ValueError):\n return False\n if dec > 0o37777777777 or dec < 0:\n return False\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning True if the IP address is in decimal notation.", "response": "def is_dec(ip):\n \"\"\"Return true if the IP address is in decimal notation.\"\"\"\n try:\n dec = int(str(ip))\n except ValueError:\n return False\n if dec > 4294967295 or dec < 0:\n return False\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _check_nm(nm, notation):\n # Convert to decimal, and check if it's in the list of valid netmasks.\n _NM_CHECK_FUNCT = {\n NM_DOT: _dot_to_dec,\n NM_HEX: _hex_to_dec,\n NM_BIN: _bin_to_dec,\n NM_OCT: _oct_to_dec,\n NM_DEC: _dec_to_dec_long}\n try:\n dec = _NM_CHECK_FUNCT[notation](nm, check=True)\n except ValueError:\n return False\n if dec in _NETMASKS_VALUES:\n return True\n return False", "response": "Function internally used to check if the given netmask\n is of the specified notation."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef is_bits_nm(nm):\n try:\n bits = int(str(nm))\n except ValueError:\n return False\n if bits > 32 or bits < 0:\n return False\n return True", "response": "Return true if the netmask is in bits notatation."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns True if the netmask is in wildcard bits notatation.", "response": "def is_wildcard_nm(nm):\n \"\"\"Return true if the netmask is in wildcard bits notatation.\"\"\"\n try:\n dec = 0xFFFFFFFF - _dot_to_dec(nm, check=True)\n except ValueError:\n return False\n if dec in _NETMASKS_VALUES:\n return True\n return False"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _dot_to_dec(ip, check=True):\n if check and not is_dot(ip):\n raise ValueError('_dot_to_dec: invalid IP: \"%s\"' % ip)\n octets = str(ip).split('.')\n dec = 0\n dec |= int(octets[0]) << 24\n dec |= int(octets[1]) << 16\n dec |= int(octets[2]) << 8\n dec |= int(octets[3])\n return dec", "response": "Dotted decimal notation to decimal conversion."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _dec_to_dot(ip):\n first = int((ip >> 24) & 255)\n second = int((ip >> 16) & 255)\n third = int((ip >> 8) & 255)\n fourth = int(ip & 255)\n return '%d.%d.%d.%d' % (first, second, third, fourth)", "response": "Decimal to dotted decimal notation conversion."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _BYTES_TO_BITS():\n the_table = 256*[None]\n bits_per_byte = list(range(7, -1, -1))\n for n in range(256):\n l = n\n bits = 8*[None]\n for i in bits_per_byte:\n bits[i] = '01'[n & 1]\n n >>= 1\n the_table[l] = ''.join(bits)\n return the_table", "response": "Generate a table to convert a whole byte to binary."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _dec_to_bin(ip):\n bits = []\n while ip:\n bits.append(_BYTES_TO_BITS[ip & 255])\n ip >>= 8\n bits.reverse()\n return ''.join(bits) or 32*'0'", "response": "Decimal to binary conversion."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _wildcard_to_dec(nm, check=False):\n if check and not is_wildcard_nm(nm):\n raise ValueError('_wildcard_to_dec: invalid netmask: \"%s\"' % nm)\n return 0xFFFFFFFF - _dot_to_dec(nm, check=False)", "response": "Wildcard bits to decimal conversion."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _is_notation(ip, notation, _isnm):\n notation_orig = notation\n notation = _get_notation(notation)\n if notation not in _CHECK_FUNCT_KEYS:\n raise ValueError('_is_notation: unkown notation: \"%s\"' % notation_orig)\n return _CHECK_FUNCT[notation][_isnm](ip)", "response": "Internally used to check if an IP is in the given notation."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _detect(ip, _isnm):\n ip = str(ip)\n if len(ip) > 1:\n if ip[0:2] == '0x':\n if _CHECK_FUNCT[IP_HEX][_isnm](ip):\n return IP_HEX\n elif ip[0] == '0':\n if _CHECK_FUNCT[IP_OCT][_isnm](ip):\n return IP_OCT\n if _CHECK_FUNCT[IP_DOT][_isnm](ip):\n return IP_DOT\n elif _isnm and _CHECK_FUNCT[NM_BITS][_isnm](ip):\n return NM_BITS\n elif _CHECK_FUNCT[IP_DEC][_isnm](ip):\n return IP_DEC\n elif _isnm and _CHECK_FUNCT[NM_WILDCARD][_isnm](ip):\n return NM_WILDCARD\n elif _CHECK_FUNCT[IP_BIN][_isnm](ip):\n return IP_BIN\n return IP_UNKNOWN", "response": "Function internally used to detect the notation of the\n given IP or netmask."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef convert(ip, notation=IP_DOT, inotation=IP_UNKNOWN, check=True):\n return _convert(ip, notation, inotation, _check=check, _isnm=False)", "response": "Convert a given IP address to another notation."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nconverts a netmask to another notation.", "response": "def convert_nm(nm, notation=IP_DOT, inotation=IP_UNKNOWN, check=True):\n \"\"\"Convert a netmask to another notation.\"\"\"\n return _convert(nm, notation, inotation, _check=check, _isnm=True)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nset the IP address and netmask.", "response": "def set(self, ip, notation=IP_UNKNOWN):\n \"\"\"Set the IP address/netmask.\"\"\"\n self._ip_dec = int(_convert(ip, notation=IP_DEC, inotation=notation,\n _check=True, _isnm=self._isnm))\n self._ip = _convert(self._ip_dec, notation=IP_DOT, inotation=IP_DEC,\n _check=False, _isnm=self._isnm)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns the hexadecimal notation of the address or netmask.", "response": "def get_hex(self):\n \"\"\"Return the hexadecimal notation of the address/netmask.\"\"\"\n return _convert(self._ip_dec, notation=IP_HEX,\n inotation=IP_DEC, _check=False, _isnm=self._isnm)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the binary notation of the address and netmask.", "response": "def get_bin(self):\n \"\"\"Return the binary notation of the address/netmask.\"\"\"\n return _convert(self._ip_dec, notation=IP_BIN,\n inotation=IP_DEC, _check=False, _isnm=self._isnm)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning the octal notation of the address or netmask.", "response": "def get_oct(self):\n \"\"\"Return the octal notation of the address/netmask.\"\"\"\n return _convert(self._ip_dec, notation=IP_OCT,\n inotation=IP_DEC, _check=False, _isnm=self._isnm)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nprepares the item to be compared with this address / netmask.", "response": "def _cmp_prepare(self, other):\n \"\"\"Prepare the item to be compared with this address/netmask.\"\"\"\n if isinstance(other, self.__class__):\n return other._ip_dec\n elif isinstance(other, int):\n # NOTE: this hides the fact that \"other\" can be a non valid IP/nm.\n return other\n return self.__class__(other)._ip_dec"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nsumming two IP addresses.", "response": "def _add(self, other):\n \"\"\"Sum two IP addresses.\"\"\"\n if isinstance(other, self.__class__):\n sum_ = self._ip_dec + other._ip_dec\n elif isinstance(other, int):\n sum_ = self._ip_dec + other\n else:\n other = self.__class__(other)\n sum_ = self._ip_dec + other._ip_dec\n return sum_"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _sub(self, other):\n if isinstance(other, self.__class__):\n sub = self._ip_dec - other._ip_dec\n if isinstance(other, int):\n sub = self._ip_dec - other\n else:\n other = self.__class__(other)\n sub = self._ip_dec - other._ip_dec\n return sub", "response": "Subtract two IP addresses."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn the bits notation of the netmask.", "response": "def get_bits(self):\n \"\"\"Return the bits notation of the netmask.\"\"\"\n return _convert(self._ip, notation=NM_BITS,\n inotation=IP_DOT, _check=False, _isnm=self._isnm)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_wildcard(self):\n return _convert(self._ip, notation=NM_WILDCARD,\n inotation=IP_DOT, _check=False, _isnm=self._isnm)", "response": "Return the wildcard bits notation of the netmask."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef set(self, ip, netmask=None):\n if isinstance(ip, str) and netmask is None:\n ipnm = ip.split('/')\n if len(ipnm) != 2:\n raise ValueError('set: invalid CIDR: \"%s\"' % ip)\n ip = ipnm[0]\n netmask = ipnm[1]\n if isinstance(ip, IPv4Address):\n self._ip = ip\n else:\n self._ip = IPv4Address(ip)\n if isinstance(netmask, IPv4NetMask):\n self._nm = netmask\n else:\n self._nm = IPv4NetMask(netmask)\n ipl = int(self._ip)\n nml = int(self._nm)\n base_add = ipl & nml\n self._ip_num = 0xFFFFFFFF - 1 - nml\n # NOTE: quite a mess.\n # This's here to handle /32 (-1) and /31 (0) netmasks.\n if self._ip_num in (-1, 0):\n if self._ip_num == -1:\n self._ip_num = 1\n else:\n self._ip_num = 2\n self._net_ip = None\n self._bc_ip = None\n self._first_ip_dec = base_add\n self._first_ip = IPv4Address(self._first_ip_dec, notation=IP_DEC)\n if self._ip_num == 1:\n last_ip_dec = self._first_ip_dec\n else:\n last_ip_dec = self._first_ip_dec + 1\n self._last_ip = IPv4Address(last_ip_dec, notation=IP_DEC)\n return\n self._net_ip = IPv4Address(base_add, notation=IP_DEC)\n self._bc_ip = IPv4Address(base_add + self._ip_num + 1, notation=IP_DEC)\n self._first_ip_dec = base_add + 1\n self._first_ip = IPv4Address(self._first_ip_dec, notation=IP_DEC)\n self._last_ip = IPv4Address(base_add + self._ip_num, notation=IP_DEC)", "response": "Set the IP address and netmask."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nchange the current IP.", "response": "def set_ip(self, ip):\n \"\"\"Change the current IP.\"\"\"\n self.set(ip=ip, netmask=self._nm)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef set_netmask(self, netmask):\n self.set(ip=self._ip, netmask=netmask)", "response": "Change the netmask of the current log entry."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning true if the given address in amongst the usable addresses and is contained in this one.", "response": "def is_valid_ip(self, ip):\n \"\"\"Return true if the given address in amongst the usable addresses,\n or if the given CIDR is contained in this one.\"\"\"\n if not isinstance(ip, (IPv4Address, CIDR)):\n if str(ip).find('/') == -1:\n ip = IPv4Address(ip)\n else:\n # Support for CIDR strings/objects, an idea of Nicola Novello.\n ip = CIDR(ip)\n if isinstance(ip, IPv4Address):\n if ip < self._first_ip or ip > self._last_ip:\n return False\n elif isinstance(ip, CIDR):\n # NOTE: manage /31 networks; 127.0.0.1/31 is considered to\n # be included in 127.0.0.1/8.\n if ip._nm._ip_dec == 0xFFFFFFFE \\\n and self._nm._ip_dec != 0xFFFFFFFE:\n compare_to_first = self._net_ip._ip_dec\n compare_to_last = self._bc_ip._ip_dec\n else:\n compare_to_first = self._first_ip._ip_dec\n compare_to_last = self._last_ip._ip_dec\n if ip._first_ip._ip_dec < compare_to_first or \\\n ip._last_ip._ip_dec > compare_to_last:\n return False\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nuploading a file to S3 possibly using the multi - part uploader", "response": "async def upload_file(self, bucket, file, uploadpath=None, key=None,\n ContentType=None, **kw):\n \"\"\"Upload a file to S3 possibly using the multi-part uploader\n Return the key uploaded\n \"\"\"\n is_filename = False\n\n if hasattr(file, 'read'):\n if hasattr(file, 'seek'):\n file.seek(0)\n file = file.read()\n size = len(file)\n elif key:\n size = len(file)\n else:\n is_filename = True\n size = os.stat(file).st_size\n key = os.path.basename(file)\n\n assert key, 'key not available'\n\n if not ContentType:\n ContentType, _ = mimetypes.guess_type(key)\n\n if uploadpath:\n if not uploadpath.endswith('/'):\n uploadpath = '%s/' % uploadpath\n key = '%s%s' % (uploadpath, key)\n\n params = dict(Bucket=bucket, Key=key)\n\n if not ContentType:\n ContentType = 'application/octet-stream'\n\n params['ContentType'] = ContentType\n\n if size > MULTI_PART_SIZE and is_filename:\n resp = await _multipart(self, file, params)\n elif is_filename:\n with open(file, 'rb') as fp:\n params['Body'] = fp.read()\n resp = await self.put_object(**params)\n else:\n params['Body'] = file\n resp = await self.put_object(**params)\n if 'Key' not in resp:\n resp['Key'] = key\n if 'Bucket' not in resp:\n resp['Bucket'] = bucket\n return resp"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def copy_storage_object(self, source_bucket, source_key,\n bucket, key):\n \"\"\"Copy a file from one bucket into another\n \"\"\"\n info = await self.head_object(Bucket=source_bucket, Key=source_key)\n size = info['ContentLength']\n\n if size > MULTI_PART_SIZE:\n result = await _multipart_copy(self, source_bucket, source_key,\n bucket, key, size)\n else:\n result = await self.copy_object(\n Bucket=bucket, Key=key,\n CopySource=_source_string(source_bucket, source_key)\n )\n return result", "response": "Copy a file from one bucket into another."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\nasync def _upload_file(self, full_path):\n rel_path = os.path.relpath(full_path, self.folder)\n key = s3_key(os.path.join(self.key, rel_path))\n ct = self.content_types.get(key.split('.')[-1])\n with open(full_path, 'rb') as fp:\n file = fp.read()\n try:\n await self.botocore.upload_file(self.bucket, file, key=key,\n ContentType=ct)\n except Exception as exc:\n LOGGER.error('Could not upload \"%s\": %s', key, exc)\n self.failures[key] = self.all.pop(full_path)\n return\n size = self.all.pop(full_path)\n self.success[key] = size\n self.total_size += size\n percentage = 100*(1 - len(self.all)/self.total_files)\n message = '{0:.0f}% completed - uploaded \"{1}\" - {2}'.format(\n percentage, key, convert_bytes(size))\n LOGGER.info(message)", "response": "Coroutine for uploading a single file to S3."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncreate a paginator for an operation.", "response": "def get_paginator(self, operation_name):\n \"\"\"Create a paginator for an operation.\n :type operation_name: string\n :param operation_name: The operation name. This is the same name\n as the method name on the client. For example, if the\n method name is ``create_foo``, and you'd normally invoke the\n operation as ``client.create_foo(**kwargs)``, if the\n ``create_foo`` operation can be paginated, you can use the\n call ``client.get_paginator(\"create_foo\")``.\n :raise OperationNotPageableError: Raised if the operation is not\n pageable. You can use the ``client.can_paginate`` method to\n check if an operation is pageable.\n :rtype: L{botocore.paginate.Paginator}\n :return: A paginator object.\n \"\"\"\n if not self.can_paginate(operation_name):\n raise OperationNotPageableError(operation_name=operation_name)\n else:\n actual_operation_name = self._PY_TO_OP_NAME[operation_name]\n # substitute iterator with async one\n Paginator.PAGE_ITERATOR_CLS = AsyncPageIterator\n paginator = Paginator(\n getattr(self, operation_name),\n self._cache['page_config'][actual_operation_name])\n return paginator"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ntrigger an event on this channel", "response": "async def trigger(self, event, data=None, socket_id=None):\n '''Trigger an ``event`` on this channel\n '''\n json_data = json.dumps(data, cls=self.pusher.encoder)\n query_string = self.signed_query(event, json_data, socket_id)\n signed_path = \"%s?%s\" % (self.path, query_string)\n pusher = self.pusher\n absolute_url = pusher.get_absolute_path(signed_path)\n response = await pusher.http.post(\n absolute_url, data=json_data,\n headers=[('Content-Type', 'application/json')])\n response.raise_for_status()\n return response.status_code == 202"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\nasync def connect(self):\n '''Connect to a Pusher websocket\n '''\n if not self._consumer:\n waiter = self._waiter = asyncio.Future()\n try:\n address = self._websocket_host()\n self.logger.info('Connect to %s', address)\n self._consumer = await self.http.get(address)\n if self._consumer.status_code != 101:\n raise PusherError(\"Could not connect to websocket\")\n except Exception as exc:\n waiter.set_exception(exc)\n raise\n else:\n await waiter\n return self._consumer", "response": "Connect to a Pusher websocket"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nhandle incoming messages from the pusher.", "response": "def on_message(self, websocket, message):\n '''Handle websocket incoming messages\n '''\n waiter = self._waiter\n self._waiter = None\n encoded = json.loads(message)\n event = encoded.get('event')\n channel = encoded.get('channel')\n data = json.loads(encoded.get('data'))\n try:\n if event == PUSHER_ERROR:\n raise PusherError(data['message'], data['code'])\n elif event == PUSHER_CONNECTION:\n self.socket_id = data.get('socket_id')\n self.logger.info('Succesfully connected on socket %s',\n self.socket_id)\n waiter.set_result(self.socket_id)\n elif event == PUSHER_SUBSCRIBED:\n self.logger.info('Succesfully subscribed to %s',\n encoded.get('channel'))\n elif channel:\n self[channel]._event(event, data)\n except Exception as exc:\n if waiter:\n waiter.set_exception(exc)\n else:\n self.logger.exception('pusher error')"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef urlsafe_nopadding_b64decode(data):\n '''URL safe Base64 decode without padding (=)'''\n\n padding = len(data) % 4\n if padding != 0:\n padding = 4 - padding\n padding = '=' * padding\n data = data + padding\n return urlsafe_b64decode(data)", "response": "URL safe Base64 decode without padding"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ndecoding a limited set of HTML entities.", "response": "def decode_html_entities(html):\n \"\"\"\n Decodes a limited set of HTML entities.\n \"\"\"\n if not html:\n return html\n\n for entity, char in six.iteritems(html_entity_map):\n html = html.replace(entity, char)\n\n return html"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef set_signature_passphrases(self, signature_passphrases):\n '''Set signature passphrases'''\n self.signature_passphrases = self._update_dict(signature_passphrases,\n {}, replace_data=True)", "response": "Set the signature passphrases for this resource."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nsetting the set of encryption passphrases for this resource.", "response": "def set_encryption_passphrases(self, encryption_passphrases):\n '''Set encryption passphrases'''\n self.encryption_passphrases = self._update_dict(encryption_passphrases,\n {}, replace_data=True)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef set_algorithms(self, signature=None, encryption=None,\n serialization=None, compression=None):\n '''Set algorithms used for sealing. Defaults can not be overridden.'''\n\n self.signature_algorithms = \\\n self._update_dict(signature, self.DEFAULT_SIGNATURE)\n\n self.encryption_algorithms = \\\n self._update_dict(encryption, self.DEFAULT_ENCRYPTION)\n\n self.serialization_algorithms = \\\n self._update_dict(serialization, self.DEFAULT_SERIALIZATION)\n\n self.compression_algorithms = \\\n self._update_dict(compression, self.DEFAULT_COMPRESSION)", "response": "Sets the algorithms used for sealing. Defaults can not be overridden."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngets algorithms used for sealing", "response": "def get_algorithms(self):\n '''Get algorithms used for sealing'''\n\n return {\n 'signature': self.signature_algorithms,\n 'encryption': self.encryption_algorithms,\n 'serialization': self.serialization_algorithms,\n 'compression': self.compression_algorithms,\n }"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef verify_signature(self, data):\n '''Verify sealed data signature'''\n\n data = self._remove_magic(data)\n data = urlsafe_nopadding_b64decode(data)\n options = self._read_header(data)\n data = self._add_magic(data)\n self._unsign_data(data, options)", "response": "Verify sealed data signature"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nencode data with specific algorithm", "response": "def _encode(self, data, algorithm, key=None):\n '''Encode data with specific algorithm'''\n\n if algorithm['type'] == 'hmac':\n return data + self._hmac_generate(data, algorithm, key)\n elif algorithm['type'] == 'aes':\n return self._aes_encrypt(data, algorithm, key)\n elif algorithm['type'] == 'no-serialization':\n return data\n elif algorithm['type'] == 'json':\n return json.dumps(data)\n elif algorithm['type'] == 'no-compression':\n return data\n elif algorithm['type'] == 'gzip':\n return self._zlib_compress(data, algorithm)\n else:\n raise Exception('Algorithm not supported: %s' % algorithm['type'])"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _decode(self, data, algorithm, key=None):\n '''Decode data with specific algorithm'''\n\n if algorithm['type'] == 'hmac':\n verify_signature = data[-algorithm['hash_size']:]\n data = data[:-algorithm['hash_size']]\n signature = self._hmac_generate(data, algorithm, key)\n if not const_equal(verify_signature, signature):\n raise Exception('Invalid signature')\n return data\n elif algorithm['type'] == 'aes':\n return self._aes_decrypt(data, algorithm, key)\n elif algorithm['type'] == 'no-serialization':\n return data\n elif algorithm['type'] == 'json':\n return json.loads(data)\n elif algorithm['type'] == 'no-compression':\n return data\n elif algorithm['type'] == 'gzip':\n return self._zlib_decompress(data, algorithm)\n else:\n raise Exception('Algorithm not supported: %s' % algorithm['type'])", "response": "Decode data with specific algorithm"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _sign_data(self, data, options):\n '''Add signature to data'''\n\n if options['signature_algorithm_id'] not in self.signature_algorithms:\n raise Exception('Unknown signature algorithm id: %d'\n % options['signature_algorithm_id'])\n\n signature_algorithm = \\\n self.signature_algorithms[options['signature_algorithm_id']]\n\n algorithm = self._get_algorithm_info(signature_algorithm)\n\n key_salt = get_random_bytes(algorithm['salt_size'])\n key = self._generate_key(options['signature_passphrase_id'],\n self.signature_passphrases, key_salt, algorithm)\n\n data = self._encode(data, algorithm, key)\n\n return data + key_salt", "response": "Add signature to data"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _unsign_data(self, data, options):\n '''Verify and remove signature'''\n\n if options['signature_algorithm_id'] not in self.signature_algorithms:\n raise Exception('Unknown signature algorithm id: %d'\n % options['signature_algorithm_id'])\n\n signature_algorithm = \\\n self.signature_algorithms[options['signature_algorithm_id']]\n\n algorithm = self._get_algorithm_info(signature_algorithm)\n\n key_salt = ''\n if algorithm['salt_size']:\n key_salt = data[-algorithm['salt_size']:]\n data = data[:-algorithm['salt_size']]\n\n key = self._generate_key(options['signature_passphrase_id'],\n self.signature_passphrases, key_salt, algorithm)\n\n data = self._decode(data, algorithm, key)\n\n return data", "response": "Verify and remove signature"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _encrypt_data(self, data, options):\n '''Encrypt data'''\n\n if options['encryption_algorithm_id'] not in self.encryption_algorithms:\n raise Exception('Unknown encryption algorithm id: %d'\n % options['encryption_algorithm_id'])\n\n encryption_algorithm = \\\n self.encryption_algorithms[options['encryption_algorithm_id']]\n\n algorithm = self._get_algorithm_info(encryption_algorithm)\n\n key_salt = get_random_bytes(algorithm['salt_size'])\n key = self._generate_key(options['encryption_passphrase_id'],\n self.encryption_passphrases, key_salt, algorithm)\n\n data = self._encode(data, algorithm, key)\n\n return data + key_salt", "response": "Encrypt data with the key and passphrase"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _remove_magic(self, data):\n '''Verify and remove magic'''\n\n if not self.magic:\n return data\n\n magic_size = len(self.magic)\n magic = data[:magic_size]\n if magic != self.magic:\n raise Exception('Invalid magic')\n data = data[magic_size:]\n\n return data", "response": "Verify and remove magic from data"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _add_header(self, data, options):\n '''Add header to data'''\n\n # pylint: disable=W0142\n\n version_info = self._get_version_info(options['version'])\n\n flags = options['flags']\n\n header_flags = dict(\n (i, str(int(j))) for i, j in options['flags'].iteritems())\n header_flags = ''.join(version_info['flags'](**header_flags))\n header_flags = int(header_flags, 2)\n options['flags'] = header_flags\n\n header = version_info['header']\n header = header(**options)\n header = pack(version_info['header_format'], *header)\n\n if 'timestamp' in flags and flags['timestamp']:\n timestamp = long(time())\n timestamp = pack(version_info['timestamp_format'], timestamp)\n header = header + timestamp\n\n return header + data", "response": "Add header to data"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _read_header(self, data):\n '''Read header from data'''\n\n # pylint: disable=W0212\n\n version = self._read_version(data)\n version_info = self._get_version_info(version)\n header_data = data[:version_info['header_size']]\n header = version_info['header']\n header = header._make(\n unpack(version_info['header_format'], header_data))\n header = dict(header._asdict())\n\n flags = list(\"{0:0>8b}\".format(header['flags']))\n flags = dict(version_info['flags']._make(flags)._asdict())\n flags = dict((i, bool(int(j))) for i, j in flags.iteritems())\n header['flags'] = flags\n\n timestamp = None\n if flags['timestamp']:\n ts_start = version_info['header_size']\n ts_end = ts_start + version_info['timestamp_size']\n timestamp_data = data[ts_start:ts_end]\n timestamp = unpack(\n version_info['timestamp_format'], timestamp_data)[0]\n header['info'] = {'timestamp': timestamp}\n\n return header", "response": "Read the header from data"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nremoves the header from the data", "response": "def _remove_header(self, data, options):\n '''Remove header from data'''\n\n version_info = self._get_version_info(options['version'])\n header_size = version_info['header_size']\n\n if options['flags']['timestamp']:\n header_size += version_info['timestamp_size']\n\n data = data[header_size:]\n\n return data"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _read_version(self, data):\n '''Read header version from data'''\n\n version = ord(data[0])\n if version not in self.VERSIONS:\n raise Exception('Version not defined: %d' % version)\n return version", "response": "Read the version from data"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _generate_key(pass_id, passphrases, salt, algorithm):\n '''Generate and return PBKDF2 key'''\n\n if pass_id not in passphrases:\n raise Exception('Passphrase not defined for id: %d' % pass_id)\n\n passphrase = passphrases[pass_id]\n\n if len(passphrase) < 32:\n raise Exception('Passphrase less than 32 characters long')\n\n digestmod = EncryptedPickle._get_hashlib(algorithm['pbkdf2_algorithm'])\n\n encoder = PBKDF2(passphrase, salt,\n iterations=algorithm['pbkdf2_iterations'],\n digestmodule=digestmod)\n\n return encoder.read(algorithm['key_size'])", "response": "Generate and return PBKDF2 key"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _update_dict(data, default_data, replace_data=False):\n '''Update algorithm definition type dictionaries'''\n\n if not data:\n data = default_data.copy()\n return data\n\n if not isinstance(data, dict):\n raise TypeError('Value not dict type')\n if len(data) > 255:\n raise ValueError('More than 255 values defined')\n for i in data.keys():\n if not isinstance(i, int):\n raise TypeError('Index not int type')\n if i < 0 or i > 255:\n raise ValueError('Index value out of range')\n\n if not replace_data:\n data.update(default_data)\n\n return data", "response": "Update algorithm definition type dictionaries"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _get_hashlib(digestmode):\n '''Generate HMAC hash'''\n if digestmode == 'sha1':\n return SHA\n if digestmode == 'sha256':\n return SHA256\n elif digestmode == 'sha384':\n return SHA384\n elif digestmode == 'sha512':\n return SHA512\n else:\n raise Exception('digestmode not supported: %s'\n % digestmode)", "response": "Generate HMAC hash from digestmode"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef getTableOfContents(self):\n\n self.directory_size = self.getDirectorySize()\n if self.directory_size > 65536:\n self.directory_size += 2\n self.requestContentDirectory()\n\n\n # and find the offset from start of file where it can be found\n directory_start = unpack(\"i\", self.raw_bytes[self.directory_end + 16: self.directory_end + 20])[0]\n\n # find the data in the raw_bytes\n self.raw_bytes = self.raw_bytes\n current_start = directory_start - self.start\n filestart = 0\n compressedsize = 0\n tableOfContents = []\n\n try:\n while True:\n # get file name size (n), extra len (m) and comm len (k)\n zip_n = unpack(\"H\", self.raw_bytes[current_start + 28: current_start + 28 + 2])[0]\n zip_m = unpack(\"H\", self.raw_bytes[current_start + 30: current_start + 30 + 2])[0]\n zip_k = unpack(\"H\", self.raw_bytes[current_start + 32: current_start + 32 + 2])[0]\n\n filename = self.raw_bytes[current_start + 46: current_start + 46 + zip_n]\n\n # check if this is the index file\n filestart = unpack(\"I\", self.raw_bytes[current_start + 42: current_start + 42 + 4])[0]\n compressedsize = unpack(\"I\", self.raw_bytes[current_start + 20: current_start + 20 + 4])[0]\n uncompressedsize = unpack(\"I\", self.raw_bytes[current_start + 24: current_start + 24 + 4])[0]\n tableItem = {\n 'filename': filename,\n 'compressedsize': compressedsize,\n 'uncompressedsize': uncompressedsize,\n 'filestart': filestart\n }\n tableOfContents.append(tableItem)\n\n # not this file, move along\n current_start = current_start + 46 + zip_n + zip_m + zip_k\n except:\n pass\n\n self.tableOfContents = tableOfContents\n return tableOfContents", "response": "This function returns the contents of the internal tableOfContents list. It will raise an exception if the server does not support ranged requests."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef make_postcard(self, npix=300, shape=(1070, 1132), buffer_size=15):\n \n source = self.kic\n client = kplr.API()\n targ = client.target(source)\n \n channel = [targ.params['Channel_0'], targ.params['Channel_1'], \n targ.params['Channel_2'], targ.params['Channel_3']]\n\n col = [targ.params['Column_0'], targ.params['Column_1'], \n targ.params['Column_2'], targ.params['Column_3']] \n\n row = [targ.params['Row_0'], targ.params['Row_1'], \n targ.params['Row_2'], targ.params['Row_3']] \n \n\n if None in row:\n raise ValueError('Star not on detector all quarters!')\n\n if None in col:\n raise ValueError('Star not on detector all quarters!')\n \n center = np.array([npix/2, npix/2])\n \n \n # If star close to edge, shift frame so that we have the full npix by npix\n # In this case, postcard will not be centered on target star\n if (np.min(col) < npix/2):\n jump = npix/2 - np.min(col) + buffer_size\n col += jump\n center[1] -= jump\n \n if (np.min(row) < npix/2):\n jump = npix/2 - np.min(row) + buffer_size\n row += jump\n center[0] -= jump\n \n if (np.max(row) > shape[0] - npix/2):\n jump = shape[0]-npix/2 - np.max(row) - buffer_size\n row += jump\n center[0] -= jump\n \n if (np.max(col) > shape[1] - npix/2):\n jump = shape[1]-npix/2 - np.max(col) - buffer_size\n col += jump\n center[1] -= jump\n \n fin_arr = np.zeros((len(self.times), npix, npix))\n\n for icount, iname in enumerate(self.obs_filenames): \n a = fits.open(self.ffi_dir+iname)\n\n \n quarter = a[0].header['quarter']\n\n if int(quarter) == 0:\n season = 3\n else:\n season = (int(quarter) - 2) % 4\n\n #season_arr[icount] = season\n img = a[channel[season]].data\n img -= np.median(img)\n \n \n ymin = int(max([int(row[season])-npix/2,0]))\n ymax = int(min([int(row[season])+npix/2,img.shape[0]]))\n xmin = int(max([int(col[season])-npix/2,0]))\n xmax = int(min([int(col[season])+npix/2,img.shape[1]]))\n\n pimg = img[ymin:ymax,xmin:xmax]\n fin_arr[icount,:,:] = pimg\n \n self.postcard = fin_arr\n self.integrated_postcard = np.sum(self.postcard, axis=0)\n self.center = center", "response": "This function will make a postcard region around the target star."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef find_other_sources(self, edge_lim = 0.015, min_val = 5000, \n ntargets = 250, extend_region_size=3, remove_excess=4,\n plot_flag = False, plot_window=15):\n \"\"\"\n Identify apertures for all sources on the postcard, both for the \n target and potential reference stars\n \n Args: \n edge_lim: The initial limit for the creation of apertures. The aperture will be a region of\n contiguous pixels with flux values larger than the product of ``edge_lim`` and the brightest\n pixel value for this star, as long as that product is larger than ``min_val`` (default: ``0.015``)\n min_val: Threshold for the minimum flux value in the ``integrated_postcard`` for a pixel to be included \n in the default apertures (default: ``5000``)\n ntargets: The maximum number of potential reference stars to be included in the analysis (default: ``250``)\n extend_region_size: After the initial apertures are generated, they will be optionally extended an\n additional number of pixels following this flag. Safe practice for reasonable apertures is to \n leave ``min_val`` at a value well above the noise and then extend apertures via this flag until \n they are of suitable size (default: ``3``)\n remove_excess: Stars with apertures that touch will be combined into a single aperture. \n This is done by iterating through the starlist; this flag represents the number of times the\n list will be iterated through to delete redundant apertures (default: ``4``)\n plot_flag: If true, a series of diagnostic plots will appear while this function runs to observe\n apertures for the target star and other stars.\n (default: ``False``)\n plot_window: If ``plot_flag`` is ``True``, the size of the region to be plotted around the target star\n to show the drawn aperture for visualization purposes only (default: ``15``)\n \n \"\"\"\n j,i = self.center\n \n region = self.integrated_postcard + 0.0\n if plot_flag == True:\n ff = plt.imshow(self.integrated_postcard, interpolation='nearest', cmap='gray', \n vmax = np.percentile(region, 99.6))\n plt.colorbar(ff)\n plt.show()\n targets = np.zeros_like(self.integrated_postcard)\n sizeimg = np.shape(targets)[0]\n \n jj = j + 0\n ii = i + 0\n \n edge = edge_lim\n \n lim = max(min_val, self.integrated_postcard[int(j), int(i)]*edge)\n \n maxpt = np.percentile(self.integrated_postcard, 94)\n \n bin_img = (region > lim)\n lab_img, n_features = label(bin_img)\n \n key_targ = (lab_img == (lab_img[int(j), int(i)]))\n tot = np.sum(key_targ)\n \n targets[key_targ] = 1\n region[key_targ] = 0.0\n \n\n \n lim = np.zeros(ntargets)\n for peaks in range(1,ntargets):\n k = np.argmax(region)\n j,i = np.unravel_index(k, region.shape)\n lim[peaks] = max(maxpt, edge*region[j,i])\n\n\n bin_img = (region >= lim[peaks])\n lab_img, n_features = label(bin_img)\n\n key_targ = (lab_img == (lab_img[j,i]))\n targets[key_targ] = peaks + 1\n region[key_targ] = 0.0\n \n lab_img, n_features = label(targets)\n for i in range(1, ntargets+1):\n for j in range(extend_region_size):\n border= mh.labeled.border(targets, 0, i)\n\n targets[border*(region < (10)*lim[peaks])] = i\n for i in range(2, ntargets+1):\n for j in range(2, ntargets+1):\n if i != j:\n border = mh.labeled.border(targets, i, j)\n if np.sum(border) != 0:\n targets[targets == j] = i\n \n targets = mh.labeled.remove_bordering(targets)\n for k in range(remove_excess):\n for i in range(ntargets):\n if np.sum(self.integrated_postcard[targets == i]) < 0.01:\n targets[targets > i] -= 1\n\n self.targets = targets\n \n if plot_flag == True:\n plt.imshow(self.targets, interpolation='nearest')\n plt.show()\n\n plt.imshow(((targets == 1)*self.integrated_postcard + (targets == 1)*100000)\n [jj-plot_window:jj+plot_window,ii-plot_window:ii+plot_window], \n interpolation='nearest', cmap='gray', vmax=np.percentile(self.integrated_postcard, 99.6))\n plt.show()\n\n plt.imshow((np.ceil(targets/100.0)*self.integrated_postcard+np.ceil(targets/500.0)*3500000), \n interpolation='nearest', cmap='gray', vmax=np.percentile(self.integrated_postcard, 99.99))\n plt.show()", "response": "Find other sources on the postcard."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ndoes photometry and estimates uncertainties by calculating the scatter around a linear fit to the data.", "response": "def do_photometry(self):\n \"\"\"\n Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data\n in each orientation. This function is called by other functions and generally the user will not need\n to interact with it directly.\n \"\"\"\n \n std_f = np.zeros(4)\n data_save = np.zeros_like(self.postcard)\n self.obs_flux = np.zeros_like(self.reference_flux)\n\n\n for i in range(4):\n g = np.where(self.qs == i)[0]\n wh = np.where(self.times[g] > 54947)\n\n data_save[g] = np.roll(self.postcard[g], int(self.roll_best[i,0]), axis=1)\n data_save[g] = np.roll(data_save[g], int(self.roll_best[i,1]), axis=2)\n\n self.target_flux_pixels = data_save[:,self.targets == 1]\n self.target_flux = np.sum(self.target_flux_pixels, axis=1)\n \n self.obs_flux[g] = self.target_flux[g] / self.reference_flux[g]\n self.obs_flux[g] /= np.median(self.obs_flux[g[wh]])\n \n fitline = np.polyfit(self.times[g][wh], self.obs_flux[g][wh], 1)\n std_f[i] = np.max([np.std(self.obs_flux[g][wh]/(fitline[0]*self.times[g][wh]+fitline[1])), 0.001])\n \n self.flux_uncert = std_f"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef generate_panel(self, img):\n plt.figure(figsize=(14,6))\n ax = plt.gca()\n fig = plt.gcf()\n plt.subplot(122)\n \n \n data_save = np.zeros_like(self.postcard)\n self.roll_best = np.zeros((4,2))\n \n for i in range(4):\n g = np.where(self.qs == i)[0]\n wh = np.where(self.times[g] > 54947)\n\n self.roll_best[i] = self.do_rolltest(g, wh)\n \n self.do_photometry()\n for i in range(4):\n g = np.where(self.qs == i)[0]\n plt.errorbar(self.times[g], self.obs_flux[g], yerr=self.flux_uncert[i], fmt=fmt[i])\n \n plt.xlabel('Time', fontsize=20)\n plt.ylabel('Relative Flux', fontsize=20)\n \n \n plt.subplot(121)\n implot = plt.imshow(img, interpolation='nearest', cmap='gray', vmin=98000*52, vmax=104000*52)\n cid = fig.canvas.mpl_connect('button_press_event', self.onclick)\n \n plt.show(block=True)", "response": "Generates the figure shown in adjust_aperture for visualization purposes."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef adjust_aperture(self, image_region=15, ignore_bright=0):\n self.ignore_bright = ignore_bright\n self.calc_fluxes()\n \n self.coordsx = []\n self.coordsy = []\n \n jj, ii = self.center\n jj, ii = int(jj), int(ii) # Indices must be integer\n plt.ion()\n img = np.sum(((self.targets == 1)*self.postcard + (self.targets == 1)*100000)\n [:,jj-image_region:jj+image_region,ii-image_region:ii+image_region], axis=0)\n self.generate_panel(img)\n \n while len(self.coordsx) != 0:\n for i in range(len(self.coordsx)):\n if self.targets[self.coordsy[i]+jj-image_region,self.coordsx[i]+ii-image_region] != 1:\n self.targets[self.coordsy[i]+jj-image_region,self.coordsx[i]+ii-image_region] = 1\n elif self.targets[self.coordsy[i]+jj-image_region,self.coordsx[i]+ii-image_region] == 1:\n self.targets[self.coordsy[i]+jj-image_region,self.coordsx[i]+ii-image_region] = 0\n if self.coordsy[i] == 0:\n thiscol = np.where(self.targets[:,self.coordsx[i]+ii-image_region] == 1)\n self.targets[thiscol,self.coordsx[i]+ii-image_region] = 0\n if self.coordsx[i] == 0:\n thiscol = np.where(self.targets[self.coordsy[i]+jj-image_region,:] == 1)\n self.targets[self.coordsy[i]+jj-image_region, thiscol] = 0\n\n\n self.coordsx = []\n self.coordsy = []\n img = np.sum(((self.targets == 1)*self.postcard + \n (self.targets == 1)*100000)[:,jj-image_region:jj+image_region,ii-image_region:ii+image_region],\n axis=0)\n self.generate_panel(img)", "response": "This function updates the aperture and the light curve in the aperture panel."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncalculate the normalized photometry for the target aperture.", "response": "def data_for_target(self, do_roll=True, ignore_bright=0):\n \"\"\"\n Determine the normalized photometry, accounting for effects shared by reference stars. Does not provide\n the opportunity to adjust the aperture\n \n Args: \n image_region: If ``True`` allow the aperture to be shifted up to one pixel in both the x and y\n directions to account for differential velocity aberration (default: ``True``)\n ignore_bright: The number of brightest stars to be ignored in the determination of the flux from \n reference stars. If there is reason to believe (for example) that saturated stars may behave\n differently than the target star, they can be avoided with this flag (default: ``0``)\n \n \"\"\"\n self.ignore_bright = ignore_bright\n self.calc_fluxes()\n self.roll_best = np.zeros((4,2))\n\n \n if do_roll == True:\n for i in range(4):\n g = np.where(self.qs == i)[0]\n wh = np.where(self.times[g] > 54947)\n\n self.roll_best[i] = self.do_rolltest(g, wh)\n \n self.do_photometry()"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncalculates the total flux in each object in each epoch and returns a numpy array of the fluxes in each object.", "response": "def calc_fluxes(self, min_flux = 5000, outlier_iterations=5,\n max_outlier_obs=4, outlier_limit=1.7):\n \"\"\"\n Determine the suitable reference stars, and then the total flux in those stars and \n in the target star in each epoch\n \n Args: \n min_flux: The size of the region around the target star to be plotted. Images will be a square \n with side length ``image_region`` (default: ``5000``)\n outlier_iterations: The number of iterations to remove outliers from the reference star sample\n (stars at epochs with more than ``max_outlier_obs`` observations more than ``outlier_limit`` standard\n deviations from the median value for all stars after normalization) (default: ``5``)\n max_outlier_obs: The maximum number of epochs at which a star is allowed to be more than ``outlier_limit``\n standard deviations from the median value for all stars before it is removed as a suitable\n reference star (default: ``4``)\n outlier_limit: The level of deviation (measured in standard deviations) which a target is allowed\n to be discrepant from the median. If it is this discrepant at more than ``max_outlier_obs``\n epochs, it is removed from consideration (default: ``1.7``)\n \n \"\"\"\n \n jj, ii = self.center\n \n\n \n numer = np.zeros(len(self.times))\n denom = np.zeros(len(self.times))\n factr = np.zeros(len(self.times))\n \n numer_pix = self.postcard[:,self.targets == 1]\n numer = np.sum(numer_pix, axis=1)\n \n tar_vals = np.zeros((len(self.times), int(np.max(self.targets)+1-2-self.ignore_bright)))\n \n for i in range(2+self.ignore_bright,int(np.max(self.targets)+1)):\n tval = np.sum(self.postcard[:,self.targets == i], axis=1)\n #denom += tval/np.median(tval)\n tar_vals[:,i-2-self.ignore_bright] = tval #/ np.median(tval)\n \n for i in range(len(self.obs_filenames)):\n if np.max(tar_vals[i]) < min_flux:\n tar_vals[self.qs == self.qs[i]] = 0.0\n\n all_tar = np.zeros((len(self.times), int(np.max(self.targets)-self.ignore_bright)))\n all_tar[:,0] = numer\n all_tar[:,1:] = tar_vals\n \n self.photometry_array = all_tar\n \n for i in range(len(tar_vals[0])):\n for j in range(4):\n g = np.where(self.qs == j)[0] \n tar_vals[g,i] /= (np.median(tar_vals[g,i])+1e-15)\n \n\n tar_vals_old = tar_vals + 0.0\n \n for i in range(outlier_iterations):\n nonzeros = np.where(tar_vals[0,:] != 0)[0]\n med = np.median(tar_vals[:,nonzeros], axis=1)\n std = np.std(tar_vals[:,nonzeros], axis=1)\n\n if np.sum(tar_vals) != 0.0:\n tar_vals_old = tar_vals + 0.0\n\n for k in range(len(tar_vals[0])):\n h = np.where((np.abs(med-tar_vals[:,k])/std) > outlier_limit)[0]\n if len(h) >= max_outlier_obs:\n tar_vals[:,k] = 0\n\n if np.sum(tar_vals) == 0.0:\n tar_vals = tar_vals_old + 0.0\n\n denom = np.sum(tar_vals, axis=1)\n self.target_flux_pixels = numer_pix\n self.reference_flux = denom"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncalculate the centroid positions for the target star at all epochs.", "response": "def calc_centroids(self):\n \"\"\"\n Identify the centroid positions for the target star at all epochs. Useful for verifying that there is\n no correlation between flux and position, as might be expected for high proper motion stars.\n \"\"\"\n self.cm = np.zeros((len(self.postcard), 2))\n for i in range(len(self.postcard)):\n target = self.postcard[i]\n target[self.targets != 1] = 0.0\n self.cm[i] = center_of_mass(target)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ndefining the spotsignal for each single cadence object.", "response": "def define_spotsignal(self):\n \"\"\"\n Identify the \"expected\" flux value at the time of each observation based on the \n Kepler long-cadence data, to ensure variations observed are not the effects of a single\n large starspot. Only works if the target star was targeted for long or short cadence\n observations during the primary mission.\n \"\"\"\n client = kplr.API()\n star = client.star(self.kic)\n\n lcs = star.get_light_curves(short_cadence=False)\n time, flux, ferr, qual = [], [], [], []\n for lc in lcs:\n with lc.open() as f:\n hdu_data = f[1].data\n time.append(hdu_data[\"time\"])\n flux.append(hdu_data[\"pdcsap_flux\"])\n ferr.append(hdu_data[\"pdcsap_flux_err\"])\n qual.append(hdu_data[\"sap_quality\"])\n tout = np.array([])\n fout = np.array([])\n eout = np.array([])\n for i in range(len(flux)):\n t = time[i][qual[i] == 0]\n f = flux[i][qual[i] == 0]\n e = ferr[i][qual[i] == 0]\n\n t = t[np.isfinite(f)]\n e = e[np.isfinite(f)]\n f = f[np.isfinite(f)]\n\n e /= np.median(f)\n f /= np.median(f)\n tout = np.append(tout, t[50:]+54833)\n fout = np.append(fout, f[50:])\n eout = np.append(eout, e[50:])\n\n self.spot_signal = np.zeros(52)\n\n for i in range(len(self.times)):\n if self.times[i] < 55000:\n self.spot_signal[i] = 1.0\n else:\n self.spot_signal[i] = fout[np.abs(self.times[i] - tout) == np.min(np.abs(self.times[i] - tout))]"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef model_uncert(self):\n Y = self.photometry_array.T\n Y /= np.median(Y, axis=1)[:, None]\n C = np.median(Y, axis=0)\n \n nstars, nobs = np.shape(Y)\n \n Z = np.empty((nstars, 4))\n \n qs = self.qs.astype(int)\n \n for s in range(4):\n Z[:, s] = np.median((Y / C)[:, qs == s], axis=1)\n\n resid2 = (Y - Z[:, qs] * C)**2\n z = Z[:, qs]\n trend = z * C[None, :]\n \n lnS = np.log(np.nanmedian(resid2, axis=0))\n jitter = np.log(0.1*np.nanmedian(np.abs(np.diff(Y, axis=1))))\n\n cal_ferr = np.sqrt(np.exp(2*(jitter/trend))+z**2*np.exp(lnS)[None, :])\n \n self.modeled_uncert = cal_ferr\n self.target_uncert = cal_ferr[0]", "response": "Estimate the photometric uncertainties on each data point following Equation A. 2 of The Paper."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nappending line to internal list.", "response": "def _print(self, line=''):\n \"\"\"Append line to internal list. \n Uses self.tabs to format indents.\n \n Keyword arguments:\n line -- line to append\n \"\"\"\n self.lines.append('{}{}'.format('\\t'*self.tabs , line))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndumping single enum type.", "response": "def _dump_enum(self, e, top=''):\n \"\"\"Dump single enum type.\n \n Keyword arguments:\n top -- top namespace\n \"\"\"\n self._print()\n self._print('enum {} {{'.format(e.name))\n self.defines.append('{}.{}'.format(top,e.name))\n \n self.tabs+=1\n for v in e.value:\n self._print('{} = {};'.format(v.name, v.number))\n self.tabs-=1\n self._print('}')"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ndump a single field.", "response": "def _dump_field(self, fd):\n \"\"\"Dump single field.\n \"\"\"\n v = {}\n v['label'] = Pbd.LABELS[fd.label]\n v['type'] = fd.type_name if len(fd.type_name) > 0 else Pbd.TYPES[fd.type]\n v['name'] = fd.name\n v['number'] = fd.number\n v['default'] = '[default = {}]'.format(fd.default_value) if len(fd.default_value) > 0 else ''\n \n f = '{label} {type} {name} = {number} {default};'.format(**v)\n f = ' '.join(f.split())\n self._print(f)\n \n if len(fd.type_name) > 0:\n self.uses.append(fd.type_name)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _dump_message(self, m, top=''):\n self._print()\n self._print('message {} {{'.format(m.name))\n self.defines.append('{}.{}'.format(top, m.name))\n self.tabs+=1\n \n for f in m.field:\n self._dump_field(f)\n \n for e in m.enum_type:\n self._dump_enum(e, top='{}.{}'.format(top, m.name))\n \n for n in m.nested_type:\n self._dump_message(n, top='{}.{}'.format(top, m.name))\n \n self.tabs-=1\n self._print('}')", "response": "Dump a single message type."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _walk(self, fd):\n top = '.{}'.format(fd.package) if len(fd.package) > 0 else ''\n \n for e in fd.enum_type: self._dump_enum(e, top)\n for m in fd.message_type: self. _dump_message(m, top)", "response": "Walk and dump the class metadata."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ndisassembling serialized protocol buffers file.", "response": "def disassemble(self):\n \"\"\"Disassemble serialized protocol buffers file.\n \"\"\"\n ser_pb = open(self.input_file, 'rb').read() # Read serialized pb file\n \n fd = FileDescriptorProto()\n fd.ParseFromString(ser_pb)\n self.name = fd.name\n \n self._print('// Reversed by pbd (https://github.com/rsc-dev/pbd)')\n self._print('syntax = \"proto2\";')\n self._print('')\n \n if len(fd.package) > 0:\n self._print('package {};'.format(fd.package))\n self.package = fd.package\n else:\n self._print('// Package not defined')\n \n self._walk(fd)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ndumps the proto file to given directory.", "response": "def dump(self, out_dir='.'):\n \"\"\"Dump proto file to given directory.\n \n Keyword arguments:\n out_dir -- dump directory. Default='.'\n \"\"\"\n uri = out_dir + os.sep + self.name\n with open(uri, 'w') as fh:\n fh.write('\\n'.join(self.lines))"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nfinds all missing imports in list of Pbd instances.", "response": "def find_imports(self, pbds):\n \"\"\"Find all missing imports in list of Pbd instances.\n \"\"\"\n # List of types used, but not defined\n imports = list(set(self.uses).difference(set(self.defines)))\n \n # Clumpsy, but enought for now \n for imp in imports:\n for p in pbds:\n if imp in p.defines:\n self.imports.append(p.name)\n break\n \n self.imports = list(set(self.imports))\n \n for import_file in self.imports:\n self.lines.insert(2, 'import \"{}\";'.format(import_file))"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning a dict from a fasta file and the number of sequences as the second return value.", "response": "def fasta_file_to_dict(fasta_file, id=True, header=False, seq=False):\n \"\"\"Returns a dict from a fasta file and the number of sequences as the second return value.\n fasta_file can be a string path or a file object.\n The key of fasta_dict can be set using the keyword arguments and\n results in a combination of id, header, sequence, in that order. joined with '||'. (default: id)\n Duplicate keys are checked and a warning is logged if found.\n The value of fasta_dict is a python dict with 3 keys: header, id and seq\n\n Changelog:\n 2014/11/17:\n * Added support for url escaped id\n \"\"\"\n fasta_file_f = fasta_file\n if isinstance(fasta_file, str):\n fasta_file_f = open(fasta_file, 'rb')\n\n fasta_dict = OrderedDict()\n keys = ['id', 'header', 'seq']\n flags = dict([('id', id), ('header', header), ('seq', seq)])\n entry = dict([('id', ''), ('header', ''), ('seq', '')])\n count = 0\n line_num = 0\n\n for line in fasta_file_f:\n line = line.strip()\n if line and line[0] == '>':\n count += 1\n key = '||'.join([entry[i] for i in keys if flags[i]])\n if key: # key != ''\n if key in fasta_dict: # check for duplicate key\n logger.warning('%s : Line %d : Duplicate %s [%s] : ID = [%s].', fasta_file_f.name, line_num, '||'.join([i for i in keys if flags[i]]), key[:25] + (key[25:] and '..'), entry['id'])\n entry['seq'] = ''.join(entry['seq'])\n fasta_dict[key] = entry\n # check for url escaped id\n if id:\n unescaped_id = unquote(entry['id'])\n if id != unescaped_id:\n key = '||'.join([unescaped_id] + [entry[i] for i in keys if i != 'id' and flags[i]])\n entry['unescaped_id'] = unescaped_id\n fasta_dict[key] = entry\n entry = dict()\n entry['header'] = line\n entry['id'] = line.split()[0][1:]\n entry['seq'] = []\n else:\n entry['seq'].append(line.upper())\n line_num += 1\n\n if isinstance(fasta_file, str):\n fasta_file_f.close()\n\n key = '||'.join([entry[i] for i in keys if flags[i]])\n if key: # key != ''\n if key in fasta_dict:\n logger.warning('%s : Line %d : Duplicate %s [%s] : ID = [%s].', fasta_file_f.name, line_num, '||'.join([i for i in keys if flags[i]]), key[:25] + (key[25:] and '..'), entry['id'])\n entry['seq'] = ''.join(entry['seq'])\n fasta_dict[key] = entry\n # check for url escaped id\n if id:\n unescaped_id = unquote(entry['id'])\n if id != unescaped_id:\n key = '||'.join([unescaped_id] + [entry[i] for i in keys if i != 'id' and flags[i]])\n entry['unescaped_id'] = unescaped_id\n fasta_dict[key] = entry\n\n return fasta_dict, count"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef fasta_dict_to_file(fasta_dict, fasta_file, line_char_limit=None):\n fasta_fp = fasta_file\n if isinstance(fasta_file, str):\n fasta_fp = open(fasta_file, 'wb')\n\n for key in fasta_dict:\n seq = fasta_dict[key]['seq']\n if line_char_limit:\n seq = '\\n'.join([seq[i:i+line_char_limit] for i in range(0, len(seq), line_char_limit)])\n fasta_fp.write(u'{0:s}\\n{1:s}\\n'.format(fasta_dict[key]['header'], seq))", "response": "Write a dictionary to a fasta file"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncheck whether child features are within the coordinate boundaries of parent features.", "response": "def check_parent_boundary(self):\n \"\"\"\n checks whether child features are within the coordinate boundaries of parent features\n\n :return:\n \"\"\"\n for line in self.lines:\n for parent_feature in line['parents']:\n ok = False\n for parent_line in parent_feature:\n if parent_line['start'] <= line['start'] and line['end'] <= parent_line['end']:\n ok = True\n break\n if not ok:\n self.add_line_error(line, {'message': 'This feature is not contained within the feature boundaries of parent: {0:s}: {1:s}'.format(\n parent_feature[0]['attributes']['ID'],\n ','.join(['({0:s}, {1:d}, {2:d})'.format(line['seqid'], line['start'], line['end']) for line in parent_feature])\n ), 'error_type': 'BOUNDS', 'location': 'parent_boundary'})"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncheck if the phase of the current node is correct", "response": "def check_phase(self):\n \"\"\"\n 1. get a list of CDS with the same parent\n 2. sort according to strand\n 3. calculate and validate phase\n \"\"\"\n plus_minus = set(['+', '-'])\n for k, g in groupby(sorted([line for line in self.lines if line['line_type'] == 'feature' and line['type'] == 'CDS' and 'Parent' in line['attributes']], key=lambda x: x['attributes']['Parent']), key=lambda x: x['attributes']['Parent']):\n cds_list = list(g)\n strand_set = list(set([line['strand'] for line in cds_list]))\n if len(strand_set) != 1:\n for line in cds_list:\n self.add_line_error(line, {'message': 'Inconsistent CDS strand with parent: {0:s}'.format(k), 'error_type': 'STRAND'})\n continue\n if len(cds_list) == 1:\n if cds_list[0]['phase'] != 0:\n self.add_line_error(cds_list[0], {'message': 'Wrong phase {0:d}, should be {1:d}'.format(cds_list[0]['phase'], 0), 'error_type': 'PHASE'})\n continue\n strand = strand_set[0]\n if strand not in plus_minus:\n # don't process unknown strands\n continue\n if strand == '-':\n # sort end descending\n sorted_cds_list = sorted(cds_list, key=lambda x: x['end'], reverse=True)\n else:\n sorted_cds_list = sorted(cds_list, key=lambda x: x['start'])\n phase = 0\n for line in sorted_cds_list:\n if line['phase'] != phase:\n self.add_line_error(line, {'message': 'Wrong phase {0:d}, should be {1:d}'.format(line['phase'], phase), 'error_type': 'PHASE'})\n phase = (3 - ((line['end'] - line['start'] + 1 - phase) % 3)) % 3"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef check_reference(self, sequence_region=False, fasta_embedded=False, fasta_external=False, check_bounds=True, check_n=True, allowed_num_of_n=0, feature_types=('CDS',)):\n # collect lines with errors in this set\n error_lines = set()\n # check if we have a parsed gff3\n if not self.lines:\n self.logger.debug('.parse(gff_file) before calling .check_bounds()')\n return error_lines\n # setup default line_types\n check_n_feature_types = set(feature_types)\n if len(check_n_feature_types) == 0:\n check_n_feature_types.add('CDS')\n # compile regex\n n_segments_finditer = re.compile(r'[Nn]+').finditer\n # check_all_sources mode\n check_all_sources = True\n if sequence_region or fasta_embedded or fasta_external:\n check_all_sources = False\n # get a list of line_data with valid start and end coordinates and unescape the seqid\n start_end_error_locations = set(('start', 'end', 'start,end'))\n valid_line_data_seqid = [(line_data, unquote(line_data['seqid'])) for line_data in self.lines if line_data['line_type'] == 'feature' and line_data['seqid'] != '.' and (not line_data['line_errors'] or not [error_info for error_info in line_data['line_errors'] if 'location' in error_info and error_info['location'] in start_end_error_locations])]\n checked_at_least_one_source = False\n # check directive\n # don't use any directives with errors\n valid_sequence_regions = dict([(unquote(line_data['seqid']), line_data) for line_data in self.lines if line_data['directive'] == '##sequence-region' and not line_data['line_errors']])\n unresolved_seqid = set()\n if (check_all_sources or sequence_region) and valid_sequence_regions:\n checked_at_least_one_source = True\n for line_data, seqid in valid_line_data_seqid:\n if seqid not in valid_sequence_regions and seqid not in unresolved_seqid:\n unresolved_seqid.add(seqid)\n error_lines.add(line_data['line_index'])\n self.add_line_error(line_data, {'message': u'Seqid not found in any ##sequence-region: {0:s}'.format(\n seqid), 'error_type': 'BOUNDS', 'location': 'sequence_region'})\n continue\n if line_data['start'] < valid_sequence_regions[seqid]['start']:\n error_lines.add(line_data['line_index'])\n self.add_line_error(line_data, {'message': 'Start is less than the ##sequence-region start: %d' % valid_sequence_regions[seqid]['start'], 'error_type': 'BOUNDS', 'location': 'sequence_region'})\n if line_data['end'] > valid_sequence_regions[seqid]['end']:\n error_lines.add(line_data['line_index'])\n self.add_line_error(line_data, {'message': 'End is greater than the ##sequence-region end: %d' % valid_sequence_regions[seqid]['end'], 'error_type': 'BOUNDS', 'location': 'sequence_region'})\n elif sequence_region:\n self.logger.debug('##sequence-region not found in GFF3')\n # check fasta_embedded\n unresolved_seqid = set()\n if (check_all_sources or fasta_embedded) and self.fasta_embedded:\n checked_at_least_one_source = True\n for line_data, seqid in valid_line_data_seqid:\n if seqid not in self.fasta_embedded and seqid not in unresolved_seqid:\n unresolved_seqid.add(seqid)\n error_lines.add(line_data['line_index'])\n self.add_line_error(line_data, {'message': 'Seqid not found in the embedded ##FASTA: %s' % seqid, 'error_type': 'BOUNDS', 'location': 'fasta_embedded'})\n continue\n # check bounds\n if line_data['end'] > len(self.fasta_embedded[seqid]['seq']):\n error_lines.add(line_data['line_index'])\n self.add_line_error(line_data, {'message': 'End is greater than the embedded ##FASTA sequence length: %d' % len(self.fasta_embedded[seqid]['seq']), 'error_type': 'BOUNDS', 'location': 'fasta_embedded'})\n # check n\n if check_n and line_data['type'] in check_n_feature_types:\n \"\"\"\n >>> timeit(\"a.lower().count('n')\", \"import re; a = ('ASDKADSJHFIUDNNNNNNNnnnnSHFD'*50)\")\n 5.540903252684302\n >>> timeit(\"a.count('n'); a.count('N')\", \"import re; a = ('ASDKADSJHFIUDNNNNNNNnnnnSHFD'*50)\")\n 2.3504867946058425\n >>> timeit(\"re.findall('[Nn]+', a)\", \"import re; a = ('ASDKADSJHFIUDNNNNNNNnnnnSHFD'*50)\")\n 30.60731204915959\n \"\"\"\n n_count = self.fasta_embedded[seqid]['seq'].count('N', line_data['start'] - 1, line_data['end']) + self.fasta_embedded[seqid]['seq'].count('n', line_data['start'] - 1, line_data['end'])\n if n_count > allowed_num_of_n:\n # get detailed segments info\n n_segments = [(m.start(), m.end() - m.start()) for m in n_segments_finditer(self.fasta_embedded[seqid]['seq'], line_data['start'] - 1, line_data['end'])]\n n_segments_str = ['(%d, %d)' % (m[0], m[1]) for m in n_segments]\n error_lines.add(line_data['line_index'])\n self.add_line_error(line_data, {'message': 'Found %d Ns in %s feature of length %d using the embedded ##FASTA, consists of %d segment (start, length): %s' % (n_count, line_data['type'], line_data['end'] - line_data['start'], len(n_segments), ', '.join(n_segments_str)), 'error_type': 'N_COUNT', 'n_segments': n_segments, 'location': 'fasta_embedded'})\n elif fasta_embedded:\n self.logger.debug('Embedded ##FASTA not found in GFF3')\n # check fasta_external\n unresolved_seqid = set()\n if (check_all_sources or fasta_external) and self.fasta_external:\n checked_at_least_one_source = True\n for line_data, seqid in valid_line_data_seqid:\n if seqid not in self.fasta_external and seqid not in unresolved_seqid:\n unresolved_seqid.add(seqid)\n error_lines.add(line_data['line_index'])\n self.add_line_error(line_data, {'message': 'Seqid not found in the external FASTA file: %s' % seqid, 'error_type': 'BOUNDS', 'location': 'fasta_external'})\n continue\n # check bounds\n if line_data['end'] > len(self.fasta_external[seqid]['seq']):\n error_lines.add(line_data['line_index'])\n self.add_line_error(line_data, {'message': 'End is greater than the external FASTA sequence length: %d' % len(self.fasta_external[seqid]['seq']), 'error_type': 'BOUNDS', 'location': 'fasta_external'})\n # check n\n if check_n and line_data['type'] in check_n_feature_types:\n n_count = self.fasta_external[seqid]['seq'].count('N', line_data['start'] - 1, line_data['end']) + self.fasta_external[seqid]['seq'].count('n', line_data['start'] - 1, line_data['end'])\n if n_count > allowed_num_of_n:\n # get detailed segments info\n n_segments = [(m.start(), m.end() - m.start()) for m in n_segments_finditer(self.fasta_external[seqid]['seq'], line_data['start'] - 1, line_data['end'])]\n n_segments_str = ['(%d, %d)' % (m[0], m[1]) for m in n_segments]\n error_lines.add(line_data['line_index'])\n self.add_line_error(line_data, {'message': 'Found %d Ns in %s feature of length %d using the external FASTA, consists of %d segment (start, length): %s' % (n_count, line_data['type'], line_data['end'] - line_data['start'], len(n_segments), ', '.join(n_segments_str)), 'error_type': 'N_COUNT', 'n_segments': n_segments, 'location': 'fasta_external'})\n elif fasta_external:\n self.logger.debug('External FASTA file not given')\n if check_all_sources and not checked_at_least_one_source:\n self.logger.debug('Unable to perform bounds check, requires at least one of the following sources: ##sequence-region, embedded ##FASTA, or external FASTA file')\n return error_lines", "response": "Checks the validity of the reference sequence."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef parse(self, gff_file, strict=False):\n valid_strand = set(('+', '-', '.', '?'))\n valid_phase = set((0, 1, 2))\n multi_value_attributes = set(('Parent', 'Alias', 'Note', 'Dbxref', 'Ontology_term'))\n valid_attribute_target_strand = set(('+', '-', ''))\n reserved_attributes = set(('ID', 'Name', 'Alias', 'Parent', 'Target', 'Gap', 'Derives_from', 'Note', 'Dbxref', 'Ontology_term', 'Is_circular'))\n\n # illegal character check\n # Literal use of tab, newline, carriage return, the percent (%) sign, and control characters must be encoded using RFC 3986 Percent-Encoding; no other characters may be encoded.\n # control characters: \\x00-\\x1f\\x7f this includes tab(\\x09), newline(\\x0a), carriage return(\\x0d)\n # seqid may contain any characters, but must escape any characters not in the set [a-zA-Z0-9.:^*$@!+_?-|]\n # URL escaping rules are used for tags or values containing the following characters: \",=;\".\n #>>> timeit(\"unescaped_seqid('Un.7589')\", \"import re; unescaped_seqid = re.compile(r'[^a-zA-Z0-9.:^*$@!+_?|%-]|%(?![0-9a-fA-F]{2})').search\")\n #0.4128372745785036\n #>>> timeit(\"unescaped_seqid2('Un.7589')\", \"import re; unescaped_seqid2 = re.compile(r'^([a-zA-Z0-9.:^*$@!+_?|-]|%[0-9a-fA-F]{2})+$').search\")\n #0.9012313532265175\n unescaped_seqid = re.compile(r'[^a-zA-Z0-9.:^*$@!+_?|%-]|%(?![0-9a-fA-F]{2})').search\n unescaped_field = re.compile(r'[\\x00-\\x1f\\x7f]|%(?![0-9a-fA-F]{2})').search\n\n gff_fp = gff_file\n if isinstance(gff_file, str):\n gff_fp = open(gff_file, 'r')\n\n lines = []\n current_line_num = 1 # line numbers start at 1\n features = defaultdict(list)\n # key = the unresolved id, value = a list of line_data(dict)\n unresolved_parents = defaultdict(list)\n\n for line_raw in gff_fp:\n line_data = {\n 'line_index': current_line_num - 1,\n 'line_raw': line_raw,\n 'line_status': 'normal',\n 'parents': [],\n 'children': [],\n 'line_type': '',\n 'directive': '',\n 'line_errors': [],\n 'type': '',\n }\n line_strip = line_raw.strip()\n if line_strip != line_raw[:len(line_strip)]:\n self.add_line_error(line_data, {'message': 'White chars not allowed at the start of a line', 'error_type': 'FORMAT', 'location': ''})\n if current_line_num == 1 and not line_strip.startswith('##gff-version'):\n self.add_line_error(line_data, {'message': '\"##gff-version\" missing from the first line', 'error_type': 'FORMAT', 'location': ''})\n if len(line_strip) == 0:\n line_data['line_type'] = 'blank'\n continue\n if line_strip.startswith('##'):\n line_data['line_type'] = 'directive'\n if line_strip.startswith('##sequence-region'):\n # ##sequence-region seqid start end\n # This element is optional, but strongly encouraged because it allows parsers to perform bounds checking on features.\n # only one ##sequence-region directive may be given for any given seqid\n # all features on that landmark feature (having that seqid) must be contained within the range defined by that ##sequence-region diretive. An exception to this rule is allowed when a landmark feature is marked with the Is_circular attribute.\n line_data['directive'] = '##sequence-region'\n tokens = list(line_strip.split()[1:])\n if len(tokens) != 3:\n self.add_line_error(line_data, {'message': 'Expecting 3 fields, got %d: %s' % (len(tokens) - 1, repr(tokens[1:])), 'error_type': 'FORMAT', 'location': ''})\n if len(tokens) > 0:\n line_data['seqid'] = tokens[0]\n # check for duplicate ##sequence-region seqid\n if [True for d in lines if ('directive' in d and d['directive'] == '##sequence-region' and 'seqid' in d and d['seqid'] == line_data['seqid'])]:\n self.add_line_error(line_data, {'message': '##sequence-region seqid: \"%s\" may only appear once' % line_data['seqid'], 'error_type': 'FORMAT', 'location': ''})\n try:\n all_good = True\n try:\n line_data['start'] = int(tokens[1])\n if line_data['start'] < 1:\n self.add_line_error(line_data, {'message': 'Start is not a valid 1-based integer coordinate: \"%s\"' % tokens[1], 'error_type': 'FORMAT', 'location': ''})\n except ValueError:\n all_good = False\n self.add_line_error(line_data, {'message': 'Start is not a valid integer: \"%s\"' % tokens[1], 'error_type': 'FORMAT', 'location': ''})\n line_data['start'] = tokens[1]\n try:\n line_data['end'] = int(tokens[2])\n if line_data['end'] < 1:\n self.add_line_error(line_data, {'message': 'End is not a valid 1-based integer coordinate: \"%s\"' % tokens[2], 'error_type': 'FORMAT', 'location': ''})\n except ValueError:\n all_good = False\n self.add_line_error(line_data, {'message': 'End is not a valid integer: \"%s\"' % tokens[2], 'error_type': 'FORMAT', 'location': ''})\n line_data['start'] = tokens[2]\n # if all_good then both start and end are int, so we can check if start is not less than or equal to end\n if all_good and line_data['start'] > line_data['end']:\n self.add_line_error(line_data, {'message': 'Start is not less than or equal to end', 'error_type': 'FORMAT', 'location': ''})\n except IndexError:\n pass\n elif line_strip.startswith('##gff-version'):\n # The GFF version, always 3 in this specification must be present, must be the topmost line of the file and may only appear once in the file.\n line_data['directive'] = '##gff-version'\n # check if it appeared before\n if [True for d in lines if ('directive' in d and d['directive'] == '##gff-version')]:\n self.add_line_error(line_data, {'message': '##gff-version missing from the first line', 'error_type': 'FORMAT', 'location': ''})\n tokens = list(line_strip.split()[1:])\n if len(tokens) != 1:\n self.add_line_error(line_data, {'message': 'Expecting 1 field, got %d: %s' % (len(tokens) - 1, repr(tokens[1:])), 'error_type': 'FORMAT', 'location': ''})\n if len(tokens) > 0:\n try:\n line_data['version'] = int(tokens[0])\n if line_data['version'] != 3:\n self.add_line_error(line_data, {'message': 'Version is not \"3\": \"%s\"' % tokens[0], 'error_type': 'FORMAT', 'location': ''})\n except ValueError:\n self.add_line_error(line_data, {'message': 'Version is not a valid integer: \"%s\"' % tokens[0], 'error_type': 'FORMAT', 'location': ''})\n line_data['version'] = tokens[0]\n elif line_strip.startswith('###'):\n # This directive (three # signs in a row) indicates that all forward references to feature IDs that have been seen to this point have been resolved.\n line_data['directive'] = '###'\n elif line_strip.startswith('##FASTA'):\n # This notation indicates that the annotation portion of the file is at an end and that the\n # remainder of the file contains one or more sequences (nucleotide or protein) in FASTA format.\n line_data['directive'] = '##FASTA'\n self.logger.info('Reading embedded ##FASTA sequence')\n self.fasta_embedded, count = fasta_file_to_dict(gff_fp)\n self.logger.info('%d sequences read' % len(self.fasta_embedded))\n elif line_strip.startswith('##feature-ontology'):\n # ##feature-ontology URI\n # This directive indicates that the GFF3 file uses the ontology of feature types located at the indicated URI or URL.\n line_data['directive'] = '##feature-ontology'\n tokens = list(line_strip.split()[1:])\n if len(tokens) != 1:\n self.add_line_error(line_data, {'message': 'Expecting 1 field, got %d: %s' % (len(tokens) - 1, repr(tokens[1:])), 'error_type': 'FORMAT', 'location': ''})\n if len(tokens) > 0:\n line_data['URI'] = tokens[0]\n elif line_strip.startswith('##attribute-ontology'):\n # ##attribute-ontology URI\n # This directive indicates that the GFF3 uses the ontology of attribute names located at the indicated URI or URL.\n line_data['directive'] = '##attribute-ontology'\n tokens = list(line_strip.split()[1:])\n if len(tokens) != 1:\n self.add_line_error(line_data, {'message': 'Expecting 1 field, got %d: %s' % (len(tokens) - 1, repr(tokens[1:])), 'error_type': 'FORMAT', 'location': ''})\n if len(tokens) > 0:\n line_data['URI'] = tokens[0]\n elif line_strip.startswith('##source-ontology'):\n # ##source-ontology URI\n # This directive indicates that the GFF3 uses the ontology of source names located at the indicated URI or URL.\n line_data['directive'] = '##source-ontology'\n tokens = list(line_strip.split()[1:])\n if len(tokens) != 1:\n self.add_line_error(line_data, {'message': 'Expecting 1 field, got %d: %s' % (len(tokens) - 1, repr(tokens[1:])), 'error_type': 'FORMAT', 'location': ''})\n if len(tokens) > 0:\n line_data['URI'] = tokens[0]\n elif line_strip.startswith('##species'):\n # ##species NCBI_Taxonomy_URI\n # This directive indicates the species that the annotations apply to.\n line_data['directive'] = '##species'\n tokens = list(line_strip.split()[1:])\n if len(tokens) != 1:\n self.add_line_error(line_data, {'message': 'Expecting 1 field, got %d: %s' % (len(tokens) - 1, repr(tokens[1:])), 'error_type': 'FORMAT', 'location': ''})\n if len(tokens) > 0:\n line_data['NCBI_Taxonomy_URI'] = tokens[0]\n elif line_strip.startswith('##genome-build'):\n # ##genome-build source buildName\n # The genome assembly build name used for the coordinates given in the file.\n line_data['directive'] = '##genome-build'\n tokens = list(line_strip.split()[1:])\n if len(tokens) != 2:\n self.add_line_error(line_data, {'message': 'Expecting 2 fields, got %d: %s' % (len(tokens) - 1, repr(tokens[1:])), 'error_type': 'FORMAT', 'location': ''})\n if len(tokens) > 0:\n line_data['source'] = tokens[0]\n try:\n line_data['buildName'] = tokens[1]\n except IndexError:\n pass\n else:\n self.add_line_error(line_data, {'message': 'Unknown directive', 'error_type': 'FORMAT', 'location': ''})\n tokens = list(line_strip.split())\n line_data['directive'] = tokens[0]\n elif line_strip.startswith('#'):\n line_data['line_type'] = 'comment'\n else:\n # line_type may be a feature or unknown\n line_data['line_type'] = 'feature'\n tokens = list(map(str.strip, line_raw.split('\\t')))\n if len(tokens) != 9:\n self.add_line_error(line_data, {'message': 'Features should contain 9 fields, got %d: %s' % (len(tokens) - 1, repr(tokens[1:])), 'error_type': 'FORMAT', 'location': ''})\n for i, t in enumerate(tokens):\n if not t:\n self.add_line_error(line_data, {'message': 'Empty field: %d, must have a \".\"' % (i + 1), 'error_type': 'FORMAT', 'location': ''})\n try:\n line_data['seqid'] = tokens[0]\n if unescaped_seqid(tokens[0]):\n self.add_line_error(line_data, {'message': 'Seqid must escape any characters not in the set [a-zA-Z0-9.:^*$@!+_?-|]: \"%s\"' % tokens[0], 'error_type': 'FORMAT', 'location': ''})\n line_data['source'] = tokens[1]\n if unescaped_field(tokens[1]):\n self.add_line_error(line_data, {'message': 'Source must escape the percent (%%) sign and any control characters: \"%s\"' % tokens[1], 'error_type': 'FORMAT', 'location': ''})\n line_data['type'] = tokens[2]\n if unescaped_field(tokens[2]):\n self.add_line_error(line_data, {'message': 'Type must escape the percent (%%) sign and any control characters: \"%s\"' % tokens[2], 'error_type': 'FORMAT', 'location': ''})\n all_good = True\n try:\n line_data['start'] = int(tokens[3])\n if line_data['start'] < 1:\n self.add_line_error(line_data, {'message': 'Start is not a valid 1-based integer coordinate: \"%s\"' % tokens[3], 'error_type': 'FORMAT', 'location': 'start'})\n except ValueError:\n all_good = False\n line_data['start'] = tokens[3]\n if line_data['start'] != '.':\n self.add_line_error(line_data, {'message': 'Start is not a valid integer: \"%s\"' % line_data['start'], 'error_type': 'FORMAT', 'location': 'start'})\n try:\n line_data['end'] = int(tokens[4])\n if line_data['end'] < 1:\n self.add_line_error(line_data, {'message': 'End is not a valid 1-based integer coordinate: \"%s\"' % tokens[4], 'error_type': 'FORMAT', 'location': 'end'})\n except ValueError:\n all_good = False\n line_data['end'] = tokens[4]\n if line_data['end'] != '.':\n self.add_line_error(line_data, {'message': 'End is not a valid integer: \"%s\"' % line_data['end'], 'error_type': 'FORMAT', 'location': 'end'})\n # if all_good then both start and end are int, so we can check if start is not less than or equal to end\n if all_good and line_data['start'] > line_data['end']:\n self.add_line_error(line_data, {'message': 'Start is not less than or equal to end', 'error_type': 'FORMAT', 'location': 'start,end'})\n try:\n line_data['score'] = float(tokens[5])\n except ValueError:\n line_data['score'] = tokens[5]\n if line_data['score'] != '.':\n self.add_line_error(line_data, {'message': 'Score is not a valid floating point number: \"%s\"' % line_data['score'], 'error_type': 'FORMAT', 'location': ''})\n line_data['strand'] = tokens[6]\n if line_data['strand'] not in valid_strand: # set(['+', '-', '.', '?'])\n self.add_line_error(line_data, {'message': 'Strand has illegal characters: \"%s\"' % tokens[6], 'error_type': 'FORMAT', 'location': ''})\n try:\n line_data['phase'] = int(tokens[7])\n if line_data['phase'] not in valid_phase: # set([0, 1, 2])\n self.add_line_error(line_data, {'message': 'Phase is not 0, 1, or 2: \"%s\"' % tokens[7], 'error_type': 'FORMAT', 'location': ''})\n except ValueError:\n line_data['phase'] = tokens[7]\n if line_data['phase'] != '.':\n self.add_line_error(line_data, {'message': 'Phase is not a valid integer: \"%s\"' % line_data['phase'], 'error_type': 'FORMAT', 'location': ''})\n elif line_data['type'] == 'CDS':\n self.add_line_error(line_data, {'message': 'Phase is required for all CDS features', 'error_type': 'FORMAT', 'location': ''})\n # parse attributes, ex: ID=exon00003;Parent=mRNA00001,mRNA00003;Name=EXON.1\n # URL escaping rules are used for tags or values containing the following characters: \",=;\". Spaces are allowed in this field, but tabs must be replaced with the %09 URL escape.\n # Note that attribute names are case sensitive. \"Parent\" is not the same as \"parent\".\n # All attributes that begin with an uppercase letter are reserved for later use. Attributes that begin with a lowercase letter can be used freely by applications.\n if unescaped_field(tokens[8]):\n self.add_line_error(line_data, {'message': 'Attributes must escape the percent (%) sign and any control characters', 'error_type': 'FORMAT', 'location': ''})\n attribute_tokens = tuple(tuple(t for t in a.split('=')) for a in tokens[8].split(';') if a)\n line_data['attributes'] = {}\n if len(attribute_tokens) == 1 and len(attribute_tokens[0]) == 1 and attribute_tokens[0][0] == '.':\n pass # no attributes\n else:\n for a in attribute_tokens:\n if len(a) != 2:\n self.add_line_error(line_data, {'message': 'Attributes must contain one and only one equal (=) sign: \"%s\"' % ('='.join(a)), 'error_type': 'FORMAT', 'location': ''})\n try:\n tag, value = a\n except ValueError:\n tag, value = a[0], ''\n if not tag:\n self.add_line_error(line_data, {'message': 'Empty attribute tag: \"%s\"' % '='.join(a), 'error_type': 'FORMAT', 'location': ''})\n if not value.strip():\n self.add_line_error(line_data, {'message': 'Empty attribute value: \"%s\"' % '='.join(a), 'error_type': 'FORMAT', 'location': ''}, log_level=logging.WARNING)\n if tag in line_data['attributes']:\n self.add_line_error(line_data, {'message': 'Found multiple attribute tags: \"%s\"' % tag, 'error_type': 'FORMAT', 'location': ''})\n if tag in multi_value_attributes: # set(['Parent', 'Alias', 'Note', 'Dbxref', 'Ontology_term'])\n if value.find(', ') >= 0:\n self.add_line_error(line_data, {'message': 'Found \", \" in %s attribute, possible unescaped \",\": \"%s\"' % (tag, value), 'error_type': 'FORMAT', 'location': ''}, log_level=logging.WARNING)\n # In addition to Parent, the Alias, Note, Dbxref and Ontology_term attributes can have multiple values.\n if tag in line_data['attributes']: # if this tag has been seen before\n if tag == 'Note': # don't check for duplicate notes\n line_data['attributes'][tag].extend(value.split(','))\n else: # only add non duplicate values\n line_data['attributes'][tag].extend([s for s in value.split(',') if s not in line_data['attributes'][tag]])\n else:\n line_data['attributes'][tag] = value.split(',')\n # check for duplicate values\n if tag != 'Note' and len(line_data['attributes'][tag]) != len(set(line_data['attributes'][tag])):\n count_values = [(len(list(group)), key) for key, group in groupby(sorted(line_data['attributes'][tag]))]\n self.add_line_error(line_data, {'message': '%s attribute has identical values (count, value): %s' % (tag, ', '.join(['(%d, %s)' % (c, v) for c, v in count_values if c > 1])), 'error_type': 'FORMAT', 'location': ''})\n # remove duplicate\n line_data['attributes'][tag] = list(set(line_data['attributes'][tag]))\n\n if tag == 'Parent':\n for feature_id in line_data['attributes']['Parent']:\n try:\n line_data['parents'].append(features[feature_id])\n for ld in features[feature_id]:\n # no need to check if line_data in ld['children'], because it is impossible, each ld maps to only one feature_id, so the ld we get are all different\n ld['children'].append(line_data)\n except KeyError: # features[id]\n self.add_line_error(line_data, {'message': '%s attribute has unresolved forward reference: %s' % (tag, feature_id), 'error_type': 'FORMAT', 'location': ''})\n unresolved_parents[feature_id].append(line_data)\n elif tag == 'Target':\n if value.find(',') >= 0:\n self.add_line_error(line_data, {'message': 'Value of %s attribute contains unescaped \",\": \"%s\"' % (tag, value), 'error_type': 'FORMAT', 'location': ''})\n target_tokens = value.split(' ')\n if len(target_tokens) < 3 or len(target_tokens) > 4:\n self.add_line_error(line_data, {'message': 'Target attribute should have 3 or 4 values, got %d: %s' % (len(target_tokens), repr(tokens)), 'error_type': 'FORMAT', 'location': ''})\n line_data['attributes'][tag] = {}\n try:\n line_data['attributes'][tag]['target_id'] = target_tokens[0]\n all_good = True\n try:\n line_data['attributes'][tag]['start'] = int(target_tokens[1])\n if line_data['attributes'][tag]['start'] < 1:\n self.add_line_error(line_data, {'message': 'Start value of Target attribute is not a valid 1-based integer coordinate: \"%s\"' % target_tokens[1], 'error_type': 'FORMAT', 'location': ''})\n except ValueError:\n all_good = False\n line_data['attributes'][tag]['start'] = target_tokens[1]\n self.add_line_error(line_data, {'message': 'Start value of Target attribute is not a valid integer: \"%s\"' % line_data['attributes'][tag]['start'], 'error_type': 'FORMAT', 'location': ''})\n try:\n line_data['attributes'][tag]['end'] = int(target_tokens[2])\n if line_data['attributes'][tag]['end'] < 1:\n self.add_line_error(line_data, {'message': 'End value of Target attribute is not a valid 1-based integer coordinate: \"%s\"' % target_tokens[2], 'error_type': 'FORMAT', 'location': ''})\n except ValueError:\n all_good = False\n line_data['attributes'][tag]['end'] = target_tokens[2]\n self.add_line_error(line_data, {'message': 'End value of Target attribute is not a valid integer: \"%s\"' % line_data['attributes'][tag]['end'], 'error_type': 'FORMAT', 'location': ''})\n # if all_good then both start and end are int, so we can check if start is not less than or equal to end\n if all_good and line_data['attributes'][tag]['start'] > line_data['attributes'][tag]['end']:\n self.add_line_error(line_data, {'message': 'Start is not less than or equal to end', 'error_type': 'FORMAT', 'location': ''})\n line_data['attributes'][tag]['strand'] = target_tokens[3]\n if line_data['attributes'][tag]['strand'] not in valid_attribute_target_strand: # set(['+', '-', ''])\n self.add_line_error(line_data, {'message': 'Strand value of Target attribute has illegal characters: \"%s\"' % line_data['attributes'][tag]['strand'], 'error_type': 'FORMAT', 'location': ''})\n except IndexError:\n pass\n else:\n if value.find(',') >= 0:\n self.add_line_error(line_data, {'message': 'Value of %s attribute contains unescaped \",\": \"%s\"' % (tag, value), 'error_type': 'FORMAT', 'location': ''})\n line_data['attributes'][tag] = value\n if tag == 'Is_circular' and value != 'true':\n self.add_line_error(line_data, {'message': 'Value of Is_circular attribute is not \"true\": \"%s\"' % value, 'error_type': 'FORMAT', 'location': ''})\n elif tag[:1].isupper() and tag not in reserved_attributes: # {'ID', 'Name', 'Alias', 'Parent', 'Target', 'Gap', 'Derives_from', 'Note', 'Dbxref', 'Ontology_term', 'Is_circular'}\n self.add_line_error(line_data, {'message': 'Unknown reserved (uppercase) attribute: \"%s\"' % tag, 'error_type': 'FORMAT', 'location': ''})\n elif tag == 'ID':\n # check for duplicate ID in non-adjacent lines\n if value in features and lines[-1]['attributes'][tag] != value:\n self.add_line_error(line_data, {'message': 'Duplicate ID: \"%s\" in non-adjacent lines: %s' % (value, ','.join([str(f['line_index'] + 1) for f in features[value]])), 'error_type': 'FORMAT', 'location': ''}, log_level=logging.WARNING)\n features[value].append(line_data)\n except IndexError:\n pass\n current_line_num += 1\n lines.append(line_data)\n\n if isinstance(gff_file, str):\n gff_fp.close()\n\n # global look up of unresolved parents\n for feature_id in unresolved_parents:\n if feature_id in features:\n for line in unresolved_parents[feature_id]:\n self.add_line_error(line, {'message': 'Unresolved forward reference: \"%s\", found defined in lines: %s' % (feature_id, ','.join([str(ld['line_index'] + 1) for ld in features[feature_id]])), 'error_type': 'FORMAT', 'location': ''})\n\n self.lines = lines\n self.features = features\n return 1", "response": "Parse the GFF file into a set of data structures."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn list of line_data with line_index as first element", "response": "def descendants(self, line_data):\n \"\"\"\n BFS graph algorithm\n :param line_data: line_data(dict) with line_data['line_index'] or line_index(int)\n :return: list of line_data(dict)\n \"\"\"\n # get start node\n try:\n start = line_data['line_index']\n except TypeError:\n start = self.lines[line_data]['line_index']\n visited_set, visited_list, queue = set(), [], [start]\n while queue:\n node = queue.pop(0)\n if node not in visited_set:\n visited_set.add(node)\n visited_list.append(self.lines[node])\n queue.extend([ld['line_index'] for ld in self.lines[node]['children'] if ld['line_index'] not in visited_set])\n return visited_list[1:]"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef adopt(self, old_parent, new_parent):\n try: # assume line_data(dict)\n old_id = old_parent['attributes']['ID']\n except TypeError:\n try: # assume line_index(int)\n old_id = self.lines[old_parent]['attributes']['ID']\n except TypeError: # assume feature_id(str)\n old_id = old_parent\n old_feature = self.features[old_id]\n old_indexes = [ld['line_index'] for ld in old_feature]\n try: # assume line_data(dict)\n new_id = new_parent['attributes']['ID']\n except TypeError:\n try: # assume line_index(int)\n new_id = self.lines[new_parent]['attributes']['ID']\n except TypeError: # assume feature_id(str)\n new_id = new_parent\n new_feature = self.features[new_id]\n new_indexes = [ld['line_index'] for ld in new_feature]\n # build a list of children to be moved\n # add the child to the new parent's children list if its not already there\n # update the child's parent list and parent attribute\n # finally remove the old parent's children list\n children = old_feature[0]['children']\n new_parent_children_set = set([ld['line_index'] for ld in new_feature[0]['children']])\n for child in children:\n if child['line_index'] not in new_parent_children_set:\n new_parent_children_set.add(child['line_index'])\n for new_ld in new_feature:\n new_ld['children'].append(child)\n child['parents'].append(new_feature)\n child['attributes']['Parent'].append(new_id)\n # remove multiple, list.remove() only removes 1\n child['parents'] = [f for f in child['parents'] if f[0]['attributes']['ID'] != old_id]\n child['attributes']['Parent'] = [d for d in child['attributes']['Parent'] if d != old_id]\n for old_ld in old_feature:\n old_ld['children'] = []\n return children", "response": "Transfer children from old_parent to new_parent."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef remove(self, line_data, root_type=None):\n roots = [ld for ld in self.ancestors(line_data) if (root_type and ld['line_type'] == root_type) or (not root_type and not ld['parents'])] or [line_data]\n for root in roots:\n root['line_status'] = 'removed'\n root_descendants = self.descendants(root)\n for root_descendant in root_descendants:\n root_descendant['line_status'] = 'removed'\n root_ancestors = self.ancestors(root) # BFS, so we will process closer ancestors first\n for root_ancestor in root_ancestors:\n if len([ld for ld in root_ancestor['children'] if ld['line_status'] != 'removed']) == 0: # if all children of a root_ancestor is removed\n # remove this root_ancestor\n root_ancestor['line_status'] = 'removed'", "response": "Removes a line_data from the data structure."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef sequence(self, line_data, child_type=None, reference=None):\n # get start node\n reference = reference or self.fasta_external or self.fasta_embedded\n if not reference:\n raise Exception('External or embedded fasta reference needed')\n try:\n line_index = line_data['line_index']\n except TypeError:\n line_index = self.lines[line_data]['line_index']\n ld = self.lines[line_index]\n if ld['type'] != 'feature':\n return None\n seq = reference[ld['seqid']][ld['start']-1:ld['end']]\n if ld['strand'] == '-':\n seq = complement(seq[::-1])\n return seq", "response": "Get the sequence of line_data according to the columns seqid start end strand and child_type"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef abfIDfromFname(fname):\n fname=os.path.abspath(fname)\n basename=os.path.basename(fname)\n return os.path.splitext(basename)[0]", "response": "given a filename return the ABFs ID string."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ndetermine the protocol used to record an ABF file", "response": "def abfProtocol(fname):\n \"\"\"Determine the protocol used to record an ABF file\"\"\"\n f=open(fname,'rb')\n raw=f.read(30*1000) #it should be in the first 30k of the file\n f.close()\n raw=raw.decode(\"utf-8\",\"ignore\")\n raw=raw.split(\"Clampex\")[1].split(\".pro\")[0]\n protocol = os.path.basename(raw) # the whole protocol filename\n protocolID = protocol.split(\" \")[0] # just the first number\n return protocolID"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngiving the bytestring ABF header make and launch HTML.", "response": "def headerHTML(header,fname):\n \"\"\"given the bytestring ABF header, make and launch HTML.\"\"\"\n html=\"\"\n html+=\"
%s
\"%(fname)\n html+=pprint.pformat(header, indent=1)\n html=html.replace(\"\\n\",' ').replace(\" \",\" \")\n html=html.replace(r\"\\x00\",\"\")\n html+=\"\"\n print(\"saving header file:\",fname)\n f=open(fname,'w')\n f.write(html)\n f.close()\n webbrowser.open(fname)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef setsweep(self, sweep=0, channel=0):\n try:\n sweep=int(sweep)\n except:\n self.log.error(\"trying to set sweep to [%s]\",sweep)\n return\n if sweep<0:\n sweep=self.sweeps-1-sweep # if negative, start from the end\n sweep=max(0,min(sweep,self.sweeps-1)) # correct for out of range sweeps\n if 'sweep' in dir(self) and self.sweep == sweep and self.derivative is False:\n self.log.debug(\"sweep %d already set\",sweep)\n return\n #self.log.debug(\"loading sweep %d (Ch%d)\",sweep,channel)\n self.channels=self.ABFblock.segments[sweep].size[\"analogsignals\"]\n if self.channels>1 and sweep==0:\n self.log.info(\"WARNING: multichannel not yet supported!\") #TODO:\n self.trace = self.ABFblock.segments[sweep].analogsignals[channel]\n self.sweep=sweep # currently selected sweep\n self.channel=channel # currently selected channel\n\n # sweep information\n self.rate = int(self.trace.sampling_rate) # Hz\n self.period = float(1/self.rate) # seconds (inverse of sample rate)\n self.pointsPerSec = int(self.rate) # for easy access\n self.pointsPerMs = int(self.rate/1000.0) # for easy access\n self.sweepSize = len(self.trace) # number of data points per sweep\n self.sweepInterval = self.trace.duration.magnitude # sweep interval (seconds)\n self.sweepLength = float(self.trace.t_stop-self.trace.t_start) # in seconds\n self.length = self.sweepLength*self.sweeps # length (sec) of total recording\n self.lengthMinutes = self.length/60.0 # length (minutes) of total recording\n\n if str(self.trace.dimensionality) == 'pA':\n self.units,self.units2=\"pA\",\"clamp current (pA)\"\n self.unitsD,self.unitsD2=\"pA/ms\",\"current velocity (pA/ms)\"\n self.protoUnits,self.protoUnits2=\"mV\",\"command voltage (mV)\"\n elif str(self.trace.dimensionality) == 'mV':\n self.units,self.units2=\"mV\",\"membrane potential (mV)\"\n self.unitsD,self.unitsD2=\"V/s\",\"potential velocity (V/s)\"\n self.protoUnits,self.protoUnits2=\"pA\",\"command current (pA)\"\n else:\n self.units,self.units2=\"?\",\"unknown units\"\n self.unitsD,self.unitsD2=\"?\",\"unknown units\"\n\n # sweep data\n self.sweepY = self.trace.magnitude # sweep data (mV or pA)\n self.sweepT = self.trace.times.magnitude # actual sweep times (sec)\n self.sweepStart = float(self.trace.t_start) # time start of sweep (sec)\n self.sweepX2 = self.sweepT-self.trace.t_start.magnitude # sweeps overlap\n self.sweepX = self.sweepX2+sweep*self.sweepInterval # assume no gaps\n if self.derivative:\n self.log.debug(\"taking derivative\")\n #self.sweepD=np.diff(self.sweepY) # take derivative\n self.sweepD=self.sweepY[1:]-self.sweepY[:-1] # better?\n self.sweepD=np.insert(self.sweepD,0,self.sweepD[0]) # add a point\n self.sweepD/=(self.period*1000) # correct for sample rate\n else:\n self.sweepD=[0] # derivative is forced to be empty\n\n # generate the protocol too\n self.generate_protocol()", "response": "set the sweep and channel of an ABF. Both start at 0."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\niterate over every sweep", "response": "def setsweeps(self):\n \"\"\"iterate over every sweep\"\"\"\n for sweep in range(self.sweeps):\n self.setsweep(sweep)\n yield self.sweep"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nread the header and populate self with information about comments", "response": "def comments_load(self):\n \"\"\"read the header and populate self with information about comments\"\"\"\n self.comment_times,self.comment_sweeps,self.comment_tags=[],[],[]\n self.comments=0 # will be >0 if comments exist\n self.comment_text=\"\"\n\n try:\n # this used to work\n self.comment_tags = list(self.ABFblock.segments[0].eventarrays[0].annotations['comments'])\n self.comment_times = list(self.ABFblock.segments[0].eventarrays[0].times/self.trace.itemsize)\n self.comment_sweeps = list(self.comment_times)\n except:\n # now this notation seems to work\n for events in self.ABFblock.segments[0].events: # this should only happen once actually\n self.comment_tags = events.annotations['comments'].tolist()\n self.comment_times = np.array(events.times.magnitude/self.trace.itemsize)\n self.comment_sweeps = self.comment_times/self.sweepInterval\n\n for i,c in enumerate(self.comment_tags):\n self.comment_tags[i]=c.decode(\"utf-8\")"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngenerating the protocol for the current sweep.", "response": "def generate_protocol(self):\n \"\"\"\n Recreate the command stimulus (protocol) for the current sweep.\n It's not stored point by point (that's a waste of time and memory!)\n Instead it's stored as a few (x,y) points which can be easily graphed.\n\n TODO: THIS\n for segment in abf.ABFreader.read_protocol():\n for analogsignal in segment.analogsignals:\n print(analogsignal)\n plt.plot(analogsignal)\n plt.show()\n plt.close('all')\n\n \"\"\"\n # TODO: elegantly read the protocol like this:\n #abf.ABFreader.read_protocol()[0].analogsignals()[sigNum]\n\n\n\n # TODO: right now this works only for the first channel\n\n # correct for weird recording/protocol misalignment\n #what is magic here? 64-bit data points? #1,000,000/64 = 15625 btw\n self.offsetX = int(self.sweepSize/64)\n\n # if there's not a header, get out of here!\n if not len(self.header['dictEpochInfoPerDAC']):\n self.log.debug(\"no protocol defined, so I'll make one\")\n self.protoX,self.protoY=[0,self.sweepX[-1]],[self.holding,self.holding]\n self.protoSeqX,self.protoSeqY=[0],[self.holding]\n return\n\n # load our protocol from the header\n proto=self.header['dictEpochInfoPerDAC'][self.channel]\n\n # prepare our (x,y) pair arrays\n self.protoX,self.protoY=[] ,[]\n\n # assume our zero time point is the \"holding\" value\n self.protoX.append(0)\n self.protoY.append(self.holding) #TODO: what is this???\n\n # now add x,y points for each change in the protocol\n for step in proto:\n dX = proto[step]['lEpochInitDuration']\n Y = proto[step]['fEpochInitLevel']+proto[step]['fEpochLevelInc']*self.sweep\n # we have a new Y value, so add it to the last time point\n self.protoX.append(self.protoX[-1])\n self.protoY.append(Y)\n # now add the same Y point after \"dX\" amount of time\n self.protoX.append(self.protoX[-1]+dX)\n self.protoY.append(Y)\n # TODO: detect ramps and warn what's up\n\n # The last point is probably holding current\n finalVal=self.holding #regular holding\n # although if it's set to \"use last value\", maybe that should be the last one\n if self.header['listDACInfo'][0]['nInterEpisodeLevel']:\n finalVal=self.protoY[-1]\n\n # add the shift to the final value to the list\n self.protoX.append(self.protoX[-1])\n self.protoY.append(finalVal)\n # and again as the very last time point\n self.protoX.append(self.sweepSize)\n self.protoY.append(finalVal)\n\n # update the sequence of protocols now (eliminate duplicate entries)\n for i in range(1,len(self.protoX)-1): #correct for weird ABF offset issue.\n self.protoX[i]=self.protoX[i]+self.offsetX\n self.protoSeqY=[self.protoY[0]]\n self.protoSeqX=[self.protoX[0]]\n for i in range(1,len(self.protoY)):\n if not self.protoY[i]==self.protoY[i-1]:\n self.protoSeqY.append(self.protoY[i])\n self.protoSeqX.append(self.protoX[i])\n if self.protoY[0]!=self.protoY[1]:\n self.protoY.insert(1,self.protoY[0])\n self.protoX.insert(1,self.protoX[1])\n self.protoY.insert(1,self.protoY[0])\n self.protoX.insert(1,self.protoX[0]+self.offsetX/2)\n self.protoSeqY.append(finalVal)\n self.protoSeqX.append(self.sweepSize)\n\n # convert lists to numpy arrays and do any final conversions\n self.protoX=np.array(self.protoX)/self.pointsPerSec\n self.protoY=np.array(self.protoY)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nget the protocol of the current sweep", "response": "def get_protocol(self,sweep):\n \"\"\"\n given a sweep, return the protocol as [Xs,Ys].\n This is good for plotting/recreating the protocol trace.\n There may be duplicate numbers.\n \"\"\"\n self.setsweep(sweep)\n return list(self.protoX),list(self.protoY)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngets the protocol sequence for a given sweep", "response": "def get_protocol_sequence(self,sweep):\n \"\"\"\n given a sweep, return the protocol as condensed sequence.\n This is better for comparing similarities and determining steps.\n There should be no duplicate numbers.\n \"\"\"\n self.setsweep(sweep)\n return list(self.protoSeqX),list(self.protoSeqY)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nget start and stop times of an epoch", "response": "def epochTimes(self,nEpoch=2):\n \"\"\"\n alternative to the existing abf protocol stuff\n return the start/stop time of an epoch.\n Epoch start at zero.\n A=0, B=1, C=2, D=3, ...\n \"\"\"\n times=[]\n durations=[]\n for epoch in self.header['dictEpochInfoPerDAC'][self.channel].values():\n print(epoch['lEpochInitDuration']/self.pointsPerSec)\n times.append(sum(durations))\n durations.append(epoch['lEpochInitDuration']/self.pointsPerSec)\n times.append(sum(durations))\n times=np.array(times)+self.offsetX/self.pointsPerSec # WHY?!?\n if nEpoch:\n return times[nEpoch],times[nEpoch+1]\n else:\n return times"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef average(self,t1=0,t2=None,setsweep=False):\n if setsweep:\n self.setsweep(setsweep)\n if t2 is None or t2>self.sweepLength:\n t2=self.sweepLength\n self.log.debug(\"resetting t2 to [%f]\",t2)\n t1=max(t1,0)\n if t1>t2:\n self.log.error(\"t1 cannot be larger than t2\")\n return False\n I1,I2=int(t1*self.pointsPerSec),int(t2*self.pointsPerSec)\n if I1==I2:\n return np.nan\n return np.average(self.sweepY[I1:I2])", "response": "return the average of part of the current sweep."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef averageSweep(self,sweepFirst=0,sweepLast=None):\n if sweepLast is None:\n sweepLast=self.sweeps-1\n nSweeps=sweepLast-sweepFirst+1\n runningSum=np.zeros(len(self.sweepY))\n self.log.debug(\"averaging sweep %d to %d\",sweepFirst,sweepLast)\n for sweep in np.arange(nSweeps)+sweepFirst:\n self.setsweep(sweep)\n runningSum+=self.sweepY.flatten()\n average=runningSum/nSweeps\n #TODO: standard deviation?\n return average", "response": "Return an average sweep of multiple sweeps."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ncreates kernel based on this ABF info.", "response": "def kernel_gaussian(self, sizeMS, sigmaMS=None, forwardOnly=False):\n \"\"\"create kernel based on this ABF info.\"\"\"\n sigmaMS=sizeMS/10 if sigmaMS is None else sigmaMS\n size,sigma=sizeMS*self.pointsPerMs,sigmaMS*self.pointsPerMs\n self.kernel=swhlab.common.kernel_gaussian(size,sigma,forwardOnly)\n return self.kernel"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef sweepYfiltered(self):\n assert self.kernel is not None\n return swhlab.common.convolve(self.sweepY,self.kernel)", "response": "Returns the filtered sweepY of the current sweep."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef phasicNet(self,biggestEvent=50,m1=.5,m2=None):\n\n # determine marks (between which we will analyze)\n m1=0 if m1 is None else self.pointsPerSec*m1\n m2=-1 if m2 is None else self.pointsPerSec*m2\n\n # acquire the baseline-subtracted sweep\n Y=self.sweepYsmartbase()[int(m1):int(m2)]\n\n # create the histogram\n nBins=1000\n hist,bins=np.histogram(Y,bins=nBins,range=[-biggestEvent,biggestEvent],density=True)\n histSmooth=swhlab.common.lowpass(hist)\n\n # normalize height to 1\n #TODO: should it be normalized first or not?\n #YES if reporting the ratio of the up/down area, NO if reporting the up-down difference\n #hist,histSmooth=hist/max(histSmooth),histSmooth/max(histSmooth)\n\n # center the peak at 0 pA\n peakI=np.where(histSmooth==max(histSmooth))[0][0]\n hist=np.roll(hist,int(nBins/2-peakI))\n histSmooth=np.roll(histSmooth,int(nBins/2-peakI))\n\n # calculate our mirrored difference\n downward,upward=np.split(histSmooth,2)\n downward=downward[::-1]\n diff=np.sum(upward-downward)\n\n # convert our \"pA/time\" to \"pA/sec\"\n diff=diff/(len(Y)/self.pointsPerSec)\n\n return diff", "response": "Calculates the phasic difference between positive and negative phasic events\n Returns the phasic difference value of the current sweep."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef output_touch(self):\n if not os.path.exists(self.outFolder):\n self.log.debug(\"creating %s\",self.outFolder)\n os.mkdir(self.outFolder)", "response": "ensure the. whlab folder exists."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ngive a list of dicts return just the dicts.", "response": "def dictFlat(l):\n \"\"\"Given a list of list of dicts, return just the dicts.\"\"\"\n if type(l) is dict:\n return [l]\n if \"numpy\" in str(type(l)):\n return l\n dicts=[]\n for item in l:\n if type(item)==dict:\n dicts.append(item)\n elif type(item)==list:\n for item2 in item:\n dicts.append(item2)\n return dicts"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef listCount(l):\n for i in range(len(l)):\n l[i]=len(l[i])\n return l", "response": "returns len ( each item in a list as a list"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns all key from a list of dicts.", "response": "def dictVals(l,key):\n \"\"\"Return all 'key' from a list of dicts. (or list of list of dicts)\"\"\"\n dicts=dictFlat(l)\n vals=np.empty(len(dicts))*np.nan\n for i in range(len(dicts)):\n if key in dicts[i]:\n vals[i]=dicts[i][key]\n return vals"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef dictAvg(listOfDicts,key,stdErr=False):\n vals=dictVals(listOfDicts,key)\n if len(vals) and np.any(vals):\n av=np.nanmean(vals)\n er=np.nanstd(vals)\n if stdErr:\n er=er/np.sqrt(np.count_nonzero(~np.isnan(er)))\n else:\n av,er=np.nan,np.nan\n return av,er", "response": "Given a list of dicts d return AV and SD."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a list of dicts with fake data.", "response": "def dummyListOfDicts(size=100):\n \"\"\"\n returns a list (of the given size) of dicts with fake data.\n some dictionary keys are missing for some of the items.\n \"\"\"\n titles=\"ahp,halfwidth,peak,expT,expI,sweep\".split(\",\")\n ld=[] #list of dicts\n for i in range(size):\n d={}\n for t in titles:\n if int(np.random.random(1)*100)>5: #5% of values are missing\n d[t]=float(np.random.random(1)*100) #random number 0-100\n if t==\"sweep\" and \"sweep\" in d.keys():\n d[t]=int(d[t])\n ld.append(d)\n return ld"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef matrixValues(matrix,key):\n assert key in matrix.dtype.names\n col=matrix.dtype.names.index(key)\n values=np.empty(len(matrix))*np.nan\n for i in range(len(matrix)):\n values[i]=matrix[i][col]\n return values", "response": "given a key return a list of values from the matrix with that key."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef matrixToDicts(data):\n\n # 1D array\n if \"float\" in str(type(data[0])):\n d={}\n for x in range(len(data)):\n d[data.dtype.names[x]]=data[x]\n return d\n\n # 2D array\n l=[]\n for y in range(len(data)):\n d={}\n for x in range(len(data[y])):\n d[data.dtype.names[x]]=data[y][x]\n l.append(d)\n return l", "response": "given a recarray return it as a list of dicts."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nconverts a list of dicts to a structured array.", "response": "def matrixfromDicts(dicts):\n \"\"\"\n Give a list of dicts (or list of list of dicts) return a structured array.\n Headings will be sorted in alphabetical order.\n \"\"\"\n if 'numpy' in str(type(dicts)):\n return dicts #already an array?\n names=set([])\n dicts=dictFlat(dicts)\n for item in dicts:\n names=names.union(list(item.keys()))\n names=sorted(list(names))\n data=np.empty((len(dicts),len(names)),dtype=float)*np.nan\n for y in range(len(dicts)):\n for key in dicts[y].keys():\n for x in range(len(names)):\n if names[x] in dicts[y]:\n data[y,x]=dicts[y][names[x]]\n if len(dicts):\n data=np.core.records.fromarrays(data.transpose(),names=names)\n return data"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nconvert a list into a list of HTML tables.", "response": "def htmlListToTR(l,trClass=None,tdClass=None,td1Class=None):\n \"\"\"\n turns a list into a
something
\n call this when generating HTML tables dynamically.\n \"\"\"\n html=\"
\"\n for item in l:\n if 'array' in str(type(item)):\n item=item[0] #TODO: why is this needed\n html+=\"
%s
\"%item\n html+=\"
\"\n if trClass:\n html=html.replace(\"
\",'
'%trClass)\n if td1Class:\n html=html.replace(\"
\",'
'%td1Class,1)\n if tdClass:\n html=html.replace(\"
\",'
'%tdClass)\n\n\n return html"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef html_temp_launch(html):\n fname = tempfile.gettempdir()+\"/swhlab/temp.html\"\n with open(fname,'w') as f:\n f.write(html)\n webbrowser.open(fname)", "response": "given text make it a temporary HTML file and launch it"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nshowing everything we can about an object s projects and methods.", "response": "def checkOut(thing,html=True):\n \"\"\"show everything we can about an object's projects and methods.\"\"\"\n msg=\"\"\n for name in sorted(dir(thing)):\n if not \"__\" in name:\n msg+=\"%s\\n\"%name\n try:\n msg+=\" ^-VALUE: %s\\n\"%getattr(thing,name)()\n except:\n pass\n if html:\n html=''+msg+''\n html=html.replace(\" \",\" \").replace(\"\\n\",\" \")\n fname = tempfile.gettempdir()+\"/swhlab/checkout.html\"\n with open(fname,'w') as f:\n f.write(html)\n webbrowser.open(fname)\n print(msg.replace('','').replace('',''))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nconverting a 2d numpy array into an Origin worksheet.", "response": "def matrixToWks(data,names=None,units=None,bookName=None,sheetName=\" \",xCol=None):\n \"\"\"\n Put 2d numpy data into an Origin worksheet.\n If bookname and sheetname are given try to load data into that book/sheet.\n If the book/sheet doesn't exist, create it.\n \"\"\"\n if type(data) is list:\n data=matrixfromDicts(data)\n if not names:\n names=[\"\"]*len(data[0])\n if data.dtype.names:\n names=list(data.dtype.names)\n if not units:\n units=[\"\"]*len(data[0])\n for i in range(len(units)):\n if names[i] in UNITS.keys():\n units[i]=UNITS[names[i]]\n if 'recarray' in str(type(data)): #make it a regular array\n data=data.view(float).reshape(data.shape + (-1,))\n if xCol and xCol in names:\n xCol=names.index(xCol)\n names.insert(0,names[xCol])\n units.insert(0,units[xCol])\n data=np.insert(data,0,data[:,xCol],1)\n\n if not bookName:\n bookName=\"tempBook\"\n if not sheetName:\n sheetName=\"temp-\"+str(time.clock())[-5:]\n\n try:\n import PyOrigin\n PyOrigin.LT_execute(\"\") #try to crash a non-orign environment\n except:\n print(\" -- PyOrigin not running, making HTML output.\")\n matrixToHTML(data,names,units,bookName,sheetName,xCol)\n return\n\n nrows,ncols=len(data),len(data[0])\n if 'recarray' in str(type(data)): #convert structured array to regular array\n data=np.array(data.view(),dtype=float).reshape((nrows,ncols))\n data=np.transpose(data) #transpose it\n\n PyOrigin.LT_execute(\"activateSheet(%s, %s)\"%(bookName,sheetName))\n wks=PyOrigin.ActiveLayer()\n while wks.GetColCount() < ncols:\n wks.InsertCol(wks.GetColCount(),'')\n for i in range(ncols):\n col=wks.Columns(i)\n col.SetLongName(names[i])\n col.SetUnits(units[i])\n wks.SetData(data,0,0)\n PyOrigin.LT_execute(\"FixNanBug\")\n PyOrigin.LT_execute(\"ABFPathToMetaData\")"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nputting 2d numpy data into a temporary HTML file.", "response": "def matrixToHTML(data,names=None,units=None,bookName=None,sheetName=None,xCol=None):\n \"\"\"Put 2d numpy data into a temporary HTML file.\"\"\"\n if not names:\n names=[\"\"]*len(data[0])\n if data.dtype.names:\n names=list(data.dtype.names)\n if not units:\n units=[\"\"]*len(data[0])\n for i in range(len(units)):\n if names[i] in UNITS.keys():\n units[i]=UNITS[names[i]]\n if 'recarray' in str(type(data)): #make it a regular array\n data=data.view(float).reshape(data.shape + (-1,))\n if xCol and xCol in names:\n xCol=names.index(xCol)\n names.insert(0,names[xCol])\n units.insert(0,units[xCol])\n data=np.insert(data,0,data[:,xCol],1)\n\n htmlFname = tempfile.gettempdir()+\"/swhlab/WKS-%s.%s.html\"%(bookName,sheetName)\n html=\"\"\"\n \n \"\"\"\n html+=\"
FauxRigin
\"\n if bookName or sheetName:\n html+='%s / %s
'%(bookName,sheetName)\n html+=\"
\"\n #cols=list(range(len(names)))\n colNames=['']\n for i in range(len(units)):\n label=\"%s (%d)\"%(chr(i+ord('A')),i)\n colNames.append(label)\n html+=htmlListToTR(colNames,'labelCol','labelCol')\n html+=htmlListToTR(['Long Name']+list(names),'name',td1Class='labelRow')\n html+=htmlListToTR(['Units']+list(units),'units',td1Class='labelRow')\n cutOff=False\n for y in range(len(data)):\n html+=htmlListToTR([y+1]+list(data[y]),trClass='data%d'%(y%2),td1Class='labelRow')\n if y>=200:\n cutOff=True\n break\n html+=\"
\"\n html=html.replace(\">nan<\",\">--<\")\n html=html.replace(\">None<\",\"><\")\n if cutOff:\n html+=\"
... showing only %d of %d rows ...
\"%(y,len(data))\n html+=\"\"\n with open(htmlFname,'w') as f:\n f.write(html)\n webbrowser.open(htmlFname)\n return"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn an XML object", "response": "def XMLtoPython(xmlStr=r\"C:\\Apps\\pythonModules\\GSTemp.xml\"):\n \"\"\"\n given a string or a path to an XML file, return an XML object.\n \"\"\"\n #TODO: this absolute file path crazy stuff needs to stop!\n if os.path.exists(xmlStr):\n with open(xmlStr) as f:\n xmlStr=f.read()\n print(xmlStr)\n print(\"DONE\")\n return"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef fit_exp(y,graphToo=False):\n x=np.arange(len(y))\n try:\n params, cv = scipy.optimize.curve_fit(algo_exp, x, y, p0=(1,1e-6,1))\n except:\n print(\" !! curve fit failed (%.02f points)\"%len(x))\n return np.nan,np.nan,np.nan,np.nan #can't fit so little data!\n m,t,b=params\n tau=1/t\n if graphToo:\n pylab.figure(figsize=(6,4))\n pylab.grid()\n pylab.title(\"FIT ASSESSMENT\")\n pylab.plot(x,y,'o',mfc='none',ms=10)\n pylab.plot(x,algo_exp(x,m,t,b),'b-',lw=2)\n pylab.show()\n return m,t,b,tau", "response": "Exponential fit. Returns [ multiplier t offset time constant"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\naligns a numpy array of XY columns into a single array of XYYY columns.", "response": "def numpyAlignXY(data):\n \"\"\"\n given a numpy array (XYXYXY columns), return it aligned.\n data returned will be XYYY. NANs may be returned.\n \"\"\"\n print(data)\n Xs=data.flatten()[::2] # get all X values\n Xs=Xs[~np.isnan(Xs)] # remove nans\n Xs=sorted(list(set(Xs))) # eliminate duplicates then sort it\n aligned=np.empty((len(Xs),int(len(data[0])/2+1)))*np.nan\n aligned[:,0]=Xs\n for col in range(0,len(data[0]),2):\n for row in range(len(data)):\n X=data[row,col]\n Y=data[row,col+1]\n if np.isnan(X) or np.isnan(Y):\n continue\n aligned[Xs.index(X),int(col/2+1)]=Y\n return aligned"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef filter_gaussian(Ys,sigma,plotToo=False):\n timeA=time.time()\n window=scipy.signal.gaussian(len(Ys),sigma)\n window/=sum(window)\n Ys2=np.convolve(Ys,window,'same')\n print(\"LEN:\",len(Ys2),len(Ys))\n timeB=time.time()\n print(\"convolution took %.03f ms\"%((timeB-timeA)*1000))\n if len(Ys2)!=len(Ys):\n print(\"?!?!?!? convolution point size mismatch\")\n if plotToo:\n pylab.plot(Ys,label='original',alpha=.2)\n pylab.plot(Ys2,'b-',label='smooth')\n pylab.legend()\n pylab.show()\n return Ys2", "response": "simple gaussian convolution. Returns same number of points as gotten."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef where_cross(data,threshold):\n Is=np.where(data>threshold)[0]\n Is=np.concatenate(([0],Is))\n Ds=Is[:-1]-Is[1:]+1\n return Is[np.where(Ds)[0]+1]", "response": "return a list of Is where the data first crosses threshold."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning a list of dicts as a 2d matrix.", "response": "def originFormat_listOfDicts(l):\n \"\"\"Return [{},{},{}] as a 2d matrix.\"\"\"\n titles=[]\n for d in l:\n for k in d.keys():\n if not k in titles:\n titles.append(k)\n titles.sort()\n data=np.empty((len(l),len(titles)))*np.nan\n for y in range(len(l)):\n for x in range(len(titles)):\n if titles[x] in l[y].keys():\n data[y][x]=l[y][titles[x]]\n return titles,data"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef originFormat(thing):\n if type(thing) is list and type(thing[0]) is dict:\n return originFormat_listOfDicts(thing)\n if type(thing) is list and type(thing[0]) is list:\n return originFormat_listOfDicts(dictFlat(thing))\n else:\n print(\" !! I don't know how to format this object!\")\n print(thing)", "response": "Try to format anything as a 2D matrix with column names."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef pickle_save(thing,fname):\n pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n return thing", "response": "save something to a pickle file"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nconverting a dictionary to a pretty formatted string.", "response": "def msgDict(d,matching=None,sep1=\"=\",sep2=\"\\n\",sort=True,cantEndWith=None):\n \"\"\"convert a dictionary to a pretty formatted string.\"\"\"\n msg=\"\"\n if \"record\" in str(type(d)):\n keys=d.dtype.names\n else:\n keys=d.keys()\n if sort:\n keys=sorted(keys)\n for key in keys:\n if key[0]==\"_\":\n continue\n if matching:\n if not key in matching:\n continue\n if cantEndWith and key[-len(cantEndWith)]==cantEndWith:\n continue\n if 'float' in str(type(d[key])):\n s=\"%.02f\"%d[key]\n else:\n s=str(d[key])\n if \"object\" in s:\n s='